n8n-nodes-nexlogiq-commerce 1.0.2 → 1.0.4

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.
@@ -295,35 +295,59 @@ class NexlogiqCommerce {
295
295
  }
296
296
  else if (resource === 'refund' && operation === 'create') {
297
297
  const orderId = this.getNodeParameter('orderId', i);
298
- const fullRefund = this.getNodeParameter('fullRefund', i);
299
- if (fullRefund) {
300
- const orderData = await GenericFunctions_1.shopifyApiRequest.call(this, 'GET', `/orders/${orderId}.json`, {}, {}, undefined, {}, i);
301
- const order = orderData.order;
302
- responseData = (await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds.json`, {
303
- refund: {
304
- currency: order.currency,
305
- refund_line_items: (order.line_items ?? []).map((lineItem) => ({
306
- line_item_id: lineItem.id,
307
- quantity: lineItem.quantity,
308
- restock_type: 'return',
309
- })),
310
- },
311
- }, {}, undefined, {}, i)).refund;
312
- }
313
- else {
314
- const lineItems = this.getNodeParameter('refund_line_items', i, {});
315
- const currency = this.getNodeParameter('currency', i, 'USD');
316
- responseData = (await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds.json`, {
317
- refund: {
318
- currency,
319
- refund_line_items: (lineItems.item ?? []).map((item) => ({
320
- line_item_id: item.line_item_id,
321
- quantity: item.quantity,
322
- restock_type: 'return',
323
- })),
324
- },
325
- }, {}, undefined, {}, i)).refund;
326
- }
298
+ const currency = this.getNodeParameter('currency', i, 'USD');
299
+ const notify = this.getNodeParameter('notify', i, true);
300
+ const refundShipping = this.getNodeParameter('refundShipping', i, true);
301
+ const note = this.getNodeParameter('note', i, '');
302
+ // 1. Fetch Order
303
+ const orderData = await GenericFunctions_1.shopifyApiRequest.call(this, 'GET', `/orders/${orderId}.json`, {}, {}, undefined, {}, i);
304
+ const order = orderData.order;
305
+ // 2. Fetch Locations
306
+ const locationsData = await GenericFunctions_1.shopifyApiRequest.call(this, 'GET', '/locations.json', {}, {}, undefined, {}, i);
307
+ const defaultLocationId = locationsData.locations.find((l) => l.active)?.id || locationsData.locations[0].id;
308
+ // 3. Auto-map Items
309
+ const refundLineItems = order.line_items.map((item) => {
310
+ let locId = defaultLocationId;
311
+ if (order.fulfillments && order.fulfillments.length > 0) {
312
+ const fulfillment = order.fulfillments.find((f) => f.line_items.some((li) => li.id === item.id));
313
+ if (fulfillment && fulfillment.location_id) {
314
+ locId = fulfillment.location_id;
315
+ }
316
+ }
317
+ return {
318
+ line_item_id: item.id,
319
+ quantity: item.quantity,
320
+ restock_type: 'return',
321
+ location_id: locId,
322
+ };
323
+ });
324
+ // 4. Calculate Refund
325
+ const calculatePayload = {
326
+ refund: {
327
+ shipping: { full_refund: refundShipping },
328
+ refund_line_items: refundLineItems,
329
+ }
330
+ };
331
+ const calculatedData = await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds/calculate.json`, calculatePayload, {}, undefined, {}, i);
332
+ const transactions = calculatedData.refund.transactions || [];
333
+ // 5. Execute Final Refund
334
+ const finalRefundPayload = {
335
+ refund: {
336
+ currency: currency,
337
+ notify: notify,
338
+ note: note,
339
+ shipping: { full_refund: refundShipping },
340
+ refund_line_items: refundLineItems,
341
+ transactions: transactions.map((t) => ({
342
+ parent_id: t.parent_id,
343
+ amount: t.amount,
344
+ kind: 'refund',
345
+ gateway: t.gateway
346
+ }))
347
+ }
348
+ };
349
+ const refundResponse = await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds.json`, finalRefundPayload, {}, undefined, {}, i);
350
+ responseData = refundResponse.refund;
327
351
  }
