mcp-shopify-yoffi 1.1.0 → 1.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/README.md +62 -2
- package/dist/lib/discountCodes/codeList.js +93 -0
- package/dist/lib/discountCodes/manage.js +194 -0
- package/dist/lib/discountCodes/runFile.js +87 -0
- package/dist/lib/discountCodes/shopify.js +325 -0
- package/dist/lib/discountCodes/snapshot.js +63 -0
- package/dist/lib/requestWithRetry.js +33 -0
- package/dist/tools/addDiscountCodes.js +354 -0
- package/dist/tools/deleteDiscounts.js +107 -0
- package/dist/tools/getDiscountCodes.js +82 -0
- package/dist/tools/manageDiscount.js +51 -0
- package/dist/tools/registry.js +11 -1
- package/dist/tools/removeDiscountCodes.js +355 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ This is a fork of [shopify-mcp](https://github.com/GeLi2001/shopify-mcp) by GeLi
|
|
|
12
12
|
- **Metafield Management**: Get, set, and delete metafields on any resource (3 tools)
|
|
13
13
|
- **Inventory Management**: Set absolute inventory quantities at locations (1 tool)
|
|
14
14
|
- **Tag Management**: Add/remove tags on any taggable resource (1 tool)
|
|
15
|
-
- **Discount Management**: Create percentage or fixed-amount discount codes, store-wide or scoped to collections (
|
|
15
|
+
- **Discount Management**: Create percentage or fixed-amount discount codes, store-wide or scoped to collections, bulk-attach thousands of codes to an existing discount, pause/reschedule/delete discounts, export or remove codes (7 tools)
|
|
16
16
|
- **Translation Management**: List shop locales, read translatable content, and register or remove translations (4 tools)
|
|
17
17
|
- **Metaobject & File Management**: Read definitions, list/create/update/delete metaobject entries, search and upload files (6 tools)
|
|
18
18
|
- **Pagination & Sorting**: Cursor-based pagination and sort keys on all list queries
|
|
@@ -493,7 +493,11 @@ All list query tools (`get-products`, `get-customers`, `get-orders`, `get-custom
|
|
|
493
493
|
- `tags` (array of strings, required): Tags to add or remove
|
|
494
494
|
- `action` (string, required): `"add"` or `"remove"`
|
|
495
495
|
|
|
496
|
-
### Discount Management (
|
|
496
|
+
### Discount Management (7 tools)
|
|
497
|
+
|
|
498
|
+
Bulk and maintenance tools (3–7) need the `read_discounts` and `write_discounts` scopes.
|
|
499
|
+
|
|
500
|
+
**Finding a discount:** every tool accepts the discount GID, the number from the admin URL (`/discounts/2269857186117`) or any code that is on it. Searching by code only works while that code is still on the discount. If a code was removed (for example the discount's own main code, which `remove-discount-codes` with `keepCsvPath` removes together with every other code not in the list), use the ID from the admin URL or one of the codes that are still on it.
|
|
497
501
|
|
|
498
502
|
1. **`create-discount`**
|
|
499
503
|
|
|
@@ -529,6 +533,62 @@ All list query tools (`get-products`, `get-customers`, `get-orders`, `get-custom
|
|
|
529
533
|
- `excludeProductIds` (array of strings, optional): Product GIDs to exclude from an otherwise store-wide discount
|
|
530
534
|
- `combinesWith` (object, optional): `{ productDiscounts, orderDiscounts, shippingDiscounts }` combination rules
|
|
531
535
|
|
|
536
|
+
3. **`add-discount-codes`**
|
|
537
|
+
|
|
538
|
+
- Attach many single-use codes (up to 100,000) to an existing code discount, including app discounts (e.g. SMART). Uploads in batches of 250 and writes two files: `<run>-result.csv` (every code with its status) and `<run>-partner.csv` (only usable codes). Only counts and samples are returned to the chat, never the full code list. Local (stdio) mode only.
|
|
539
|
+
- Statuses: `attached`, `skipped` (already on this discount), `conflict` (on another discount), `failed` (with Shopify's reason)
|
|
540
|
+
- Safe to repeat: each call stops after `maxSeconds`; calling again with the same input resumes from the result file and never uploads a code twice
|
|
541
|
+
- Inputs:
|
|
542
|
+
- `discount` (string, required): Discount GID, the number from the admin URL (`/discounts/123`), or a code already on the discount
|
|
543
|
+
- `generate` (object, optional): `{ count, prefix, length }`, e.g. `{ count: 25000, prefix: "DB-" }`. Uses readable characters only (no 0/O, 1/I/L)
|
|
544
|
+
- `csvPath` (string, optional): Partner CSV with its own codes (`code` column or first column, comma or semicolon). Use this or `generate`
|
|
545
|
+
- `outputDir` (string, optional): Folder for the result files. Required with `generate`; defaults to the CSV's folder
|
|
546
|
+
- `runName` (string, optional): Name of the result files. A new name starts a new run
|
|
547
|
+
- `dryRun` (boolean, default `true`): Show the discount details, plan and warnings without uploading. Reads the discount's current codes, so codes already on it are reported as `alreadyOnDiscount`, not as "would upload"
|
|
548
|
+
- `verify` (boolean, default `false`): Code-by-code reconciliation. Pages through all codes on the discount and compares them with the CSV / result file: `ok`, `missing` (in list, not on discount) and `extra` (on discount, not in list). Writes `<run>-verify.csv` and sets missing codes back to pending, so the next run uploads exactly those. Uploads nothing
|
|
549
|
+
- `maxSeconds` (number, default 50): Time budget per call
|
|
550
|
+
- Resilience: throttled requests are retried (about 47 s), network problems and requests without an answer after 25 s are retried 5 times. If it still fails, the call returns the counts plus `interrupted` instead of an error; calling again continues. `<run>-partner.csv` is written once, when the run is finished. If Windows locks a file (virus scanner, preview), the write is retried and otherwise reported in `fileWarnings` without aborting the call
|
|
551
|
+
|
|
552
|
+
4. **`manage-discount`**
|
|
553
|
+
|
|
554
|
+
- Pause (`deactivate`), reactivate (`activate`) or reschedule (change start/end date) an existing code discount, native or app (e.g. SMART). Codes are kept. Returns the discount before and after
|
|
555
|
+
- Inputs:
|
|
556
|
+
- `discount` (string, required): Discount GID, the number from the admin URL, or one of its codes
|
|
557
|
+
- `action` (string, required): `"activate"`, `"deactivate"` or `"reschedule"`
|
|
558
|
+
- `startsAt` (string, optional): `reschedule` only, new start (ISO 8601)
|
|
559
|
+
- `endsAt` (string or null, optional): `reschedule` only, new end (ISO 8601); `null` removes the end date
|
|
560
|
+
|
|
561
|
+
5. **`delete-discounts`**
|
|
562
|
+
|
|
563
|
+
- Permanently delete code discounts including all their codes (e.g. test discounts). Explicit discounts only, never by search. Default `dryRun=true` lists what would be deleted. Discounts already used in orders are skipped unless `allowUsed=true`. Discounts that are not found are reported, so repeating a call is safe
|
|
564
|
+
- Inputs:
|
|
565
|
+
- `discounts` (array of strings, required, max 50): GID, admin URL number or a code of each discount
|
|
566
|
+
- `dryRun` (boolean, default `true`): Only show what would be deleted
|
|
567
|
+
- `confirmCount` (number): Required when `dryRun=false`: the number of discounts that would be deleted (`wouldDelete` from the dry run). A wrong or missing number refuses the deletion
|
|
568
|
+
- `allowUsed` (boolean, default `false`): Also delete discounts that were used in orders
|
|
569
|
+
- `maxSeconds` (number, default 50): How long to wait for Shopify's delete job
|
|
570
|
+
|
|
571
|
+
6. **`get-discount-codes`**
|
|
572
|
+
|
|
573
|
+
- Look up a discount by ID, admin URL number or any of its codes (which discount does this code belong to?) and show its details. With `outputDir` it exports all codes to `<run>-codes.csv`; large discounts (25,000+) take several calls, repeat the same input to continue. The chat only gets details, counts and sample codes
|
|
574
|
+
- Inputs:
|
|
575
|
+
- `discount` (string, required): GID, admin URL number or a code
|
|
576
|
+
- `outputDir` (string, optional): Folder for the CSV export (local mode only)
|
|
577
|
+
- `runName` (string, optional): Name of the export files
|
|
578
|
+
- `maxSeconds` (number, default 50): Time budget per call
|
|
579
|
+
|
|
580
|
+
7. **`remove-discount-codes`**
|
|
581
|
+
|
|
582
|
+
- Remove codes from a discount without deleting it, e.g. extra codes after an upload. Three modes: `codes` (explicit list), `removeCsvPath` (codes to remove) or `keepCsvPath` (codes that must stay, everything else is removed). Default `dryRun=true` reads the discount once, builds the plan and writes `<run>-remove-plan.csv` (code + status) and a state file `<run>-remove-state.json`. The first real run needs `confirmCount` equal to the planned count; after that the run is confirmed. Large removals (25,000 codes) continue over several calls: repeat the same input (same `runName`, no `confirmCount`); each call works through the saved plan without re-reading the discount, so it is not affected by the count changing while Shopify's jobs run. When everything is removed, the discount is read once more to check; codes still there are retried. Batches start at 250 codes and drop to 100 if Shopify rejects them. Never removes all codes of a discount, and `keepCsvPath` is refused if none of its codes is on the discount. Note: `keepCsvPath` also removes the discount's own main code unless it is in the list; afterwards the discount can no longer be found by that code, only by its ID or a remaining code
|
|
583
|
+
- Inputs:
|
|
584
|
+
- `discount` (string, required): GID, admin URL number or a code
|
|
585
|
+
- `codes` / `removeCsvPath` / `keepCsvPath`: exactly one of them
|
|
586
|
+
- `outputDir` (string, required): Folder for the run files (local mode only)
|
|
587
|
+
- `runName` (string, optional): Name of the run files. The same name continues the run, a new name starts a new one
|
|
588
|
+
- `dryRun` (boolean, default `true`): Build and show the plan, remove nothing
|
|
589
|
+
- `confirmCount` (number): Required on the first `dryRun=false` call of a run: the count from the dry run. Not needed when continuing
|
|
590
|
+
- `maxSeconds` (number, default 50): Time budget per call
|
|
591
|
+
|
|
532
592
|
### Translation Management (4 tools)
|
|
533
593
|
|
|
534
594
|
Requires the `read_locales`, `read_translations` and `write_translations` scopes. Translations are written directly to the live store; there is no review step and no exclusion rules or glossary are applied.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { randomInt } from "node:crypto";
|
|
2
|
+
// No 0/O, 1/I/L: easy to read and type from a printed voucher.
|
|
3
|
+
const ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
|
|
4
|
+
/** Generate `count` unique random codes (case-insensitive unique, like Shopify). */
|
|
5
|
+
export function generateCodes(count, prefix, length, existing = new Set()) {
|
|
6
|
+
const out = [];
|
|
7
|
+
const seen = new Set(existing);
|
|
8
|
+
while (out.length < count) {
|
|
9
|
+
let s = prefix;
|
|
10
|
+
for (let i = 0; i < length; i++)
|
|
11
|
+
s += ALPHABET[randomInt(ALPHABET.length)];
|
|
12
|
+
const key = s.toLowerCase();
|
|
13
|
+
if (seen.has(key))
|
|
14
|
+
continue;
|
|
15
|
+
seen.add(key);
|
|
16
|
+
out.push(s);
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
export function splitCsvLine(line, sep) {
|
|
21
|
+
const cells = [];
|
|
22
|
+
let cur = "";
|
|
23
|
+
let quoted = false;
|
|
24
|
+
for (let i = 0; i < line.length; i++) {
|
|
25
|
+
const ch = line[i];
|
|
26
|
+
if (quoted) {
|
|
27
|
+
if (ch === '"' && line[i + 1] === '"') {
|
|
28
|
+
cur += '"';
|
|
29
|
+
i++;
|
|
30
|
+
}
|
|
31
|
+
else if (ch === '"')
|
|
32
|
+
quoted = false;
|
|
33
|
+
else
|
|
34
|
+
cur += ch;
|
|
35
|
+
}
|
|
36
|
+
else if (ch === '"')
|
|
37
|
+
quoted = true;
|
|
38
|
+
else if (ch === sep) {
|
|
39
|
+
cells.push(cur);
|
|
40
|
+
cur = "";
|
|
41
|
+
}
|
|
42
|
+
else
|
|
43
|
+
cur += ch;
|
|
44
|
+
}
|
|
45
|
+
cells.push(cur);
|
|
46
|
+
return cells.map((c) => c.trim());
|
|
47
|
+
}
|
|
48
|
+
const CODE_HEADERS = ["code", "codes", "discount code", "gutscheincode", "rabattcode"];
|
|
49
|
+
/**
|
|
50
|
+
* Parse a partner CSV: comma or semicolon, optional BOM, optional header.
|
|
51
|
+
* Uses the code column if there is a header, otherwise the first column.
|
|
52
|
+
*/
|
|
53
|
+
export function parseCodesCsv(text) {
|
|
54
|
+
const lines = text.replace(/^/, "").split(/\r?\n/);
|
|
55
|
+
const first = lines.find((l) => l.trim()) ?? "";
|
|
56
|
+
const sep = (first.match(/;/g)?.length ?? 0) > (first.match(/,/g)?.length ?? 0) ? ";" : ",";
|
|
57
|
+
let col = 0;
|
|
58
|
+
let start = 0;
|
|
59
|
+
const header = splitCsvLine(first, sep).map((h) => h.toLowerCase());
|
|
60
|
+
const codeCol = header.findIndex((h) => CODE_HEADERS.includes(h));
|
|
61
|
+
if (codeCol >= 0) {
|
|
62
|
+
col = codeCol;
|
|
63
|
+
start = lines.indexOf(first) + 1;
|
|
64
|
+
}
|
|
65
|
+
const seen = new Set();
|
|
66
|
+
const result = { codes: [], duplicates: [], invalid: [] };
|
|
67
|
+
for (let i = start; i < lines.length; i++) {
|
|
68
|
+
if (!lines[i].trim())
|
|
69
|
+
continue;
|
|
70
|
+
const value = splitCsvLine(lines[i], sep)[col] ?? "";
|
|
71
|
+
let reason = null;
|
|
72
|
+
if (!value)
|
|
73
|
+
reason = "empty";
|
|
74
|
+
else if (/\s/.test(value))
|
|
75
|
+
reason = "contains whitespace";
|
|
76
|
+
else if (value.length > 255)
|
|
77
|
+
reason = "longer than 255 characters";
|
|
78
|
+
else if (/^\d+([.,]\d+)?E\+?\d+$/i.test(value))
|
|
79
|
+
reason = "looks like an Excel number (e.g. 1.2E+11): re-export as text";
|
|
80
|
+
if (reason) {
|
|
81
|
+
result.invalid.push({ line: i + 1, value: value.slice(0, 60), reason });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const key = value.toLowerCase(); // Shopify codes are case-insensitive
|
|
85
|
+
if (seen.has(key)) {
|
|
86
|
+
result.duplicates.push(value);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
seen.add(key);
|
|
90
|
+
result.codes.push(value);
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { gql } from "graphql-request";
|
|
2
|
+
import { requestWithRetry, sleep } from "../requestWithRetry.js";
|
|
3
|
+
import { checkUserErrors } from "../toolUtils.js";
|
|
4
|
+
// ── Activate / deactivate ─────────────────────────────────────────────
|
|
5
|
+
const ACTIVATE_MUTATION = gql `
|
|
6
|
+
#graphql
|
|
7
|
+
|
|
8
|
+
mutation ManageDiscountActivate($id: ID!) {
|
|
9
|
+
discountCodeActivate(id: $id) {
|
|
10
|
+
codeDiscountNode {
|
|
11
|
+
id
|
|
12
|
+
}
|
|
13
|
+
userErrors {
|
|
14
|
+
field
|
|
15
|
+
message
|
|
16
|
+
code
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
`;
|
|
21
|
+
const DEACTIVATE_MUTATION = gql `
|
|
22
|
+
#graphql
|
|
23
|
+
|
|
24
|
+
mutation ManageDiscountDeactivate($id: ID!) {
|
|
25
|
+
discountCodeDeactivate(id: $id) {
|
|
26
|
+
codeDiscountNode {
|
|
27
|
+
id
|
|
28
|
+
}
|
|
29
|
+
userErrors {
|
|
30
|
+
field
|
|
31
|
+
message
|
|
32
|
+
code
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
`;
|
|
37
|
+
export async function setDiscountActive(client, id, active) {
|
|
38
|
+
const data = await requestWithRetry(client, active ? ACTIVATE_MUTATION : DEACTIVATE_MUTATION, { id });
|
|
39
|
+
const payload = active ? data.discountCodeActivate : data.discountCodeDeactivate;
|
|
40
|
+
checkUserErrors(payload.userErrors, active ? "activate discount" : "deactivate discount");
|
|
41
|
+
}
|
|
42
|
+
// ── Reschedule (start / end dates) ────────────────────────────────────
|
|
43
|
+
const RESCHEDULE_BASIC = gql `
|
|
44
|
+
#graphql
|
|
45
|
+
|
|
46
|
+
mutation ManageDiscountRescheduleBasic($id: ID!, $input: DiscountCodeBasicInput!) {
|
|
47
|
+
discountCodeBasicUpdate(id: $id, basicCodeDiscount: $input) {
|
|
48
|
+
codeDiscountNode {
|
|
49
|
+
id
|
|
50
|
+
}
|
|
51
|
+
userErrors {
|
|
52
|
+
field
|
|
53
|
+
message
|
|
54
|
+
code
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
`;
|
|
59
|
+
const RESCHEDULE_BXGY = gql `
|
|
60
|
+
#graphql
|
|
61
|
+
|
|
62
|
+
mutation ManageDiscountRescheduleBxgy($id: ID!, $input: DiscountCodeBxgyInput!) {
|
|
63
|
+
discountCodeBxgyUpdate(id: $id, bxgyCodeDiscount: $input) {
|
|
64
|
+
codeDiscountNode {
|
|
65
|
+
id
|
|
66
|
+
}
|
|
67
|
+
userErrors {
|
|
68
|
+
field
|
|
69
|
+
message
|
|
70
|
+
code
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
`;
|
|
75
|
+
const RESCHEDULE_FREE_SHIPPING = gql `
|
|
76
|
+
#graphql
|
|
77
|
+
|
|
78
|
+
mutation ManageDiscountRescheduleFreeShipping($id: ID!, $input: DiscountCodeFreeShippingInput!) {
|
|
79
|
+
discountCodeFreeShippingUpdate(id: $id, freeShippingCodeDiscount: $input) {
|
|
80
|
+
codeDiscountNode {
|
|
81
|
+
id
|
|
82
|
+
}
|
|
83
|
+
userErrors {
|
|
84
|
+
field
|
|
85
|
+
message
|
|
86
|
+
code
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
`;
|
|
91
|
+
const RESCHEDULE_APP = gql `
|
|
92
|
+
#graphql
|
|
93
|
+
|
|
94
|
+
mutation ManageDiscountRescheduleApp($id: ID!, $input: DiscountCodeAppInput!) {
|
|
95
|
+
discountCodeAppUpdate(id: $id, codeAppDiscount: $input) {
|
|
96
|
+
codeAppDiscount {
|
|
97
|
+
__typename
|
|
98
|
+
}
|
|
99
|
+
userErrors {
|
|
100
|
+
field
|
|
101
|
+
message
|
|
102
|
+
code
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
`;
|
|
107
|
+
const RESCHEDULE_BY_TYPE = {
|
|
108
|
+
DiscountCodeBasic: { query: RESCHEDULE_BASIC, payload: "discountCodeBasicUpdate" },
|
|
109
|
+
DiscountCodeBxgy: { query: RESCHEDULE_BXGY, payload: "discountCodeBxgyUpdate" },
|
|
110
|
+
DiscountCodeFreeShipping: { query: RESCHEDULE_FREE_SHIPPING, payload: "discountCodeFreeShippingUpdate" },
|
|
111
|
+
DiscountCodeApp: { query: RESCHEDULE_APP, payload: "discountCodeAppUpdate" },
|
|
112
|
+
};
|
|
113
|
+
/** Change start and/or end date. endsAt: null removes the end date. */
|
|
114
|
+
export async function rescheduleDiscount(client, id, discountType, dates) {
|
|
115
|
+
const target = RESCHEDULE_BY_TYPE[discountType];
|
|
116
|
+
if (!target)
|
|
117
|
+
throw new Error(`Cannot reschedule discounts of type ${discountType}`);
|
|
118
|
+
const input = {};
|
|
119
|
+
if (dates.startsAt !== undefined)
|
|
120
|
+
input.startsAt = dates.startsAt;
|
|
121
|
+
if (dates.endsAt !== undefined)
|
|
122
|
+
input.endsAt = dates.endsAt;
|
|
123
|
+
const data = await requestWithRetry(client, target.query, { id, input });
|
|
124
|
+
checkUserErrors(data[target.payload].userErrors, "reschedule discount");
|
|
125
|
+
}
|
|
126
|
+
// ── Bulk deletes (asynchronous Shopify jobs) ──────────────────────────
|
|
127
|
+
const DELETE_DISCOUNTS_MUTATION = gql `
|
|
128
|
+
#graphql
|
|
129
|
+
|
|
130
|
+
mutation DeleteDiscountsBulk($ids: [ID!]) {
|
|
131
|
+
discountCodeBulkDelete(ids: $ids) {
|
|
132
|
+
job {
|
|
133
|
+
id
|
|
134
|
+
done
|
|
135
|
+
}
|
|
136
|
+
userErrors {
|
|
137
|
+
field
|
|
138
|
+
message
|
|
139
|
+
code
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
`;
|
|
144
|
+
const REMOVE_CODES_MUTATION = gql `
|
|
145
|
+
#graphql
|
|
146
|
+
|
|
147
|
+
mutation RemoveDiscountCodesBulk($discountId: ID!, $ids: [ID!]) {
|
|
148
|
+
discountCodeRedeemCodeBulkDelete(discountId: $discountId, ids: $ids) {
|
|
149
|
+
job {
|
|
150
|
+
id
|
|
151
|
+
done
|
|
152
|
+
}
|
|
153
|
+
userErrors {
|
|
154
|
+
field
|
|
155
|
+
message
|
|
156
|
+
code
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
`;
|
|
161
|
+
const JOB_QUERY = gql `
|
|
162
|
+
#graphql
|
|
163
|
+
|
|
164
|
+
query ManageDiscountJob($id: ID!) {
|
|
165
|
+
job(id: $id) {
|
|
166
|
+
id
|
|
167
|
+
done
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
`;
|
|
171
|
+
/** Start deleting whole discounts. Returns the Shopify job id. */
|
|
172
|
+
export async function startDiscountBulkDelete(client, ids) {
|
|
173
|
+
const data = await requestWithRetry(client, DELETE_DISCOUNTS_MUTATION, { ids });
|
|
174
|
+
checkUserErrors(data.discountCodeBulkDelete.userErrors, "delete discounts");
|
|
175
|
+
return data.discountCodeBulkDelete.job.id;
|
|
176
|
+
}
|
|
177
|
+
/** Start removing codes (by DiscountRedeemCode GID) from one discount. Returns the Shopify job id. */
|
|
178
|
+
export async function startRedeemCodeBulkDelete(client, discountId, ids) {
|
|
179
|
+
const data = await requestWithRetry(client, REMOVE_CODES_MUTATION, { discountId, ids });
|
|
180
|
+
checkUserErrors(data.discountCodeRedeemCodeBulkDelete.userErrors, "remove discount codes");
|
|
181
|
+
return data.discountCodeRedeemCodeBulkDelete.job.id;
|
|
182
|
+
}
|
|
183
|
+
/** Poll a Shopify job until it is done or the deadline passes. Returns false if still running. */
|
|
184
|
+
export async function waitForShopifyJob(client, jobId, deadline) {
|
|
185
|
+
let delay = 500;
|
|
186
|
+
while (Date.now() < deadline) {
|
|
187
|
+
const data = await requestWithRetry(client, JOB_QUERY, { id: jobId });
|
|
188
|
+
if (data.job?.done)
|
|
189
|
+
return true;
|
|
190
|
+
await sleep(delay);
|
|
191
|
+
delay = Math.min(delay * 2, 4000);
|
|
192
|
+
}
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { sleep } from "../requestWithRetry.js";
|
|
4
|
+
import { splitCsvLine } from "./codeList.js";
|
|
5
|
+
export function csvCell(v) {
|
|
6
|
+
return /[",;\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
|
|
7
|
+
}
|
|
8
|
+
// Windows refuses to replace a file that something has open for a moment
|
|
9
|
+
// (virus scanner, Explorer preview, sync tool, an editor tab).
|
|
10
|
+
const LOCK_ERRORS = new Set(["EPERM", "EBUSY", "EACCES"]);
|
|
11
|
+
const isLockError = (e) => LOCK_ERRORS.has(e?.code);
|
|
12
|
+
/** rename that waits and retries while the target is locked (8 tries, ~7 s in total). */
|
|
13
|
+
async function renameWithRetry(from, to) {
|
|
14
|
+
for (let attempt = 0;; attempt++) {
|
|
15
|
+
try {
|
|
16
|
+
return await rename(from, to);
|
|
17
|
+
}
|
|
18
|
+
catch (e) {
|
|
19
|
+
if (!isLockError(e) || attempt >= 7)
|
|
20
|
+
throw e;
|
|
21
|
+
await sleep(200 * (attempt + 1));
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Write via temp file + rename, so a crash never leaves a half-written file.
|
|
27
|
+
* If the target stays locked it falls back to a direct write; if that fails
|
|
28
|
+
* too, it returns a warning instead of throwing (the data is in Shopify and
|
|
29
|
+
* the next save will try again). Other errors (disk full, bad path) still throw.
|
|
30
|
+
*/
|
|
31
|
+
export async function writeAtomic(path, content) {
|
|
32
|
+
const tmp = `${path}.tmp`;
|
|
33
|
+
try {
|
|
34
|
+
await writeFile(tmp, content, "utf8");
|
|
35
|
+
await renameWithRetry(tmp, path);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
if (!isLockError(e))
|
|
40
|
+
throw e;
|
|
41
|
+
await rm(tmp, { force: true }).catch(() => { });
|
|
42
|
+
try {
|
|
43
|
+
await writeFile(path, content, "utf8");
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
catch (e2) {
|
|
47
|
+
if (!isLockError(e2))
|
|
48
|
+
throw e2;
|
|
49
|
+
return `Could not write ${path}: file is locked by another program (virus scanner, preview, sync tool?). Close it; the next call writes it again.`;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Load an earlier run's result file, or null if there is none (new run). */
|
|
54
|
+
export async function readRunFile(path) {
|
|
55
|
+
if (!existsSync(path))
|
|
56
|
+
return null;
|
|
57
|
+
const lines = (await readFile(path, "utf8")).split(/\r?\n/).slice(1);
|
|
58
|
+
return lines
|
|
59
|
+
.filter((l) => l.trim())
|
|
60
|
+
.map((l) => {
|
|
61
|
+
const [code, status, detail] = splitCsvLine(l, ",");
|
|
62
|
+
return { code, status: status, detail: detail ?? "" };
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** Save the result file (all codes + status). Returns a warning if the file stayed locked. */
|
|
66
|
+
export function saveRun(runPath, rows) {
|
|
67
|
+
return writeAtomic(runPath, ["code,status,detail", ...rows.map((r) => [r.code, r.status, r.detail].map(csvCell).join(","))].join("\n") + "\n");
|
|
68
|
+
}
|
|
69
|
+
/** Save the partner file (usable codes only). Written once at the end, not after every call. */
|
|
70
|
+
export function savePartner(partnerPath, rows) {
|
|
71
|
+
const usable = rows.filter((r) => r.status === "attached" || r.status === "skipped");
|
|
72
|
+
return writeAtomic(partnerPath, ["code", ...usable.map((r) => csvCell(r.code))].join("\n") + "\n");
|
|
73
|
+
}
|
|
74
|
+
export function countStatuses(rows) {
|
|
75
|
+
const counts = {
|
|
76
|
+
pending: 0,
|
|
77
|
+
submitted: 0,
|
|
78
|
+
attached: 0,
|
|
79
|
+
skipped: 0,
|
|
80
|
+
taken: 0,
|
|
81
|
+
conflict: 0,
|
|
82
|
+
failed: 0,
|
|
83
|
+
};
|
|
84
|
+
for (const r of rows)
|
|
85
|
+
counts[r.status]++;
|
|
86
|
+
return counts;
|
|
87
|
+
}
|