-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
613 lines (535 loc) · 19.9 KB
/
Copy pathserver.js
File metadata and controls
613 lines (535 loc) · 19.9 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3001;
const SHOPIFY_API_VERSION = '2026-04';
const FETCH_TIMEOUT = 30000;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
};
function sendJSON(res, status, data) {
const body = JSON.stringify(data);
res.writeHead(status, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
});
res.end(body);
}
function sendFile(res, filePath) {
const ext = path.extname(filePath);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
return;
}
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
res.end(data);
});
}
function parseBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try { resolve(JSON.parse(body)); }
catch (e) { reject(new Error('Invalid JSON in request body')); }
});
req.on('error', reject);
});
}
async function shopifyFetch(url, options = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT);
try {
return await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timeout);
}
}
function normalizeNumericIds(ids) {
if (!Array.isArray(ids)) return [];
return [...new Set(ids
.map(id => Number.parseInt(id, 10))
.filter(Number.isSafeInteger))];
}
function normalizeCodePrefix(value) {
const cleaned = String(value || '')
.trim()
.toUpperCase()
.replace(/[^A-Z0-9_]+/g, '_')
.replace(/_+/g, '_')
.replace(/^[-_]+|[-_]+$/g, '');
return cleaned ? `${cleaned}_` : '';
}
function buildMinimumRequirement(type, value) {
const numberValue = Number.parseFloat(value);
if (!type || type === 'none' || !Number.isFinite(numberValue) || numberValue <= 0) return null;
if (type === 'subtotal') {
return {
rest: { prerequisite_subtotal_range: { greater_than_or_equal_to: String(numberValue) } },
graphql: { subtotal: { greaterThanOrEqualToSubtotal: String(numberValue.toFixed(2)) } },
};
}
if (type === 'quantity') {
const quantity = Math.max(1, Math.floor(numberValue));
return {
rest: { prerequisite_quantity_range: { greater_than_or_equal_to: String(quantity) } },
graphql: { quantity: { greaterThanOrEqualToQuantity: String(quantity) } },
};
}
return null;
}
function hasCombinesWith(combinesWith) {
return Boolean(
combinesWith?.productDiscounts ||
combinesWith?.orderDiscounts ||
combinesWith?.shippingDiscounts
);
}
function normalizeShop(shop) {
return String(shop || '')
.trim()
.replace(/^https?:\/\//i, '')
.replace(/\/.*$/, '')
.toLowerCase();
}
function isValidShopDomain(shop) {
return /^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/i.test(shop);
}
async function fetchStoreData(shop, accessToken) {
const shopRes = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/shop.json`,
{ headers: { 'X-Shopify-Access-Token': accessToken } }
);
if (!shopRes.ok) {
throw new Error(`Invalid credentials (HTTP ${shopRes.status}). Check your store URL and app permissions.`);
}
const productsRes = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/products.json?limit=250&fields=id,title,variants`,
{ headers: { 'X-Shopify-Access-Token': accessToken } }
);
if (!productsRes.ok) {
throw new Error('Failed to fetch products. Check that your app has read_products scope.');
}
const productsData = await productsRes.json();
const products = (productsData.products || []).map(product => {
const prices = product.variants
.map(variant => Number.parseFloat(variant.price))
.filter(Number.isFinite);
const skus = [...new Set(product.variants
.map(variant => variant.sku)
.filter(Boolean))];
const minPrice = prices.length ? Math.min(...prices) : null;
const maxPrice = prices.length ? Math.max(...prices) : null;
const priceLabel = minPrice === null
? ''
: minPrice === maxPrice
? minPrice.toFixed(2)
: `${minPrice.toFixed(2)}-${maxPrice.toFixed(2)}`;
return {
id: product.id,
title: product.title,
variantCount: product.variants.length,
priceLabel,
skus: skus.slice(0, 20),
skuCount: skus.length,
};
});
const variants = (productsData.products || []).flatMap(product =>
product.variants.map(variant => ({
id: variant.id,
productId: variant.product_id,
title: variant.title,
price: variant.price,
sku: variant.sku || '',
displayName: `${product.title} - ${variant.title}`,
}))
);
return { products, variants };
}
// ─── API: Connect ─────────────────────────────────────────────────────────────
async function handleConnect(req, res) {
const { shop, accessToken } = await parseBody(req);
const cleanShop = normalizeShop(shop);
if (!cleanShop || !accessToken) {
return sendJSON(res, 200, { success: false, error: 'Shop URL and Access Token are required' });
}
if (!isValidShopDomain(cleanShop)) {
return sendJSON(res, 200, {
success: false,
error: 'Enter the full Shopify store URL, for example shopifyscripts.com or shopifyscripts.myshopify.com.',
});
}
try {
const { products, variants } = await fetchStoreData(cleanShop, accessToken);
console.log(`[Connect] OK ${cleanShop}: ${products.length} products, ${variants.length} variants`);
sendJSON(res, 200, { success: true, products, variants, shop: cleanShop, accessToken });
} catch (error) {
console.error('[Connect] Error:', error.message);
sendJSON(res, 200, { success: false, error: `Connection failed: ${error.message}` });
}
}
// ─── API: Generate Discount Codes ─────────────────────────────────────────────
async function handleGenerate(req, res) {
const data = await parseBody(req);
const {
shop,
accessToken,
discountType,
amount,
quantity,
usageLimit,
totalUsageLimit,
endsAt,
codePrefix,
productIds,
variantIds,
minimumRequirementType,
minimumRequirementValue,
combinesWith,
} = data;
if (!shop || !accessToken) {
return sendJSON(res, 200, { success: false, error: 'Session expired. Please reconnect to Shopify.' });
}
const qty = Math.max(1, Math.min(4000, parseInt(quantity) || 1));
const perCodeLimit = parseInt(usageLimit) || 1;
const totalLimit = parseInt(totalUsageLimit) || null;
const valueType = discountType === 'percentage' ? 'percentage' : 'fixed_amount';
const numericAmount = Math.abs(parseFloat(amount) || 0);
const prefix = normalizeCodePrefix(codePrefix);
const selectedProductIds = normalizeNumericIds(productIds);
const selectedVariantIds = normalizeNumericIds(variantIds);
const minimumRequirement = buildMinimumRequirement(minimumRequirementType, minimumRequirementValue);
const requiresGraphQL = hasCombinesWith(combinesWith);
console.log(`[Generate] Starting: ${shop} type=${valueType} amount=${amount} qty=${qty} limit=${perCodeLimit} products=${selectedProductIds.length}`);
try {
if (requiresGraphQL) {
console.log('[Generate] Combinations requested, using GraphQL...');
return await createViaGraphQL(res, data, qty, perCodeLimit, prefix, selectedProductIds, selectedVariantIds);
}
// Step 1: Create price rule with product restrictions when selected.
const now = new Date();
const title = prefix
? prefix.replace(/[-_]+$/, '')
: 'Bulk Discount';
const hasRestrictions = selectedProductIds.length > 0 || selectedVariantIds.length > 0;
const priceRuleBody = {
price_rule: {
title,
value_type: valueType,
value: String(-numericAmount),
customer_selection: 'all',
target_type: 'line_item',
allocation_method: 'across',
once_per_customer: true,
usage_limit: totalLimit && totalLimit > 0 ? totalLimit : perCodeLimit,
starts_at: now.toISOString(),
},
};
if (minimumRequirement) {
Object.assign(priceRuleBody.price_rule, minimumRequirement.rest);
}
if (hasRestrictions) {
priceRuleBody.price_rule.target_selection = 'entitled';
if (selectedProductIds.length > 0) {
priceRuleBody.price_rule.entitled_product_ids = selectedProductIds;
}
if (selectedVariantIds.length > 0) {
priceRuleBody.price_rule.entitled_variant_ids = selectedVariantIds;
}
} else {
priceRuleBody.price_rule.target_selection = 'all';
}
if (endsAt) {
priceRuleBody.price_rule.ends_at = new Date(endsAt).toISOString();
}
console.log('[Generate] Creating price rule...');
const prRes = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/price_rules.json`,
{
method: 'POST',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(priceRuleBody),
}
);
const prBody = await prRes.text();
// If Price Rules API is gone (404/410) or entitlement not supported, fall back to GraphQL
if (prRes.status === 404 || prRes.status === 410 || (hasRestrictions && prBody.includes('item_entitlements'))) {
if (prRes.status === 404 || prRes.status === 410) {
console.log('[Generate] Price Rules API unavailable, using GraphQL...');
} else {
console.log('[Generate] Entitlements not supported via REST, using GraphQL with product restrictions...');
}
return await createViaGraphQL(res, data, qty, perCodeLimit, prefix, selectedProductIds, selectedVariantIds);
}
if (!prRes.ok) {
console.error('[Generate] Price rule error:', prBody.slice(0, 1000));
throw new Error(prBody);
}
const prData = JSON.parse(prBody);
const priceRuleId = prData.price_rule.id;
console.log(`[Generate] Price rule created: ${priceRuleId}`);
// Step 2: Generate discount codes under the price rule
const codes = await generateCodes(shop, accessToken, priceRuleId, qty, prefix);
const discounts = codes.map(c => ({
code: c.code,
title: valueType === 'percentage' ? `${amount}% off` : `$${amount} off`,
amount: String(amount),
discountType: valueType,
usageLimit: perCodeLimit,
totalUsageLimit: totalLimit,
endsAt: endsAt || null,
}));
console.log(`[Generate] Success: ${discounts.length} codes`);
sendJSON(res, 200, { success: true, discounts });
} catch (error) {
console.error('[Generate] Error:', error.message);
sendJSON(res, 200, { success: false, error: error.message });
}
}
// ─── Create discount codes via Price Rules (batch → individual) ───────────────
async function generateCodes(shop, accessToken, priceRuleId, qty, prefix) {
// Generate unique code strings
const makeCode = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let s = '';
for (let i = 0; i < 8; i++) s += chars[Math.floor(Math.random() * chars.length)];
return `${prefix}${s}`;
};
const allCodes = [];
const used = new Set();
for (let i = 0; i < qty; i++) {
let c;
do { c = makeCode(); } while (used.has(c));
used.add(c);
allCodes.push({ code: c });
}
// Try batch creation first
const batchRes = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/price_rules/${priceRuleId}/discount_codes/batch.json`,
{
method: 'POST',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify({ discount_codes: allCodes }),
}
);
if (batchRes.ok) {
const batchData = await batchRes.json();
const batchId = batchData.discount_code_creation.id;
let status = batchData.discount_code_creation.status;
let attempts = 0;
while ((status === 'queued' || status === 'running') && attempts < 60) {
await new Promise(r => setTimeout(r, 1000));
attempts++;
const sr = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/price_rules/${priceRuleId}/discount_codes/batch/${batchId}.json`,
{ headers: { 'X-Shopify-Access-Token': accessToken } }
);
if (sr.ok) {
const sd = await sr.json();
status = sd.discount_code_creation.status;
}
}
const cr = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/price_rules/${priceRuleId}/discount_codes.json?batch_id=${batchId}`,
{ headers: { 'X-Shopify-Access-Token': accessToken } }
);
if (cr.ok) {
const cd = await cr.json();
if (cd.discount_codes && cd.discount_codes.length > 0) return cd.discount_codes;
}
}
// Fallback: create individually
console.log('[Generate] Creating codes individually...');
const results = [];
for (const dc of allCodes) {
const dr = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/price_rules/${priceRuleId}/discount_codes.json`,
{
method: 'POST',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify({ discount_code: dc }),
}
);
if (dr.ok) {
const dd = await dr.json();
results.push(dd.discount_code);
}
}
if (results.length === 0) {
throw new Error('Failed to create discount codes. Verify your write_discounts scope.');
}
return results;
}
// ─── Fallback: create codes via GraphQL API ─────────────────────────────────────
async function createViaGraphQL(res, data, qty, limit, prefix, productIds, variantIds = []) {
const {
shop,
accessToken,
discountType,
amount,
totalUsageLimit,
endsAt,
minimumRequirementType,
minimumRequirementValue,
combinesWith,
} = data;
const title = prefix
? prefix.replace(/[-_]+$/, '')
: 'Bulk Discount';
const valueType = discountType === 'percentage' ? 'percentage' : 'fixed_amount';
const minimumRequirement = buildMinimumRequirement(minimumRequirementType, minimumRequirementValue);
const totalLimit = parseInt(totalUsageLimit) || null;
const makeCode = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let s = '';
for (let i = 0; i < 8; i++) s += chars[Math.floor(Math.random() * chars.length)];
return `${prefix}${s}`;
};
// Generate all codes upfront
const allCodes = [];
const used = new Set();
for (let i = 0; i < qty; i++) {
let code;
do { code = makeCode(); } while (used.has(code));
used.add(code);
allCodes.push(code);
}
const productGids = productIds.map(id => `gid://shopify/Product/${id}`);
const variantGids = variantIds.map(id => `gid://shopify/ProductVariant/${id}`);
const hasRestrictions = productGids.length > 0 || variantGids.length > 0;
const items = hasRestrictions
? {
products: {
...(productGids.length > 0 ? { productsToAdd: productGids } : {}),
...(variantGids.length > 0 ? { productVariantsToAdd: variantGids } : {}),
},
}
: { all: true };
const discounts = [];
// Create codes with concurrency 5
const CONCURRENCY = 5;
for (let i = 0; i < allCodes.length; i += CONCURRENCY) {
const batch = allCodes.slice(i, i + CONCURRENCY);
const results = await Promise.allSettled(batch.map(async (code) => {
const mutation = {
query: `
mutation discountCodeBasicCreate($input: DiscountCodeBasicInput!) {
discountCodeBasicCreate(basicCodeDiscount: $input) {
codeDiscountNode { id }
userErrors { field message code }
}
}
`,
variables: {
input: {
title,
code,
usageLimit: totalLimit && totalLimit > 0 ? totalLimit : limit,
appliesOncePerCustomer: true,
customerSelection: { all: true },
startsAt: new Date().toISOString(),
...(endsAt ? { endsAt: new Date(endsAt).toISOString() } : {}),
...(minimumRequirement ? { minimumRequirement: minimumRequirement.graphql } : {}),
...(combinesWith ? {
combinesWith: {
productDiscounts: Boolean(combinesWith.productDiscounts),
orderDiscounts: Boolean(combinesWith.orderDiscounts),
shippingDiscounts: Boolean(combinesWith.shippingDiscounts),
},
} : {}),
customerGets: {
value: valueType === 'percentage'
? { percentage: (Math.abs(parseFloat(amount) || 0) / 100).toString() }
: {
discountAmount: {
amount: (Math.abs(parseFloat(amount) || 0)).toFixed(2),
appliesOnEachItem: false,
},
},
items,
},
},
},
};
const gqlRes = await shopifyFetch(
`https://${shop}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`,
{
method: 'POST',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(mutation),
}
);
const gqlBody = await gqlRes.json();
if (!gqlRes.ok || gqlBody.errors || gqlBody.data?.discountCodeBasicCreate?.userErrors?.length) {
const errs = gqlBody.errors || gqlBody.data?.discountCodeBasicCreate?.userErrors || gqlBody;
throw new Error(JSON.stringify(errs));
}
return code;
}));
for (const r of results) {
if (r.status === 'fulfilled') {
discounts.push({
code: r.value,
title: valueType === 'percentage' ? `${amount}% off` : `$${amount} off`,
amount: String(amount),
discountType: valueType,
usageLimit: limit,
totalUsageLimit: totalLimit,
endsAt: endsAt || null,
});
} else {
console.error('[GraphQL] Code creation failed:', r.reason.message);
}
}
}
if (discounts.length === 0) {
throw new Error('GraphQL: Failed to create any discount codes');
}
console.log(`[GraphQL] Created ${discounts.length}/${qty} codes`);
sendJSON(res, 200, { success: true, discounts });
}
// ─── HTTP Router ──────────────────────────────────────────────────────────────
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const method = req.method.toUpperCase();
if (url.pathname === '/api/connect' && method === 'POST') {
handleConnect(req, res).catch(e => sendJSON(res, 500, { success: false, error: e.message }));
return;
}
if (url.pathname === '/api/generate-discounts' && method === 'POST') {
handleGenerate(req, res).catch(e => sendJSON(res, 500, { success: false, error: e.message }));
return;
}
// Serve static files
let filePath = url.pathname === '/' ? '/index.html' : url.pathname;
filePath = path.join(__dirname, 'public', filePath);
if (!filePath.startsWith(path.join(__dirname, 'public'))) {
res.writeHead(403);
res.end('Forbidden');
return;
}
sendFile(res, filePath);
});
server.listen(PORT, '127.0.0.1', () => {
console.log(`Shopify Bulk Discount Creator running at http://localhost:${PORT}`);
});