328
352
  else if (resource === 'webhook') {
329
353
  if (operation === 'create') {
@@ -11,4 +11,10 @@ export declare function shopifyGraphqlRequest(this: ShopifyContext, query: strin
11
11
  export declare function shopifyGraphqlConnectionAllItems(this: ShopifyContext, query: string, connectionPath: string[], variables?: IDataObject, itemIndex?: number, maxResults?: number): Promise<IDataObject[]>;
12
12
  export declare function shopifyApiRequestAllItems(this: ShopifyContext, propertyName: string, method: IHttpRequestMethods, resource: string, body?: any, query?: IDataObject, itemIndex?: number, maxResults?: number): Promise<any>;
13
13
  export declare function keysToSnakeCase(elements: IDataObject[] | IDataObject): IDataObject[];
14
+ export declare function smartModifyOrderItems(this: ShopifyContext, orderId: string, modifications: Array<{
15
+ lineItemId?: string;
16
+ reduceQuantityBy?: number;
17
+ newVariantId?: string;
18
+ newQuantity?: number;
19
+ }>, notifyCustomer?: boolean, itemIndex?: number): Promise<IDataObject>;
14
20
  export {};
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // nodes/Shopify nexlogiq/GenericFunctions.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.resolveShopifyCredentials = resolveShopifyCredentials;
4
5
  exports.shopifyApiRequest = shopifyApiRequest;
@@ -6,8 +7,10 @@ exports.shopifyGraphqlRequest = shopifyGraphqlRequest;
6
7
  exports.shopifyGraphqlConnectionAllItems = shopifyGraphqlConnectionAllItems;
7
8
  exports.shopifyApiRequestAllItems = shopifyApiRequestAllItems;
8
9
  exports.keysToSnakeCase = keysToSnakeCase;
10
+ exports.smartModifyOrderItems = smartModifyOrderItems;
9
11
  const change_case_1 = require("change-case");
10
12
  const n8n_workflow_1 = require("n8n-workflow");
13
+ const graphql_1 = require("./graphql"); // <--- NEW IMPORT
11
14
  const DEFAULT_SHOPIFY_API_VERSION = '2025-10';
12
15
  function sleep(ms) {
13
16
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -268,3 +271,80 @@ function keysToSnakeCase(elements) {
268
271
  }
269
272
  return list;
270
273
  }
274
+ // ==========================================
275
+ // NEW: Smart Order Modifer Engine (Nexlogiq OS)
276
+ // ==========================================
277
+ async function smartModifyOrderItems(orderId, modifications, notifyCustomer = true, itemIndex) {
278
+ const effectiveItemIndex = itemIndex ?? this.__itemIndex ?? 0;
279
+ // 1. Format Order ID for GraphQL
280
+ const formattedOrderId = orderId.includes('gid://') ? orderId : `gid://shopify/Order/${orderId}`;
281
+ // 2. Begin Edit Session
282
+ const beginResponse = await shopifyGraphqlRequest.call(this, graphql_1.SHOPIFY_GQL.orderEditBegin, { id: formattedOrderId }, effectiveItemIndex);
283
+ if (beginResponse?.data?.orderEditBegin?.userErrors?.length > 0) {
284
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Begin Edit Error: ${beginResponse.data.orderEditBegin.userErrors[0].message}`, { itemIndex: effectiveItemIndex });
285
+ }
286
+ const calculatedOrder = beginResponse?.data?.orderEditBegin?.calculatedOrder;
287
+ if (!calculatedOrder) {
288
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Failed to begin order edit session for ${orderId}`, { itemIndex: effectiveItemIndex });
289
+ }
290
+ const editSessionId = calculatedOrder.id;
291
+ const currentLineItems = calculatedOrder.lineItems?.edges?.map((edge) => edge.node) || [];
292
+ // 3. Process Modifications (Iterating through user changes safely)
293
+ for (const mod of modifications) {
294
+ // 3.a Partial or Full Remove (Mathematical Reduction)
295
+ if (mod.lineItemId && mod.reduceQuantityBy !== undefined) {
296
+ const formattedLineItemId = mod.lineItemId.includes('gid://') ? mod.lineItemId : `gid://shopify/CalculatedLineItem/${mod.lineItemId}`;
297
+ // Find the item inside the current edit session to get its current base quantity
298
+ const targetItem = currentLineItems.find((item) => item.id === formattedLineItemId || item.variant?.id?.endsWith(mod.lineItemId));
299
+ if (!targetItem) {
300
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Item ${mod.lineItemId} not found in order to reduce quantity.`, { itemIndex: effectiveItemIndex });
301
+ }
302
+ const targetQuantity = Math.max(0, targetItem.quantity - mod.reduceQuantityBy);
303
+ const reduceResponse = await shopifyGraphqlRequest.call(this, graphql_1.SHOPIFY_GQL.orderEditSetQuantity, {
304
+ id: editSessionId,
305
+ lineItemId: targetItem.id,
306
+ quantity: targetQuantity,
307
+ }, effectiveItemIndex);
308
+ if (reduceResponse?.data?.orderEditSetQuantity?.userErrors?.length > 0) {
309
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Set Quantity Error: ${reduceResponse.data.orderEditSetQuantity.userErrors[0].message}`, { itemIndex: effectiveItemIndex });
310
+ }
311
+ }
312
+ // 3.b Add new variant (Replacement or Addition)
313
+ if (mod.newVariantId && mod.newQuantity !== undefined) {
314
+ const formattedVariantId = mod.newVariantId.includes('gid://') ? mod.newVariantId : `gid://shopify/ProductVariant/${mod.newVariantId}`;
315
+ const addResponse = await shopifyGraphqlRequest.call(this, graphql_1.SHOPIFY_GQL.orderEditAddVariant, {
316
+ id: editSessionId,
317
+ variantId: formattedVariantId,
318
+ quantity: mod.newQuantity,
319
+ }, effectiveItemIndex);
320
+ if (addResponse?.data?.orderEditAddVariant?.userErrors?.length > 0) {
321
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Add Variant Error: ${addResponse.data.orderEditAddVariant.userErrors[0].message}`, { itemIndex: effectiveItemIndex });
322
+ }
323
+ }
324
+ }
325
+ // 4. Commit Edit and auto-issue invoice or hold refund
326
+ const commitResponse = await shopifyGraphqlRequest.call(this, graphql_1.SHOPIFY_GQL.orderEditCommit, {
327
+ id: editSessionId,
328
+ notifyCustomer,
329
+ }, effectiveItemIndex);
330
+ if (commitResponse?.data?.orderEditCommit?.userErrors?.length > 0) {
331
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Commit Edit Error: ${commitResponse.data.orderEditCommit.userErrors[0].message}`, { itemIndex: effectiveItemIndex });
332
+ }
333
+ // 5. Extract Financial Status to guide the AI Agent
334
+ const finalOrder = commitResponse?.data?.orderEditCommit?.order;
335
+ const outstandingAmount = parseFloat(finalOrder?.totalOutstandingSet?.presentmentMoney?.amount || "0");
336
+ const currency = finalOrder?.totalOutstandingSet?.presentmentMoney?.currencyCode || "USD";
337
+ let financialStatus = "balanced";
338
+ if (outstandingAmount > 0)
339
+ financialStatus = "outstanding_balance_due"; // Requires invoice payment from customer
340
+ if (outstandingAmount < 0)
341
+ financialStatus = "refund_required"; // Shop owes money to customer
342
+ return {
343
+ success: true,
344
+ order_id: finalOrder?.id?.split('/').pop() || orderId.split('/').pop(),
345
+ financial_status: financialStatus,
346
+ outstanding_balance: Math.abs(outstandingAmount),
347
+ currency: currency,
348
+ message: "Order items have been successfully modified.",
349
+ };
350
+ }
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // nodes/Shopify nexlogiq/OrderDescription.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.orderFields = exports.orderOperations = void 0;
4
5
  exports.orderOperations = [
@@ -37,6 +38,12 @@ exports.orderOperations = [
37
38
  description: 'Get many orders',
38
39
  action: 'Get many orders',
39
40
  },
41
+ {
42
+ name: 'Modify Items (Advanced)',
43
+ value: 'modifyItems',
44
+ description: 'Modify items in an order (Add, Remove, Replace) safely managing quantities and prices',
45
+ action: 'Modify order items',
46
+ },
40
47
  {
41
48
  name: 'Update',
42
49
  value: 'update',
@@ -132,7 +139,7 @@ exports.orderFields = [
132
139
  ],
133
140
  },
134
141
  /* -------------------------------------------------------------------------- */
135
- /* order:update, cancel, get */
142
+ /* order:update, cancel, get, modifyItems */
136
143
  /* -------------------------------------------------------------------------- */
137
144
  {
138
145
  displayName: 'Search By',
@@ -146,7 +153,7 @@ exports.orderFields = [
146
153
  displayOptions: {
147
154
  show: {
148
155
  resource: ['order'],
149
- operation: ['get'],
156
+ operation: ['get'], // searchBy is typically only for 'get' in this setup
150
157
  },
151
158
  },
152
159
  description: 'Choose how you want to find the order',
@@ -160,11 +167,82 @@ exports.orderFields = [
160
167
  displayOptions: {
161
168
  show: {
162
169
  resource: ['order'],
163
- operation: ['update', 'get', 'cancel'],
170
+ operation: ['update', 'get', 'cancel', 'modifyItems'], // أضفنا modifyItems هنا ليستفيد من هذا الحقل
164
171
  },
165
172
  },
166
173
  description: 'The System ID or the human-readable Order Number',
167
174
  },
175
+ /* -------------------------------------------------------------------------- */
176
+ /* order:modifyItems (NEW) */
177
+ /* -------------------------------------------------------------------------- */
178
+ {
179
+ displayName: 'Modifications',
180
+ name: 'modifications',
181
+ type: 'fixedCollection',
182
+ default: {},
183
+ typeOptions: {
184
+ multipleValues: true, // يسمح بإرسال تعديلات على أكثر من منتج في نفس الطلب
185
+ },
186
+ displayOptions: {
187
+ show: {
188
+ resource: ['order'],
189
+ operation: ['modifyItems'],
190
+ },
191
+ },
192
+ description: 'List of changes to apply to the order items (Add, Remove, or Replace)',
193
+ options: [
194
+ {
195
+ displayName: 'Modification',
196
+ name: 'modification',
197
+ values: [
198
+ {
199
+ displayName: 'Old Item ID (Line Item ID)',
200
+ name: 'lineItemId',
201
+ type: 'string',
202
+ default: '',
203
+ description: 'The ID of the item to remove/reduce. Leave blank if only adding new items.',
204
+ },
205
+ {
206
+ displayName: 'Reduce Quantity By',
207
+ name: 'reduceQuantityBy',
208
+ type: 'number',
209
+ default: 0,
210
+ description: 'How many pieces of the old item to remove. (e.g. 1)',
211
+ },
212
+ {
213
+ displayName: 'New Variant ID',
214
+ name: 'newVariantId',
215
+ type: 'string',
216
+ default: '',
217
+ description: 'The ID of the new product variant to add. Leave blank if only removing.',
218
+ },
219
+ {
220
+ displayName: 'New Item Quantity',
221
+ name: 'newQuantity',
222
+ type: 'number',
223
+ default: 0,
224
+ description: 'How many pieces of the new variant to add.',
225
+ },
226
+ ],
227
+ },
228
+ ],
229
+ },
230
+ {
231
+ displayName: 'Notify Customer',
232
+ name: 'notifyCustomer',
233
+ type: 'boolean',
234
+ default: true,
235
+ displayOptions: {
236
+ show: {
237
+ resource: ['order'],
238
+ operation: ['modifyItems'],
239
+ },
240
+ },
241
+ description: 'Whether to send an email to the customer with an invoice if there is a price difference',
242
+ },
243
+ /* -------------------------------------------------------------------------- */
244
+ /* order:update Fields */
245
+ /* -------------------------------------------------------------------------- */
168
246
  {
169
247
  displayName: 'Update Fields',
170
248
  name: 'updateFields',
@@ -14,10 +14,10 @@ exports.refundOperations = [
14
14
  },
15
15
  options: [
16
16
  {
17
- name: 'Create (Money Back)',
17
+ name: 'Create Full Refund',
18
18
  value: 'create',
19
- description: 'Refund a transaction to the customer',
20
- action: 'Create a refund',
19
+ description: 'Automatically refunds the entire order and restocks all items',
20
+ action: 'Create a full refund',
21
21
  },
22
22
  ],
23
23
  default: 'create',
@@ -36,102 +36,57 @@ exports.refundFields = [
36
36
  operation: ['create'],
37
37
  },
38
38
  },
39
- description: 'The ID of the order to refund',
39
+ description: 'The ID of the order to fully refund',
40
40
  },
41
41
  {
42
- displayName: 'Full Refund?',
43
- name: 'fullRefund',
44
- type: 'boolean',
45
- default: false,
42
+ displayName: 'Currency',
43
+ name: 'currency',
44
+ type: 'string',
45
+ default: 'USD',
46
46
  displayOptions: {
47
47
  show: {
48
48
  resource: ['refund'],
49
49
  operation: ['create'],
50
50
  },
51
51
  },
52
- description: 'If true, it will calculate the full amount automatically',
53
52
  },
54
53
  {
55
- displayName: 'Currency',
56
- name: 'currency',
57
- type: 'string',
58
- default: 'USD',
54
+ displayName: 'Notify Customer',
55
+ name: 'notify',
56
+ type: 'boolean',
57
+ default: true,
59
58
  displayOptions: {
60
59
  show: {
61
60
  resource: ['refund'],
62
61
  operation: ['create'],
63
- fullRefund: [false],
64
62
  },
65
63
  },
64
+ description: 'Whether to send a refund notification email to the customer',
66
65
  },
67
66
  {
68
- displayName: 'Refund Line Items',
69
- name: 'refund_line_items',
70
- type: 'fixedCollection',
71
- default: {},
72
- typeOptions: {
73
- multipleValues: true,
74
- },
67
+ displayName: 'Refund Shipping',
68
+ name: 'refundShipping',
69
+ type: 'boolean',
70
+ default: true,
75
71
  displayOptions: {
76
72
  show: {
77
73
  resource: ['refund'],
78
74
  operation: ['create'],
79
- fullRefund: [false],
80
75
  },
81
76
  },
82
- options: [
83
- {
84
- displayName: 'Items',
85
- name: 'item',
86
- values: [
87
- {
88
- displayName: 'Line Item ID',
89
- name: 'line_item_id',
90
- type: 'string',
91
- default: '',
92
- description: 'The ID of the product line item in the order',
93
- },
94
- {
95
- displayName: 'Quantity',
96
- name: 'quantity',
97
- type: 'number',
98
- default: 1,
99
- },
100
- {
101
- displayName: 'Restock Type',
102
- name: 'restock_type',
103
- type: 'options',
104
- options: [
105
- {
106
- name: 'Return (For fulfilled items)',
107
- value: 'return',
108
- },
109
- {
110
- name: 'Cancel (For unfulfilled items)',
111
- value: 'cancel',
112
- },
113
- {
114
- name: 'No Restock',
115
- value: 'no_restock',
116
- },
117
- ],
118
- default: 'return',
119
- description: 'How to handle the inventory restocking',
120
- },
121
- {
122
- displayName: 'Location ID',
123
- name: 'location_id',
124
- type: 'string',
125
- default: '',
126
- displayOptions: {
127
- hide: {
128
- restock_type: ['no_restock'],
129
- },
130
- },
131
- description: 'The ID of the location to restock the item. Map this dynamically from the Get Order node.',
132
- },
133
- ],
77
+ description: 'Whether to also refund the shipping costs',
78
+ },
79
+ {
80
+ displayName: 'Reason (Note)',
81
+ name: 'note',
82
+ type: 'string',
83
+ default: '',
84
+ displayOptions: {
85
+ show: {
86
+ resource: ['refund'],
87
+ operation: ['create'],
134
88
  },
135
- ],
89
+ },
90
+ description: 'An optional note attached to the refund (e.g., Requested by customer)',
136
91
  },
137
92
  ];
@@ -1,4 +1,5 @@
1
1
  "use strict";
2
+ // nodes/Shopify nexlogiq/Shopify.node.ts
2
3
  Object.defineProperty(exports, "__esModule", { value: true });
3
4
  exports.Shopify = void 0;
4
5
  exports.resolveShopifySystemOrderId = resolveShopifySystemOrderId;
@@ -259,6 +260,25 @@ class Shopify {
259
260
  responseData = await GenericFunctions_1.shopifyApiRequest.call(this, 'PUT', `/orders/${orderId}.json`, body, {});
260
261
  responseData = responseData.order;
261
262
  }
263
+ // =========================================================
264
+ // NEW: Modify Items Operation (Nexlogiq OS)
265
+ // =========================================================
266
+ if (operation === 'modifyItems') {
267
+ const orderId = this.getNodeParameter('orderId', i);
268
+ const notifyCustomer = this.getNodeParameter('notifyCustomer', i, true);
269
+ // جلب مصفوفة التعديلات من واجهة المستخدم
270
+ const modificationsRaw = this.getNodeParameter('modifications', i);
271
+ const rawMods = modificationsRaw?.modification || [];
272
+ // تنسيق البيانات لتجنب أي أخطاء متعلقة بأنواع البيانات (Strings to Numbers)
273
+ const formattedModifications = rawMods.map((mod) => ({
274
+ lineItemId: mod.lineItemId || undefined,
275
+ reduceQuantityBy: mod.reduceQuantityBy ? Number(mod.reduceQuantityBy) : undefined,
276
+ newVariantId: mod.newVariantId || undefined,
277
+ newQuantity: mod.newQuantity ? Number(mod.newQuantity) : undefined,
278
+ }));
279
+ // استدعاء الدالة الذكية (محرك التعديل)
280
+ responseData = await GenericFunctions_1.smartModifyOrderItems.call(this, orderId, formattedModifications, notifyCustomer, i);
281
+ }
262
282
  if (operation === 'get') {
263
283
  const searchBy = this.getNodeParameter('searchBy', i, 'id');
264
284
  const orderIdInput = this.getNodeParameter('orderId', i);
@@ -319,37 +339,59 @@ class Shopify {
319
339
  if (resource === 'refund') {
320
340
  if (operation === 'create') {
321
341
  const orderId = this.getNodeParameter('orderId', i);
322
- const fullRefund = this.getNodeParameter('fullRefund', i);
323
- let body = {};
324
- if (fullRefund) {
325
- const orderData = await GenericFunctions_1.shopifyApiRequest.call(this, 'GET', `/orders/${orderId}.json`, {}, {});
326
- const order = orderData.order;
327
- body = {
328
- refund: {
329
- currency: order.currency,
330
- refund_line_items: order.line_items.map((item) => ({
331
- line_item_id: item.id,
332
- quantity: item.quantity,
333
- restock_type: 'return',
334
- })),
335
- },
336
- };
337
- }
338
- else {
339
- const lineItems = this.getNodeParameter('refund_line_items', i);
340
- const currency = this.getNodeParameter('currency', i);
341
- body = {
342
- refund: {
343
- currency: currency,
344
- refund_line_items: lineItems.item.map((item) => ({
345
- line_item_id: item.line_item_id,
346
- quantity: item.quantity,
347
- restock_type: 'return',
348
- })),
349
- },
342
+ const currency = this.getNodeParameter('currency', i, 'USD');
343
+ const notify = this.getNodeParameter('notify', i, true);
344
+ const refundShipping = this.getNodeParameter('refundShipping', i, true);
345
+ const note = this.getNodeParameter('note', i, '');
346
+ // 1. جلب بيانات الطلب لمعرفة محتوياته
347
+ const orderData = await GenericFunctions_1.shopifyApiRequest.call(this, 'GET', `/orders/${orderId}.json`, {}, {});
348
+ const order = orderData.order;
349
+ // 2. جلب مستودعات المتجر لمعرفة الـ Location ID الافتراضي
350
+ const locationsData = await GenericFunctions_1.shopifyApiRequest.call(this, 'GET', '/locations.json', {}, {});
351
+ const defaultLocationId = locationsData.locations.find((l) => l.active)?.id || locationsData.locations[0].id;
352
+ // 3. بناء مصفوفة المنتجات المسترجعة مع تحديد المستودع الصحيح لكل منتج آلياً
353
+ const refundLineItems = order.line_items.map((item) => {
354
+ let locId = defaultLocationId;
355
+ // إذا تم شحن المنتج مسبقاً، يجب إعادته للمستودع الذي خرج منه
356
+ if (order.fulfillments && order.fulfillments.length > 0) {
357
+ const fulfillment = order.fulfillments.find((f) => f.line_items.some((li) => li.id === item.id));
358
+ if (fulfillment && fulfillment.location_id) {
359
+ locId = fulfillment.location_id;
360
+ }
361
+ }
362
+ return {
363
+ line_item_id: item.id,
364
+ quantity: item.quantity,
365
+ restock_type: 'return', // إعادة المخزون
366
+ location_id: locId, // المستودع المكتشف آلياً
350
367
  };
351
- }
352
- responseData = await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds.json`, body, {});
368
+ });
369
+ // 4. طلب "حساب المرتجع" من شوبيفاي لجلب المعاملات المالية (Transactions) لإرجاع الأموال حقيقةً
370
+ const calculatePayload = {
371
+ refund: {
372
+ shipping: { full_refund: refundShipping },
373
+ refund_line_items: refundLineItems,
374
+ }
375
+ };
376
+ const calculatedData = await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds/calculate.json`, calculatePayload, {});
377
+ const transactions = calculatedData.refund.transactions || [];
378
+ // 5. إرسال أمر الاسترجاع الكلي النهائي (الأموال + المنتجات)
379
+ const finalRefundPayload = {
380
+ refund: {
381
+ currency: currency,
382
+ notify: notify,
383
+ note: note,
384
+ shipping: { full_refund: refundShipping },
385
+ refund_line_items: refundLineItems,
386
+ transactions: transactions.map((t) => ({
387
+ parent_id: t.parent_id,
388
+ amount: t.amount,
389
+ kind: 'refund',
390
+ gateway: t.gateway
391
+ }))
392
+ }
393
+ };
394
+ responseData = await GenericFunctions_1.shopifyApiRequest.call(this, 'POST', `/orders/${orderId}/refunds.json`, finalRefundPayload, {});
353
395
  responseData = responseData.refund;
354
396
  }
355
397
  }
@@ -4,4 +4,8 @@ export declare const SHOPIFY_GQL: {
4
4
  products: string;
5
5
  draftOrders: string;
6
6
  webhookSubscriptions: string;
7
+ orderEditBegin: string;
8
+ orderEditSetQuantity: string;
9
+ orderEditAddVariant: string;
10
+ orderEditCommit: string;
7
11
  };