-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathsimulation.ts
More file actions
154 lines (131 loc) · 4.04 KB
/
Copy pathsimulation.ts
File metadata and controls
154 lines (131 loc) · 4.04 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import { Product, ProductLeaf } from "../../../commerce/types.ts";
import { AppContext } from "../../mod.ts";
import { batch } from "../batch.ts";
import { OpenAPI } from "../openapi/vcs.openapi.gen.ts";
import { getSegmentFromBag, isAnonymous } from "../segment.ts";
import {
aggregateOffers,
SCHEMA_LIST_PRICE,
SCHEMA_SALE_PRICE,
} from "../transform.ts";
type Item = NonNullable<
OpenAPI["POST /api/checkout/pub/orderForms/simulation"]["response"]["items"]
>[number];
const doSimulate = (items: {
id: string;
quantity: number;
seller: string | undefined;
}[], ctx: AppContext) => {
const {
payload: {
priceTables,
utm_campaign,
utm_source,
utmi_campaign,
campaigns,
channel,
regionId,
},
} = getSegmentFromBag(ctx);
// When removeUTMFromCacheKey is on the store has declared UTM does not
// affect content/price, so the page is cached with UTM stripped from the
// cache key. Feeding UTM into the simulation here would let a UTM-triggered
// promotion change the price and get cached generically, so skip it to keep
// the simulation consistent with the caching contract.
const utmInKey = !ctx.advancedConfigs?.removeUTMFromCacheKey;
const md = new Map<string, unknown>();
utmInKey && utm_campaign && md.set("utmCampaign", utm_campaign);
utmInKey && utm_source && md.set("utmSource", utm_source);
utmInKey && utmi_campaign && md.set("utmiCampaign", utmi_campaign);
campaigns && md.set("campaigns", [{ id: campaigns }]);
const marketingData = md.size > 0
? Object.fromEntries(md.entries())
: undefined;
const body = {
items,
marketingData,
priceTables: priceTables?.split(","),
shippingData: {
logisticsInfo: regionId && [{ regionId }],
},
};
const params = { sc: Number(channel) || undefined, RnbBehavior: 1 };
return ctx.vcs["POST /api/checkout/pub/orderForms/simulation"](params, {
body,
})
.then((res) => res.json());
};
export const extension = async (products: Product[], ctx: AppContext) => {
if (isAnonymous(ctx)) {
return products;
}
const items =
products?.flatMap((p) =>
p.isVariantOf?.hasVariant.flatMap((v) =>
v.offers?.offers.map((o) => ({
id: v.productID,
quantity: 1,
seller: o.seller,
})) ?? []
) ?? []
) ?? [];
// VTEX API limits to 300 simulations
const batched = batch(items, 300);
const responses = await Promise.all(
batched.map((batch) => doSimulate(batch, ctx)),
);
const mapped = new Map<string, Map<string, Item>>();
for (const response of responses) {
for (const item of response.items ?? []) {
if (!item?.id || !item.seller) {
continue;
}
if (!mapped.has(item.id)) {
mapped.set(item.id, new Map<string, Item>());
}
mapped.get(item.id)!.set(item.seller, item);
}
}
const fixOffer = (product: ProductLeaf): void => {
if (!product.offers) return;
const skuOffers = mapped.get(product.productID);
if (!skuOffers) return;
let changed = false;
for (const o of product.offers.offers) {
const simulated = skuOffers.get(o.seller!);
if (!simulated) continue;
const salePrice = simulated.price != null
? simulated.price / 100
: o.price;
const listPrice = simulated.listPrice != null
? simulated.listPrice / 100
: undefined;
if (salePrice !== o.price) {
o.price = salePrice;
changed = true;
}
for (const spec of o.priceSpecification) {
if (spec.priceType === SCHEMA_SALE_PRICE) {
spec.price = salePrice;
} else if (spec.priceType === SCHEMA_LIST_PRICE) {
spec.price = listPrice ?? spec.price;
}
}
}
if (changed) {
product.offers = aggregateOffers(
product.offers.offers,
product.offers.priceCurrency,
);
}
};
for (const p of products) {
fixOffer(p);
if (p.isVariantOf) {
for (const variant of p.isVariantOf.hasVariant) {
fixOffer(variant);
}
}
}
return products;
};