order-management 0.0.33 → 0.0.34

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.
@@ -1,706 +1,10 @@
1
1
  "use strict";
2
- const adminSdk = require("@medusajs/admin-sdk");
3
- const react = require("react");
4
2
  const jsxRuntime = require("react/jsx-runtime");
3
+ const react = require("react");
4
+ const adminSdk = require("@medusajs/admin-sdk");
5
5
  const ui = require("@medusajs/ui");
6
6
  const icons = require("@medusajs/icons");
7
7
  const reactRouterDom = require("react-router-dom");
8
- const ExchangeAutofillWidget = () => {
9
- const hasProcessedRef = react.useRef(false);
10
- react.useEffect(() => {
11
- if (hasProcessedRef.current) {
12
- return;
13
- }
14
- const path = window.location.pathname;
15
- const isExchangePage = path.includes("/orders/") && path.includes("/exchanges");
16
- if (!isExchangePage) {
17
- return;
18
- }
19
- console.log("[Exchange Autofill] Widget loaded on exchange page:", path);
20
- const searchParams = new URLSearchParams(window.location.search);
21
- const inboundParam = searchParams.get("inbound");
22
- const outboundParam = searchParams.get("outbound");
23
- console.log("[Exchange Autofill] Query params:", { inboundParam: !!inboundParam, outboundParam: !!outboundParam });
24
- if (!inboundParam && !outboundParam) {
25
- console.log("[Exchange Autofill] No query parameters found, exiting");
26
- return;
27
- }
28
- let inboundItems = [];
29
- let outboundItems = [];
30
- try {
31
- if (inboundParam) {
32
- const decoded = atob(decodeURIComponent(inboundParam));
33
- inboundItems = JSON.parse(decoded);
34
- }
35
- if (outboundParam) {
36
- const decoded = atob(decodeURIComponent(outboundParam));
37
- outboundItems = JSON.parse(decoded);
38
- }
39
- } catch (error) {
40
- console.error("[Exchange Autofill] Failed to decode query parameters:", error);
41
- return;
42
- }
43
- console.log("[Exchange Autofill] Decoded items:", {
44
- inboundCount: inboundItems.length,
45
- outboundCount: outboundItems.length,
46
- inboundItems,
47
- outboundItems
48
- });
49
- if (inboundItems.length === 0 && outboundItems.length === 0) {
50
- console.log("[Exchange Autofill] No items to fill, exiting");
51
- return;
52
- }
53
- hasProcessedRef.current = true;
54
- const fillForm = () => {
55
- try {
56
- let attempts = 0;
57
- const maxAttempts = 30;
58
- let inboundFilled = false;
59
- let outboundFilled = false;
60
- const tryFill = () => {
61
- attempts++;
62
- console.log(`[Exchange Autofill] Attempt ${attempts}/${maxAttempts}`);
63
- const inboundSection = findInboundSection();
64
- const outboundSection = findOutboundSection();
65
- console.log("[Exchange Autofill] Sections found:", {
66
- inbound: !!inboundSection,
67
- outbound: !!outboundSection
68
- });
69
- if (!inboundFilled && inboundItems.length > 0) {
70
- if (inboundSection) {
71
- fillInboundItems(inboundItems);
72
- inboundFilled = true;
73
- }
74
- }
75
- if (!outboundFilled && outboundItems.length > 0) {
76
- if (outboundSection) {
77
- fillOutboundItems(outboundItems);
78
- outboundFilled = true;
79
- }
80
- }
81
- if (attempts < maxAttempts && (!inboundFilled || !outboundFilled)) {
82
- setTimeout(tryFill, 500);
83
- } else if (attempts >= maxAttempts) {
84
- console.warn("[Exchange Autofill] Max attempts reached. Sections found:", {
85
- inbound: !!inboundSection,
86
- outbound: !!outboundSection
87
- });
88
- }
89
- };
90
- tryFill();
91
- } catch (error) {
92
- console.error("[Exchange Autofill] Error filling form:", error);
93
- }
94
- };
95
- setTimeout(fillForm, 1500);
96
- }, []);
97
- return null;
98
- };
99
- function fillInboundItems(items) {
100
- var _a;
101
- if (items.length === 0) return;
102
- console.log("[Exchange Autofill] Attempting to fill inbound items:", items);
103
- try {
104
- const inboundSection = findInboundSection();
105
- console.log("[Exchange Autofill] Found inbound section:", !!inboundSection);
106
- if (!inboundSection) {
107
- console.warn("[Exchange Autofill] Could not find inbound section");
108
- return;
109
- }
110
- const allLinks = inboundSection.querySelectorAll("a, button");
111
- let addItemsButton = null;
112
- for (const link of Array.from(allLinks)) {
113
- const text = ((_a = link.textContent) == null ? void 0 : _a.toLowerCase().trim()) || "";
114
- if (text.includes("add") && (text.includes("item") || text.includes("items"))) {
115
- addItemsButton = link;
116
- console.log("[Exchange Autofill] Found Add items button:", text);
117
- break;
118
- }
119
- }
120
- if (addItemsButton) {
121
- const existingItems = inboundSection.querySelectorAll('[data-testid*="item"], [data-testid*="line-item"], table tbody tr, [class*="item"]');
122
- console.log("[Exchange Autofill] Existing items count:", existingItems.length);
123
- if (existingItems.length === 0) {
124
- console.log("[Exchange Autofill] Clicking Add items button");
125
- addItemsButton.click();
126
- setTimeout(() => {
127
- waitForModal(8e3).then((modal) => {
128
- if (modal) {
129
- console.log("[Exchange Autofill] Modal appeared, waiting for content to load...");
130
- setTimeout(() => {
131
- console.log("[Exchange Autofill] Selecting items within modal");
132
- selectInboundItems(items, modal);
133
- }, 1500);
134
- } else {
135
- console.warn("[Exchange Autofill] Modal did not appear, trying direct selection");
136
- selectInboundItems(items);
137
- }
138
- });
139
- }, 500);
140
- } else {
141
- console.log("[Exchange Autofill] Items already added, skipping");
142
- }
143
- } else {
144
- console.warn("[Exchange Autofill] Could not find Add items button, trying direct selection");
145
- selectInboundItems(items);
146
- }
147
- } catch (error) {
148
- console.error("[Exchange Autofill] Error filling inbound items:", error);
149
- }
150
- }
151
- function fillOutboundItems(items) {
152
- var _a;
153
- if (items.length === 0) return;
154
- console.log("[Exchange Autofill] Attempting to fill outbound items:", items);
155
- try {
156
- const outboundSection = findOutboundSection();
157
- console.log("[Exchange Autofill] Found outbound section:", !!outboundSection);
158
- if (!outboundSection) {
159
- console.warn("[Exchange Autofill] Could not find outbound section");
160
- return;
161
- }
162
- const allLinks = outboundSection.querySelectorAll("a, button");
163
- let addItemsButton = null;
164
- for (const link of Array.from(allLinks)) {
165
- const text = ((_a = link.textContent) == null ? void 0 : _a.toLowerCase().trim()) || "";
166
- if (text.includes("add") && (text.includes("item") || text.includes("items"))) {
167
- addItemsButton = link;
168
- console.log("[Exchange Autofill] Found Add items button:", text);
169
- break;
170
- }
171
- }
172
- if (addItemsButton) {
173
- const existingItems = outboundSection.querySelectorAll('[data-testid*="item"], [data-testid*="variant"], table tbody tr, [class*="item"]');
174
- console.log("[Exchange Autofill] Existing items count:", existingItems.length);
175
- if (existingItems.length === 0) {
176
- console.log("[Exchange Autofill] Clicking Add items button");
177
- addItemsButton.click();
178
- setTimeout(() => {
179
- waitForModal(8e3).then((modal) => {
180
- if (modal) {
181
- console.log("[Exchange Autofill] Modal appeared, waiting for content to load...");
182
- setTimeout(() => {
183
- console.log("[Exchange Autofill] Selecting items within modal");
184
- selectOutboundItems(items, modal);
185
- }, 1500);
186
- } else {
187
- console.warn("[Exchange Autofill] Modal did not appear, trying direct selection");
188
- selectOutboundItems(items);
189
- }
190
- });
191
- }, 500);
192
- } else {
193
- console.log("[Exchange Autofill] Items already added, skipping");
194
- }
195
- } else {
196
- console.warn("[Exchange Autofill] Could not find Add items button, trying direct selection");
197
- selectOutboundItems(items);
198
- }
199
- } catch (error) {
200
- console.error("[Exchange Autofill] Error filling outbound items:", error);
201
- }
202
- }
203
- function waitForModal(timeout = 5e3) {
204
- return new Promise((resolve) => {
205
- const startTime = Date.now();
206
- let attemptCount = 0;
207
- const checkForModal = () => {
208
- var _a;
209
- attemptCount++;
210
- console.log(`[Exchange Autofill] Checking for modal (attempt ${attemptCount})...`);
211
- const modalSelectors = [
212
- '[role="dialog"]',
213
- "[data-modal]",
214
- '[data-testid*="modal"]',
215
- '[data-testid*="dialog"]',
216
- '[class*="Modal"]',
217
- '[class*="Dialog"]',
218
- '[class*="modal"]',
219
- '[class*="dialog"]',
220
- '[id*="modal"]',
221
- '[id*="dialog"]'
222
- ];
223
- for (const selector of modalSelectors) {
224
- try {
225
- const modal = document.querySelector(selector);
226
- if (modal) {
227
- const isVisible = modal.offsetParent !== null || window.getComputedStyle(modal).display !== "none" || window.getComputedStyle(modal).visibility !== "hidden";
228
- if (isVisible) {
229
- console.log(`[Exchange Autofill] Found modal via selector: ${selector}`);
230
- console.log(`[Exchange Autofill] Modal element:`, modal);
231
- resolve(modal);
232
- return;
233
- }
234
- }
235
- } catch {
236
- }
237
- }
238
- const allElements = document.querySelectorAll("div, section");
239
- for (const element of Array.from(allElements)) {
240
- const htmlElement = element;
241
- const style = window.getComputedStyle(htmlElement);
242
- const zIndex = parseInt(style.zIndex || "0", 10);
243
- if (zIndex > 1e3 && htmlElement.offsetParent !== null) {
244
- const text = ((_a = htmlElement.textContent) == null ? void 0 : _a.toLowerCase()) || "";
245
- if (text.includes("add") || text.includes("select") || text.includes("item")) {
246
- console.log("[Exchange Autofill] Found modal via z-index and content");
247
- resolve(htmlElement);
248
- return;
249
- }
250
- }
251
- }
252
- if (Date.now() - startTime >= timeout) {
253
- console.warn(`[Exchange Autofill] Modal not found within ${timeout}ms timeout after ${attemptCount} attempts`);
254
- console.log(`[Exchange Autofill] Current page structure - dialogs:`, document.querySelectorAll('[role="dialog"]').length);
255
- console.log(`[Exchange Autofill] Current page structure - modals:`, document.querySelectorAll('[class*="modal" i]').length);
256
- resolve(null);
257
- return;
258
- }
259
- setTimeout(checkForModal, 300);
260
- };
261
- checkForModal();
262
- });
263
- }
264
- function findInboundSection() {
265
- var _a, _b;
266
- const selectors = [
267
- '[data-testid*="inbound"]',
268
- '[aria-label*="inbound" i]',
269
- 'h2:contains("Inbound"), h3:contains("Inbound")'
270
- ];
271
- for (const selector of selectors) {
272
- try {
273
- const element = document.querySelector(selector);
274
- if (element) {
275
- return element.closest("div, section, fieldset") || element;
276
- }
277
- } catch {
278
- }
279
- }
280
- const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6, [class*="heading"]');
281
- for (const heading of Array.from(headings)) {
282
- const text = ((_a = heading.textContent) == null ? void 0 : _a.toLowerCase()) || "";
283
- if (text.includes("inbound")) {
284
- const container = heading.closest("div, section, fieldset, form");
285
- if (container) {
286
- console.log("[Exchange Autofill] Found inbound section via heading:", text);
287
- return container;
288
- }
289
- }
290
- }
291
- const allElements = document.querySelectorAll('section, div[class*="section"], fieldset');
292
- for (const element of Array.from(allElements)) {
293
- const text = ((_b = element.textContent) == null ? void 0 : _b.toLowerCase()) || "";
294
- if (text.includes("inbound") && (text.includes("add items") || text.includes("add item") || text.includes("add"))) {
295
- console.log("[Exchange Autofill] Found inbound section via text search");
296
- return element;
297
- }
298
- }
299
- return null;
300
- }
301
- function findOutboundSection() {
302
- var _a, _b;
303
- const selectors = [
304
- '[data-testid*="outbound"]',
305
- '[aria-label*="outbound" i]',
306
- 'h2:contains("Outbound"), h3:contains("Outbound")'
307
- ];
308
- for (const selector of selectors) {
309
- try {
310
- const element = document.querySelector(selector);
311
- if (element) {
312
- return element.closest("div, section, fieldset") || element;
313
- }
314
- } catch {
315
- continue;
316
- }
317
- }
318
- const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6, [class*="heading"]');
319
- for (const heading of Array.from(headings)) {
320
- const text = ((_a = heading.textContent) == null ? void 0 : _a.toLowerCase()) || "";
321
- if (text.includes("outbound")) {
322
- const container = heading.closest("div, section, fieldset, form");
323
- if (container) {
324
- console.log("[Exchange Autofill] Found outbound section via heading:", text);
325
- return container;
326
- }
327
- }
328
- }
329
- const allElements = document.querySelectorAll('section, div[class*="section"], fieldset');
330
- for (const element of Array.from(allElements)) {
331
- const text = ((_b = element.textContent) == null ? void 0 : _b.toLowerCase()) || "";
332
- if (text.includes("outbound") && (text.includes("add items") || text.includes("add item") || text.includes("add"))) {
333
- console.log("[Exchange Autofill] Found outbound section via text search");
334
- return element;
335
- }
336
- }
337
- return null;
338
- }
339
- function selectInboundItems(items, modalContainer) {
340
- var _a, _b, _c, _d;
341
- let itemsSelected = 0;
342
- const searchRoot = modalContainer || document;
343
- console.log("[Exchange Autofill] Selecting inbound items:", items);
344
- console.log("[Exchange Autofill] Search root:", modalContainer ? "modal container" : "entire document");
345
- if (modalContainer) {
346
- console.log("[Exchange Autofill] Modal container HTML:", modalContainer.outerHTML.substring(0, 500));
347
- }
348
- for (const item of items) {
349
- try {
350
- const selectors = [
351
- `input[value="${item.id}"]`,
352
- `input[data-item-id="${item.id}"]`,
353
- `[data-line-item-id="${item.id}"]`,
354
- `[data-testid*="${item.id}"]`,
355
- `[id*="${item.id}"]`
356
- ];
357
- let itemInput = null;
358
- for (const selector of selectors) {
359
- try {
360
- itemInput = searchRoot.querySelector(selector);
361
- if (itemInput) {
362
- console.log(`[Exchange Autofill] Found inbound item input via selector: ${selector}`);
363
- break;
364
- }
365
- } catch (e) {
366
- }
367
- }
368
- if (!itemInput) {
369
- const allInputs = searchRoot.querySelectorAll('input[type="checkbox"], input[type="radio"], input[type="text"], input');
370
- console.log(`[Exchange Autofill] Checking ${allInputs.length} inputs for item ${item.id}`);
371
- for (const input of Array.from(allInputs)) {
372
- const row = input.closest('tr, div, li, [role="row"], td, th');
373
- const rowText = (row == null ? void 0 : row.textContent) || "";
374
- const inputValue = input.value || "";
375
- const inputId = input.id || "";
376
- const inputName = input.name || "";
377
- if (rowText.includes(item.id) || inputValue.includes(item.id) || inputId.includes(item.id) || inputName.includes(item.id) || rowText.includes(item.id.substring(0, 15))) {
378
- itemInput = input;
379
- console.log(`[Exchange Autofill] Found inbound item input via text search - row text: ${rowText.substring(0, 100)}`);
380
- break;
381
- }
382
- }
383
- }
384
- if (!itemInput) {
385
- const allRows = searchRoot.querySelectorAll('tr, [role="row"], li, div[class*="item"], div[class*="row"], div[class*="Item"], td, [data-testid*="row"]');
386
- console.log(`[Exchange Autofill] Checking ${allRows.length} rows for item ${item.id}`);
387
- for (const row of Array.from(allRows)) {
388
- const rowText = row.textContent || "";
389
- if (rowText.includes(item.id) || rowText.includes(item.id.substring(0, 15)) || rowText.includes(item.id.substring(item.id.length - 10))) {
390
- itemInput = row.querySelector('input[type="checkbox"], input[type="radio"], input');
391
- if (!itemInput) {
392
- const clickable = row.querySelector('button, [role="button"], div[onclick], div[class*="select"]');
393
- if (clickable) {
394
- console.log(`[Exchange Autofill] Found clickable element in row, clicking it`);
395
- clickable.click();
396
- setTimeout(() => {
397
- itemInput = row.querySelector('input[type="checkbox"], input[type="radio"], input');
398
- }, 300);
399
- }
400
- }
401
- if (itemInput) {
402
- console.log(`[Exchange Autofill] Found inbound item input in row containing: ${rowText.substring(0, 100)}`);
403
- break;
404
- }
405
- }
406
- }
407
- }
408
- if (!itemInput) {
409
- const clickableElements = searchRoot.querySelectorAll('button, div[role="button"], div[class*="select"], div[class*="item"], span, label');
410
- console.log(`[Exchange Autofill] Checking ${clickableElements.length} clickable elements for item ${item.id}`);
411
- for (const element of Array.from(clickableElements)) {
412
- const elementText = element.textContent || "";
413
- if (elementText.includes(item.id) || elementText.includes(item.id.substring(0, 15))) {
414
- const nearbyInput = element.querySelector("input") || ((_a = element.closest("tr, div, li")) == null ? void 0 : _a.querySelector("input")) || ((_b = element.parentElement) == null ? void 0 : _b.querySelector("input"));
415
- if (nearbyInput) {
416
- itemInput = nearbyInput;
417
- console.log(`[Exchange Autofill] Found inbound item input near clickable element`);
418
- break;
419
- } else {
420
- console.log(`[Exchange Autofill] Clicking element containing item ID: ${elementText.substring(0, 50)}`);
421
- element.click();
422
- setTimeout(() => {
423
- const newInput = searchRoot.querySelector(`input[value*="${item.id.substring(0, 10)}"]`);
424
- if (newInput) {
425
- itemInput = newInput;
426
- }
427
- }, 500);
428
- }
429
- }
430
- }
431
- }
432
- if (itemInput) {
433
- if (itemInput.type === "checkbox" || itemInput.type === "radio") {
434
- itemInput.checked = true;
435
- const nativeInputValueSetter = (_c = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")) == null ? void 0 : _c.set;
436
- if (nativeInputValueSetter) {
437
- nativeInputValueSetter.call(itemInput, itemInput.value);
438
- }
439
- itemInput.dispatchEvent(new Event("input", { bubbles: true }));
440
- itemInput.dispatchEvent(new Event("change", { bubbles: true }));
441
- itemInput.dispatchEvent(new MouseEvent("click", { bubbles: true }));
442
- } else {
443
- itemInput.click();
444
- }
445
- const row = itemInput.closest('tr, div, li, [role="row"]');
446
- if (row) {
447
- const quantityInput = row.querySelector('input[type="number"]');
448
- if (quantityInput) {
449
- quantityInput.value = String(item.quantity);
450
- const nativeInputValueSetter = (_d = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")) == null ? void 0 : _d.set;
451
- if (nativeInputValueSetter) {
452
- nativeInputValueSetter.call(quantityInput, String(item.quantity));
453
- }
454
- quantityInput.dispatchEvent(new Event("input", { bubbles: true }));
455
- quantityInput.dispatchEvent(new Event("change", { bubbles: true }));
456
- console.log(`[Exchange Autofill] Set quantity for inbound item ${item.id}: ${item.quantity}`);
457
- }
458
- }
459
- itemsSelected++;
460
- console.log(`[Exchange Autofill] Selected inbound item: ${item.id}`);
461
- } else {
462
- console.warn(`[Exchange Autofill] Could not find input for inbound item ${item.id}`);
463
- const allElements = searchRoot.querySelectorAll("*");
464
- for (const element of Array.from(allElements)) {
465
- const text = element.textContent || "";
466
- const elementId = element.id || "";
467
- const elementClass = element.className || "";
468
- if (text.includes(item.id) || elementId.includes(item.id) || elementClass.includes(item.id.substring(0, 10))) {
469
- console.log(`[Exchange Autofill] Found element containing item ID, attempting to click:`, {
470
- tag: element.tagName,
471
- id: elementId,
472
- text: text.substring(0, 50)
473
- });
474
- element.click();
475
- setTimeout(() => {
476
- ;
477
- element.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
478
- }, 200);
479
- break;
480
- }
481
- }
482
- if (searchRoot !== document) {
483
- const allText = searchRoot.textContent || "";
484
- console.log(`[Exchange Autofill] Modal content preview (first 500 chars):`, allText.substring(0, 500));
485
- const allInputs = searchRoot.querySelectorAll("input");
486
- console.log(`[Exchange Autofill] Found ${allInputs.length} inputs in modal`);
487
- const allRows = searchRoot.querySelectorAll('tr, [role="row"], li, div');
488
- console.log(`[Exchange Autofill] Found ${allRows.length} potential rows in modal`);
489
- Array.from(allRows).slice(0, 5).forEach((row, idx) => {
490
- var _a2;
491
- console.log(`[Exchange Autofill] Row ${idx} text:`, (_a2 = row.textContent) == null ? void 0 : _a2.substring(0, 100));
492
- });
493
- }
494
- }
495
- } catch (error) {
496
- console.warn(`[Exchange Autofill] Error selecting inbound item ${item.id}:`, error);
497
- }
498
- }
499
- if (itemsSelected > 0) {
500
- setTimeout(() => {
501
- var _a2;
502
- const buttons = searchRoot.querySelectorAll('button, [role="button"]');
503
- for (const buttonEl of Array.from(buttons)) {
504
- const text = ((_a2 = buttonEl.textContent) == null ? void 0 : _a2.toLowerCase().trim()) || "";
505
- if (text.includes("add") || text.includes("confirm") || text.includes("select") || text.includes("save")) {
506
- const button = buttonEl;
507
- const buttonType = "type" in button ? button.type : void 0;
508
- if (!buttonType || buttonType === "submit" || buttonType === "button") {
509
- console.log("[Exchange Autofill] Clicking button:", text);
510
- button.click();
511
- break;
512
- }
513
- }
514
- }
515
- }, 1e3);
516
- } else {
517
- console.warn("[Exchange Autofill] No inbound items were selected");
518
- }
519
- }
520
- function selectOutboundItems(items, modalContainer) {
521
- var _a, _b, _c, _d;
522
- let itemsSelected = 0;
523
- const searchRoot = modalContainer || document;
524
- console.log("[Exchange Autofill] Selecting outbound items:", items);
525
- console.log("[Exchange Autofill] Search root:", modalContainer ? "modal container" : "entire document");
526
- if (modalContainer) {
527
- console.log("[Exchange Autofill] Modal container HTML:", modalContainer.outerHTML.substring(0, 500));
528
- }
529
- for (const item of items) {
530
- try {
531
- const selectors = [
532
- `input[value="${item.variant_id}"]`,
533
- `input[data-variant-id="${item.variant_id}"]`,
534
- `[data-variant-id="${item.variant_id}"]`,
535
- `[data-testid*="${item.variant_id}"]`,
536
- `[id*="${item.variant_id}"]`
537
- ];
538
- let variantInput = null;
539
- for (const selector of selectors) {
540
- try {
541
- variantInput = searchRoot.querySelector(selector);
542
- if (variantInput) {
543
- console.log(`[Exchange Autofill] Found outbound item input via selector: ${selector}`);
544
- break;
545
- }
546
- } catch (e) {
547
- }
548
- }
549
- if (!variantInput) {
550
- const allInputs = searchRoot.querySelectorAll('input[type="checkbox"], input[type="radio"], input[type="text"], input');
551
- console.log(`[Exchange Autofill] Checking ${allInputs.length} inputs for variant ${item.variant_id}`);
552
- for (const input of Array.from(allInputs)) {
553
- const row = input.closest('tr, div, li, [role="row"], td, th');
554
- const rowText = (row == null ? void 0 : row.textContent) || "";
555
- const inputValue = input.value || "";
556
- const inputId = input.id || "";
557
- const inputName = input.name || "";
558
- if (rowText.includes(item.variant_id) || inputValue.includes(item.variant_id) || inputId.includes(item.variant_id) || inputName.includes(item.variant_id) || rowText.includes(item.variant_id.substring(0, 15))) {
559
- variantInput = input;
560
- console.log(`[Exchange Autofill] Found outbound item input via text search - row text: ${rowText.substring(0, 100)}`);
561
- break;
562
- }
563
- }
564
- }
565
- if (!variantInput) {
566
- const allRows = searchRoot.querySelectorAll('tr, [role="row"], li, div[class*="item"], div[class*="variant"], div[class*="Variant"], td, [data-testid*="row"]');
567
- console.log(`[Exchange Autofill] Checking ${allRows.length} rows for variant ${item.variant_id}`);
568
- for (const row of Array.from(allRows)) {
569
- const rowText = row.textContent || "";
570
- if (rowText.includes(item.variant_id) || rowText.includes(item.variant_id.substring(0, 15)) || rowText.includes(item.variant_id.substring(item.variant_id.length - 10))) {
571
- variantInput = row.querySelector('input[type="checkbox"], input[type="radio"], input');
572
- if (!variantInput) {
573
- const clickable = row.querySelector('button, [role="button"], div[onclick], div[class*="select"]');
574
- if (clickable) {
575
- console.log(`[Exchange Autofill] Found clickable element in row, clicking it`);
576
- clickable.click();
577
- setTimeout(() => {
578
- variantInput = row.querySelector('input[type="checkbox"], input[type="radio"], input');
579
- }, 300);
580
- }
581
- }
582
- if (variantInput) {
583
- console.log(`[Exchange Autofill] Found outbound item input in row containing: ${rowText.substring(0, 100)}`);
584
- break;
585
- }
586
- }
587
- }
588
- }
589
- if (!variantInput) {
590
- const clickableElements = searchRoot.querySelectorAll('button, div[role="button"], div[class*="select"], div[class*="variant"], span, label');
591
- console.log(`[Exchange Autofill] Checking ${clickableElements.length} clickable elements for variant ${item.variant_id}`);
592
- for (const element of Array.from(clickableElements)) {
593
- const elementText = element.textContent || "";
594
- if (elementText.includes(item.variant_id) || elementText.includes(item.variant_id.substring(0, 15))) {
595
- const nearbyInput = element.querySelector("input") || ((_a = element.closest("tr, div, li")) == null ? void 0 : _a.querySelector("input")) || ((_b = element.parentElement) == null ? void 0 : _b.querySelector("input"));
596
- if (nearbyInput) {
597
- variantInput = nearbyInput;
598
- console.log(`[Exchange Autofill] Found outbound item input near clickable element`);
599
- break;
600
- } else {
601
- console.log(`[Exchange Autofill] Clicking element containing variant ID: ${elementText.substring(0, 50)}`);
602
- element.click();
603
- setTimeout(() => {
604
- const newInput = searchRoot.querySelector(`input[value*="${item.variant_id.substring(0, 10)}"]`);
605
- if (newInput) {
606
- variantInput = newInput;
607
- }
608
- }, 500);
609
- }
610
- }
611
- }
612
- }
613
- if (variantInput) {
614
- if (variantInput.type === "checkbox" || variantInput.type === "radio") {
615
- variantInput.checked = true;
616
- const nativeInputValueSetter = (_c = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")) == null ? void 0 : _c.set;
617
- if (nativeInputValueSetter) {
618
- nativeInputValueSetter.call(variantInput, variantInput.value);
619
- }
620
- variantInput.dispatchEvent(new Event("input", { bubbles: true }));
621
- variantInput.dispatchEvent(new Event("change", { bubbles: true }));
622
- variantInput.dispatchEvent(new MouseEvent("click", { bubbles: true }));
623
- } else {
624
- variantInput.click();
625
- }
626
- const row = variantInput.closest('tr, div, li, [role="row"]');
627
- if (row) {
628
- const quantityInput = row.querySelector('input[type="number"]');
629
- if (quantityInput) {
630
- quantityInput.value = String(item.quantity);
631
- const nativeInputValueSetter = (_d = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")) == null ? void 0 : _d.set;
632
- if (nativeInputValueSetter) {
633
- nativeInputValueSetter.call(quantityInput, String(item.quantity));
634
- }
635
- quantityInput.dispatchEvent(new Event("input", { bubbles: true }));
636
- quantityInput.dispatchEvent(new Event("change", { bubbles: true }));
637
- console.log(`[Exchange Autofill] Set quantity for outbound item ${item.variant_id}: ${item.quantity}`);
638
- }
639
- }
640
- itemsSelected++;
641
- console.log(`[Exchange Autofill] Selected outbound item: ${item.variant_id}`);
642
- } else {
643
- console.warn(`[Exchange Autofill] Could not find input for outbound item ${item.variant_id}`);
644
- const allElements = searchRoot.querySelectorAll("*");
645
- for (const element of Array.from(allElements)) {
646
- const text = element.textContent || "";
647
- const elementId = element.id || "";
648
- const elementClass = element.className || "";
649
- if (text.includes(item.variant_id) || elementId.includes(item.variant_id) || elementClass.includes(item.variant_id.substring(0, 10))) {
650
- console.log(`[Exchange Autofill] Found element containing variant ID, attempting to click:`, {
651
- tag: element.tagName,
652
- id: elementId,
653
- text: text.substring(0, 50)
654
- });
655
- element.click();
656
- setTimeout(() => {
657
- ;
658
- element.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
659
- }, 200);
660
- break;
661
- }
662
- }
663
- if (searchRoot !== document) {
664
- const allText = searchRoot.textContent || "";
665
- console.log(`[Exchange Autofill] Modal content preview (first 500 chars):`, allText.substring(0, 500));
666
- const allInputs = searchRoot.querySelectorAll("input");
667
- console.log(`[Exchange Autofill] Found ${allInputs.length} inputs in modal`);
668
- const allRows = searchRoot.querySelectorAll('tr, [role="row"], li, div');
669
- console.log(`[Exchange Autofill] Found ${allRows.length} potential rows in modal`);
670
- Array.from(allRows).slice(0, 5).forEach((row, idx) => {
671
- var _a2;
672
- console.log(`[Exchange Autofill] Row ${idx} text:`, (_a2 = row.textContent) == null ? void 0 : _a2.substring(0, 100));
673
- });
674
- }
675
- }
676
- } catch (error) {
677
- console.warn(`[Exchange Autofill] Error selecting outbound item ${item.variant_id}:`, error);
678
- }
679
- }
680
- if (itemsSelected > 0) {
681
- setTimeout(() => {
682
- var _a2;
683
- const buttons = searchRoot.querySelectorAll('button, [role="button"]');
684
- for (const buttonEl of Array.from(buttons)) {
685
- const text = ((_a2 = buttonEl.textContent) == null ? void 0 : _a2.toLowerCase().trim()) || "";
686
- if (text.includes("add") || text.includes("confirm") || text.includes("select") || text.includes("save")) {
687
- const button = buttonEl;
688
- const buttonType = "type" in button ? button.type : void 0;
689
- if (!buttonType || buttonType === "submit" || buttonType === "button") {
690
- console.log("[Exchange Autofill] Clicking button:", text);
691
- button.click();
692
- break;
693
- }
694
- }
695
- }
696
- }, 1e3);
697
- } else {
698
- console.warn("[Exchange Autofill] No outbound items were selected");
699
- }
700
- }
701
- adminSdk.defineWidgetConfig({
702
- zone: "order.details.before"
703
- });
704
8
  const useDebounce$1 = (value, delay) => {
705
9
  const [debouncedValue, setDebouncedValue] = react.useState(value);
706
10
  react.useEffect(() => {
@@ -1541,7 +845,7 @@ const SwapDetailPage = () => {
1541
845
  setIsUpdating(false);
1542
846
  }
1543
847
  };
1544
- const handleApproveClick = async () => {
848
+ const handleAutoCreateExchange = async () => {
1545
849
  if (!id) {
1546
850
  return;
1547
851
  }
@@ -1549,7 +853,7 @@ const SwapDetailPage = () => {
1549
853
  setIsApproving(true);
1550
854
  setUpdateError(null);
1551
855
  setUpdateSuccess(false);
1552
- const response = await fetch(`/admin/swaps/${id}/prepare-exchange`, {
856
+ const response = await fetch(`/admin/swaps/${id}/create-exchange`, {
1553
857
  method: "POST",
1554
858
  headers: {
1555
859
  "Content-Type": "application/json"
@@ -1558,14 +862,22 @@ const SwapDetailPage = () => {
1558
862
  });
1559
863
  if (!response.ok) {
1560
864
  const message = await response.text();
1561
- throw new Error(message || "Unable to prepare swap for exchange");
865
+ throw new Error(message || "Unable to create exchange from swap");
1562
866
  }
1563
867
  const payload = await response.json();
1564
868
  setSwap(payload.swap);
1565
- const redirectUrl = payload.redirect_url.startsWith("http") ? payload.redirect_url : `${window.location.origin}${payload.redirect_url}`;
1566
- window.location.href = redirectUrl;
869
+ setUpdateSuccess(true);
870
+ setTimeout(() => setUpdateSuccess(false), 3e3);
871
+ const detailResponse = await fetch(`/admin/swaps/${id}`, {
872
+ credentials: "include"
873
+ });
874
+ if (detailResponse.ok) {
875
+ const detailPayload = await detailResponse.json();
876
+ setSwap(detailPayload.swap);
877
+ setOrder(detailPayload.order || null);
878
+ }
1567
879
  } catch (approveErr) {
1568
- const message = approveErr instanceof Error ? approveErr.message : "Unable to prepare swap for exchange";
880
+ const message = approveErr instanceof Error ? approveErr.message : "Unable to create exchange from swap";
1569
881
  setUpdateError(message);
1570
882
  } finally {
1571
883
  setIsApproving(false);
@@ -1650,27 +962,30 @@ const SwapDetailPage = () => {
1650
962
  )
1651
963
  ] })
1652
964
  ] }),
1653
- swap.status === "requested" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-3", children: [
1654
- /* @__PURE__ */ jsxRuntime.jsx(
1655
- ui.Button,
1656
- {
1657
- variant: "primary",
1658
- onClick: handleApproveClick,
1659
- disabled: isApproving || isRejecting,
1660
- isLoading: isApproving,
1661
- children: "Approve Swap"
1662
- }
1663
- ),
1664
- /* @__PURE__ */ jsxRuntime.jsx(
1665
- ui.Button,
1666
- {
1667
- variant: "secondary",
1668
- onClick: handleReject,
1669
- disabled: isApproving || isRejecting,
1670
- isLoading: isRejecting,
1671
- children: "Reject Swap"
1672
- }
1673
- )
965
+ swap.status === "requested" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-3", children: [
966
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-3", children: [
967
+ /* @__PURE__ */ jsxRuntime.jsx(
968
+ ui.Button,
969
+ {
970
+ variant: "primary",
971
+ onClick: handleAutoCreateExchange,
972
+ disabled: isApproving || isRejecting,
973
+ isLoading: isApproving,
974
+ children: "Approve & Create Exchange"
975
+ }
976
+ ),
977
+ /* @__PURE__ */ jsxRuntime.jsx(
978
+ ui.Button,
979
+ {
980
+ variant: "danger",
981
+ onClick: handleReject,
982
+ disabled: isApproving || isRejecting,
983
+ isLoading: isRejecting,
984
+ children: "Reject Swap"
985
+ }
986
+ )
987
+ ] }),
988
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { size: "small", className: "text-ui-fg-subtle", children: "Approving will automatically create an exchange with return items and new items from the swap request" })
1674
989
  ] }),
