@joy-loyalty/hydrogen 0.0.0-stage → 0.2.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 +3 -0
- package/README.md +134 -2
- package/dist/cache-control.d.ts +8 -0
- package/dist/cache-control.js +6 -0
- package/dist/csp.d.ts +14 -0
- package/dist/csp.js +33 -0
- package/dist/headless-host-adapter.d.ts +5 -0
- package/dist/headless-host-adapter.js +197 -0
- package/dist/host-adapter/capabilities.d.ts +3 -0
- package/dist/host-adapter/capabilities.js +12 -0
- package/dist/host-adapter/data-source.d.ts +3 -0
- package/dist/host-adapter/data-source.js +49 -0
- package/dist/host-adapter/product-fetcher.d.ts +2 -0
- package/dist/host-adapter/product-fetcher.js +37 -0
- package/dist/host-adapter/promoted-collections.d.ts +2 -0
- package/dist/host-adapter/promoted-collections.js +43 -0
- package/dist/host-adapter/types.d.ts +212 -0
- package/dist/host-adapter/types.js +1 -0
- package/dist/hydrogen-cart-port.d.ts +134 -0
- package/dist/hydrogen-cart-port.js +245 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +15 -0
- package/dist/joy-widget.d.ts +29 -0
- package/dist/joy-widget.js +291 -0
- package/dist/lib/JoyProvider.d.ts +47 -0
- package/dist/lib/JoyProvider.js +95 -0
- package/dist/lib/account-links.d.ts +5 -0
- package/dist/lib/account-links.js +65 -0
- package/dist/lib/apply-behavior.d.ts +12 -0
- package/dist/lib/apply-behavior.js +26 -0
- package/dist/lib/core-loader.d.ts +63 -0
- package/dist/lib/core-loader.js +160 -0
- package/dist/lib/core-manifest.d.ts +7 -0
- package/dist/lib/core-manifest.js +54 -0
- package/dist/lib/core-preload-links.d.ts +8 -0
- package/dist/lib/core-preload-links.js +8 -0
- package/dist/lib/coupon-mapper.d.ts +95 -0
- package/dist/lib/coupon-mapper.js +167 -0
- package/dist/lib/custom-links.d.ts +22 -0
- package/dist/lib/custom-links.js +56 -0
- package/dist/lib/deeplink.d.ts +25 -0
- package/dist/lib/deeplink.js +92 -0
- package/dist/lib/earn-signup-gate.d.ts +3 -0
- package/dist/lib/earn-signup-gate.js +31 -0
- package/dist/lib/facebook-ref-link.d.ts +13 -0
- package/dist/lib/facebook-ref-link.js +31 -0
- package/dist/lib/headless-referral-origin.d.ts +2 -0
- package/dist/lib/headless-referral-origin.js +24 -0
- package/dist/lib/headless-source.d.ts +8 -0
- package/dist/lib/headless-source.js +71 -0
- package/dist/lib/image.d.ts +2 -0
- package/dist/lib/image.js +14 -0
- package/dist/lib/metafield-blob.d.ts +33 -0
- package/dist/lib/metafield-blob.js +76 -0
- package/dist/lib/money.d.ts +6 -0
- package/dist/lib/money.js +25 -0
- package/dist/lib/order-mapper.d.ts +44 -0
- package/dist/lib/order-mapper.js +141 -0
- package/dist/lib/place-order-scope.d.ts +6 -0
- package/dist/lib/place-order-scope.js +22 -0
- package/dist/lib/points.d.ts +5 -0
- package/dist/lib/points.js +10 -0
- package/dist/lib/recently-viewed-tracker.d.ts +1 -0
- package/dist/lib/recently-viewed-tracker.js +34 -0
- package/dist/lib/recommended-loader.d.ts +43 -0
- package/dist/lib/recommended-loader.js +111 -0
- package/dist/lib/referral-share.d.ts +4 -0
- package/dist/lib/referral-share.js +33 -0
- package/dist/lib/safe-navigation-url.d.ts +1 -0
- package/dist/lib/safe-navigation-url.js +9 -0
- package/dist/lib/server-token.d.ts +41 -0
- package/dist/lib/server-token.js +87 -0
- package/dist/lib/shop-locale.d.ts +1 -0
- package/dist/lib/shop-locale.js +21 -0
- package/dist/lib/social-earn.d.ts +11 -0
- package/dist/lib/social-earn.js +25 -0
- package/dist/lib/storefront-fonts.d.ts +5 -0
- package/dist/lib/storefront-fonts.js +52 -0
- package/dist/lib/token.d.ts +14 -0
- package/dist/lib/token.js +135 -0
- package/dist/lib/write-review.d.ts +2 -0
- package/dist/lib/write-review.js +44 -0
- package/dist/loyalty-page/JoyLoyaltyPage.d.ts +151 -0
- package/dist/loyalty-page/JoyLoyaltyPage.js +447 -0
- package/dist/loyalty-page/compose-home.d.ts +35 -0
- package/dist/loyalty-page/compose-home.js +177 -0
- package/dist/loyalty-page/skeleton.d.ts +11 -0
- package/dist/loyalty-page/skeleton.js +99 -0
- package/dist/orchestrator/context.d.ts +61 -0
- package/dist/orchestrator/context.js +64 -0
- package/dist/orchestrator/gated.d.ts +1 -0
- package/dist/orchestrator/gated.js +14 -0
- package/dist/orchestrator/handlers/account.d.ts +19 -0
- package/dist/orchestrator/handlers/account.js +266 -0
- package/dist/orchestrator/handlers/birthday.d.ts +6 -0
- package/dist/orchestrator/handlers/birthday.js +128 -0
- package/dist/orchestrator/handlers/earn.d.ts +5 -0
- package/dist/orchestrator/handlers/earn.js +258 -0
- package/dist/orchestrator/handlers/milestone-tier.d.ts +5 -0
- package/dist/orchestrator/handlers/milestone-tier.js +123 -0
- package/dist/orchestrator/handlers/profile.d.ts +5 -0
- package/dist/orchestrator/handlers/profile.js +262 -0
- package/dist/orchestrator/handlers/redeem.d.ts +6 -0
- package/dist/orchestrator/handlers/redeem.js +464 -0
- package/dist/orchestrator/handlers/referral.d.ts +5 -0
- package/dist/orchestrator/handlers/referral.js +218 -0
- package/dist/orchestrator/render.d.ts +2 -0
- package/dist/orchestrator/render.js +193 -0
- package/dist/render-adapter.d.ts +50 -0
- package/dist/render-adapter.js +422 -0
- package/dist/routes/joy-place-order-scope.d.ts +12 -0
- package/dist/routes/joy-place-order-scope.js +32 -0
- package/dist/routes/joy-products.d.ts +48 -0
- package/dist/routes/joy-products.js +326 -0
- package/dist/routes/joy-token.d.ts +16 -0
- package/dist/routes/joy-token.js +32 -0
- package/dist/server/get-joy-initial-data.d.ts +38 -0
- package/dist/server/get-joy-initial-data.js +61 -0
- package/dist/server/get-joy-loyalty-page-data.d.ts +27 -0
- package/dist/server/get-joy-loyalty-page-data.js +99 -0
- package/dist/server/index.d.ts +8 -0
- package/dist/server/index.js +4 -0
- package/dist/widget-controller.d.ts +2 -0
- package/dist/widget-controller.js +1 -0
- package/dist/widget-orchestrator.d.ts +88 -0
- package/dist/widget-orchestrator.js +499 -0
- package/package.json +121 -4
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { detail, pickActiveMarketStoreCredit, writeProps } from '../../widget-orchestrator.js';
|
|
2
|
+
import { mapOrder } from '../../lib/order-mapper.js';
|
|
3
|
+
import { getWriteReviewUrl } from '../../lib/write-review.js';
|
|
4
|
+
import { safeNavigationUrl } from '../../lib/safe-navigation-url.js';
|
|
5
|
+
import { resolveActiveTranslation } from '../../render-adapter.js';
|
|
6
|
+
function formatActivityDate(createdAt, locale) {
|
|
7
|
+
if (!createdAt)
|
|
8
|
+
return '';
|
|
9
|
+
const date = new Date(createdAt);
|
|
10
|
+
if (Number.isNaN(date.getTime()))
|
|
11
|
+
return '';
|
|
12
|
+
try {
|
|
13
|
+
return new Intl.DateTimeFormat(locale || undefined, { year: 'numeric', month: 'short', day: 'numeric' }).format(date);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric' }).format(date);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function toActivityViewModel(activity, locale) {
|
|
20
|
+
return {
|
|
21
|
+
id: activity.id,
|
|
22
|
+
title: activity.title,
|
|
23
|
+
points: Math.abs(activity.points),
|
|
24
|
+
isPositive: activity.points > 0 || (activity.points === 0 && activity.type === 'earn'),
|
|
25
|
+
createdAt: activity.createdAt ?? undefined,
|
|
26
|
+
date: formatActivityDate(activity.createdAt, locale),
|
|
27
|
+
couponCode: activity.couponCode ?? null,
|
|
28
|
+
orderId: activity.orderId != null ? String(activity.orderId) : null
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export function mapActivityRows(activities, ctx, countryCode) {
|
|
32
|
+
const locale = ctx.renderContext?.locale;
|
|
33
|
+
const mapActivities = ctx.coreExports?.mapActivities;
|
|
34
|
+
if (typeof mapActivities !== 'function' || !activities.every(activity => activity.rawType)) {
|
|
35
|
+
return activities.map(activity => toActivityViewModel(activity, locale));
|
|
36
|
+
}
|
|
37
|
+
const blob = (ctx.activeBlob ?? {});
|
|
38
|
+
const mapped = mapActivities(activities.map(activity => ({ ...activity, type: activity.rawType })), {
|
|
39
|
+
translation: resolveActiveTranslation(blob.translation, locale),
|
|
40
|
+
settings: blob.settings ?? {},
|
|
41
|
+
shop: blob.shop ?? {},
|
|
42
|
+
detectLocale: ctx.renderContext?.contentLocale ?? '',
|
|
43
|
+
resolvedLocale: locale ?? '',
|
|
44
|
+
countryCode: countryCode ?? ''
|
|
45
|
+
});
|
|
46
|
+
return mapped.map((row, index) => (row.title ? row : { ...row, title: activities[index].title }));
|
|
47
|
+
}
|
|
48
|
+
export function registerAccountHandlers(ctx) {
|
|
49
|
+
const { element, controller, hostAdapter, renderContext, surface, patchCustomer, tLabel } = ctx;
|
|
50
|
+
function orderMoney() {
|
|
51
|
+
const context = hostAdapter.context();
|
|
52
|
+
return {
|
|
53
|
+
currency: context.currency || 'USD',
|
|
54
|
+
currencyFormat: context.moneyFormat || '${{amount}}'
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
async function runGenerateQr() {
|
|
58
|
+
const el = element;
|
|
59
|
+
el.qrCodeLoading = true;
|
|
60
|
+
try {
|
|
61
|
+
const { qrCode } = await hostAdapter.data.generateQrCode();
|
|
62
|
+
patchCustomer({ qrImageUrl: qrCode });
|
|
63
|
+
el.qrCodeUrl = qrCode;
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
el.qrCodeLoading = false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function runAppleWalletClick() {
|
|
70
|
+
writeProps(element, { 'wallet-pass-loading': true });
|
|
71
|
+
try {
|
|
72
|
+
const cache = hostAdapter.data.getAppleWalletPassCache();
|
|
73
|
+
if (cache.createdApplePass) {
|
|
74
|
+
const exists = await hostAdapter.data.verifyApplePass();
|
|
75
|
+
if (exists) {
|
|
76
|
+
writeProps(element, { 'wallet-pass-apple-qr': cache.qrCodeDownloadApplePass || '' });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const qrUrl = await hostAdapter.data.getAppleWalletLink();
|
|
81
|
+
if (qrUrl) {
|
|
82
|
+
writeProps(element, { 'wallet-pass-apple-qr': qrUrl });
|
|
83
|
+
hostAdapter.data.setAppleWalletPassCache(qrUrl);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
writeProps(element, { 'wallet-pass-loading': false });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function runGoogleWalletClick() {
|
|
91
|
+
writeProps(element, { 'wallet-pass-loading': true });
|
|
92
|
+
try {
|
|
93
|
+
const link = await hostAdapter.data.getGoogleWalletLink();
|
|
94
|
+
if (link)
|
|
95
|
+
hostAdapter.navigate({ type: 'external', url: link });
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
writeProps(element, { 'wallet-pass-loading': false });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
let activityPage = 1;
|
|
102
|
+
let pointHistoryPage = 1;
|
|
103
|
+
function loadActivities(direction, cursor, prop = 'activities') {
|
|
104
|
+
const query = direction && cursor ? new URLSearchParams({ [direction]: cursor }) : undefined;
|
|
105
|
+
writeProps(element, prop === 'activities' ? { 'activities-loading': true } : { 'point-history-loading': true });
|
|
106
|
+
surface(hostAdapter.data
|
|
107
|
+
.getActivities(query)
|
|
108
|
+
.then(page => {
|
|
109
|
+
const rows = mapActivityRows(page.activities, ctx, hostAdapter.context().country);
|
|
110
|
+
if (prop === 'activities') {
|
|
111
|
+
activityPage = !direction ? 1 : direction === 'before' ? Math.max(1, activityPage - 1) : activityPage + 1;
|
|
112
|
+
const el = element;
|
|
113
|
+
el.activities = rows;
|
|
114
|
+
el.activityPage = activityPage;
|
|
115
|
+
writeProps(element, { 'activity-has-next': page.pagination.hasNext, 'activity-has-prev': page.pagination.hasPre });
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
pointHistoryPage = !direction ? 1 : direction === 'before' ? Math.max(1, pointHistoryPage - 1) : pointHistoryPage + 1;
|
|
119
|
+
const el = element;
|
|
120
|
+
el.pointHistory = rows;
|
|
121
|
+
el.pointHistoryPage = pointHistoryPage;
|
|
122
|
+
writeProps(element, { 'point-history-has-next': page.pagination.hasNext, 'point-history-has-prev': page.pagination.hasPre });
|
|
123
|
+
}
|
|
124
|
+
})
|
|
125
|
+
.finally(() => {
|
|
126
|
+
writeProps(element, prop === 'activities' ? { 'activities-loading': false } : { 'point-history-loading': false });
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
function loadOrders() {
|
|
130
|
+
const el = element;
|
|
131
|
+
el.ordersLoading = true;
|
|
132
|
+
surface(hostAdapter.data
|
|
133
|
+
.getOrders()
|
|
134
|
+
.then(orders => {
|
|
135
|
+
const money = orderMoney();
|
|
136
|
+
const shopDomain = hostAdapter.context().shopDomain;
|
|
137
|
+
el.orders = orders.map(order => mapOrder(order, { tLabel, money, shopDomain, locale: renderContext?.locale }));
|
|
138
|
+
writeProps(element, { 'total-orders': orders.length });
|
|
139
|
+
})
|
|
140
|
+
.finally(() => {
|
|
141
|
+
el.ordersLoading = false;
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
function loadStoreCreditTransactions(direction) {
|
|
145
|
+
const el = element;
|
|
146
|
+
const params = {};
|
|
147
|
+
if (direction === 'after' && el._scEndCursor)
|
|
148
|
+
params.after = el._scEndCursor;
|
|
149
|
+
else if (direction === 'before' && el._scStartCursor)
|
|
150
|
+
params.before = el._scStartCursor;
|
|
151
|
+
else if (direction)
|
|
152
|
+
return;
|
|
153
|
+
writeProps(element, { 'store-credit-transactions-loading': true });
|
|
154
|
+
surface(hostAdapter.data
|
|
155
|
+
.getStoreCreditTransactions(Object.keys(params).length ? params : undefined)
|
|
156
|
+
.then((page) => {
|
|
157
|
+
el.storeCreditTransactions = page.transactions;
|
|
158
|
+
el._scStartCursor = page.startCursor;
|
|
159
|
+
el._scEndCursor = page.endCursor;
|
|
160
|
+
const current = el.storeCreditTransactionsPage || 1;
|
|
161
|
+
el.storeCreditTransactionsPage = direction === 'after' ? current + 1 : direction === 'before' ? Math.max(1, current - 1) : 1;
|
|
162
|
+
writeProps(element, {
|
|
163
|
+
'store-credit-transactions-has-next': page.hasNextPage,
|
|
164
|
+
'store-credit-transactions-has-prev': page.hasPrevPage
|
|
165
|
+
});
|
|
166
|
+
})
|
|
167
|
+
.finally(() => {
|
|
168
|
+
writeProps(element, { 'store-credit-transactions-loading': false });
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
function loadImpactHistory() {
|
|
172
|
+
const el = element;
|
|
173
|
+
el.impactLoading = true;
|
|
174
|
+
surface(hostAdapter.data
|
|
175
|
+
.getImpactHistory({ limit: 20 })
|
|
176
|
+
.then((impact) => {
|
|
177
|
+
el.impactHistory = impact.events ?? [];
|
|
178
|
+
el.goodApiConnected = impact.connected === true;
|
|
179
|
+
writeProps(element, {
|
|
180
|
+
'impact-trees': impact.totals?.trees ?? 0,
|
|
181
|
+
'impact-plastic-bottles': impact.totals?.plasticBottles ?? 0
|
|
182
|
+
});
|
|
183
|
+
})
|
|
184
|
+
.finally(() => {
|
|
185
|
+
el.impactLoading = false;
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
function applyStoreCreditFromInfo(info) {
|
|
189
|
+
const sc = info.storeCredit;
|
|
190
|
+
if (sc?.enabled === false) {
|
|
191
|
+
writeProps(element, { 'show-store-credit': false, 'store-credit-loading': false });
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const { balance, currency } = pickActiveMarketStoreCredit(sc?.accounts, hostAdapter.context().activeMarketCurrency);
|
|
195
|
+
writeProps(element, {
|
|
196
|
+
'show-store-credit': true,
|
|
197
|
+
'store-credit': balance,
|
|
198
|
+
...(currency ? { 'store-credit-currency': currency } : {}),
|
|
199
|
+
'store-credit-loading': false
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
controller.on('joy-generate-qr', () => surface(runGenerateQr()));
|
|
203
|
+
controller.on('joy-activity-page-change', event => {
|
|
204
|
+
const { direction, cursor } = detail(event);
|
|
205
|
+
loadActivities(direction, cursor);
|
|
206
|
+
});
|
|
207
|
+
controller.on('joy-balance-history-page-change', event => {
|
|
208
|
+
const { direction, variant } = detail(event);
|
|
209
|
+
if (variant === 'store-credit') {
|
|
210
|
+
loadStoreCreditTransactions(direction);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (variant && variant !== 'point')
|
|
214
|
+
return;
|
|
215
|
+
const items = (element.pointHistory) ?? [];
|
|
216
|
+
const cursor = direction === 'before' ? items[0]?.id : items[items.length - 1]?.id;
|
|
217
|
+
if (cursor)
|
|
218
|
+
loadActivities(direction, cursor, 'pointHistory');
|
|
219
|
+
});
|
|
220
|
+
controller.on('joy-wallet-pass-apple-click', () => surface(runAppleWalletClick()));
|
|
221
|
+
controller.on('joy-wallet-pass-google-click', () => surface(runGoogleWalletClick()));
|
|
222
|
+
controller.on('joy-order-opened', event => {
|
|
223
|
+
const { orderId } = detail(event);
|
|
224
|
+
if (orderId == null)
|
|
225
|
+
return;
|
|
226
|
+
const el = element;
|
|
227
|
+
el.orderActivitiesLoading = true;
|
|
228
|
+
surface(hostAdapter.data
|
|
229
|
+
.getOrderActivities(String(orderId))
|
|
230
|
+
.then(activities => {
|
|
231
|
+
el.orderActivities = mapActivityRows(activities, ctx, hostAdapter.context().country);
|
|
232
|
+
})
|
|
233
|
+
.finally(() => {
|
|
234
|
+
el.orderActivitiesLoading = false;
|
|
235
|
+
}));
|
|
236
|
+
});
|
|
237
|
+
controller.on('joy-load-order', event => {
|
|
238
|
+
const { orderId } = detail(event);
|
|
239
|
+
if (orderId == null)
|
|
240
|
+
return;
|
|
241
|
+
surface(hostAdapter.data.getOrderById(String(orderId)).then(order => {
|
|
242
|
+
if (!order)
|
|
243
|
+
return;
|
|
244
|
+
const money = orderMoney();
|
|
245
|
+
element.selectedOrder = mapOrder(order, {
|
|
246
|
+
tLabel,
|
|
247
|
+
money,
|
|
248
|
+
shopDomain: hostAdapter.context().shopDomain,
|
|
249
|
+
locale: renderContext?.locale
|
|
250
|
+
});
|
|
251
|
+
}));
|
|
252
|
+
});
|
|
253
|
+
controller.on('joy-write-review', event => {
|
|
254
|
+
const { productHandle } = detail(event);
|
|
255
|
+
const rawSettings = ctx.activeBlob?.settings;
|
|
256
|
+
const { extensions } = element;
|
|
257
|
+
const url = getWriteReviewUrl(rawSettings, extensions, productHandle || '', hostAdapter.context().routesRoot);
|
|
258
|
+
const safe = url ? safeNavigationUrl(url) : null;
|
|
259
|
+
if (safe)
|
|
260
|
+
window.location.assign(url);
|
|
261
|
+
});
|
|
262
|
+
ctx.loadActivities = loadActivities;
|
|
263
|
+
ctx.loadImpactHistory = loadImpactHistory;
|
|
264
|
+
ctx.applyStoreCreditFromInfo = applyStoreCreditFromInfo;
|
|
265
|
+
return { loadOrders, loadStoreCreditTransactions };
|
|
266
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { OrchestratorContext } from '../context.js';
|
|
2
|
+
export interface BirthdayHandlerDeps {
|
|
3
|
+
replaceEarnPrograms(map: (card: Record<string, unknown>) => Record<string, unknown>): void;
|
|
4
|
+
buildLoaderFacade(): Record<string, unknown> | null;
|
|
5
|
+
}
|
|
6
|
+
export declare function registerBirthdayHandlers(ctx: OrchestratorContext, deps: BirthdayHandlerDeps): void;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { detail, readEarningProgramByEvent, writeProps } from '../../widget-orchestrator.js';
|
|
2
|
+
function setBirthdayRewardsForYear(rewardIds, existing) {
|
|
3
|
+
return { ...existing, [new Date().getFullYear()]: rewardIds };
|
|
4
|
+
}
|
|
5
|
+
function readBirthdayRewards(customer) {
|
|
6
|
+
const stored = customer?.birthdayRewards;
|
|
7
|
+
if (!stored || typeof stored !== 'object')
|
|
8
|
+
return {};
|
|
9
|
+
const clean = {};
|
|
10
|
+
for (const [year, ids] of Object.entries(stored)) {
|
|
11
|
+
if (Array.isArray(ids) && ids.every(id => typeof id === 'string'))
|
|
12
|
+
clean[year] = ids;
|
|
13
|
+
}
|
|
14
|
+
return clean;
|
|
15
|
+
}
|
|
16
|
+
export function registerBirthdayHandlers(ctx, deps) {
|
|
17
|
+
const { element, controller, hostAdapter, coreExports, surface, patchCustomer } = ctx;
|
|
18
|
+
const { replaceEarnPrograms, buildLoaderFacade } = deps;
|
|
19
|
+
async function runSaveBirthday(d) {
|
|
20
|
+
const setResult = (success) => {
|
|
21
|
+
element.setBirthdaySaveResult?.(success);
|
|
22
|
+
};
|
|
23
|
+
const program = readEarningProgramByEvent(ctx.activeBlob, 'birthday');
|
|
24
|
+
const programId = typeof program?.id === 'string' ? program.id : undefined;
|
|
25
|
+
if (!d.month || !d.day || !program || !programId) {
|
|
26
|
+
setResult(false);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const month = String(d.month).padStart(2, '0');
|
|
30
|
+
const day = String(d.day).padStart(2, '0');
|
|
31
|
+
const birthday = `${month}/${day}`;
|
|
32
|
+
const dateOfBirth = d.year ? `${d.year}-${month}-${day}` : undefined;
|
|
33
|
+
const birthdayRewards = d.rewardIds?.length
|
|
34
|
+
? setBirthdayRewardsForYear(d.rewardIds, readBirthdayRewards(ctx.activeCustomer))
|
|
35
|
+
: undefined;
|
|
36
|
+
try {
|
|
37
|
+
await hostAdapter.data.earn({
|
|
38
|
+
endpoint: '/birthday',
|
|
39
|
+
programId,
|
|
40
|
+
context: { birthday, ...(dateOfBirth ? { dateOfBirth } : {}), ...(birthdayRewards ? { birthdayRewards } : {}) }
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
setResult(false);
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
patchCustomer({ birthday, ...(dateOfBirth ? { dateOfBirth } : {}), ...(birthdayRewards ? { birthdayRewards } : {}) });
|
|
48
|
+
writeProps(element, {
|
|
49
|
+
birthday,
|
|
50
|
+
'birthday-locked': true,
|
|
51
|
+
...(dateOfBirth ? { 'date-of-birth': dateOfBirth } : {}),
|
|
52
|
+
...(birthdayRewards ? { birthdayRewards } : {})
|
|
53
|
+
});
|
|
54
|
+
setResult(true);
|
|
55
|
+
reenrichBirthdayPrograms(program);
|
|
56
|
+
}
|
|
57
|
+
function reenrichBirthdayPrograms(program) {
|
|
58
|
+
const enrich = coreExports?.renderingProps
|
|
59
|
+
?.enrichBirthdayPrograms;
|
|
60
|
+
const facade = typeof enrich === 'function' ? buildLoaderFacade() : null;
|
|
61
|
+
if (!enrich || !facade)
|
|
62
|
+
return;
|
|
63
|
+
const recomputed = { ...program };
|
|
64
|
+
enrich(facade, [recomputed], facade.data.customer);
|
|
65
|
+
replaceEarnPrograms(card => card.event === 'birthday'
|
|
66
|
+
? {
|
|
67
|
+
...card,
|
|
68
|
+
birthdayCanClaim: recomputed.birthdayCanClaim || false,
|
|
69
|
+
birthdayCountdown: recomputed.birthdayCountdown ?? -999,
|
|
70
|
+
birthdayMethod: recomputed.birthdayMethod || recomputed.typeDeliveryMethod || 'automatic'
|
|
71
|
+
}
|
|
72
|
+
: card);
|
|
73
|
+
}
|
|
74
|
+
async function runSaveBirthdayRewards(d) {
|
|
75
|
+
const setResult = (success) => {
|
|
76
|
+
element.setBirthdaySaveResult?.(success);
|
|
77
|
+
};
|
|
78
|
+
if (!d.rewardIds?.length) {
|
|
79
|
+
setResult(false);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const birthdayRewards = setBirthdayRewardsForYear(d.rewardIds, readBirthdayRewards(ctx.activeCustomer));
|
|
83
|
+
try {
|
|
84
|
+
await hostAdapter.data.setBirthdayRewards(birthdayRewards);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
setResult(false);
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
patchCustomer({ birthdayRewards });
|
|
91
|
+
writeProps(element, { birthdayRewards });
|
|
92
|
+
setResult(true);
|
|
93
|
+
}
|
|
94
|
+
async function runClaimBirthday(d) {
|
|
95
|
+
const setResult = (success) => {
|
|
96
|
+
element
|
|
97
|
+
.setEarnBirthdayClaimResult?.(success);
|
|
98
|
+
};
|
|
99
|
+
const stored = readBirthdayRewards(ctx.activeCustomer);
|
|
100
|
+
const birthdayRewards = d.rewardIds?.length
|
|
101
|
+
? setBirthdayRewardsForYear(d.rewardIds, stored)
|
|
102
|
+
: stored;
|
|
103
|
+
try {
|
|
104
|
+
await hostAdapter.data.claimBirthdayReward(Object.keys(birthdayRewards).length ? birthdayRewards : undefined);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
setResult(false);
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
patchCustomer({
|
|
111
|
+
earnBirthDayReward: true,
|
|
112
|
+
lastYearGetBirthdayReward: new Date().getFullYear(),
|
|
113
|
+
birthdayRewards
|
|
114
|
+
});
|
|
115
|
+
writeProps(element, { 'earn-birth-day-reward': true, birthdayRewards });
|
|
116
|
+
replaceEarnPrograms(card => card.event === 'birthday' ? { ...card, birthdayCanClaim: false, completed: true } : card);
|
|
117
|
+
setResult(true);
|
|
118
|
+
}
|
|
119
|
+
controller.on('joy-save-birthday', event => {
|
|
120
|
+
surface(runSaveBirthday(detail(event)));
|
|
121
|
+
});
|
|
122
|
+
controller.on('joy-save-birthday-rewards', event => {
|
|
123
|
+
surface(runSaveBirthdayRewards(detail(event)));
|
|
124
|
+
});
|
|
125
|
+
controller.on('joy-claim-birthday', event => {
|
|
126
|
+
surface(runClaimBirthday(detail(event)));
|
|
127
|
+
});
|
|
128
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { OrchestratorContext } from '../context.js';
|
|
2
|
+
export interface EarnHandlers {
|
|
3
|
+
replaceEarnPrograms(map: (card: Record<string, unknown>) => Record<string, unknown>): void;
|
|
4
|
+
}
|
|
5
|
+
export declare function registerEarnHandlers(ctx: OrchestratorContext): EarnHandlers;
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { SOCIAL_EARN_EVENT_NAMES } from '@joy-loyalty/sdk/widget-contracts';
|
|
2
|
+
import { resolveActiveTranslation } from '../../render-adapter.js';
|
|
3
|
+
import { detail, openInNewTab, writeProps } from '../../widget-orchestrator.js';
|
|
4
|
+
const SOCIAL_EARN_EVENTS = new Set(SOCIAL_EARN_EVENT_NAMES);
|
|
5
|
+
function localDateKey() {
|
|
6
|
+
const now = new Date();
|
|
7
|
+
const month = String(now.getMonth() + 1).padStart(2, '0');
|
|
8
|
+
const day = String(now.getDate()).padStart(2, '0');
|
|
9
|
+
return `${now.getFullYear()}-${month}-${day}`;
|
|
10
|
+
}
|
|
11
|
+
function readStreakState(customer) {
|
|
12
|
+
const streak = customer?.streakInteractiveWebsite;
|
|
13
|
+
return streak && typeof streak === 'object' ? streak : {};
|
|
14
|
+
}
|
|
15
|
+
function readInteractWebsiteProgram(blob) {
|
|
16
|
+
const program = blob && typeof blob === 'object' ? blob.interactWebsiteProgram : undefined;
|
|
17
|
+
return program && typeof program === 'object' ? program : undefined;
|
|
18
|
+
}
|
|
19
|
+
const INSTAGRAM_ENGAGEMENT_EARN_EVENTS = new Set([
|
|
20
|
+
'comment_instagram', 'story_mention_instagram', 'story_reply_instagram', 'live_comment_instagram'
|
|
21
|
+
]);
|
|
22
|
+
function fileToBase64(file) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const reader = new FileReader();
|
|
25
|
+
reader.onload = () => resolve(String(reader.result));
|
|
26
|
+
reader.onerror = () => reject(reader.error ?? new Error('[joy] failed to read image file'));
|
|
27
|
+
reader.readAsDataURL(file);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
export function registerEarnHandlers(ctx) {
|
|
31
|
+
const { element, controller, hostAdapter, coreExports, renderContext, surface, patchCustomer, isAuthed, refresh, toast } = ctx;
|
|
32
|
+
function replaceEarnPrograms(map) {
|
|
33
|
+
const el = element;
|
|
34
|
+
const cards = Array.isArray(el.earnPrograms) ? el.earnPrograms : [];
|
|
35
|
+
el.earnPrograms = cards.map(map);
|
|
36
|
+
}
|
|
37
|
+
function setEarnResult(success, extra) {
|
|
38
|
+
element
|
|
39
|
+
.setEarnActionResult?.(success, extra);
|
|
40
|
+
}
|
|
41
|
+
function resetEarnAction() {
|
|
42
|
+
element.resetEarnActionState?.();
|
|
43
|
+
}
|
|
44
|
+
async function uploadEarnFiles(files) {
|
|
45
|
+
if (!files?.length)
|
|
46
|
+
return [];
|
|
47
|
+
const images = await Promise.all(files.map(async (file) => ({
|
|
48
|
+
imageBase64: await fileToBase64(file),
|
|
49
|
+
imageName: file.name,
|
|
50
|
+
imageType: file.type
|
|
51
|
+
})));
|
|
52
|
+
const { urls } = await hostAdapter.data.earnUpload({ images });
|
|
53
|
+
const uploaded = (urls ?? []).filter(Boolean);
|
|
54
|
+
if (uploaded.length !== files.length)
|
|
55
|
+
throw new Error('[joy] some earn images failed to upload');
|
|
56
|
+
return uploaded;
|
|
57
|
+
}
|
|
58
|
+
async function buildEarnRequestWithUploads(d) {
|
|
59
|
+
const programId = d.option?.id;
|
|
60
|
+
if (!programId)
|
|
61
|
+
return null;
|
|
62
|
+
if (d.submitReceiptData) {
|
|
63
|
+
const images = d.submitReceiptData.imageFiles?.length
|
|
64
|
+
? await uploadEarnFiles(d.submitReceiptData.imageFiles)
|
|
65
|
+
: d.submitReceiptData.imageUrls ?? [];
|
|
66
|
+
if (!images.length)
|
|
67
|
+
return null;
|
|
68
|
+
return { endpoint: '/activity/submit-receipt', programId, context: { images } };
|
|
69
|
+
}
|
|
70
|
+
const form = d.submitFormData;
|
|
71
|
+
if (!form)
|
|
72
|
+
return null;
|
|
73
|
+
if ((d.option?.event ?? '').toLowerCase() === 'google_maps_review') {
|
|
74
|
+
return { endpoint: '/google-maps-review', programId, context: { urlReview: form.submittedContent ?? '' } };
|
|
75
|
+
}
|
|
76
|
+
const imageUrls = form.imageFiles?.length ? await uploadEarnFiles(form.imageFiles) : form.imageUrls ?? [];
|
|
77
|
+
return {
|
|
78
|
+
endpoint: '/submit-form',
|
|
79
|
+
programId,
|
|
80
|
+
context: { submittedContent: form.submittedContent ?? '', ...(imageUrls.length ? { imageUrls } : {}) }
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async function runEarn(d) {
|
|
84
|
+
const programId = d.option?.id;
|
|
85
|
+
if (!programId)
|
|
86
|
+
return;
|
|
87
|
+
const event = (d.option?.event ?? '').toLowerCase();
|
|
88
|
+
if (event === 'streak_interact_website') {
|
|
89
|
+
await runStreakClaim(programId);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (INSTAGRAM_ENGAGEMENT_EARN_EVENTS.has(event)) {
|
|
93
|
+
resetEarnAction();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const hasForm = !!d.submitFormData;
|
|
97
|
+
const hasReceipt = !!d.submitReceiptData;
|
|
98
|
+
const isSocial = SOCIAL_EARN_EVENTS.has(event);
|
|
99
|
+
if (d.url && !isSocial && !hasForm && !hasReceipt) {
|
|
100
|
+
resetEarnAction();
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
if (hasForm || hasReceipt) {
|
|
105
|
+
const request = await buildEarnRequestWithUploads(d);
|
|
106
|
+
if (!request) {
|
|
107
|
+
setEarnResult(false);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
await hostAdapter.data.earn(request);
|
|
111
|
+
setEarnResult(true, { pendingApproval: true });
|
|
112
|
+
ctx.loadActivities();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const result = await hostAdapter.data.earnSocial(programId);
|
|
116
|
+
const totalPoints = result?.totalPoints;
|
|
117
|
+
if (typeof totalPoints === 'number')
|
|
118
|
+
writeProps(element, { points: totalPoints });
|
|
119
|
+
setEarnResult(true);
|
|
120
|
+
ctx.loadActivities();
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
setEarnResult(false);
|
|
124
|
+
surface(Promise.reject(error));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function runStreakClaim(programId) {
|
|
128
|
+
try {
|
|
129
|
+
const result = await hostAdapter.data.earnSocial(programId);
|
|
130
|
+
const totalPoints = result?.totalPoints;
|
|
131
|
+
if (typeof totalPoints === 'number')
|
|
132
|
+
writeProps(element, { points: totalPoints });
|
|
133
|
+
repaintStreakCard(programId, totalPoints);
|
|
134
|
+
setEarnResult(true);
|
|
135
|
+
ctx.loadActivities();
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
setEarnResult(false);
|
|
139
|
+
surface(Promise.reject(error));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
function repaintStreakCard(programId, totalPoints) {
|
|
143
|
+
const build = coreExports?.renderingProps
|
|
144
|
+
?.buildStreakCardEnrichment;
|
|
145
|
+
const program = readInteractWebsiteProgram(ctx.activeBlob);
|
|
146
|
+
if (typeof build !== 'function' || program?.id !== programId)
|
|
147
|
+
return;
|
|
148
|
+
const translation = resolveActiveTranslation(ctx.activeBlob?.translation, renderContext?.locale);
|
|
149
|
+
const streakDay = build(program, ctx.activeCustomer, translation).currentStreak + 1;
|
|
150
|
+
const previous = readStreakState(ctx.activeCustomer);
|
|
151
|
+
const customer = patchCustomer({
|
|
152
|
+
...(typeof totalPoints === 'number' ? { point: totalPoints } : {}),
|
|
153
|
+
streakInteractiveWebsite: { ...previous, streakDay, programId, lastVisitDate: localDateKey() }
|
|
154
|
+
});
|
|
155
|
+
const enrichment = build(program, customer, translation);
|
|
156
|
+
replaceEarnPrograms(card => (card.id === programId ? { ...card, ...enrichment } : card));
|
|
157
|
+
element.refreshSelectedEarnOption?.();
|
|
158
|
+
writeProps(element, { 'current-streak': streakDay, 'can-claim-streak': enrichment.canClaimStreak });
|
|
159
|
+
}
|
|
160
|
+
async function runDailyVisitClaim(programId) {
|
|
161
|
+
try {
|
|
162
|
+
const result = await hostAdapter.data.earnSocial(programId);
|
|
163
|
+
const totalPoints = result?.totalPoints;
|
|
164
|
+
if (typeof totalPoints === 'number')
|
|
165
|
+
writeProps(element, { points: totalPoints });
|
|
166
|
+
writeProps(element, { 'daily-visit-claimable': false });
|
|
167
|
+
ctx.loadActivities();
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
element.resetDailyVisitClaiming?.();
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
async function runNewsletterSubscribe(programId) {
|
|
175
|
+
const setResult = (success) => {
|
|
176
|
+
element.setEarnNewsletterResult?.(success);
|
|
177
|
+
};
|
|
178
|
+
if (!programId) {
|
|
179
|
+
setResult(false);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
const result = await hostAdapter.data.earnSocial(programId);
|
|
184
|
+
const totalPoints = typeof result?.totalPoints === 'number' ? result.totalPoints : undefined;
|
|
185
|
+
if (totalPoints !== undefined)
|
|
186
|
+
writeProps(element, { points: totalPoints });
|
|
187
|
+
patchCustomer({
|
|
188
|
+
...(totalPoints !== undefined ? { point: totalPoints } : {}),
|
|
189
|
+
acceptsMarketing: true,
|
|
190
|
+
earnSignUpNewsletter: true
|
|
191
|
+
});
|
|
192
|
+
replaceEarnPrograms(card => (card.event === 'sign_up_newsletter' ? { ...card, completed: true } : card));
|
|
193
|
+
setResult(true);
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
setResult(false);
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async function runSmsSubscribe() {
|
|
201
|
+
const setResult = (success) => {
|
|
202
|
+
element.setSmsSubscribeResult?.(success);
|
|
203
|
+
};
|
|
204
|
+
if (!isAuthed()) {
|
|
205
|
+
setResult(false);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
await hostAdapter.data.updateProfile({ acceptsSmsMarketing: true });
|
|
210
|
+
patchCustomer({ acceptsSmsMarketing: true });
|
|
211
|
+
setResult(true);
|
|
212
|
+
toast('Subscribed successfully!');
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
setResult(false);
|
|
216
|
+
toast(error instanceof Error && error.message ? error.message : 'Failed to subscribe');
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
function runLineAuth() {
|
|
220
|
+
if (!isAuthed())
|
|
221
|
+
return;
|
|
222
|
+
surface(hostAdapter.data.getLineAuthUrl().then((result) => {
|
|
223
|
+
if (result.authUrl)
|
|
224
|
+
openInNewTab(result.authUrl);
|
|
225
|
+
}));
|
|
226
|
+
}
|
|
227
|
+
async function runJoin() {
|
|
228
|
+
const el = element;
|
|
229
|
+
try {
|
|
230
|
+
await hostAdapter.data.joinProgram('widget');
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
el.optInJoinResult = { success: false };
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
el.optInJoinResult = { success: true };
|
|
237
|
+
void refresh();
|
|
238
|
+
}
|
|
239
|
+
controller.on('joy-earn-action', event => {
|
|
240
|
+
surface(runEarn(detail(event)));
|
|
241
|
+
});
|
|
242
|
+
controller.on('joy-earn-newsletter', event => {
|
|
243
|
+
const { option } = detail(event);
|
|
244
|
+
surface(runNewsletterSubscribe(option?.id));
|
|
245
|
+
});
|
|
246
|
+
controller.on('joy-subscribe-sms-marketing', () => void runSmsSubscribe());
|
|
247
|
+
controller.on('joy-daily-visit-claim', event => {
|
|
248
|
+
const { programId } = detail(event);
|
|
249
|
+
if (!programId) {
|
|
250
|
+
element.resetDailyVisitClaiming?.();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
surface(runDailyVisitClaim(programId));
|
|
254
|
+
});
|
|
255
|
+
controller.on('joy-line-auth-request', () => runLineAuth());
|
|
256
|
+
controller.on('joy-join-program', () => surface(runJoin()));
|
|
257
|
+
return { replaceEarnPrograms };
|
|
258
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { OrchestratorContext } from '../context.js';
|
|
2
|
+
export interface MilestoneTierHandlerDeps {
|
|
3
|
+
buildLoaderFacade(): Record<string, unknown> | null;
|
|
4
|
+
}
|
|
5
|
+
export declare function registerMilestoneTierHandlers(ctx: OrchestratorContext, deps: MilestoneTierHandlerDeps): void;
|