Browse Source

feat(core): Implement add/remove Surcharge methods in OrderService

Relates to #583
Michael Bromley 5 years ago
parent
commit
6cf6984d89

+ 1 - 1
packages/core/src/config/vendure-config.ts

@@ -402,7 +402,7 @@ export interface OrderOptions {
      *
      * @default DefaultStockAllocationStrategy
      */
-    stockAllocationStrategy: StockAllocationStrategy;
+    stockAllocationStrategy?: StockAllocationStrategy;
     /**
      * @description
      * Defines the strategy used to merge a guest Order and an existing Order when

+ 1 - 1
packages/core/src/entity/surcharge/surcharge.entity.ts

@@ -36,7 +36,7 @@ export class Surcharge extends VendureEntity {
     @Column('simple-json')
     taxLines: TaxLine[];
 
-    @ManyToOne(type => Order, order => order.surcharges)
+    @ManyToOne(type => Order, order => order.surcharges, { onDelete: 'CASCADE' })
     order: Order;
 
     @Calculated()

+ 33 - 0
packages/core/src/service/services/order.service.ts

@@ -457,6 +457,39 @@ export class OrderService {
         return updatedOrder;
     }
 
+    async addSurchargeToOrder(
+        ctx: RequestContext,
+        orderId: ID,
+        surchargeInput: Partial<Omit<Surcharge, 'id' | 'createdAt' | 'updatedAt' | 'order'>>,
+    ): Promise<Order> {
+        const order = await this.getOrderOrThrow(ctx, orderId);
+        const surcharge = await this.connection.getRepository(ctx, Surcharge).save(
+            new Surcharge({
+                taxLines: [],
+                sku: '',
+                listPriceIncludesTax: ctx.channel.pricesIncludeTax,
+                order,
+                ...surchargeInput,
+            }),
+        );
+        order.surcharges.push(surcharge);
+        const updatedOrder = await this.applyPriceAdjustments(ctx, order);
+        return updatedOrder;
+    }
+
+    async removeSurchargeFromOrder(ctx: RequestContext, orderId: ID, surchargeId: ID): Promise<Order> {
+        const order = await this.getOrderOrThrow(ctx, orderId);
+        const surcharge = await this.connection.getEntityOrThrow(ctx, Surcharge, surchargeId);
+        if (order.surcharges.find(s => idsAreEqual(s.id, surcharge.id))) {
+            order.surcharges = order.surcharges.filter(s => !idsAreEqual(s.id, surchargeId));
+            const updatedOrder = await this.applyPriceAdjustments(ctx, order);
+            await this.connection.getRepository(ctx, Surcharge).remove(surcharge);
+            return updatedOrder;
+        } else {
+            return order;
+        }
+    }
+
     async applyCouponCode(
         ctx: RequestContext,
         orderId: ID,