1 | |
2 |
|
3 | |
4 | * Complete Draft Order |
5 | * Turn a draft order into an order. By default the order is marked as paid; set payment_pending to create it with "due on receipt" payment terms instead, so payment can be collected later (needs the write_payment_terms scope). |
6 | */ |
7 | export async function main( |
8 | auth: RT.Shopify, |
9 | draft_order_id: string, |
10 | payment_pending: boolean | undefined |
11 | ) { |
12 | const id = draft_order_id.startsWith("gid://") |
13 | ? draft_order_id |
14 | : `gid://shopify/DraftOrder/${draft_order_id}` |
15 | const endpoint = `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json` |
16 | const headers = { |
17 | "X-Shopify-Access-Token": auth.token, |
18 | "Content-Type": "application/json", |
19 | Accept: "application/json", |
20 | } |
21 | const call = async (body: { query: string; variables?: object }) => { |
22 | const response = await fetch(endpoint, { |
23 | method: "POST", |
24 | headers, |
25 | body: JSON.stringify(body), |
26 | }) |
27 | if (!response.ok) { |
28 | throw new Error(`${response.status} ${await response.text()}`) |
29 | } |
30 | const { data, errors } = await response.json() |
31 | if (errors) { |
32 | throw new Error(JSON.stringify(errors)) |
33 | } |
34 | return data |
35 | } |
36 |
|
37 | |
38 | if (payment_pending) { |
39 | const { paymentTermsTemplates } = await call({ |
40 | query: `query { paymentTermsTemplates(paymentTermsType: RECEIPT) { id } }`, |
41 | }) |
42 | const { draftOrderUpdate } = await call({ |
43 | query: `mutation ($id: ID!, $input: DraftOrderInput!) { draftOrderUpdate(id: $id, input: $input) { draftOrder { id } userErrors { field message } } }`, |
44 | variables: { |
45 | id, |
46 | input: { |
47 | paymentTerms: { paymentTermsTemplateId: paymentTermsTemplates[0].id }, |
48 | }, |
49 | }, |
50 | }) |
51 | if (draftOrderUpdate.userErrors.length) { |
52 | throw new Error(JSON.stringify(draftOrderUpdate.userErrors)) |
53 | } |
54 | } |
55 |
|
56 | const data = await call({ |
57 | query: `mutation ($id: ID!) { draftOrderComplete(id: $id) { draftOrder { id name status completedAt order { id legacyResourceId name displayFinancialStatus displayFulfillmentStatus totalPriceSet { shopMoney { amount currencyCode } } } } userErrors { field message } } }`, |
58 | variables: { id }, |
59 | }) |
60 |
|
61 | if (data.draftOrderComplete.userErrors.length) { |
62 | throw new Error(JSON.stringify(data.draftOrderComplete.userErrors)) |
63 | } |
64 |
|
65 | return data.draftOrderComplete |
66 | } |
67 |
|