-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin_order.html
More file actions
452 lines (393 loc) · 17.3 KB
/
Copy pathadmin_order.html
File metadata and controls
452 lines (393 loc) · 17.3 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
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link href="images/favicon.png" rel="shortcut icon">
<title>Kardiy - Elegant - Fast - Reliable - Cheap</title>
<!--====== Google Font ======-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,700,800" rel="stylesheet">
<!--====== Vendor Css ======-->
<link rel="stylesheet" href="css/vendor.css">
<!--====== Utility-Spacing ======-->
<link rel="stylesheet" href="css/utility.css">
<!--====== App ======-->
<link rel="stylesheet" href="css/app.css">
<script src="user.js"></script>
<script>
(async () => {
try {
if (typeof window.checkSession === 'function') {
await window.checkSession(); // refresh session so role is up-to-date
}
const user = typeof window.getCurrentUser === 'function'
? window.getCurrentUser()
: null;
const role = user?.role || user?.user_role || '';
const isAdmin = role === 'admin' || role === 'super_admin';
if (!isAdmin) {
showToast('Access denied. Please sign in with an admin account.', { type: 'error' });
window.location.href = 'index.html';
}
} catch (err) {
console.error('Admin check failed:', err);
window.location.href = 'index.html';
}
})();
</script>
</head>
<body class="config">
<div class="preloader is-active">
<div class="preloader__wrap">
<img class="preloader__img" src="images/preloader.png" alt="">
</div>
</div>
<!--====== Main App ======-->
<div id="app">
<!--====== Main Header ======-->
<div id="header-placeholder"></div>
<script>
(async () => {
const el = document.getElementById('header-placeholder');
const resp = await fetch('top_bar.html?_=' + Date.now()); // bust cache
const html = await resp.text();
el.innerHTML = html;
await window.checkSession();
// Execute any <script> tags inside the injected HTML
document.dispatchEvent(new CustomEvent('user:changed'));
el.querySelectorAll('script').forEach((old) => {
const s = document.createElement('script');
if (old.src) {
s.src = old.src; s.async = old.async; s.defer = old.defer || false;
} else {
s.textContent = old.textContent;
}
document.head.appendChild(s);
});
// Call menu builder with already-fetched products if we have them
const tryInit = () => {
if (typeof window.initHeaderMenu === 'function') {
window.initHeaderMenu(window.__ALL_PRODUCTS__ || null);
}
};
// tiny delay to ensure the function is defined
setTimeout(tryInit, 0);
})();
</script>
<!--====== End - Main Header ======-->
<!--====== App Content ======-->
<div class="app-content">
<!--====== Section 1 ======-->
<div class="u-s-p-y-60">
<div class="section__content">
<div class="container">
<div class="breadcrumb">
<div class="breadcrumb__wrap">
<ul class="breadcrumb__list">
<li class="has-separator">
<a href="index.html">Home</a>
</li>
<li class="is-marked">
<a href="admin_order.html">Admin Orders</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!--====== End - Section 1 ======-->
<!--====== Section 2 ======-->
<div class="u-s-p-b-60">
<div class="section__content">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="u-s-m-b-30">
<button class="btn btn--e-transparent-brand-b-2" onclick="showFilter('paid')">Waiting</button>
<button class="btn btn--e-transparent-brand-b-2" onclick="showFilter('shipped')">Shipped</button>
<button class="btn btn--e-transparent-brand-b-2" onclick="showFilter('returnreq')">Return Requested</button>
</div>
<div id="orders-container"></div>
</div>
</div>
</div>
</div>
</div>
<!--====== End - Section 2 ======-->
</div>
<!--====== End - App Content ======-->
<!--====== Main Footer ======-->
<div id="footer-placeholder"></div>
<script>
(async () => {
const el = document.getElementById('footer-placeholder');
const resp = await fetch('footer.html?_=' + Date.now()); // Fetch footer.html
const html = await resp.text();
el.innerHTML = html;
})();
</script>
</div>
</div>
<!--====== End - Main App ======-->
<!--====== Google Analytics: change UA-XXXXX-Y to be your site's ID ======-->
<script>
window.ga = function() { ga.q.push(arguments) }; ga.q = []; ga.l = +new Date;
ga('create', 'UA-XXXXX-Y', 'auto'); ga('send', 'pageview')
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
<!--====== Vendor Js ======-->
<script src="js/vendor.js"></script>
<!--====== jQuery Shopnav plugin ======-->
<script src="js/jquery.shopnav.js"></script>
<!--====== App ======-->
<script src="js/app.js"></script>
<!--====== Noscript ======-->
<noscript>
<div class="app-setting">
<div class="container">
<div class="row">
<div class="col-12">
<div class="app-setting__wrap">
<h1 class="app-setting__h1">JavaScript is disabled in your browser.</h1>
<span class="app-setting__text">Please enable JavaScript in your browser or upgrade to a JavaScript-capable browser.</span>
</div>
</div>
</div>
</div>
</div>
</noscript>
<script>
(() => {
if (window.__ADMIN_ORDERS_PATCH__) return;
window.__ADMIN_ORDERS_PATCH__ = true;
const ORDERS_API = `${API_ROOT}/orders`;
let currentFilter = 'paid';
async function fetchOrders() {
try {
const r = await fetch(ORDERS_API, { credentials: 'include' });
if (!r.ok) return [];
return await r.json();
} catch { return []; }
}
function formatUser(jsonStr) {
try {
const u = JSON.parse(jsonStr);
return `${u.user_name || ''} ${u.user_surname || ''} (${u.user_email || ''})`;
} catch {
return jsonStr;
}
}
function formatProducts(jsonStr) {
try {
const prods = JSON.parse(jsonStr);
return prods.map(p => {
// Create a string for the options, if they exist
let optionsStr = '';
if (p.options && typeof p.options === 'object' && Object.keys(p.options).length > 0) {
const optionsArray = Object.entries(p.options).map(([key, value]) => `${key}: ${value}`);
optionsStr = `<br><small style="color: #666;">(${optionsArray.join(', ')})</small>`;
}
// The original product info string
let productInfo = `${p.product_name} x ${p.product_amount}`;
if (p.host && p.host.toLowerCase() === 'amazon' && p.host_id) {
const amazonUrl = `https://www.amazon.com/dp/${p.host_id}`;
// Append a small, non-intrusive link to the product name
productInfo += ` <a href="${amazonUrl}" target="_blank" style="font-size: 0.8em; text-decoration: underline; color: #007bff;">(View Product)</a>`;
}
// Add pricing for the admin view
if (p.product_unit_price) {
productInfo += ` @ $${p.product_unit_price} = $${p.product_total}`;
}
return productInfo + optionsStr;
}).join('<br>');
} catch {
return jsonStr;
}
}
function renderOrders(orders) {
// Update this filter to catch all return-related statuses
const filtered = orders.filter(o =>
(currentFilter === 'returnreq' && ['returnreq', 'returnapproved', 'returnrejec'].includes(o.order_status)) ||
o.order_status === currentFilter
);
const container = document.getElementById('orders-container');
if (!container) return;
container.innerHTML = '';
for (let i = 0; i < filtered.length; i += 3) {
// THIS IS THE FIX: These two lines were missing.
// A new row is created for every 3 items.
const rowDiv = document.createElement('div');
rowDiv.className = 'row u-s-m-b-30';
for (let j = 0; j < 3; j++) {
const ord = filtered[i + j];
if (!ord) break;
// --- CORE NEW LOGIC: Determine actions based on order_host ---
let detailsHtml = '';
const hostType = (ord.order_host || 'self').toLowerCase();
if (ord.order_status === 'paid') {
if (hostType === 'amazon') {
detailsHtml = `
<tr><td>Fulfillment</td><td><strong style="color: #ff9900;">Manual (Amazon)</strong></td></tr>
<tr><td>Status</td><td>Awaiting Tracking Info</td></tr>
<tr><td>Tracking #</td><td><input type="text" id="track-${ord.order_id}" class="input-text" placeholder="Enter tracking number"></td></tr>
<tr><td colspan="2"><button class="btn btn--e-brand-b-2" onclick="saveManualTracking('${ord.order_id}')">Save Tracking</button></td></tr>
`;
} else if (hostType === 'aliexpress') {
detailsHtml = `
<tr><td>Fulfillment</td><td><strong style="color: #ff4747;">Automated (DSers)</strong></td></tr>
<tr><td>DSers Ref ID</td><td>${ord.order_host_reference || 'Pending...'}</td></tr>
<tr><td>Status</td><td>Awaiting Tracking Sync</td></tr>
<tr><td colspan="2"><button class="btn btn--e-brand-b-2" onclick="syncDsersTracking('${ord.order_id}', this)">Sync Tracking from DSers</button></td></tr>
`;
} else { // Self-hosted
detailsHtml = `
<tr><td>Fulfillment</td><td><strong>Self-Hosted</strong></td></tr>
<tr><td>Status</td><td>Ready to Ship</td></tr>
<tr><td colspan="2"><button class="btn btn--e-brand-b-2" onclick="generateTicket('${ord.order_id}')">Generate Shipping Ticket 🎟️</button></td></tr>
`;
}
} else if (ord.order_status === 'shipped') {
const trackingUrl = ord.order_trackingURL || `https://www.google.com/search?q=${encodeURIComponent(ord.order_trackingNumber)}`;
detailsHtml = `
<tr><td>Status</td><td><strong style="color: #28a745;">Shipped</strong></td></tr>
<tr><td>Tracking</td><td>
<a href="${trackingUrl}" target="_blank">${ord.order_trackingNumber || 'N/A'}</a>
</td></tr>
`;
// Only show the "View/Print Label" button for self-hosted orders that have a label URL
if (hostType === 'self' && ord.order_labelURL) {
detailsHtml += `
<tr><td>Shipping Label</td><td>
<a href="${ord.order_labelURL}" target="_blank" class="btn btn--e-brand-b-2 btn--s">View/Print Label</a>
</td></tr>
`;
}
} else { // For returnreq, returnapproved, etc.
detailsHtml = `<tr><td>Status</td><td>${ord.order_status}</td></tr>`;
}
const colDiv = document.createElement('div');
colDiv.className = 'col-lg-4';
// UPDATE the innerHTML to use the new detailsHtml variable
colDiv.innerHTML = `
<table class="o-summary__table">
<tbody>
<tr><td>Order ID</td><td>${ord.order_id}</td></tr>
<tr><td>User</td><td>${formatUser(ord.order_user)}</td></tr>
<tr><td>Products</td><td>${formatProducts(ord.order_product)}</td></tr>
<tr><td>Address</td><td>${ord.order_address}</td></tr>
${detailsHtml}
</tbody>
</table>
`;
// This line was causing the error because rowDiv didn't exist
rowDiv.appendChild(colDiv);
}
container.appendChild(rowDiv);
}
}
// --- ADD THESE NEW FUNCTIONS AT THE GLOBAL SCOPE (near saveTrack) ---
window.approveReturn = async function(order_id) {
if (!confirm('Are you sure you want to approve this return?')) return;
try {
const r = await fetch(`${ORDERS_API}/${order_id}/manage-return`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ action: 'approve' })
});
if (r.ok) {
init(); // Refresh list
showToast('Return approved successfully.', { type: 'success' });
} else {
showToast('We couldn\'t approve that return. Please try again.', { type: 'error' });
}
} catch {
showToast('Something went wrong while approving. Please try again.', { type: 'error' });
}
};
window.declineReturn = async function(order_id) {
const reason = prompt('Please provide a reason for declining this return request:');
if (reason === null) return; // User clicked cancel
if (!reason.trim()) {
showToast('Please provide a reason before declining a return.', { type: 'warning' });
return;
}
try {
const r = await fetch(`${ORDERS_API}/${order_id}/manage-return`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ action: 'decline', reason: reason.trim() })
});
if (r.ok) {
init(); // Refresh list
showToast('Return declined successfully.', { type: 'success' });
} else {
showToast('We couldn\'t decline that return. Please try again.', { type: 'error' });
}
} catch {
showToast('Something went wrong while declining. Please try again.', { type: 'error' });
}
};
window.showFilter = async function(filter) {
currentFilter = filter;
const orders = await fetchOrders();
renderOrders(orders);
};
window.saveTrack = async function(order_id) {
const input = document.getElementById(`track-${order_id}`);
if (!input) return;
const track = input.value.trim();
try {
const r = await fetch(`${ORDERS_API}/${order_id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ order_trackingNumber: track })
});
if (r.ok) {
await init();
} else {
showToast('We couldn\'t update that tracking number.', { type: 'error' });
}
} catch {
showToast('Something went wrong while updating the tracking number.', { type: 'error' });
}
};
window.generateTicket = async function(order_id) {
const button = event.target;
button.textContent = 'Generating...';
button.disabled = true;
try {
const res = await fetch(`${ORDERS_API}/${order_id}/generate-ticket`, {
method: 'POST',
credentials: 'include'
});
const result = await res.json();
if (!res.ok) {
throw new Error(result.error || 'An unknown error occurred.');
}
// No redirect needed. Just show a success message and refresh the list.
showToast(`Shipping label created. Tracking: ${result.tracking_number}`, { type: 'success' });
fetchOrders(); // This refreshes the order list, moving the order to "Shipped"
} catch (e) {
showToast(`We couldn't generate the shipping label. ${e.message || ''}`.trim(), { type: 'error' });
button.textContent = 'Generate Shipping Ticket 🎟️';
button.disabled = false;
}
};
async function init() {
const orders = await fetchOrders();
renderOrders(orders);
const pre = document.querySelector('.preloader');
if (pre) pre.classList.remove('is-active');
}
document.addEventListener('DOMContentLoaded', init);
})();
</script>
</body>
</html>