|
1
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"; |
|
2
|
import { AdminOrder } from "@medusajs/framework/types"; |
|
3
|
import { |
|
4
|
ContainerRegistrationKeys, |
|
5
|
OrderWorkflowEvents, |
|
6
|
} from "@medusajs/framework/utils"; |
|
7
|
|
|
8
|
import { createGiftCardsWorkflow } from "../workflows/gift-cards/workflows/create-gift-cards"; |
|
9
|
|
|
10
|
export default async function createGiftCardHandler({ |
|
11
|
event: { data }, |
|
12
|
container, |
|
13
|
}: SubscriberArgs<{ id: string }>) { |
|
14
|
const orderId = data.id; |
|
15
|
const query = container.resolve(ContainerRegistrationKeys.QUERY); |
|
16
|
|
|
17
|
const { |
|
18
|
data: [order], |
|
19
|
} = await query.graph({ |
|
20
|
entity: "order", |
|
21
|
filters: { id: orderId }, |
|
22
|
fields: [ |
|
23
|
"id", |
|
24
|
"currency_code", |
|
25
|
"items.id", |
|
26
|
"items.subtotal", |
|
27
|
"items.quantity", |
|
28
|
"items.*", |
|
29
|
"items.product.is_giftcard", |
|
30
|
"total", |
|
31
|
"subtotal", |
|
32
|
"tax_total", |
|
33
|
], |
|
34
|
}); |
|
35
|
|
|
36
|
const giftCardLineItems = (order as AdminOrder).items.filter( |
|
37
|
(item) => !!item.product?.is_giftcard |
|
38
|
); |
|
39
|
|
|
40
|
if (giftCardLineItems.length === 0) { |
|
41
|
return; |
|
42
|
} |
|
43
|
|
|
44
|
for (const giftCardLineItem of giftCardLineItems) { |
|
45
|
// For each gift card line item quantity, create a gift card using for const giftCard of giftCardLineItem.quantity |
|
46
|
for (let i = 0; i < giftCardLineItem.quantity; i++) { |
|
47
|
const giftCardValue = |
|
48
|
giftCardLineItem.subtotal / giftCardLineItem.quantity; |
|
49
|
|
|
50
|
const { |
|
51
|
result: [giftCard], |
|
52
|
} = await createGiftCardsWorkflow.run({ |
|
53
|
input: [ |
|
54
|
{ |
|
55
|
value: giftCardValue, |
|
56
|
currency_code: order.currency_code, |
|
57
|
line_item_id: giftCardLineItem.id, |
|
58
|
reference: "order", |
|
59
|
reference_id: order.id, |
|
60
|
metadata: {}, |
|
61
|
}, |
|
62
|
], |
|
63
|
container, |
|
64
|
}); |
|
65
|
} |
|
66
|
} |
|
67
|
} |
|
68
|
|
|
69
|
export const config: SubscriberConfig = { |
|
70
|
event: OrderWorkflowEvents.PLACED, |
|
71
|
}; |