refactor(js): migrate JavaScript files to module directories
Move 47 JS files from static/{admin,vendor,shared}/js/ to their
respective module directories app/modules/*/static/*/js/:
- Orders: orders.js, order-detail.js
- Catalog: products.js (renamed from vendor-products.js), product-*.js
- Inventory: inventory.js (admin & vendor)
- Customers: customers.js, users.js, user-*.js
- Billing: billing-history.js, subscriptions.js, subscription-tiers.js,
billing.js, invoices.js, feature-store.js, upgrade-prompts.js
- Messaging: messages.js, notifications.js, email-templates.js
- Marketplace: marketplace*.js, letzshop*.js, onboarding.js
- Monitoring: monitoring.js, background-tasks.js, imports.js, logs.js
- Dev Tools: testing-*.js, code-quality-*.js
Update 39 templates to reference new module static paths using
url_for('{module}_static', path='...') pattern.
Files staying in static/ (platform core):
- admin: dashboard, login, platforms, vendors, companies, admin-users,
settings, components, init-alpine, module-config
- vendor: dashboard, login, profile, settings, team, media, init-alpine
- shared: api-client, utils, money, icons, log-config, vendor-selector,
media-picker
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
616
app/modules/orders/static/admin/js/orders.js
Normal file
616
app/modules/orders/static/admin/js/orders.js
Normal file
@@ -0,0 +1,616 @@
|
||||
// noqa: js-006 - async init pattern is safe, loadData has try/catch
|
||||
// static/admin/js/orders.js
|
||||
/**
|
||||
* Admin orders management page logic
|
||||
* View and manage orders across all vendors
|
||||
*/
|
||||
|
||||
const adminOrdersLog = window.LogConfig.loggers.adminOrders ||
|
||||
window.LogConfig.createLogger('adminOrders', false);
|
||||
|
||||
adminOrdersLog.info('Loading...');
|
||||
|
||||
function adminOrders() {
|
||||
adminOrdersLog.info('adminOrders() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'orders',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
saving: false,
|
||||
|
||||
// Orders data
|
||||
orders: [],
|
||||
stats: {
|
||||
total_orders: 0,
|
||||
pending_orders: 0,
|
||||
processing_orders: 0,
|
||||
shipped_orders: 0,
|
||||
delivered_orders: 0,
|
||||
cancelled_orders: 0,
|
||||
refunded_orders: 0,
|
||||
total_revenue: 0,
|
||||
vendors_with_orders: 0
|
||||
},
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
vendor_id: '',
|
||||
status: '',
|
||||
channel: ''
|
||||
},
|
||||
|
||||
// Available vendors for filter dropdown
|
||||
vendors: [],
|
||||
|
||||
// Selected vendor (for prominent display)
|
||||
selectedVendor: null,
|
||||
|
||||
// Tom Select instance
|
||||
vendorSelectInstance: null,
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Modal states
|
||||
showStatusModal: false,
|
||||
showDetailModal: false,
|
||||
selectedOrder: null,
|
||||
selectedOrderDetail: null,
|
||||
|
||||
// Status update form
|
||||
statusForm: {
|
||||
status: '',
|
||||
tracking_number: '',
|
||||
reason: ''
|
||||
},
|
||||
|
||||
// Mark as shipped modal
|
||||
showMarkAsShippedModal: false,
|
||||
markingAsShipped: false,
|
||||
shipForm: {
|
||||
tracking_number: '',
|
||||
tracking_url: '',
|
||||
shipping_carrier: ''
|
||||
},
|
||||
|
||||
// Debounce timer
|
||||
searchTimeout: null,
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) {
|
||||
pages.push('...');
|
||||
}
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) {
|
||||
pages.push('...');
|
||||
}
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
async init() {
|
||||
adminOrdersLog.info('Orders init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._adminOrdersInitialized) {
|
||||
adminOrdersLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._adminOrdersInitialized = true;
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
// Initialize Tom Select for vendor filter
|
||||
this.initVendorSelect();
|
||||
|
||||
// Check localStorage for saved vendor
|
||||
const savedVendorId = localStorage.getItem('orders_selected_vendor_id');
|
||||
if (savedVendorId) {
|
||||
adminOrdersLog.info('Restoring saved vendor:', savedVendorId);
|
||||
// Restore vendor after a short delay to ensure TomSelect is ready
|
||||
// restoreSavedVendor will call loadOrders() after setting the filter
|
||||
setTimeout(async () => {
|
||||
await this.restoreSavedVendor(parseInt(savedVendorId));
|
||||
}, 200);
|
||||
// Load stats and vendors, but not orders (restoreSavedVendor will do that)
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors()
|
||||
]);
|
||||
} else {
|
||||
// No saved vendor - load all data including unfiltered orders
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors(),
|
||||
this.loadOrders()
|
||||
]);
|
||||
}
|
||||
|
||||
adminOrdersLog.info('Orders initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Restore saved vendor from localStorage
|
||||
*/
|
||||
async restoreSavedVendor(vendorId) {
|
||||
try {
|
||||
const vendor = await apiClient.get(`/admin/vendors/${vendorId}`);
|
||||
if (this.vendorSelectInstance && vendor) {
|
||||
// Add the vendor as an option and select it
|
||||
this.vendorSelectInstance.addOption({
|
||||
id: vendor.id,
|
||||
name: vendor.name,
|
||||
vendor_code: vendor.vendor_code
|
||||
});
|
||||
this.vendorSelectInstance.setValue(vendor.id, true);
|
||||
|
||||
// Set the filter state (this is the key fix!)
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = vendor.id;
|
||||
|
||||
adminOrdersLog.info('Restored vendor:', vendor.name);
|
||||
|
||||
// Load orders with the vendor filter applied
|
||||
await this.loadOrders();
|
||||
}
|
||||
} catch (error) {
|
||||
adminOrdersLog.warn('Failed to restore saved vendor, clearing localStorage:', error);
|
||||
localStorage.removeItem('orders_selected_vendor_id');
|
||||
// Load unfiltered orders as fallback
|
||||
await this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize Tom Select for vendor autocomplete
|
||||
*/
|
||||
initVendorSelect() {
|
||||
const selectEl = this.$refs.vendorSelect;
|
||||
if (!selectEl) {
|
||||
adminOrdersLog.warn('Vendor select element not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for Tom Select to be available
|
||||
if (typeof TomSelect === 'undefined') {
|
||||
adminOrdersLog.warn('TomSelect not loaded, retrying in 100ms');
|
||||
setTimeout(() => this.initVendorSelect(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
this.vendorSelectInstance = new TomSelect(selectEl, {
|
||||
valueField: 'id',
|
||||
labelField: 'name',
|
||||
searchField: ['name', 'vendor_code'],
|
||||
placeholder: 'Search vendor by name or code...',
|
||||
allowEmptyOption: true,
|
||||
load: async (query, callback) => {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/vendors', {
|
||||
search: query,
|
||||
limit: 50
|
||||
});
|
||||
callback(response.vendors || []);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to search vendors:', error);
|
||||
callback([]);
|
||||
}
|
||||
},
|
||||
render: {
|
||||
option: (data, escape) => {
|
||||
return `<div class="flex items-center justify-between py-1">
|
||||
<span>${escape(data.name)}</span>
|
||||
<span class="text-xs text-gray-400 font-mono">${escape(data.vendor_code || '')}</span>
|
||||
</div>`;
|
||||
},
|
||||
item: (data, escape) => {
|
||||
return `<div>${escape(data.name)}</div>`;
|
||||
}
|
||||
},
|
||||
onChange: (value) => {
|
||||
if (value) {
|
||||
const vendor = this.vendorSelectInstance.options[value];
|
||||
this.selectedVendor = vendor;
|
||||
this.filters.vendor_id = value;
|
||||
// Save to localStorage
|
||||
localStorage.setItem('orders_selected_vendor_id', value.toString());
|
||||
} else {
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('orders_selected_vendor_id');
|
||||
}
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
}
|
||||
});
|
||||
|
||||
adminOrdersLog.info('Vendor select initialized');
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear vendor filter
|
||||
*/
|
||||
clearVendorFilter() {
|
||||
if (this.vendorSelectInstance) {
|
||||
this.vendorSelectInstance.clear();
|
||||
}
|
||||
this.selectedVendor = null;
|
||||
this.filters.vendor_id = '';
|
||||
// Clear from localStorage
|
||||
localStorage.removeItem('orders_selected_vendor_id');
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load order statistics
|
||||
*/
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/orders/stats');
|
||||
this.stats = response;
|
||||
adminOrdersLog.info('Loaded stats:', this.stats);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load stats:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load available vendors for filter
|
||||
*/
|
||||
async loadVendors() {
|
||||
try {
|
||||
const response = await apiClient.get('/admin/orders/vendors');
|
||||
this.vendors = response.vendors || [];
|
||||
adminOrdersLog.info('Loaded vendors:', this.vendors.length);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load vendors:', error);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load orders with filtering and pagination
|
||||
*/
|
||||
async loadOrders() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: (this.pagination.page - 1) * this.pagination.per_page,
|
||||
limit: this.pagination.per_page
|
||||
});
|
||||
|
||||
// Add filters
|
||||
if (this.filters.search) {
|
||||
params.append('search', this.filters.search);
|
||||
}
|
||||
if (this.filters.vendor_id) {
|
||||
params.append('vendor_id', this.filters.vendor_id);
|
||||
}
|
||||
if (this.filters.status) {
|
||||
params.append('status', this.filters.status);
|
||||
}
|
||||
if (this.filters.channel) {
|
||||
params.append('channel', this.filters.channel);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/admin/orders?${params.toString()}`);
|
||||
|
||||
this.orders = response.orders || [];
|
||||
this.pagination.total = response.total || 0;
|
||||
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
|
||||
|
||||
adminOrdersLog.info('Loaded orders:', this.orders.length, 'of', this.pagination.total);
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load orders:', error);
|
||||
this.error = error.message || 'Failed to load orders';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Debounced search handler
|
||||
*/
|
||||
debouncedSearch() {
|
||||
clearTimeout(this.searchTimeout);
|
||||
this.searchTimeout = setTimeout(() => {
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
}, 300);
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh orders list
|
||||
*/
|
||||
async refresh() {
|
||||
await Promise.all([
|
||||
this.loadStats(),
|
||||
this.loadVendors(),
|
||||
this.loadOrders()
|
||||
]);
|
||||
},
|
||||
|
||||
/**
|
||||
* View order details
|
||||
*/
|
||||
async viewOrder(order) {
|
||||
try {
|
||||
const response = await apiClient.get(`/admin/orders/${order.id}`);
|
||||
this.selectedOrderDetail = response;
|
||||
this.showDetailModal = true;
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to load order details:', error);
|
||||
Utils.showToast('Failed to load order details.', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open status update modal
|
||||
*/
|
||||
openStatusModal(order) {
|
||||
this.selectedOrder = order;
|
||||
this.statusForm = {
|
||||
status: order.status,
|
||||
tracking_number: order.tracking_number || '',
|
||||
reason: ''
|
||||
};
|
||||
this.showStatusModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Update order status
|
||||
*/
|
||||
async updateStatus() {
|
||||
if (!this.selectedOrder || this.statusForm.status === this.selectedOrder.status) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
const payload = {
|
||||
status: this.statusForm.status
|
||||
};
|
||||
|
||||
if (this.statusForm.tracking_number) {
|
||||
payload.tracking_number = this.statusForm.tracking_number;
|
||||
}
|
||||
|
||||
if (this.statusForm.reason) {
|
||||
payload.reason = this.statusForm.reason;
|
||||
}
|
||||
|
||||
await apiClient.patch(`/admin/orders/${this.selectedOrder.id}/status`, payload);
|
||||
|
||||
adminOrdersLog.info('Updated order status:', this.selectedOrder.id);
|
||||
|
||||
this.showStatusModal = false;
|
||||
this.selectedOrder = null;
|
||||
|
||||
Utils.showToast('Order status updated successfully.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to update order status:', error);
|
||||
Utils.showToast(error.message || 'Failed to update status.', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Open mark as shipped modal
|
||||
*/
|
||||
openMarkAsShippedModal(order) {
|
||||
this.selectedOrder = order;
|
||||
this.shipForm = {
|
||||
tracking_number: order.tracking_number || '',
|
||||
tracking_url: order.tracking_url || '',
|
||||
shipping_carrier: order.shipping_carrier || ''
|
||||
};
|
||||
this.showMarkAsShippedModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark order as shipped
|
||||
*/
|
||||
async markAsShipped() {
|
||||
if (!this.selectedOrder) return;
|
||||
|
||||
this.markingAsShipped = true;
|
||||
try {
|
||||
const payload = {};
|
||||
|
||||
if (this.shipForm.tracking_number) {
|
||||
payload.tracking_number = this.shipForm.tracking_number;
|
||||
}
|
||||
if (this.shipForm.tracking_url) {
|
||||
payload.tracking_url = this.shipForm.tracking_url;
|
||||
}
|
||||
if (this.shipForm.shipping_carrier) {
|
||||
payload.shipping_carrier = this.shipForm.shipping_carrier;
|
||||
}
|
||||
|
||||
await apiClient.post(`/admin/orders/${this.selectedOrder.id}/ship`, payload);
|
||||
|
||||
adminOrdersLog.info('Marked order as shipped:', this.selectedOrder.id);
|
||||
|
||||
this.showMarkAsShippedModal = false;
|
||||
this.selectedOrder = null;
|
||||
|
||||
Utils.showToast('Order marked as shipped successfully.', 'success');
|
||||
|
||||
await this.refresh();
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to mark order as shipped:', error);
|
||||
Utils.showToast(error.message || 'Failed to mark as shipped.', 'error');
|
||||
} finally {
|
||||
this.markingAsShipped = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Download shipping label for an order
|
||||
*/
|
||||
async downloadShippingLabel(order) {
|
||||
try {
|
||||
const labelInfo = await apiClient.get(`/admin/orders/${order.id}/shipping-label`);
|
||||
|
||||
if (labelInfo.label_url) {
|
||||
// Open label URL in new tab
|
||||
window.open(labelInfo.label_url, '_blank');
|
||||
} else {
|
||||
Utils.showToast('No shipping label URL available for this order.', 'warning');
|
||||
}
|
||||
} catch (error) {
|
||||
adminOrdersLog.error('Failed to get shipping label:', error);
|
||||
Utils.showToast(error.message || 'Failed to get shipping label.', 'error');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get CSS class for status badge
|
||||
*/
|
||||
getStatusClass(status) {
|
||||
const classes = {
|
||||
pending: 'text-orange-700 bg-orange-100 dark:bg-orange-700 dark:text-orange-100',
|
||||
processing: 'text-blue-700 bg-blue-100 dark:bg-blue-700 dark:text-blue-100',
|
||||
shipped: 'text-purple-700 bg-purple-100 dark:bg-purple-700 dark:text-purple-100',
|
||||
delivered: 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100',
|
||||
cancelled: 'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100',
|
||||
refunded: 'text-gray-700 bg-gray-100 dark:bg-gray-700 dark:text-gray-100'
|
||||
};
|
||||
return classes[status] || 'text-gray-700 bg-gray-100 dark:bg-gray-700 dark:text-gray-100';
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(price, currency = 'EUR') {
|
||||
if (price === null || price === undefined) return '-';
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: currency || 'EUR'
|
||||
}).format(price);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateString) {
|
||||
if (!dateString) return '-';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Format time for display
|
||||
*/
|
||||
formatTime(dateString) {
|
||||
if (!dateString) return '';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleTimeString('en-GB', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Format full date and time
|
||||
*/
|
||||
formatDateTime(dateString) {
|
||||
if (!dateString) return '-';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('en-GB', {
|
||||
day: '2-digit',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Previous page
|
||||
*/
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Next page
|
||||
*/
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Go to specific page
|
||||
*/
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadOrders();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
381
app/modules/orders/static/vendor/js/order-detail.js
vendored
Normal file
381
app/modules/orders/static/vendor/js/order-detail.js
vendored
Normal file
@@ -0,0 +1,381 @@
|
||||
// app/modules/orders/static/vendor/js/order-detail.js
|
||||
/**
|
||||
* Vendor order detail page logic
|
||||
* View order details, manage status, handle shipments, and invoice integration
|
||||
*/
|
||||
|
||||
const orderDetailLog = window.LogConfig.loggers.orderDetail ||
|
||||
window.LogConfig.createLogger('orderDetail', false);
|
||||
|
||||
orderDetailLog.info('Loading...');
|
||||
|
||||
function vendorOrderDetail() {
|
||||
orderDetailLog.info('vendorOrderDetail() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'orders',
|
||||
|
||||
// Order ID from URL
|
||||
orderId: window.orderDetailData?.orderId || null,
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
saving: false,
|
||||
creatingInvoice: false,
|
||||
downloadingPdf: false,
|
||||
|
||||
// Order data
|
||||
order: null,
|
||||
shipmentStatus: null,
|
||||
invoice: null,
|
||||
|
||||
// Modal states
|
||||
showStatusModal: false,
|
||||
showShipAllModal: false,
|
||||
newStatus: '',
|
||||
trackingNumber: '',
|
||||
trackingProvider: '',
|
||||
|
||||
// Order statuses
|
||||
statuses: [
|
||||
{ value: 'pending', label: 'Pending', color: 'yellow' },
|
||||
{ value: 'processing', label: 'Processing', color: 'blue' },
|
||||
{ value: 'partially_shipped', label: 'Partially Shipped', color: 'orange' },
|
||||
{ value: 'shipped', label: 'Shipped', color: 'indigo' },
|
||||
{ value: 'delivered', label: 'Delivered', color: 'green' },
|
||||
{ value: 'cancelled', label: 'Cancelled', color: 'red' },
|
||||
{ value: 'refunded', label: 'Refunded', color: 'gray' }
|
||||
],
|
||||
|
||||
async init() {
|
||||
orderDetailLog.info('Order detail init() called, orderId:', this.orderId);
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._orderDetailInitialized) {
|
||||
orderDetailLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._orderDetailInitialized = true;
|
||||
|
||||
// IMPORTANT: Call parent init first to set vendorCode from URL
|
||||
const parentInit = data().init;
|
||||
if (parentInit) {
|
||||
await parentInit.call(this);
|
||||
}
|
||||
|
||||
if (!this.orderId) {
|
||||
this.error = 'Order ID not provided';
|
||||
this.loading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.loadOrderDetails();
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Init failed:', error);
|
||||
this.error = 'Failed to load order details';
|
||||
}
|
||||
|
||||
orderDetailLog.info('Order detail initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load order details from API
|
||||
*/
|
||||
async loadOrderDetails() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
// Load order details
|
||||
const orderResponse = await apiClient.get(
|
||||
`/vendor/orders/${this.orderId}`
|
||||
);
|
||||
this.order = orderResponse;
|
||||
this.newStatus = this.order.status;
|
||||
|
||||
orderDetailLog.info('Loaded order:', this.order.order_number);
|
||||
|
||||
// Load shipment status
|
||||
await this.loadShipmentStatus();
|
||||
|
||||
// Load invoice if exists
|
||||
await this.loadInvoice();
|
||||
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Failed to load order details:', error);
|
||||
this.error = error.message || 'Failed to load order details';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load shipment status for partial shipment tracking
|
||||
*/
|
||||
async loadShipmentStatus() {
|
||||
try {
|
||||
const response = await apiClient.get(
|
||||
`/vendor/orders/${this.orderId}/shipment-status`
|
||||
);
|
||||
this.shipmentStatus = response;
|
||||
orderDetailLog.info('Loaded shipment status:', response);
|
||||
} catch (error) {
|
||||
orderDetailLog.warn('Failed to load shipment status:', error);
|
||||
// Not critical - continue without shipment status
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Load invoice for this order
|
||||
*/
|
||||
async loadInvoice() {
|
||||
try {
|
||||
// Search for invoices linked to this order
|
||||
const response = await apiClient.get(
|
||||
`/vendor/invoices?order_id=${this.orderId}&limit=1`
|
||||
);
|
||||
if (response.invoices && response.invoices.length > 0) {
|
||||
this.invoice = response.invoices[0];
|
||||
orderDetailLog.info('Loaded invoice:', this.invoice.invoice_number);
|
||||
}
|
||||
} catch (error) {
|
||||
orderDetailLog.warn('Failed to load invoice:', error);
|
||||
// Not critical - continue without invoice
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get status color class
|
||||
*/
|
||||
getStatusColor(status) {
|
||||
const statusObj = this.statuses.find(s => s.value === status);
|
||||
return statusObj ? statusObj.color : 'gray';
|
||||
},
|
||||
|
||||
/**
|
||||
* Get status label
|
||||
*/
|
||||
getStatusLabel(status) {
|
||||
const statusObj = this.statuses.find(s => s.value === status);
|
||||
return statusObj ? statusObj.label : status;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get item shipment status
|
||||
*/
|
||||
getItemShipmentStatus(itemId) {
|
||||
if (!this.shipmentStatus?.items) return null;
|
||||
return this.shipmentStatus.items.find(i => i.item_id === itemId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if item can be shipped
|
||||
*/
|
||||
canShipItem(itemId) {
|
||||
const status = this.getItemShipmentStatus(itemId);
|
||||
if (!status) return true; // Assume can ship if no status
|
||||
return !status.is_fully_shipped;
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(cents) {
|
||||
if (cents === null || cents === undefined) return '-';
|
||||
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
const currency = window.VENDOR_CONFIG?.currency || 'EUR';
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: currency
|
||||
}).format(cents / 100);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date/time for display
|
||||
*/
|
||||
formatDateTime(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
return new Date(dateStr).toLocaleDateString(locale, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Update order status
|
||||
*/
|
||||
async updateOrderStatus(status) {
|
||||
this.saving = true;
|
||||
try {
|
||||
const payload = { status };
|
||||
|
||||
// Add tracking info if shipping
|
||||
if (status === 'shipped' && this.trackingNumber) {
|
||||
payload.tracking_number = this.trackingNumber;
|
||||
payload.tracking_provider = this.trackingProvider;
|
||||
}
|
||||
|
||||
await apiClient.put(
|
||||
`/vendor/orders/${this.orderId}/status`,
|
||||
payload
|
||||
);
|
||||
|
||||
Utils.showToast(`Order status updated to ${this.getStatusLabel(status)}`, 'success');
|
||||
await this.loadOrderDetails();
|
||||
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Failed to update status:', error);
|
||||
Utils.showToast(error.message || 'Failed to update status', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Confirm status update from modal
|
||||
*/
|
||||
async confirmStatusUpdate() {
|
||||
await this.updateOrderStatus(this.newStatus);
|
||||
this.showStatusModal = false;
|
||||
this.trackingNumber = '';
|
||||
this.trackingProvider = '';
|
||||
},
|
||||
|
||||
/**
|
||||
* Ship a single item
|
||||
*/
|
||||
async shipItem(itemId) {
|
||||
this.saving = true;
|
||||
try {
|
||||
await apiClient.post(
|
||||
`/vendor/orders/${this.orderId}/items/${itemId}/ship`,
|
||||
{}
|
||||
);
|
||||
|
||||
Utils.showToast('Item shipped successfully', 'success');
|
||||
await this.loadOrderDetails();
|
||||
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Failed to ship item:', error);
|
||||
Utils.showToast(error.message || 'Failed to ship item', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Ship all remaining items
|
||||
*/
|
||||
async shipAllItems() {
|
||||
this.saving = true;
|
||||
try {
|
||||
// Ship each unshipped item
|
||||
const unshippedItems = this.shipmentStatus?.items?.filter(i => !i.is_fully_shipped) || [];
|
||||
|
||||
for (const item of unshippedItems) {
|
||||
await apiClient.post(
|
||||
`/vendor/orders/${this.orderId}/items/${item.item_id}/ship`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
// Update order status to shipped with tracking
|
||||
const payload = { status: 'shipped' };
|
||||
if (this.trackingNumber) {
|
||||
payload.tracking_number = this.trackingNumber;
|
||||
payload.tracking_provider = this.trackingProvider;
|
||||
}
|
||||
|
||||
await apiClient.put(
|
||||
`/vendor/orders/${this.orderId}/status`,
|
||||
payload
|
||||
);
|
||||
|
||||
Utils.showToast('All items shipped', 'success');
|
||||
this.showShipAllModal = false;
|
||||
this.trackingNumber = '';
|
||||
this.trackingProvider = '';
|
||||
await this.loadOrderDetails();
|
||||
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Failed to ship all items:', error);
|
||||
Utils.showToast(error.message || 'Failed to ship items', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Create invoice for this order
|
||||
*/
|
||||
async createInvoice() {
|
||||
this.creatingInvoice = true;
|
||||
try {
|
||||
const response = await apiClient.post(
|
||||
`/vendor/invoices`,
|
||||
{ order_id: this.orderId }
|
||||
);
|
||||
|
||||
this.invoice = response;
|
||||
Utils.showToast(`Invoice ${response.invoice_number} created`, 'success');
|
||||
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Failed to create invoice:', error);
|
||||
Utils.showToast(error.message || 'Failed to create invoice', 'error');
|
||||
} finally {
|
||||
this.creatingInvoice = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Download invoice PDF
|
||||
*/
|
||||
async downloadInvoicePdf() {
|
||||
if (!this.invoice) return;
|
||||
|
||||
this.downloadingPdf = true;
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/v1/vendor/${this.vendorCode}/invoices/${this.invoice.id}/pdf`,
|
||||
{
|
||||
headers: {
|
||||
'Authorization': `Bearer ${window.Auth?.getToken()}`
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to download PDF');
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${this.invoice.invoice_number}.pdf`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
a.remove();
|
||||
|
||||
Utils.showToast('Invoice downloaded', 'success');
|
||||
|
||||
} catch (error) {
|
||||
orderDetailLog.error('Failed to download invoice PDF:', error);
|
||||
Utils.showToast(error.message || 'Failed to download PDF', 'error');
|
||||
} finally {
|
||||
this.downloadingPdf = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
482
app/modules/orders/static/vendor/js/orders.js
vendored
Normal file
482
app/modules/orders/static/vendor/js/orders.js
vendored
Normal file
@@ -0,0 +1,482 @@
|
||||
// app/modules/orders/static/vendor/js/orders.js
|
||||
/**
|
||||
* Vendor orders management page logic
|
||||
* View and manage vendor's orders
|
||||
*/
|
||||
|
||||
const vendorOrdersLog = window.LogConfig.loggers.vendorOrders ||
|
||||
window.LogConfig.createLogger('vendorOrders', false);
|
||||
|
||||
vendorOrdersLog.info('Loading...');
|
||||
|
||||
function vendorOrders() {
|
||||
vendorOrdersLog.info('vendorOrders() called');
|
||||
|
||||
return {
|
||||
// Inherit base layout state
|
||||
...data(),
|
||||
|
||||
// Set page identifier
|
||||
currentPage: 'orders',
|
||||
|
||||
// Loading states
|
||||
loading: true,
|
||||
error: '',
|
||||
saving: false,
|
||||
|
||||
// Orders data
|
||||
orders: [],
|
||||
stats: {
|
||||
total: 0,
|
||||
pending: 0,
|
||||
processing: 0,
|
||||
completed: 0,
|
||||
cancelled: 0
|
||||
},
|
||||
|
||||
// Order statuses for filter and display
|
||||
statuses: [
|
||||
{ value: 'pending', label: 'Pending', color: 'yellow' },
|
||||
{ value: 'processing', label: 'Processing', color: 'blue' },
|
||||
{ value: 'partially_shipped', label: 'Partially Shipped', color: 'orange' },
|
||||
{ value: 'shipped', label: 'Shipped', color: 'indigo' },
|
||||
{ value: 'delivered', label: 'Delivered', color: 'green' },
|
||||
{ value: 'completed', label: 'Completed', color: 'green' },
|
||||
{ value: 'cancelled', label: 'Cancelled', color: 'red' },
|
||||
{ value: 'refunded', label: 'Refunded', color: 'gray' }
|
||||
],
|
||||
|
||||
// Filters
|
||||
filters: {
|
||||
search: '',
|
||||
status: '',
|
||||
date_from: '',
|
||||
date_to: ''
|
||||
},
|
||||
|
||||
// Pagination
|
||||
pagination: {
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
pages: 0
|
||||
},
|
||||
|
||||
// Modal states
|
||||
showDetailModal: false,
|
||||
showStatusModal: false,
|
||||
showBulkStatusModal: false,
|
||||
selectedOrder: null,
|
||||
newStatus: '',
|
||||
bulkStatus: '',
|
||||
|
||||
// Bulk selection
|
||||
selectedOrders: [],
|
||||
|
||||
// Debounce timer
|
||||
searchTimeout: null,
|
||||
|
||||
// Computed: Total pages
|
||||
get totalPages() {
|
||||
return this.pagination.pages;
|
||||
},
|
||||
|
||||
// Computed: Start index for pagination display
|
||||
get startIndex() {
|
||||
if (this.pagination.total === 0) return 0;
|
||||
return (this.pagination.page - 1) * this.pagination.per_page + 1;
|
||||
},
|
||||
|
||||
// Computed: End index for pagination display
|
||||
get endIndex() {
|
||||
const end = this.pagination.page * this.pagination.per_page;
|
||||
return end > this.pagination.total ? this.pagination.total : end;
|
||||
},
|
||||
|
||||
// Computed: Page numbers for pagination
|
||||
get pageNumbers() {
|
||||
const pages = [];
|
||||
const totalPages = this.totalPages;
|
||||
const current = this.pagination.page;
|
||||
|
||||
if (totalPages <= 7) {
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
} else {
|
||||
pages.push(1);
|
||||
if (current > 3) pages.push('...');
|
||||
const start = Math.max(2, current - 1);
|
||||
const end = Math.min(totalPages - 1, current + 1);
|
||||
for (let i = start; i <= end; i++) {
|
||||
pages.push(i);
|
||||
}
|
||||
if (current < totalPages - 2) pages.push('...');
|
||||
pages.push(totalPages);
|
||||
}
|
||||
return pages;
|
||||
},
|
||||
|
||||
// Computed: Check if all visible orders are selected
|
||||
get allSelected() {
|
||||
return this.orders.length > 0 && this.selectedOrders.length === this.orders.length;
|
||||
},
|
||||
|
||||
// Computed: Check if some but not all orders are selected
|
||||
get someSelected() {
|
||||
return this.selectedOrders.length > 0 && this.selectedOrders.length < this.orders.length;
|
||||
},
|
||||
|
||||
async init() {
|
||||
vendorOrdersLog.info('Orders init() called');
|
||||
|
||||
// Guard against multiple initialization
|
||||
if (window._vendorOrdersInitialized) {
|
||||
vendorOrdersLog.warn('Already initialized, skipping');
|
||||
return;
|
||||
}
|
||||
window._vendorOrdersInitialized = true;
|
||||
|
||||
// IMPORTANT: Call parent init first to set vendorCode from URL
|
||||
const parentInit = data().init;
|
||||
if (parentInit) {
|
||||
await parentInit.call(this);
|
||||
}
|
||||
|
||||
// Load platform settings for rows per page
|
||||
if (window.PlatformSettings) {
|
||||
this.pagination.per_page = await window.PlatformSettings.getRowsPerPage();
|
||||
}
|
||||
|
||||
try {
|
||||
await this.loadOrders();
|
||||
} catch (error) {
|
||||
vendorOrdersLog.error('Init failed:', error);
|
||||
this.error = 'Failed to initialize orders page';
|
||||
}
|
||||
|
||||
vendorOrdersLog.info('Orders initialization complete');
|
||||
},
|
||||
|
||||
/**
|
||||
* Load orders with filtering and pagination
|
||||
*/
|
||||
async loadOrders() {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
skip: (this.pagination.page - 1) * this.pagination.per_page,
|
||||
limit: this.pagination.per_page
|
||||
});
|
||||
|
||||
// Add filters
|
||||
if (this.filters.search) {
|
||||
params.append('search', this.filters.search);
|
||||
}
|
||||
if (this.filters.status) {
|
||||
params.append('status', this.filters.status);
|
||||
}
|
||||
if (this.filters.date_from) {
|
||||
params.append('date_from', this.filters.date_from);
|
||||
}
|
||||
if (this.filters.date_to) {
|
||||
params.append('date_to', this.filters.date_to);
|
||||
}
|
||||
|
||||
const response = await apiClient.get(`/vendor/orders?${params.toString()}`);
|
||||
|
||||
this.orders = response.orders || [];
|
||||
this.pagination.total = response.total || 0;
|
||||
this.pagination.pages = Math.ceil(this.pagination.total / this.pagination.per_page);
|
||||
|
||||
// Calculate stats
|
||||
this.calculateStats();
|
||||
|
||||
vendorOrdersLog.info('Loaded orders:', this.orders.length, 'of', this.pagination.total);
|
||||
} catch (error) {
|
||||
vendorOrdersLog.error('Failed to load orders:', error);
|
||||
this.error = error.message || 'Failed to load orders';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Calculate order statistics
|
||||
*/
|
||||
calculateStats() {
|
||||
this.stats = {
|
||||
total: this.pagination.total,
|
||||
pending: this.orders.filter(o => o.status === 'pending').length,
|
||||
processing: this.orders.filter(o => o.status === 'processing').length,
|
||||
completed: this.orders.filter(o => ['completed', 'delivered'].includes(o.status)).length,
|
||||
cancelled: this.orders.filter(o => o.status === 'cancelled').length
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Debounced search handler
|
||||
*/
|
||||
debouncedSearch() {
|
||||
clearTimeout(this.searchTimeout);
|
||||
this.searchTimeout = setTimeout(() => {
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
}, 300);
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply filter and reload
|
||||
*/
|
||||
applyFilter() {
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all filters
|
||||
*/
|
||||
clearFilters() {
|
||||
this.filters = {
|
||||
search: '',
|
||||
status: '',
|
||||
date_from: '',
|
||||
date_to: ''
|
||||
};
|
||||
this.pagination.page = 1;
|
||||
this.loadOrders();
|
||||
},
|
||||
|
||||
/**
|
||||
* View order details - navigates to detail page
|
||||
*/
|
||||
viewOrder(order) {
|
||||
window.location.href = `/vendor/${this.vendorCode}/orders/${order.id}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Open status change modal
|
||||
*/
|
||||
openStatusModal(order) {
|
||||
this.selectedOrder = order;
|
||||
this.newStatus = order.status;
|
||||
this.showStatusModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Update order status
|
||||
*/
|
||||
async updateStatus() {
|
||||
if (!this.selectedOrder || !this.newStatus) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
await apiClient.put(`/vendor/orders/${this.selectedOrder.id}/status`, {
|
||||
status: this.newStatus
|
||||
});
|
||||
|
||||
Utils.showToast('Order status updated', 'success');
|
||||
vendorOrdersLog.info('Updated order status:', this.selectedOrder.id, this.newStatus);
|
||||
|
||||
this.showStatusModal = false;
|
||||
this.selectedOrder = null;
|
||||
await this.loadOrders();
|
||||
} catch (error) {
|
||||
vendorOrdersLog.error('Failed to update status:', error);
|
||||
Utils.showToast(error.message || 'Failed to update status', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get status color class
|
||||
*/
|
||||
getStatusColor(status) {
|
||||
const statusObj = this.statuses.find(s => s.value === status);
|
||||
return statusObj ? statusObj.color : 'gray';
|
||||
},
|
||||
|
||||
/**
|
||||
* Get status label
|
||||
*/
|
||||
getStatusLabel(status) {
|
||||
const statusObj = this.statuses.find(s => s.value === status);
|
||||
return statusObj ? statusObj.label : status;
|
||||
},
|
||||
|
||||
/**
|
||||
* Format price for display
|
||||
*/
|
||||
formatPrice(cents) {
|
||||
if (!cents && cents !== 0) return '-';
|
||||
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
const currency = window.VENDOR_CONFIG?.currency || 'EUR';
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: 'currency',
|
||||
currency: currency
|
||||
}).format(cents / 100);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format date for display
|
||||
*/
|
||||
formatDate(dateStr) {
|
||||
if (!dateStr) return '-';
|
||||
const locale = window.VENDOR_CONFIG?.locale || 'en-GB';
|
||||
return new Date(dateStr).toLocaleDateString(locale, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Previous page
|
||||
*/
|
||||
previousPage() {
|
||||
if (this.pagination.page > 1) {
|
||||
this.pagination.page--;
|
||||
this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Next page
|
||||
*/
|
||||
nextPage() {
|
||||
if (this.pagination.page < this.totalPages) {
|
||||
this.pagination.page++;
|
||||
this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Pagination: Go to specific page
|
||||
*/
|
||||
goToPage(pageNum) {
|
||||
if (pageNum !== '...' && pageNum >= 1 && pageNum <= this.totalPages) {
|
||||
this.pagination.page = pageNum;
|
||||
this.loadOrders();
|
||||
}
|
||||
},
|
||||
|
||||
// ============================================================================
|
||||
// BULK OPERATIONS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Toggle select all orders on current page
|
||||
*/
|
||||
toggleSelectAll() {
|
||||
if (this.allSelected) {
|
||||
this.selectedOrders = [];
|
||||
} else {
|
||||
this.selectedOrders = this.orders.map(o => o.id);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Toggle selection of a single order
|
||||
*/
|
||||
toggleSelect(orderId) {
|
||||
const index = this.selectedOrders.indexOf(orderId);
|
||||
if (index === -1) {
|
||||
this.selectedOrders.push(orderId);
|
||||
} else {
|
||||
this.selectedOrders.splice(index, 1);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if order is selected
|
||||
*/
|
||||
isSelected(orderId) {
|
||||
return this.selectedOrders.includes(orderId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all selections
|
||||
*/
|
||||
clearSelection() {
|
||||
this.selectedOrders = [];
|
||||
},
|
||||
|
||||
/**
|
||||
* Open bulk status change modal
|
||||
*/
|
||||
openBulkStatusModal() {
|
||||
if (this.selectedOrders.length === 0) return;
|
||||
this.bulkStatus = '';
|
||||
this.showBulkStatusModal = true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Execute bulk status update
|
||||
*/
|
||||
async bulkUpdateStatus() {
|
||||
if (this.selectedOrders.length === 0 || !this.bulkStatus) return;
|
||||
|
||||
this.saving = true;
|
||||
try {
|
||||
let successCount = 0;
|
||||
for (const orderId of this.selectedOrders) {
|
||||
try {
|
||||
await apiClient.put(`/vendor/orders/${orderId}/status`, {
|
||||
status: this.bulkStatus
|
||||
});
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
vendorOrdersLog.warn(`Failed to update order ${orderId}:`, error);
|
||||
}
|
||||
}
|
||||
Utils.showToast(`${successCount} order(s) updated to ${this.getStatusLabel(this.bulkStatus)}`, 'success');
|
||||
this.showBulkStatusModal = false;
|
||||
this.clearSelection();
|
||||
await this.loadOrders();
|
||||
} catch (error) {
|
||||
vendorOrdersLog.error('Bulk status update failed:', error);
|
||||
Utils.showToast(error.message || 'Failed to update orders', 'error');
|
||||
} finally {
|
||||
this.saving = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Export selected orders as CSV
|
||||
*/
|
||||
exportSelectedOrders() {
|
||||
if (this.selectedOrders.length === 0) return;
|
||||
|
||||
const selectedOrderData = this.orders.filter(o => this.selectedOrders.includes(o.id));
|
||||
|
||||
// Build CSV content
|
||||
const headers = ['Order ID', 'Date', 'Customer', 'Status', 'Total'];
|
||||
const rows = selectedOrderData.map(o => [
|
||||
o.order_number || o.id,
|
||||
this.formatDate(o.created_at),
|
||||
o.customer_name || o.customer_email || '-',
|
||||
this.getStatusLabel(o.status),
|
||||
this.formatPrice(o.total)
|
||||
]);
|
||||
|
||||
const csvContent = [
|
||||
headers.join(','),
|
||||
...rows.map(row => row.map(cell => `"${cell}"`).join(','))
|
||||
].join('\n');
|
||||
|
||||
// Download
|
||||
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = `orders_export_${new Date().toISOString().split('T')[0]}.csv`;
|
||||
link.click();
|
||||
|
||||
Utils.showToast(`Exported ${selectedOrderData.length} order(s)`, 'success');
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user