diff --git a/packages/medusa-plugin-segment/src/subscribers/order.js b/packages/medusa-plugin-segment/src/subscribers/order.js index fe422dca4a..c5eac08e03 100644 --- a/packages/medusa-plugin-segment/src/subscribers/order.js +++ b/packages/medusa-plugin-segment/src/subscribers/order.js @@ -5,12 +5,76 @@ class OrderSubscriber { orderService, claimService, returnService, + fulfillmentService, }) { this.orderService_ = orderService this.returnService_ = returnService this.claimService_ = claimService + this.fulfillmentService_ = fulfillmentService + + eventBusService.subscribe( + "order.shipment_created", + async ({ id, fulfillment_id }) => { + const order = await this.orderService_.retrieve(id, { + select: [ + "shipping_total", + "discount_total", + "tax_total", + "refunded_total", + "gift_card_total", + "subtotal", + "total", + ], + relations: [ + "customer", + "billing_address", + "shipping_address", + "discounts", + "shipping_methods", + "payments", + "fulfillments", + "returns", + "items", + "gift_cards", + "gift_card_transactions", + "swaps", + "swaps.return_order", + "swaps.payment", + "swaps.shipping_methods", + "swaps.shipping_address", + "swaps.additional_items", + "swaps.fulfillments", + ], + }) + + const fulfillment = await this.fulfillmentService_.retrieve( + fulfillment_id, + { + relations: ["items"], + } + ) + + const toBuildFrom = { + ...order, + provider_id: fulfillment.provider, + items: fulfillment.items.map((i) => + order.items.find((l) => l.id === i.item_id) + ), + } + + const orderData = await segmentService.buildOrder(toBuildFrom) + const orderEvent = { + event: "Order Shipped", + userId: order.customer_id, + properties: orderData, + timestamp: fulfillment.shipped_at, + } + + segmentService.track(orderEvent) + } + ) eventBusService.subscribe("claim.created", async ({ id }) => { const claim = await this.claimService_.retrieve(id, {