payload-abandoned-cart 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +217 -0
- package/dist/index.d.ts +274 -0
- package/dist/index.js +873 -0
- package/package.json +66 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,873 @@
|
|
|
1
|
+
import { getRandomValues, timingSafeEqual } from 'crypto';
|
|
2
|
+
|
|
3
|
+
// src/amount.ts
|
|
4
|
+
var decimalsFor = (currency, decimals2) => {
|
|
5
|
+
if (typeof decimals2 === "number") {
|
|
6
|
+
return Number.isFinite(decimals2) && decimals2 >= 0 ? Math.trunc(decimals2) : 2;
|
|
7
|
+
}
|
|
8
|
+
const value = decimals2[currency];
|
|
9
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 2;
|
|
10
|
+
};
|
|
11
|
+
var formatAmount = (amount, currency, decimals2 = 2) => {
|
|
12
|
+
if (amount === null || !Number.isFinite(amount)) {
|
|
13
|
+
return "";
|
|
14
|
+
}
|
|
15
|
+
const places = decimalsFor(currency, decimals2);
|
|
16
|
+
const major = (amount / 10 ** places).toFixed(places);
|
|
17
|
+
return currency ? `${major} ${currency}` : major;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/cart.ts
|
|
21
|
+
var stringValue = (value) => {
|
|
22
|
+
if (typeof value === "string" && value !== "") {
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
return typeof value === "number" && Number.isFinite(value) ? String(value) : null;
|
|
26
|
+
};
|
|
27
|
+
var numberValue = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
28
|
+
var timeValue = (value) => {
|
|
29
|
+
if (typeof value !== "string" && !(value instanceof Date)) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
const time = new Date(value).getTime();
|
|
33
|
+
return Number.isFinite(time) ? time : null;
|
|
34
|
+
};
|
|
35
|
+
var cartLines = (cart) => Array.isArray(cart.items) ? cart.items.filter(
|
|
36
|
+
(line) => line !== null && typeof line === "object"
|
|
37
|
+
) : [];
|
|
38
|
+
var itemCount = (cart) => cartLines(cart).reduce((total, line) => {
|
|
39
|
+
const quantity = numberValue(line.quantity);
|
|
40
|
+
return total + (quantity === null ? 0 : quantity);
|
|
41
|
+
}, 0);
|
|
42
|
+
var emailOf = (value) => {
|
|
43
|
+
if (typeof value === "string") {
|
|
44
|
+
return value.includes("@") ? value : null;
|
|
45
|
+
}
|
|
46
|
+
if (value && typeof value === "object") {
|
|
47
|
+
return emailOf(value.email);
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
};
|
|
51
|
+
var resolveRecipient = async (payload, config, cart, req) => {
|
|
52
|
+
const direct = emailOf(cart[config.emailFieldName]);
|
|
53
|
+
if (direct) {
|
|
54
|
+
return direct;
|
|
55
|
+
}
|
|
56
|
+
const customer = cart.customer;
|
|
57
|
+
if (!customer) {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
const embedded = emailOf(customer);
|
|
61
|
+
if (embedded) {
|
|
62
|
+
return embedded;
|
|
63
|
+
}
|
|
64
|
+
const id = stringValue(customer);
|
|
65
|
+
if (id === null) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const doc = await payload.findByID({
|
|
69
|
+
id,
|
|
70
|
+
collection: config.customersSlug,
|
|
71
|
+
depth: 0,
|
|
72
|
+
disableErrors: true,
|
|
73
|
+
overrideAccess: true,
|
|
74
|
+
...req ? { req } : {}
|
|
75
|
+
});
|
|
76
|
+
return emailOf(doc);
|
|
77
|
+
};
|
|
78
|
+
var recoveryURL = (payload, config, token2) => {
|
|
79
|
+
const hostConfig = payload.config;
|
|
80
|
+
const origin = (config.serverURL || hostConfig?.serverURL || "").replace(/\/+$/, "");
|
|
81
|
+
const api = hostConfig?.routes?.api ?? "/api";
|
|
82
|
+
return `${origin}${api}${config.recoverEndpointPath}?token=${encodeURIComponent(token2)}`;
|
|
83
|
+
};
|
|
84
|
+
var buildContext = (args) => {
|
|
85
|
+
const { cart, config, recoveryURL: url, step, to } = args;
|
|
86
|
+
const currency = stringValue(cart.currency)?.toUpperCase() ?? "";
|
|
87
|
+
const subtotal = numberValue(cart.subtotal);
|
|
88
|
+
return {
|
|
89
|
+
abandonedAt: stringValue(cart.abandonedAt) ?? "",
|
|
90
|
+
cart,
|
|
91
|
+
cartID: String(cart.id),
|
|
92
|
+
currency,
|
|
93
|
+
itemCount: itemCount(cart),
|
|
94
|
+
lineCount: cartLines(cart).length,
|
|
95
|
+
recoveryURL: url,
|
|
96
|
+
step,
|
|
97
|
+
subtotal,
|
|
98
|
+
subtotalFormatted: formatAmount(subtotal, currency, config.currencyDecimals),
|
|
99
|
+
to
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
// src/attribution.ts
|
|
104
|
+
var orderContextKey = "payloadAbandonedCartOrderID";
|
|
105
|
+
var captureOrder = (config) => {
|
|
106
|
+
const hook = ({ doc, operation, req }) => {
|
|
107
|
+
if (config.disabled || operation !== "create") {
|
|
108
|
+
return doc;
|
|
109
|
+
}
|
|
110
|
+
const context = req.context ?? {};
|
|
111
|
+
context[orderContextKey] = doc.id;
|
|
112
|
+
req.context = context;
|
|
113
|
+
return doc;
|
|
114
|
+
};
|
|
115
|
+
return hook;
|
|
116
|
+
};
|
|
117
|
+
var attributeRecovery = (config) => {
|
|
118
|
+
const hook = async ({
|
|
119
|
+
doc,
|
|
120
|
+
operation,
|
|
121
|
+
previousDoc,
|
|
122
|
+
req
|
|
123
|
+
}) => {
|
|
124
|
+
if (config.disabled || operation !== "update") {
|
|
125
|
+
return doc;
|
|
126
|
+
}
|
|
127
|
+
if (!doc.purchasedAt || previousDoc?.purchasedAt) {
|
|
128
|
+
return doc;
|
|
129
|
+
}
|
|
130
|
+
const visited = timeValue(doc.recoveryVisitedAt);
|
|
131
|
+
const purchased = timeValue(doc.purchasedAt) ?? Date.now();
|
|
132
|
+
if (visited === null) {
|
|
133
|
+
return doc;
|
|
134
|
+
}
|
|
135
|
+
if (purchased - visited > config.attributionWindowHours * 60 * 60 * 1e3) {
|
|
136
|
+
return doc;
|
|
137
|
+
}
|
|
138
|
+
const context = req.context ?? {};
|
|
139
|
+
const orderID = context[orderContextKey];
|
|
140
|
+
if (orderID === void 0 || orderID === null) {
|
|
141
|
+
req.payload.logger.info(
|
|
142
|
+
`payload-abandoned-cart: cart ${String(
|
|
143
|
+
doc.id
|
|
144
|
+
)} was recovered and purchased, but no order was created in the same request to attribute it to`
|
|
145
|
+
);
|
|
146
|
+
return doc;
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
await req.payload.update({
|
|
150
|
+
id: orderID,
|
|
151
|
+
collection: config.ordersSlug,
|
|
152
|
+
data: {
|
|
153
|
+
recoveredFromCart: doc.id,
|
|
154
|
+
recoveryEmailStep: numberValue(doc.recoveryEmailsSent) ?? 0
|
|
155
|
+
},
|
|
156
|
+
depth: 0,
|
|
157
|
+
overrideAccess: true,
|
|
158
|
+
req
|
|
159
|
+
});
|
|
160
|
+
} catch (error) {
|
|
161
|
+
req.payload.logger.error(
|
|
162
|
+
`payload-abandoned-cart: could not attribute order ${String(orderID)} to cart ${String(
|
|
163
|
+
doc.id
|
|
164
|
+
)}: ${error instanceof Error ? error.message : String(error)}`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return doc;
|
|
168
|
+
};
|
|
169
|
+
return hook;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// src/templates.ts
|
|
173
|
+
var token = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
|
174
|
+
var replaceable = (value) => {
|
|
175
|
+
if (value === null || value === void 0) {
|
|
176
|
+
return "";
|
|
177
|
+
}
|
|
178
|
+
if (typeof value === "string") {
|
|
179
|
+
return value;
|
|
180
|
+
}
|
|
181
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
182
|
+
return String(value);
|
|
183
|
+
}
|
|
184
|
+
return null;
|
|
185
|
+
};
|
|
186
|
+
var renderPlaceholders = (input, context) => input.replace(token, (whole, name) => {
|
|
187
|
+
if (!Object.hasOwn(context, name)) {
|
|
188
|
+
return whole;
|
|
189
|
+
}
|
|
190
|
+
const value = replaceable(context[name]);
|
|
191
|
+
return value === null ? whole : value;
|
|
192
|
+
});
|
|
193
|
+
var renderTemplate = async (template, context) => {
|
|
194
|
+
if (typeof template === "function") {
|
|
195
|
+
return await template(context);
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
subject: renderPlaceholders(template.subject, context),
|
|
199
|
+
text: renderPlaceholders(template.text, context),
|
|
200
|
+
...template.html === void 0 ? {} : { html: renderPlaceholders(template.html, context) }
|
|
201
|
+
};
|
|
202
|
+
};
|
|
203
|
+
var first = {
|
|
204
|
+
subject: "You left something behind",
|
|
205
|
+
text: [
|
|
206
|
+
"Your basket is still here.",
|
|
207
|
+
"",
|
|
208
|
+
"Items: {{itemCount}}",
|
|
209
|
+
"Total: {{subtotalFormatted}}",
|
|
210
|
+
"",
|
|
211
|
+
"Pick up where you left off:",
|
|
212
|
+
"{{recoveryURL}}"
|
|
213
|
+
].join("\n")
|
|
214
|
+
};
|
|
215
|
+
var second = {
|
|
216
|
+
subject: "Your basket is still waiting",
|
|
217
|
+
text: [
|
|
218
|
+
"The items you chose are still in your basket.",
|
|
219
|
+
"",
|
|
220
|
+
"Items: {{itemCount}}",
|
|
221
|
+
"Total: {{subtotalFormatted}}",
|
|
222
|
+
"",
|
|
223
|
+
"This link stops working once the basket expires:",
|
|
224
|
+
"{{recoveryURL}}"
|
|
225
|
+
].join("\n")
|
|
226
|
+
};
|
|
227
|
+
var later = {
|
|
228
|
+
subject: "Last chance on your basket",
|
|
229
|
+
text: [
|
|
230
|
+
"This is the last message about the basket you left.",
|
|
231
|
+
"",
|
|
232
|
+
"Items: {{itemCount}}",
|
|
233
|
+
"Total: {{subtotalFormatted}}",
|
|
234
|
+
"",
|
|
235
|
+
"{{recoveryURL}}"
|
|
236
|
+
].join("\n")
|
|
237
|
+
};
|
|
238
|
+
var defaultTemplates = [first, second, later];
|
|
239
|
+
var defaultTemplateFor = (index) => {
|
|
240
|
+
const chosen = defaultTemplates[index] ?? defaultTemplates[defaultTemplates.length - 1];
|
|
241
|
+
return chosen ?? first;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// src/config.ts
|
|
245
|
+
var defaultDelays = [60, 1440];
|
|
246
|
+
var positiveInteger = (value, fallback) => {
|
|
247
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
248
|
+
return fallback;
|
|
249
|
+
}
|
|
250
|
+
const rounded = Math.trunc(value);
|
|
251
|
+
return rounded > 0 ? rounded : fallback;
|
|
252
|
+
};
|
|
253
|
+
var nonNegativeInteger = (value, fallback) => {
|
|
254
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
255
|
+
return fallback;
|
|
256
|
+
}
|
|
257
|
+
const rounded = Math.trunc(value);
|
|
258
|
+
return rounded >= 0 ? rounded : fallback;
|
|
259
|
+
};
|
|
260
|
+
var text = (value, fallback) => typeof value === "string" ? value : fallback;
|
|
261
|
+
var flag = (value, fallback) => typeof value === "boolean" ? value : fallback;
|
|
262
|
+
var optionalText = (value) => typeof value === "string" && value !== "" ? value : null;
|
|
263
|
+
var path = (value, fallback) => {
|
|
264
|
+
const given = text(value, fallback) || fallback;
|
|
265
|
+
return given.startsWith("/") ? given : `/${given}`;
|
|
266
|
+
};
|
|
267
|
+
var target = (value, fallback) => {
|
|
268
|
+
const given = text(value, fallback);
|
|
269
|
+
if (given === "") {
|
|
270
|
+
return "";
|
|
271
|
+
}
|
|
272
|
+
if (/^https?:\/\//.test(given)) {
|
|
273
|
+
return given;
|
|
274
|
+
}
|
|
275
|
+
return given.startsWith("/") ? given : `/${given}`;
|
|
276
|
+
};
|
|
277
|
+
var decimals = (value) => {
|
|
278
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
|
|
279
|
+
return Math.trunc(value);
|
|
280
|
+
}
|
|
281
|
+
return value && typeof value === "object" ? value : 2;
|
|
282
|
+
};
|
|
283
|
+
var defaultDelayFor = (index) => defaultDelays[index] ?? 1440 * (index + 1);
|
|
284
|
+
var resolveStep = (step, index) => ({
|
|
285
|
+
delayMinutes: nonNegativeInteger(step?.delayMinutes, defaultDelayFor(index)),
|
|
286
|
+
template: step?.template ?? defaultTemplateFor(index)
|
|
287
|
+
});
|
|
288
|
+
var defaultSteps = [{}, {}];
|
|
289
|
+
var resolveSteps = (incoming) => {
|
|
290
|
+
const given = Array.isArray(incoming) ? incoming : defaultSteps;
|
|
291
|
+
return given.filter((step) => step !== null && typeof step === "object").map(resolveStep).sort((left, right) => left.delayMinutes - right.delayMinutes);
|
|
292
|
+
};
|
|
293
|
+
var resolveConfig = (incoming = {}) => ({
|
|
294
|
+
attributionWindowHours: positiveInteger(incoming.attributionWindowHours, 168),
|
|
295
|
+
cartsSlug: text(incoming.cartsSlug, "carts") || "carts",
|
|
296
|
+
currencyDecimals: decimals(incoming.currencyDecimals),
|
|
297
|
+
customersSlug: text(incoming.customersSlug, "users") || "users",
|
|
298
|
+
disabled: incoming.disabled === true,
|
|
299
|
+
emailFieldName: text(incoming.emailFieldName, "customerEmail") || "customerEmail",
|
|
300
|
+
from: optionalText(incoming.from),
|
|
301
|
+
idleMinutes: positiveInteger(incoming.idleMinutes, 60),
|
|
302
|
+
markLimit: positiveInteger(incoming.markLimit, 200),
|
|
303
|
+
ordersSlug: text(incoming.ordersSlug, "orders") || "orders",
|
|
304
|
+
recoverEndpointPath: path(incoming.recoverEndpointPath, "/abandoned-cart/recover"),
|
|
305
|
+
redirectPath: target(incoming.redirectPath, "/cart"),
|
|
306
|
+
redirectWithSecret: flag(incoming.redirectWithSecret, true),
|
|
307
|
+
replyTo: optionalText(incoming.replyTo),
|
|
308
|
+
sendLimit: positiveInteger(incoming.sendLimit, 100),
|
|
309
|
+
serverURL: text(incoming.serverURL, "").replace(/\/+$/, ""),
|
|
310
|
+
statusFieldName: text(incoming.statusFieldName, "status") || "status",
|
|
311
|
+
steps: resolveSteps(incoming.steps),
|
|
312
|
+
sweepEndpointPath: path(incoming.sweepEndpointPath, "/abandoned-cart/sweep"),
|
|
313
|
+
sweepSecret: text(incoming.sweepSecret, ""),
|
|
314
|
+
tokenTtlHours: positiveInteger(incoming.tokenTtlHours, 336)
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// src/fields.ts
|
|
318
|
+
var closed = {
|
|
319
|
+
create: () => false,
|
|
320
|
+
read: () => false,
|
|
321
|
+
update: () => false
|
|
322
|
+
};
|
|
323
|
+
var cartEmailField = (config) => ({
|
|
324
|
+
name: config.emailFieldName,
|
|
325
|
+
type: "email",
|
|
326
|
+
admin: {
|
|
327
|
+
position: "sidebar"
|
|
328
|
+
},
|
|
329
|
+
index: true,
|
|
330
|
+
label: "Customer email"
|
|
331
|
+
});
|
|
332
|
+
var cartRecoveryFields = () => [
|
|
333
|
+
{
|
|
334
|
+
name: "abandonedAt",
|
|
335
|
+
type: "date",
|
|
336
|
+
admin: {
|
|
337
|
+
date: { pickerAppearance: "dayAndTime" },
|
|
338
|
+
position: "sidebar",
|
|
339
|
+
readOnly: true
|
|
340
|
+
},
|
|
341
|
+
index: true,
|
|
342
|
+
label: "Abandoned at"
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
name: "recoveryToken",
|
|
346
|
+
type: "text",
|
|
347
|
+
access: closed,
|
|
348
|
+
admin: {
|
|
349
|
+
hidden: true
|
|
350
|
+
},
|
|
351
|
+
index: true
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
name: "recoveryTokenExpiresAt",
|
|
355
|
+
type: "date",
|
|
356
|
+
admin: {
|
|
357
|
+
hidden: true
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
name: "recoveryEmailsSent",
|
|
362
|
+
type: "number",
|
|
363
|
+
admin: {
|
|
364
|
+
position: "sidebar",
|
|
365
|
+
readOnly: true
|
|
366
|
+
},
|
|
367
|
+
defaultValue: 0,
|
|
368
|
+
label: "Recovery messages sent",
|
|
369
|
+
min: 0
|
|
370
|
+
},
|
|
371
|
+
{
|
|
372
|
+
name: "lastRecoveryEmailAt",
|
|
373
|
+
type: "date",
|
|
374
|
+
admin: {
|
|
375
|
+
date: { pickerAppearance: "dayAndTime" },
|
|
376
|
+
position: "sidebar",
|
|
377
|
+
readOnly: true
|
|
378
|
+
},
|
|
379
|
+
label: "Last recovery message"
|
|
380
|
+
},
|
|
381
|
+
{
|
|
382
|
+
name: "recoveryVisitedAt",
|
|
383
|
+
type: "date",
|
|
384
|
+
admin: {
|
|
385
|
+
date: { pickerAppearance: "dayAndTime" },
|
|
386
|
+
position: "sidebar",
|
|
387
|
+
readOnly: true
|
|
388
|
+
},
|
|
389
|
+
index: true,
|
|
390
|
+
label: "Recovery link followed at"
|
|
391
|
+
}
|
|
392
|
+
];
|
|
393
|
+
var orderAttributionFields = (config) => [
|
|
394
|
+
{
|
|
395
|
+
name: "recoveredFromCart",
|
|
396
|
+
type: "relationship",
|
|
397
|
+
admin: {
|
|
398
|
+
position: "sidebar",
|
|
399
|
+
readOnly: true
|
|
400
|
+
},
|
|
401
|
+
index: true,
|
|
402
|
+
label: "Recovered from cart",
|
|
403
|
+
relationTo: config.cartsSlug
|
|
404
|
+
},
|
|
405
|
+
{
|
|
406
|
+
name: "recoveryEmailStep",
|
|
407
|
+
type: "number",
|
|
408
|
+
admin: {
|
|
409
|
+
position: "sidebar",
|
|
410
|
+
readOnly: true
|
|
411
|
+
},
|
|
412
|
+
label: "Recovery messages before the sale"
|
|
413
|
+
}
|
|
414
|
+
];
|
|
415
|
+
|
|
416
|
+
// src/status.ts
|
|
417
|
+
var optionValues = (options) => {
|
|
418
|
+
if (!Array.isArray(options)) {
|
|
419
|
+
return [];
|
|
420
|
+
}
|
|
421
|
+
return options.map((option) => typeof option === "string" ? option : option?.value).filter((value) => typeof value === "string");
|
|
422
|
+
};
|
|
423
|
+
var collectionFields = (payload, slug) => {
|
|
424
|
+
const collections = payload.collections;
|
|
425
|
+
const fields = collections?.[slug]?.config?.fields;
|
|
426
|
+
return Array.isArray(fields) ? fields : [];
|
|
427
|
+
};
|
|
428
|
+
var writesStatus = (payload, config) => {
|
|
429
|
+
const field = collectionFields(payload, config.cartsSlug).find(
|
|
430
|
+
(candidate) => candidate.name === config.statusFieldName
|
|
431
|
+
);
|
|
432
|
+
if (!field || field.virtual === true || field.type !== "select") {
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
return optionValues(field.options).includes("abandoned");
|
|
436
|
+
};
|
|
437
|
+
var hex = (byte) => byte.toString(16).padStart(2, "0");
|
|
438
|
+
var createRecoveryToken = () => {
|
|
439
|
+
const bytes = new Uint8Array(32);
|
|
440
|
+
getRandomValues(bytes);
|
|
441
|
+
return Array.from(bytes, hex).join("");
|
|
442
|
+
};
|
|
443
|
+
var expiresAt = (from, hours) => new Date(from.getTime() + hours * 60 * 60 * 1e3).toISOString();
|
|
444
|
+
var isExpired = (value, now) => {
|
|
445
|
+
if (typeof value !== "string" && !(value instanceof Date)) {
|
|
446
|
+
return true;
|
|
447
|
+
}
|
|
448
|
+
const time = new Date(value).getTime();
|
|
449
|
+
return !Number.isFinite(time) || time <= now.getTime();
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
// src/recover.ts
|
|
453
|
+
var findByToken = async (payload, config, token2, req) => {
|
|
454
|
+
const result = await payload.find({
|
|
455
|
+
collection: config.cartsSlug,
|
|
456
|
+
depth: 0,
|
|
457
|
+
limit: 1,
|
|
458
|
+
overrideAccess: true,
|
|
459
|
+
pagination: false,
|
|
460
|
+
where: { recoveryToken: { equals: token2 } },
|
|
461
|
+
...req ? { req } : {}
|
|
462
|
+
});
|
|
463
|
+
return result.docs[0] ?? null;
|
|
464
|
+
};
|
|
465
|
+
var recoverCart = async (payload, token2, incoming = {}, req) => {
|
|
466
|
+
const config = resolveConfig(incoming);
|
|
467
|
+
if (config.disabled || typeof token2 !== "string" || token2 === "") {
|
|
468
|
+
return { reason: "unknown", recovered: false };
|
|
469
|
+
}
|
|
470
|
+
const cart = await findByToken(payload, config, token2, req);
|
|
471
|
+
if (!cart) {
|
|
472
|
+
return { reason: "unknown", recovered: false };
|
|
473
|
+
}
|
|
474
|
+
if (cart.purchasedAt) {
|
|
475
|
+
return { reason: "purchased", recovered: false };
|
|
476
|
+
}
|
|
477
|
+
const now = /* @__PURE__ */ new Date();
|
|
478
|
+
if (isExpired(cart.recoveryTokenExpiresAt, now)) {
|
|
479
|
+
return { reason: "expired", recovered: false };
|
|
480
|
+
}
|
|
481
|
+
const withStatus = writesStatus(payload, config);
|
|
482
|
+
const updated = await payload.update({
|
|
483
|
+
id: cart.id,
|
|
484
|
+
collection: config.cartsSlug,
|
|
485
|
+
data: {
|
|
486
|
+
abandonedAt: null,
|
|
487
|
+
recoveryVisitedAt: cart.recoveryVisitedAt ?? now.toISOString(),
|
|
488
|
+
...withStatus ? { [config.statusFieldName]: "active" } : {}
|
|
489
|
+
},
|
|
490
|
+
depth: 0,
|
|
491
|
+
overrideAccess: true,
|
|
492
|
+
...req ? { req } : {}
|
|
493
|
+
});
|
|
494
|
+
const doc = updated;
|
|
495
|
+
const secret = typeof doc.secret === "string" && doc.secret !== "" ? doc.secret : null;
|
|
496
|
+
return { cart: doc, recovered: true, secret };
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
// src/sweep.ts
|
|
500
|
+
var reason = (error) => error instanceof Error ? error.message : String(error);
|
|
501
|
+
var findCarts = async (payload, config, where, limit, sort, req) => {
|
|
502
|
+
const result = await payload.find({
|
|
503
|
+
collection: config.cartsSlug,
|
|
504
|
+
depth: 0,
|
|
505
|
+
limit,
|
|
506
|
+
overrideAccess: true,
|
|
507
|
+
pagination: false,
|
|
508
|
+
sort,
|
|
509
|
+
where,
|
|
510
|
+
...req ? { req } : {}
|
|
511
|
+
});
|
|
512
|
+
return result.docs;
|
|
513
|
+
};
|
|
514
|
+
var markAbandonedCarts = async (payload, incoming = {}, req) => {
|
|
515
|
+
const config = resolveConfig(incoming);
|
|
516
|
+
if (config.disabled) {
|
|
517
|
+
return 0;
|
|
518
|
+
}
|
|
519
|
+
const now = /* @__PURE__ */ new Date();
|
|
520
|
+
const cutoff = new Date(now.getTime() - config.idleMinutes * 60 * 1e3).toISOString();
|
|
521
|
+
const withStatus = writesStatus(payload, config);
|
|
522
|
+
const carts = await findCarts(
|
|
523
|
+
payload,
|
|
524
|
+
config,
|
|
525
|
+
{
|
|
526
|
+
and: [
|
|
527
|
+
{ abandonedAt: { exists: false } },
|
|
528
|
+
{ purchasedAt: { exists: false } },
|
|
529
|
+
{ updatedAt: { less_than: cutoff } }
|
|
530
|
+
]
|
|
531
|
+
},
|
|
532
|
+
config.markLimit,
|
|
533
|
+
"updatedAt",
|
|
534
|
+
req
|
|
535
|
+
);
|
|
536
|
+
let marked = 0;
|
|
537
|
+
for (const cart of carts) {
|
|
538
|
+
if (cartLines(cart).length === 0) {
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
await payload.update({
|
|
543
|
+
id: cart.id,
|
|
544
|
+
collection: config.cartsSlug,
|
|
545
|
+
data: {
|
|
546
|
+
abandonedAt: now.toISOString(),
|
|
547
|
+
recoveryEmailsSent: 0,
|
|
548
|
+
recoveryToken: createRecoveryToken(),
|
|
549
|
+
recoveryTokenExpiresAt: expiresAt(now, config.tokenTtlHours),
|
|
550
|
+
...withStatus ? { [config.statusFieldName]: "abandoned" } : {}
|
|
551
|
+
},
|
|
552
|
+
depth: 0,
|
|
553
|
+
overrideAccess: true,
|
|
554
|
+
...req ? { req } : {}
|
|
555
|
+
});
|
|
556
|
+
marked += 1;
|
|
557
|
+
} catch (error) {
|
|
558
|
+
payload.logger.error(
|
|
559
|
+
`payload-abandoned-cart: could not mark cart ${String(cart.id)} abandoned: ${reason(error)}`
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return marked;
|
|
564
|
+
};
|
|
565
|
+
var dueStep = (config, cart, now) => {
|
|
566
|
+
const step = numberValue(cart.recoveryEmailsSent) ?? 0;
|
|
567
|
+
const entry = config.steps[step];
|
|
568
|
+
const abandoned = timeValue(cart.abandonedAt);
|
|
569
|
+
if (!entry || abandoned === null) {
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
return now.getTime() >= abandoned + entry.delayMinutes * 60 * 1e3 ? step : null;
|
|
573
|
+
};
|
|
574
|
+
var composeMessage = async (args) => {
|
|
575
|
+
const { cart, config, payload, step, to, token: token2 } = args;
|
|
576
|
+
const entry = config.steps[step];
|
|
577
|
+
if (!entry) {
|
|
578
|
+
throw new Error(`no template for step ${step}`);
|
|
579
|
+
}
|
|
580
|
+
const context = buildContext({
|
|
581
|
+
cart,
|
|
582
|
+
config,
|
|
583
|
+
recoveryURL: recoveryURL(payload, config, token2),
|
|
584
|
+
step: step + 1,
|
|
585
|
+
to
|
|
586
|
+
});
|
|
587
|
+
const body = await renderTemplate(entry.template, context);
|
|
588
|
+
return {
|
|
589
|
+
subject: body.subject,
|
|
590
|
+
text: body.text,
|
|
591
|
+
to,
|
|
592
|
+
...body.html === void 0 ? {} : { html: body.html },
|
|
593
|
+
...config.from === null ? {} : { from: config.from },
|
|
594
|
+
...config.replyTo === null ? {} : { replyTo: config.replyTo }
|
|
595
|
+
};
|
|
596
|
+
};
|
|
597
|
+
var sendRecoveryEmails = async (payload, incoming = {}, req) => {
|
|
598
|
+
const config = resolveConfig(incoming);
|
|
599
|
+
if (config.disabled || config.steps.length === 0) {
|
|
600
|
+
return { sent: 0, skipped: 0 };
|
|
601
|
+
}
|
|
602
|
+
const now = /* @__PURE__ */ new Date();
|
|
603
|
+
const carts = await findCarts(
|
|
604
|
+
payload,
|
|
605
|
+
config,
|
|
606
|
+
{
|
|
607
|
+
and: [
|
|
608
|
+
{ abandonedAt: { exists: true } },
|
|
609
|
+
{ purchasedAt: { exists: false } },
|
|
610
|
+
{
|
|
611
|
+
or: [
|
|
612
|
+
{ recoveryEmailsSent: { exists: false } },
|
|
613
|
+
{ recoveryEmailsSent: { less_than: config.steps.length } }
|
|
614
|
+
]
|
|
615
|
+
}
|
|
616
|
+
]
|
|
617
|
+
},
|
|
618
|
+
config.sendLimit,
|
|
619
|
+
"abandonedAt",
|
|
620
|
+
req
|
|
621
|
+
);
|
|
622
|
+
let sent = 0;
|
|
623
|
+
let skipped = 0;
|
|
624
|
+
for (const cart of carts) {
|
|
625
|
+
const step = dueStep(config, cart, now);
|
|
626
|
+
if (step === null || cartLines(cart).length === 0) {
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
let message;
|
|
630
|
+
try {
|
|
631
|
+
const to = await resolveRecipient(payload, config, cart, req);
|
|
632
|
+
if (!to) {
|
|
633
|
+
payload.logger.warn(
|
|
634
|
+
`payload-abandoned-cart: no address for cart ${String(cart.id)}, nothing sent`
|
|
635
|
+
);
|
|
636
|
+
skipped += 1;
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
const existing = typeof cart.recoveryToken === "string" ? cart.recoveryToken : "";
|
|
640
|
+
const stale = existing === "" || isExpired(cart.recoveryTokenExpiresAt, now);
|
|
641
|
+
const token2 = stale ? createRecoveryToken() : existing;
|
|
642
|
+
message = await composeMessage({ cart, config, payload, step, to, token: token2 });
|
|
643
|
+
await payload.update({
|
|
644
|
+
id: cart.id,
|
|
645
|
+
collection: config.cartsSlug,
|
|
646
|
+
data: {
|
|
647
|
+
lastRecoveryEmailAt: now.toISOString(),
|
|
648
|
+
recoveryEmailsSent: step + 1,
|
|
649
|
+
...stale ? {
|
|
650
|
+
recoveryToken: token2,
|
|
651
|
+
recoveryTokenExpiresAt: expiresAt(now, config.tokenTtlHours)
|
|
652
|
+
} : {}
|
|
653
|
+
},
|
|
654
|
+
depth: 0,
|
|
655
|
+
overrideAccess: true,
|
|
656
|
+
...req ? { req } : {}
|
|
657
|
+
});
|
|
658
|
+
} catch (error) {
|
|
659
|
+
payload.logger.error(
|
|
660
|
+
`payload-abandoned-cart: could not prepare a recovery message for cart ${String(
|
|
661
|
+
cart.id
|
|
662
|
+
)}: ${reason(error)}`
|
|
663
|
+
);
|
|
664
|
+
skipped += 1;
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
try {
|
|
668
|
+
await payload.sendEmail({ ...message });
|
|
669
|
+
sent += 1;
|
|
670
|
+
} catch (error) {
|
|
671
|
+
payload.logger.error(
|
|
672
|
+
`payload-abandoned-cart: recovery message for cart ${String(cart.id)} was not sent: ${reason(
|
|
673
|
+
error
|
|
674
|
+
)}`
|
|
675
|
+
);
|
|
676
|
+
skipped += 1;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return { sent, skipped };
|
|
680
|
+
};
|
|
681
|
+
var runAbandonedCartSweep = async (payload, incoming = {}, req) => {
|
|
682
|
+
const marked = await markAbandonedCarts(payload, incoming, req);
|
|
683
|
+
const { sent, skipped } = await sendRecoveryEmails(payload, incoming, req);
|
|
684
|
+
return { marked, sent, skipped };
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
// src/endpoints.ts
|
|
688
|
+
var refusalStatus = {
|
|
689
|
+
expired: 410,
|
|
690
|
+
purchased: 409,
|
|
691
|
+
unknown: 404
|
|
692
|
+
};
|
|
693
|
+
var refusalMessage = {
|
|
694
|
+
expired: "This recovery link has expired.",
|
|
695
|
+
purchased: "This basket has already been paid for.",
|
|
696
|
+
unknown: "This recovery link is not valid."
|
|
697
|
+
};
|
|
698
|
+
var secretMatches = (given, expected) => {
|
|
699
|
+
const left = Buffer.from(given);
|
|
700
|
+
const right = Buffer.from(expected);
|
|
701
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
702
|
+
};
|
|
703
|
+
var authorised = (req, config) => {
|
|
704
|
+
if (req.user) {
|
|
705
|
+
return true;
|
|
706
|
+
}
|
|
707
|
+
if (!config.sweepSecret) {
|
|
708
|
+
return false;
|
|
709
|
+
}
|
|
710
|
+
const header = req.headers?.get("authorization") ?? "";
|
|
711
|
+
const prefix = "Bearer ";
|
|
712
|
+
return header.startsWith(prefix) && secretMatches(header.slice(prefix.length), config.sweepSecret);
|
|
713
|
+
};
|
|
714
|
+
var tokenFromRequest = (req) => {
|
|
715
|
+
const query = req.query;
|
|
716
|
+
const value = query?.token;
|
|
717
|
+
if (typeof value === "string") {
|
|
718
|
+
return value;
|
|
719
|
+
}
|
|
720
|
+
return Array.isArray(value) && typeof value[0] === "string" ? value[0] : "";
|
|
721
|
+
};
|
|
722
|
+
var redirectLocation = (config, outcome) => {
|
|
723
|
+
const separator = config.redirectPath.includes("?") ? "&" : "?";
|
|
724
|
+
if (!outcome.recovered) {
|
|
725
|
+
return `${config.redirectPath}${separator}recovery=${outcome.reason}`;
|
|
726
|
+
}
|
|
727
|
+
const parts = [`cart=${encodeURIComponent(String(outcome.cart.id))}`];
|
|
728
|
+
if (config.redirectWithSecret && outcome.secret) {
|
|
729
|
+
parts.push(`secret=${encodeURIComponent(outcome.secret)}`);
|
|
730
|
+
}
|
|
731
|
+
return `${config.redirectPath}${separator}${parts.join("&")}`;
|
|
732
|
+
};
|
|
733
|
+
var recoverEndpoint = (config) => ({
|
|
734
|
+
handler: async (req) => {
|
|
735
|
+
let outcome;
|
|
736
|
+
try {
|
|
737
|
+
outcome = await recoverCart(req.payload, tokenFromRequest(req), config, req);
|
|
738
|
+
} catch (error) {
|
|
739
|
+
req.payload.logger.error({
|
|
740
|
+
err: error,
|
|
741
|
+
msg: "payload-abandoned-cart: a recovery link could not be followed"
|
|
742
|
+
});
|
|
743
|
+
return Response.json({ message: "Could not restore this basket." }, { status: 500 });
|
|
744
|
+
}
|
|
745
|
+
if (config.redirectPath !== "") {
|
|
746
|
+
return new Response(null, {
|
|
747
|
+
headers: { location: redirectLocation(config, outcome) },
|
|
748
|
+
status: 302
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
if (!outcome.recovered) {
|
|
752
|
+
return Response.json(
|
|
753
|
+
{ message: refusalMessage[outcome.reason], reason: outcome.reason },
|
|
754
|
+
{ status: refusalStatus[outcome.reason] }
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
return Response.json({
|
|
758
|
+
cart: outcome.cart.id,
|
|
759
|
+
recovered: true,
|
|
760
|
+
...config.redirectWithSecret && outcome.secret ? { secret: outcome.secret } : {}
|
|
761
|
+
});
|
|
762
|
+
},
|
|
763
|
+
method: "get",
|
|
764
|
+
path: config.recoverEndpointPath
|
|
765
|
+
});
|
|
766
|
+
var sweepEndpoint = (config) => ({
|
|
767
|
+
handler: async (req) => {
|
|
768
|
+
if (!authorised(req, config)) {
|
|
769
|
+
return Response.json({ message: "Not allowed to run the sweep." }, { status: 401 });
|
|
770
|
+
}
|
|
771
|
+
try {
|
|
772
|
+
const result = await runAbandonedCartSweep(req.payload, config);
|
|
773
|
+
return Response.json(result);
|
|
774
|
+
} catch (error) {
|
|
775
|
+
req.payload.logger.error({
|
|
776
|
+
err: error,
|
|
777
|
+
msg: "payload-abandoned-cart: the sweep did not finish"
|
|
778
|
+
});
|
|
779
|
+
return Response.json({ message: "The sweep did not finish." }, { status: 500 });
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
method: "post",
|
|
783
|
+
path: config.sweepEndpointPath
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
// src/index.ts
|
|
787
|
+
var nameOf = (field) => {
|
|
788
|
+
const named2 = field;
|
|
789
|
+
return typeof named2.name === "string" ? named2.name : "";
|
|
790
|
+
};
|
|
791
|
+
var named = (fields) => fields.map(nameOf);
|
|
792
|
+
var withCartFields = (collection, config) => {
|
|
793
|
+
const existing = named(collection.fields);
|
|
794
|
+
const additions = [
|
|
795
|
+
...existing.includes(config.emailFieldName) ? [] : [cartEmailField(config)],
|
|
796
|
+
...cartRecoveryFields().filter((field) => !existing.includes(nameOf(field)))
|
|
797
|
+
];
|
|
798
|
+
const hooks = collection.hooks ?? {};
|
|
799
|
+
return {
|
|
800
|
+
...collection,
|
|
801
|
+
fields: [...collection.fields, ...additions],
|
|
802
|
+
hooks: {
|
|
803
|
+
...hooks,
|
|
804
|
+
afterChange: [...hooks.afterChange ?? [], attributeRecovery(config)]
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
};
|
|
808
|
+
var withOrderFields = (collection, config) => {
|
|
809
|
+
const existing = named(collection.fields);
|
|
810
|
+
const additions = orderAttributionFields(config).filter(
|
|
811
|
+
(field) => !existing.includes(nameOf(field))
|
|
812
|
+
);
|
|
813
|
+
const hooks = collection.hooks ?? {};
|
|
814
|
+
return {
|
|
815
|
+
...collection,
|
|
816
|
+
fields: [...collection.fields, ...additions],
|
|
817
|
+
hooks: {
|
|
818
|
+
...hooks,
|
|
819
|
+
afterChange: [...hooks.afterChange ?? [], captureOrder(config)]
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
};
|
|
823
|
+
var shadowedByCollection = (path2, slugs) => {
|
|
824
|
+
const first2 = path2.split("/")[1];
|
|
825
|
+
return typeof first2 === "string" && first2 !== "" && slugs.includes(first2);
|
|
826
|
+
};
|
|
827
|
+
var reportProblems = (existing, problems) => async (payload) => {
|
|
828
|
+
if (existing) {
|
|
829
|
+
await existing(payload);
|
|
830
|
+
}
|
|
831
|
+
for (const problem of problems) {
|
|
832
|
+
payload.logger.error(`payload-abandoned-cart: ${problem}`);
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
var abandonedCartPlugin = (incoming = {}) => (incomingConfig) => {
|
|
836
|
+
const config = resolveConfig(incoming);
|
|
837
|
+
const collections = incomingConfig.collections ?? [];
|
|
838
|
+
const slugs = collections.map((collection) => collection.slug);
|
|
839
|
+
if (!slugs.includes(config.cartsSlug)) {
|
|
840
|
+
return incomingConfig;
|
|
841
|
+
}
|
|
842
|
+
const nextCollections = collections.map((collection) => {
|
|
843
|
+
if (collection.slug === config.cartsSlug) {
|
|
844
|
+
return withCartFields(collection, config);
|
|
845
|
+
}
|
|
846
|
+
return collection.slug === config.ordersSlug ? withOrderFields(collection, config) : collection;
|
|
847
|
+
});
|
|
848
|
+
const problems = [];
|
|
849
|
+
if (!slugs.includes(config.ordersSlug)) {
|
|
850
|
+
problems.push(
|
|
851
|
+
`no collection with the slug ${config.ordersSlug} was found, so recovered sales are marked on the cart but not on any order.`
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
for (const path2 of [config.recoverEndpointPath, config.sweepEndpointPath]) {
|
|
855
|
+
if (shadowedByCollection(path2, slugs)) {
|
|
856
|
+
problems.push(
|
|
857
|
+
`the endpoint path ${path2} starts with a collection slug, so Payload routes it to that collection and never reaches the handler. Give it a first segment that is not a collection slug.`
|
|
858
|
+
);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
const next = {
|
|
862
|
+
...incomingConfig,
|
|
863
|
+
collections: nextCollections,
|
|
864
|
+
endpoints: [
|
|
865
|
+
...incomingConfig.endpoints ?? [],
|
|
866
|
+
recoverEndpoint(config),
|
|
867
|
+
sweepEndpoint(config)
|
|
868
|
+
]
|
|
869
|
+
};
|
|
870
|
+
return problems.length === 0 ? next : { ...next, onInit: reportProblems(incomingConfig.onInit, problems) };
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
export { abandonedCartPlugin, createRecoveryToken, defaultTemplates, formatAmount, markAbandonedCarts, recoverCart, renderPlaceholders, renderTemplate, runAbandonedCartSweep, sendRecoveryEmails };
|