-
Notifications
You must be signed in to change notification settings - Fork 1
/
actions.js
74 lines (74 loc) · 2.39 KB
/
actions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import fetch from "./commercetools/auth.js";
import { decode } from "js-base64";
const getMessage = (req) =>
JSON.parse(decode(req?.body?.message?.data));
// const getMessage = (req) => req?.body;
const actions = [
(req) =>
Promise.resolve().then(() => {
const message = getMessage(req);
console.log("message:", JSON.stringify(message));
if (!message.order?.customerId) {
return;
}
return fetch(`/customers/${message.order.customerId}`)
.then((response) => response.json())
.then((customer) => {
const price = message.order.totalPrice;
const points =
Math.ceil(
price.centAmount / 10 ** price.fractionDigits
) + (customer?.custom?.fields?.points || 0);
const PRODUCT_TYPE =
"9598aa94-2994-4f43-8471-69f65f46c7e3";
const CUSTOMER_GROUP =
"9d4f125f-67c6-4817-89eb-4e904b3c3774";
const actions = [
// add total amount to customer points
{
action: "setCustomType",
type: {
key: "customerPoints",
typeId: "type",
},
},
// add total amount to customer points
{
action: "setCustomField",
name: "points",
value: points,
},
// add customer to customer group if an order line has certain product type
message.order?.customerId &&
(message.order?.lineItems || []).some(
//if product is of type ... then do this
({ productType }) =>
productType?.id === PRODUCT_TYPE
)
? {
action: "setCustomerGroup",
customerGroup: {
id: CUSTOMER_GROUP,
typeId: "customer-group",
},
}
: false,
].filter((action) => action);
return fetch(
`/customers/${message.order.customerId}`,
{
method: "POST",
body: JSON.stringify({
version: customer.version,
actions,
}),
}
).then((result) => result.json());
});
}),
];
export default (req) =>
actions.reduce(
(acc, action) => acc.then(() => action(req)),
Promise.resolve()
);