Jelajahi Sumber

fix(core): Prevent multiple ProductVariantPrice creation

Closes #652
Michael Bromley 5 tahun lalu
induk
melakukan
c85303373e

+ 21 - 8
packages/core/src/service/services/product-variant.service.ts

@@ -325,12 +325,17 @@ export class ProductVariantService {
         }
 
         const defaultChannelId = this.channelService.getDefaultChannel().id;
-        await this.createProductVariantPrice(ctx, createdVariant.id, input.price, ctx.channelId);
+        await this.createOrUpdateProductVariantPrice(ctx, createdVariant.id, input.price, ctx.channelId);
         if (!idsAreEqual(ctx.channelId, defaultChannelId)) {
             // When creating a ProductVariant _not_ in the default Channel, we still need to
             // create a ProductVariantPrice for it in the default Channel, otherwise errors will
             // result when trying to query it there.
-            await this.createProductVariantPrice(ctx, createdVariant.id, input.price, defaultChannelId);
+            await this.createOrUpdateProductVariantPrice(
+                ctx,
+                createdVariant.id,
+                input.price,
+                defaultChannelId,
+            );
         }
         return createdVariant.id;
     }
@@ -400,17 +405,25 @@ export class ProductVariantService {
     /**
      * Creates a ProductVariantPrice for the given ProductVariant/Channel combination.
      */
-    async createProductVariantPrice(
+    async createOrUpdateProductVariantPrice(
         ctx: RequestContext,
         productVariantId: ID,
         price: number,
         channelId: ID,
     ): Promise<ProductVariantPrice> {
-        const variantPrice = new ProductVariantPrice({
-            price,
-            channelId,
+        let variantPrice = await this.connection.getRepository(ctx, ProductVariantPrice).findOne({
+            where: {
+                variant: productVariantId,
+                channelId,
+            },
         });
-        variantPrice.variant = new ProductVariant({ id: productVariantId });
+        if (!variantPrice) {
+            variantPrice = new ProductVariantPrice({
+                channelId,
+                variant: new ProductVariant({ id: productVariantId }),
+            });
+        }
+        variantPrice.price = price;
         return this.connection.getRepository(ctx, ProductVariantPrice).save(variantPrice);
     }
 
@@ -478,7 +491,7 @@ export class ProductVariantService {
             this.applyChannelPriceAndTax(variant, ctx);
             await this.channelService.assignToChannels(ctx, Product, variant.productId, [input.channelId]);
             await this.channelService.assignToChannels(ctx, ProductVariant, variant.id, [input.channelId]);
-            await this.createProductVariantPrice(
+            await this.createOrUpdateProductVariantPrice(
                 ctx,
                 variant.id,
                 variant.price * priceFactor,