1675
990
  swap.status === "requested" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-lg border border-ui-border-base bg-ui-bg-base p-6", children: [
1676
991
  /* @__PURE__ */ jsxRuntime.jsx(ui.Heading, { level: "h2", className: "mb-4 text-lg", children: "Update Status" }),
@@ -1846,12 +1161,7 @@ const config = adminSdk.defineRouteConfig({
1846
1161
  icon: icons.ArrowPath
1847
1162
  });
1848
1163
  const i18nTranslations0 = {};
1849
- const widgetModule = { widgets: [
1850
- {
1851
- Component: ExchangeAutofillWidget,
1852
- zone: ["order.details.before"]
1853
- }
1854
- ] };
1164
+ const widgetModule = { widgets: [] };
1855
1165
  const routeModule = {
1856
1166
  routes: [
1857
1167
  {
@@ -1874,12 +1184,6 @@ const routeModule = {
1874
1184
  };
1875
1185
  const menuItemModule = {
1876
1186
  menuItems: [
1877
- {
1878
- label: config$3.label,
1879
- icon: config$3.icon,
1880
- path: "/returns",
1881
- nested: void 0
1882
- },
1883
1187
  {
1884
1188
  label: config$2.label,
1885
1189
  icon: config$2.icon,
@@ -1887,9 +1191,9 @@ const menuItemModule = {
1887
1191
  nested: void 0
1888
1192
  },
1889
1193
  {
1890
- label: config$1.label,
1891
- icon: config$1.icon,
1892
- path: "/returns/:id",
1194
+ label: config$3.label,
1195
+ icon: config$3.icon,
1196
+ path: "/returns",
1893
1197
  nested: void 0
1894
1198
  },
1895
1199
  {
@@ -1897,6 +1201,12 @@ const menuItemModule = {
1897
1201
  icon: config.icon,
1898
1202
  path: "/swaps/:id",
1899
1203
  nested: void 0
1204
+ },
1205
+ {
1206
+ label: config$1.label,
1207
+ icon: config$1.icon,
1208
+ path: "/returns/:id",
1209
+ nested: void 0
1900
1210
  }
1901
1211
  ]
1902
1212
  };