Repository navigation
Expand file tree
/
Copy pathshopify.js
More file actions
404 lines (360 loc) · 13.3 KB
/
Copy pathshopify.js
File metadata and controls
404 lines (360 loc) · 13.3 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
const API_VERSION = '2026-10';
const LOOKUP_TIMEOUT_MS = 8000;
const { cannedReply } = require('./router');
function shopName() {
return String(process.env.SHOPIFY_SHOP || process.env.SHOPIFY_STORE || '').trim();
}
function hasStaticToken() {
return Boolean(String(process.env.SHOPIFY_ACCESS_TOKEN || '').trim());
}
function hasClientCredentials() {
const id = String(process.env.SHOPIFY_CLIENT_ID || '').trim();
const secret = String(process.env.SHOPIFY_CLIENT_SECRET || '').trim();
return Boolean(id && secret);
}
function isConfigured() {
return Boolean(shopName() && (hasStaticToken() || hasClientCredentials()));
}
function storeHost() {
const raw = shopName()
.replace(/^https?:\/\//i, '')
.replace(/\/.*$/, '');
if (!raw) return '';
return raw.includes('.') ? raw : `${raw}.myshopify.com`;
}
let cachedToken = null;
function resetShopifyAuth() {
cachedToken = null;
}
async function adminToken(fetchImpl, now = Date.now()) {
const staticToken = String(process.env.SHOPIFY_ACCESS_TOKEN || '').trim();
if (staticToken) return staticToken;
if (cachedToken && cachedToken.expiresAt > now + 60_000) return cachedToken.token;
const body = new URLSearchParams({
grant_type: 'client_credentials',
client_id: String(process.env.SHOPIFY_CLIENT_ID || '').trim(),
client_secret: String(process.env.SHOPIFY_CLIENT_SECRET || '').trim(),
});
const res = await fetchImpl(`https://${storeHost()}/admin/oauth/access_token`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
},
body,
signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
});
if (!res.ok) {
const err = new Error('shopify token');
err.reason = res.status === 401 || res.status === 403 ? 'auth' : 'error';
throw err;
}
let data;
try {
data = await res.json();
} catch {
const err = new Error('shopify token');
err.reason = 'error';
throw err;
}
const token = String(data?.access_token || '');
if (!token) {
const err = new Error('shopify token');
err.reason = 'auth';
throw err;
}
const ttl = Number(data.expires_in) > 0 ? Number(data.expires_in) : 86399;
cachedToken = { token, expiresAt: now + ttl * 1000 };
return token;
}
function isOrderQuestion(text) {
const s = String(text || '');
if (/\bin order to\b/i.test(s)) return false;
return (
/\b(my|the)\s+order\b/i.test(s) ||
/\border\s*(#|number|id|num|status)\b/i.test(s) ||
/\bwhere\s+is\s+my\s+order\b/i.test(s) ||
/\btracking\b/i.test(s) ||
/#\d{3,}/.test(s)
);
}
function needsWriteHuman(text) {
const s = String(text || '');
return (
/\brefunds?\b/i.test(s) ||
/\bwrong address\b/i.test(s) ||
/\bchange (my )?(the )?(shipping )?address\b/i.test(s) ||
/\bcancel (my )?(the )?(order|purchase)\b/i.test(s)
);
}
function extractLookupKeys(text) {
const s = String(text || '');
const numbered =
s.match(/#\s*(\d{3,})\b/) ||
s.match(/\border\s*(?:number|no\.?|id|#)?\s*[#:]?\s*(\d{3,})\b/i);
const mail = s.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i);
return {
orderName: numbered ? `#${numbered[1]}` : '',
email: mail ? mail[0] : '',
};
}
function hasLookupKey(text) {
const keys = extractLookupKeys(text);
return Boolean(keys.orderName || keys.email);
}
function normalizeEmail(raw) {
const email = String(raw || '').trim().toLowerCase();
if (email.length < 3 || email.length > 254) return '';
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return '';
return email;
}
function shouldLookup(route, text, { verifiedEmail } = {}) {
if (!isConfigured()) return false;
if (!normalizeEmail(verifiedEmail)) return false;
if (route?.intent === 'shipping_quote') return false;
if (route?.lane === 'shop') return true;
if (route?.lane === 'money' && hasLookupKey(text)) return true;
return false;
}
function payLabel(status) {
const key = String(status || '').toLowerCase();
if (key === 'paid') return 'paid';
if (key === 'pending') return 'pending payment';
if (key === 'refunded') return 'refunded';
if (key === 'partially_refunded') return 'partially refunded';
if (key === 'voided') return 'voided';
if (key === 'authorized') return 'authorized';
return key || 'unknown payment status';
}
function shipLabel(order) {
if (order.cancelled) return 'cancelled';
const key = String(order.fulfillmentStatus || '').toLowerCase();
if (key === 'fulfilled') return 'shipped';
if (key === 'partial') return 'partially shipped';
if (key === 'restocked') return 'restocked';
return 'not shipped';
}
function formatDate(iso) {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
return d.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short',
year: 'numeric',
timeZone: 'UTC',
});
}
function addressLooksComplete(addr) {
if (!addr || typeof addr !== 'object') return false;
return Boolean(
addr.city && (addr.country || addr.country_code) && (addr.zip || addr.address1)
);
}
function summarizeOrder(raw) {
const fulfillments = Array.isArray(raw?.fulfillments) ? raw.fulfillments : [];
const trackings = [];
for (const f of fulfillments) {
const numbers = Array.isArray(f.tracking_numbers) && f.tracking_numbers.length
? f.tracking_numbers
: f.tracking_number
? [f.tracking_number]
: [];
const urls = Array.isArray(f.tracking_urls) && f.tracking_urls.length
? f.tracking_urls
: f.tracking_url
? [f.tracking_url]
: [];
numbers.filter(Boolean).forEach((number, i) => {
trackings.push({
number: String(number),
url: String(urls[i] || urls[0] || ''),
company: String(f.tracking_company || ''),
});
});
}
const titles = (raw?.line_items || [])
.map((item) => String(item?.title || '').trim())
.filter(Boolean);
const addr = raw?.shipping_address || {};
return {
name: String(raw?.name || '').trim(),
createdAt: raw?.created_at || '',
cancelled: Boolean(raw?.cancelled_at),
financialStatus: String(raw?.financial_status || ''),
fulfillmentStatus: String(raw?.fulfillment_status || ''),
titles,
trackings,
city: String(addr.city || '').trim(),
country: String(addr.country || addr.country_code || '').trim(),
addressComplete: addressLooksComplete(addr),
};
}
function payShip(order) {
return `${payLabel(order.financialStatus)}, ${shipLabel(order)}`;
}
function formatUserReply(order) {
const name = order.name || 'That order';
const lines = [`${name} is ${payShip(order)}.`];
if (order.trackings.length) {
for (const t of order.trackings) {
lines.push(t.company ? `${t.company}: ${t.number}` : t.number);
if (t.url) lines.push(t.url);
}
} else if (!order.cancelled) {
lines.push('No tracking is available on this order yet. A delivery date is not confirmed.');
}
const when = formatDate(order.createdAt);
if (when) lines.push(`Ordered ${when}.`);
if (order.titles.length) {
lines.push('Items:');
for (const title of order.titles.slice(0, 8)) lines.push(`- ${title}`);
}
return lines.join('\n');
}
function formatStaffFacts(order) {
const lines = [`${order.name || 'Order'} ${payShip(order)}`];
for (const t of order.trackings) {
lines.push(t.company ? `${t.company} ${t.number}` : t.number);
if (t.url) lines.push(t.url);
}
if (order.titles.length) lines.push(`Items: ${order.titles.slice(0, 8).join(', ')}`);
if (order.city || order.country) {
lines.push(`Ship to: ${[order.city, order.country].filter(Boolean).join(', ')}`);
}
lines.push(`Address looks complete: ${order.addressComplete ? 'yes' : 'no'}`);
return lines.join('\n');
}
function buildUserReply(lookup, question) {
if (!isConfigured()) return null;
if (needsWriteHuman(question)) {
const extra = lookup?.order ? `\n\nThe order I found is ${payShip(lookup.order)}.` : '';
return `${cannedReply({ lane: 'money', area: 'shop' }, question)}${extra}`;
}
if (lookup?.reason === 'unverified') {
return 'To check your order privately, use /order and verify the email on the order. Please do not post your email or order details here.';
}
if (lookup?.reason === 'no-key') {
return 'Use /order to verify the email on your order and check its details privately.';
}
if (lookup?.reason === 'error' || lookup?.reason === 'auth') {
return 'The order check is temporarily unavailable. Your order needs a team review rather than an unverified status or delivery date.';
}
if (!lookup?.order) {
return 'The verified lookup did not find that exact order. Your order number and verified email need a team review; no order status is confirmed.';
}
return formatUserReply(lookup.order);
}
function staffReason(lookup, question) {
if (needsWriteHuman(question)) return 'Refund, cancel, or address change needs a person';
if (lookup?.reason === 'no-key') return 'Needs order number or email on the order';
if (lookup?.reason === 'miss') return 'Shopify miss';
if (lookup?.reason === 'error' || lookup?.reason === 'auth') return 'Shopify lookup failed';
if (lookup?.order) return 'Order lookup for staff check';
return 'Order question';
}
function filterKnowledge(snippets) {
const list = snippets || [];
if (!isConfigured()) return list;
return list.filter((s) => !/cannot see shopify/i.test(String(s || '')));
}
async function shopifyList(params, fetchImpl) {
const host = storeHost();
const url = new URL(`https://${host}/admin/api/${API_VERSION}/orders.json`);
url.searchParams.set('status', 'any');
url.searchParams.set('limit', '5');
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
let token;
try {
token = await adminToken(fetchImpl);
} catch (err) {
return { ok: false, reason: err.reason || 'error' };
}
const res = await fetchImpl(url, {
headers: {
'X-Shopify-Access-Token': token,
Accept: 'application/json',
},
signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
});
if (res.status === 401 || res.status === 403) return { ok: false, reason: 'auth' };
if (!res.ok) return { ok: false, reason: 'error' };
// Shopify silently falls forward when a pinned version is retired. Do not
// interpret customer records using an untested response contract.
const servedVersion = res.headers?.get?.('X-Shopify-API-Version');
if (servedVersion && servedVersion !== API_VERSION) {
console.warn('[Shopify] API version mismatch; order lookup withheld.');
return { ok: false, reason: 'error' };
}
let data;
try {
data = await res.json();
} catch {
return { ok: false, reason: 'error' };
}
const orders = Array.isArray(data?.orders) ? data.orders : [];
return { ok: true, raw: orders, orders: orders.map(summarizeOrder) };
}
async function ordersForVerifiedEmail(email, { fetchImpl, limit = 5 } = {}) {
const bound = normalizeEmail(email);
if (!bound) return { ok: false, reason: 'unverified', orders: [] };
if (!isConfigured()) return { ok: false, reason: 'unconfigured', orders: [] };
const listed = await shopifyList({ email: bound, limit: String(limit) }, fetchImpl || fetch);
if (!listed.ok) return { ok: false, reason: listed.reason, orders: [] };
return { ok: true, orders: listed.raw.filter((raw) => orderEmailMatches(raw, bound)).map(summarizeOrder) };
}
async function hasRecentOrderForEmail(email, { fetchImpl } = {}) {
const found = await ordersForVerifiedEmail(email, { fetchImpl, limit: 1 });
if (!found.ok) throw new Error(`Shopify lookup failed: ${found.reason}`);
return found.orders.length > 0;
}
function orderEmailMatches(raw, verifiedEmail) {
return normalizeEmail(raw?.email) === normalizeEmail(verifiedEmail);
}
async function lookupOrder(text, { fetchImpl, verifiedEmail } = {}) {
if (!isConfigured()) return { ok: false, reason: 'unconfigured' };
const bound = normalizeEmail(verifiedEmail);
if (!bound) return { ok: false, reason: 'unverified' };
const keys = extractLookupKeys(text);
const fetchFn = fetchImpl || fetch;
try {
if (keys.orderName) {
const byName = await shopifyList({ name: keys.orderName }, fetchFn);
if (!byName.ok) return { ok: false, reason: byName.reason };
const exact = byName.raw.find((raw) =>
String(raw?.name || '').trim() === keys.orderName && orderEmailMatches(raw, bound));
// A requested number is an exact lookup, never permission to substitute
// another order belonging to the same verified email.
return exact ? { ok: true, order: summarizeOrder(exact) } : { ok: false, reason: 'miss' };
}
const byEmail = await shopifyList({ email: bound }, fetchFn);
if (!byEmail.ok) return { ok: false, reason: byEmail.reason };
const owned = byEmail.raw.find((raw) => orderEmailMatches(raw, bound));
return owned ? { ok: true, order: summarizeOrder(owned) } : { ok: false, reason: 'miss' };
} catch (err) {
console.error('[Shopify] lookup failed; private request details withheld.');
return { ok: false, reason: 'error' };
}
}
module.exports = {
API_VERSION,
isConfigured,
storeHost,
resetShopifyAuth,
isOrderQuestion,
needsWriteHuman,
extractLookupKeys,
hasLookupKey,
shouldLookup,
normalizeEmail,
summarizeOrder,
formatUserReply,
formatStaffFacts,
buildUserReply,
staffReason,
filterKnowledge,
lookupOrder,
ordersForVerifiedEmail,
hasRecentOrderForEmail,
};