front/src/views/order/myOrders/index.vue
zzh b011a5caee
All checks were successful
Build and Deploy Front / deploy (push) Successful in 6m33s
feat: 下单申报表头配置与产品线路排序,完善自动触发、店铺订单与权限相关能力
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:03:30 +08:00

2690 lines
86 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script lang="ts" setup>
import {
ref,
computed,
onMounted,
nextTick,
watch,
reactive,
defineAsyncComponent,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { IconCalendar, IconDown, IconQuestionCircleFill } from '@arco-design/web-vue/es/icon';
import { Message, Modal } from '@arco-design/web-vue';
import dayjs from 'dayjs';
import HandsontablePro from '@/components/HandsontablePro/index.vue';
import PaginationPro from '@/components/PaginationPro/index.vue';
import SlidingTabs from '@/components/SlidingTabs/index.vue';
import { useTableContainerHeight } from '@/composables/useTableContainerHeight';
import { useI18n } from 'vue-i18n';
import {
adaptOrderListHeaderFilters,
withServerFilterColumns,
withSortableColumns,
} from '@/utils/headerFilterAdapter';
import {
ORDER_EXPORT_MAX_ROWS,
ORDER_LIST_DEFAULT_DAYS,
buildDefaultCreateTimeRange,
formatCreateTimeRangeParam,
isDefaultCreateTimeRange,
} from '@/utils/headerFilterLimits';
import {
postOrderList,
getOrderStatusCounts,
getOrderDetail,
postOrderPreDeclare,
postOrderIntercept,
postOrderCancelIntercept,
postOrderDelete,
postOrderPrint,
postOrderExport,
postOrderBatchJob,
waitOrderBatchJob,
isOrderBatchQueueDisabledError,
formatBatchJobFailureMessage,
formatBatchJobSummaryMessage,
resolveBatchJobItemRowLabel,
postOrderHandleStatusUpdate,
} from '@/api/order';
import { notifyCustomerBalanceChanged } from '@/api/customer/accountFlow';
import { buildFailGuideFromReason } from '@/utils/parcelCreateFailGuide';
import {
MY_ORDERS_COLUMN_CATALOG,
MY_ORDERS_COLUMN_STORAGE_KEY,
MY_ORDERS_DEFAULT_KEYS,
FULFILL_ORDERS_COLUMN_STORAGE_KEY,
FULFILL_ORDERS_DEFAULT_KEYS,
buildHotColumns,
getActiveScheme,
loadColumnConfigState,
saveColumnConfigState,
type ColumnScheme,
} from './columnConfig';
import { filterMyOrdersColumns, filterMyOrdersFieldKeys } from './customerFieldMask';
import { useHiprintClientState } from '@/utils/hiprint/hiprintClientState';
import { fetchPrintUrlsForOrders, getCachedPrintUrl } from '@/utils/printSessionCache';
/** 详情/弹层按需分包,代发订单与我的订单共用本页 */
const OrderDetailDrawer = defineAsyncComponent(
() => import('./components/OrderDetailDrawer.vue'),
);
const OrderPayConfirmModal = defineAsyncComponent(
() => import('./components/OrderPayConfirmModal.vue'),
);
const CreatePickupOrderModal = defineAsyncComponent(
() => import('./components/CreatePickupOrderModal.vue'),
);
const MarkProblematicModal = defineAsyncComponent(
() => import('./components/MarkProblematicModal.vue'),
);
const MarkClaimedModal = defineAsyncComponent(
() => import('./components/MarkClaimedModal.vue'),
);
const StockBindModal = defineAsyncComponent(() => import('./components/StockBindModal.vue'));
const ColumnConfigModal = defineAsyncComponent(
() => import('../components/ColumnConfigModal.vue'),
);
const OrderPrintModal = defineAsyncComponent(
() => import('@/components/PrintTemplate/OrderPrintModal.vue'),
);
import {
ORDER_STATUS_TABS,
ORDER_STATUS_ALL,
ORDER_STATUS_LIST,
resolveOrderStatusCode,
isOrderDeletable,
isOrderNotShipped,
getOrderStatusMeta,
buildOrderStatusTagHtml,
buildOrderStatusSubTagHtml,
buildBooleanTagHtml,
} from '@/constants/orderStatus';
import { buildStatusTagHtml } from '@/utils/statusTag';
import {
ORDER_HANDLE_STATUS_ALL,
ORDER_HANDLE_STATUS_LIST,
isOrderHandleSubTabParent,
resolveOrderHandleStatusCode,
getOrderHandleStatusMeta,
type OrderHandleStatusCode,
} from '@/constants/orderHandleStatus';
import {
FULFILL_PROGRESS_ALL,
FULFILL_PROGRESS_TABS,
FULFILL_PROGRESS_TAB_SET,
} from '@/constants/fulfillProgress';
import { hasPermission } from '@/utils/rbac-permission';
import { renderWarehouseActionBtn, wrapWarehouseActions } from '@/utils/warehouseActionRenderer';
import { buildWaybillContextFromRow, openAskAdvisor } from '@/composables/useAskAdvisor';
defineOptions({
name: 'MyOrders',
});
const { t, te } = useI18n();
const route = useRoute();
const router = useRouter();
const isFulfillList = computed(() => route.meta.listMode === 'fulfill');
const listFulfillmentTypeFilter = computed(() =>
isFulfillList.value ? 'warehouse' : undefined,
);
const { tableContainerRef, tableHeight } = useTableContainerHeight();
// 订单详情抽屉(首次打开再挂载)
const detailDrawerMounted = ref(false);
const detailDrawerRef = ref<{
openDrawer?: (opts?: { tab?: string }) => void;
startBasicEdit?: () => void;
} | null>(null);
const currentOrder = ref<any>(null);
const columnConfigMounted = ref(false);
const createPickupMounted = ref(false);
const columnConfigModalRef = ref<{ open?: () => void } | null>(null);
const createPickupModalRef = ref<{
open?: (
rows: Array<{
id: number | string;
serviceNo?: string;
warehouseId?: number;
customerId?: number;
}>,
) => void;
} | null>(null);
async function waitForRef<T>(
get: () => T | null | undefined,
ready: (v: T) => boolean,
retries = 40,
): Promise<T | null> {
for (let i = 0; i < retries; i++) {
await nextTick();
const v = get();
if (v != null && ready(v)) return v;
await new Promise((r) => setTimeout(r, 40));
}
return null;
}
async function ensureDetailDrawer() {
detailDrawerMounted.value = true;
return waitForRef(
() => detailDrawerRef.value,
(v) => typeof v.openDrawer === 'function',
);
}
/** 兼容后端 camelCase / PascalCase */
function pick(raw: Record<string, any> | undefined, ...keys: string[]) {
if (!raw) return undefined;
for (const k of keys) {
const v = raw[k];
if (v !== undefined && v !== null && v !== '') return v;
}
return undefined;
}
/** 列表行与表格列对齐:接口用 serviceNo/clientNo/trackNo,表格用运单号/客户单号/跟踪号 */
function normalizeOrderRow(raw: any) {
const r = raw?.receiver || raw?.Receiver || {};
const wl = raw?.weightList || raw?.WeightList;
const lastW =
Array.isArray(wl) && wl.length ? wl[wl.length - 1] : undefined;
const serviceNo = pick(raw, 'serviceNo', 'ServiceNo', 'waybillNo', 'WaybillNo');
const clientNo = pick(raw, 'clientNo', 'ClientNo', 'customerOrderNo', 'CustomerOrderNo');
const trackNo = pick(raw, 'trackNo', 'TrackNo', 'trackingNo', 'TrackingNo');
const downstreamServiceNo = pick(raw, 'downstreamServiceNo', 'DownstreamServiceNo');
const productCode = pick(raw, 'productCode', 'ProductCode');
const productName = pick(raw, 'productName', 'ProductName');
const channelCode = pick(raw, 'channelCode', 'ChannelCode');
const channelName = pick(raw, 'channelName', 'ChannelName');
const isPaidRaw = pick(raw, 'isPaid', 'IsPaid');
return {
...raw,
waybillNo: serviceNo ?? '',
customerOrderNo: clientNo ?? '',
trackingNo: trackNo ?? '',
downstreamServiceNo: downstreamServiceNo ?? '',
productCode: productCode ?? '',
productName: productName ?? productCode ?? '',
channelCode: channelCode ?? '',
channelName: channelName ?? channelCode ?? '',
isPaid: isPaidRaw === true || isPaidRaw === 1 || isPaidRaw === '1',
consignee: pick(raw, 'consignee', 'Consignee') ?? pick(r, 'recipientsName', 'RecipientsName') ?? '',
consigneePhone: pick(raw, 'consigneePhone', 'ConsigneePhone') ?? pick(r, 'phone', 'Phone') ?? '',
consigneeAddress: pick(raw, 'consigneeAddress', 'ConsigneeAddress') ?? pick(r, 'streetAddress1', 'StreetAddress1') ?? '',
consigneePostcode: pick(raw, 'consigneePostcode', 'ConsigneePostcode') ?? pick(r, 'zipCode', 'ZipCode') ?? '',
consigneeState: pick(raw, 'consigneeState', 'ConsigneeState') ?? pick(r, 'province', 'Province') ?? '',
consigneeCity: pick(raw, 'consigneeCity', 'ConsigneeCity') ?? pick(r, 'city', 'City') ?? '',
consigneeCountry: pick(raw, 'consigneeCountry', 'ConsigneeCountry') ?? pick(r, 'country', 'Country') ?? '',
consigneeCountryName: pick(raw, 'consigneeCountryName', 'ConsigneeCountryName') ?? '',
ioss: pick(raw, 'ioss', 'Ioss', 'IOSS') ?? '',
eori: pick(raw, 'eori', 'Eori', 'EORI') ?? pick(r, 'eori', 'Eori') ?? '',
shippingMethod: productName ?? productCode ?? '',
serviceChannel: channelName ?? channelCode ?? '',
chargeableWeight:
pick(raw, 'chargeableWeight', 'ChargeableWeight') ??
pick(lastW as any, 'chargeableWeight', 'ChargeableWeight') ??
'',
receivableAmount: pick(raw, 'receivableAmount', 'ReceivableAmount') ?? '',
declaredSum: pick(raw, 'declaredSum', 'DeclaredSum') ?? raw?.declaredSum ?? null,
declaredCurrency: pick(raw, 'declaredCurrency', 'DeclaredCurrency') ?? raw?.declaredCurrency ?? '',
additionalServices: pick(raw, 'additionalServices', 'AdditionalServices') ?? raw?.additionalServices,
hasInsurance: (() => {
const hi = pick(raw, 'hasInsurance', 'HasInsurance');
if (hi === true || hi === 1 || hi === '1') return true;
if (hi === false || hi === 0 || hi === '0') return false;
return undefined;
})(),
orderStatus: pick(raw, 'orderStatus', 'OrderStatus') ?? raw?.orderStatus,
predeclareFailReason: pick(raw, 'predeclareFailReason', 'PredeclareFailReason') ?? '',
allocationPendingReason: pick(raw, 'allocationPendingReason', 'AllocationPendingReason') ?? '',
status: resolveOrderStatusCode(raw) || pick(raw, 'status', 'Status') || raw?.status,
handleStatus: pick(raw, 'handleStatus', 'HandleStatus') ?? raw?.handleStatus,
handleStatusName: pick(raw, 'handleStatusName', 'HandleStatusName') ?? raw?.handleStatusName,
cargoAttribute: pick(raw, 'cargoAttribute', 'CargoAttribute') ?? raw?.cargoAttribute,
createTime: pick(raw, 'createTime', 'CreateTime') ?? raw?.createTime,
receiveTime: pick(raw, 'receiveTime', 'ReceiveTime') ?? raw?.receiveTime,
shipTime: pick(raw, 'shipTime', 'ShipTime') ?? raw?.shipTime,
payTime: pick(raw, 'payTime', 'PayTime') ?? raw?.payTime,
signTime: pick(raw, 'signTime', 'SignTime') ?? raw?.signTime,
warehouse: pick(raw, 'warehouse', 'Warehouse') ?? raw?.warehouse,
carrierWaybillNo: pick(raw, 'carrierWaybillNo', 'CarrierWaybillNo') ?? '',
pickupNo: pick(raw, 'pickupNo', 'PickupNo') ?? '',
inboundMethod: pick(raw, 'inboundMethod', 'InboundMethod') ?? '',
fulfillmentType: pick(raw, 'fulfillmentType', 'FulfillmentType') ?? 'direct',
fulfillmentSource: pick(raw, 'fulfillmentSource', 'FulfillmentSource') ?? '',
stockBindStatus: pick(raw, 'stockBindStatus', 'StockBindStatus') ?? 'none',
stockBindLineCount: pick(raw, 'stockBindLineCount', 'StockBindLineCount') ?? 0,
stockBindQtyTotal: pick(raw, 'stockBindQtyTotal', 'StockBindQtyTotal') ?? 0,
domesticTrackingNos: pick(raw, 'domesticTrackingNos', 'DomesticTrackingNos') ?? '',
fulfillProgress: pick(raw, 'fulfillProgress', 'FulfillProgress') ?? '',
primaryBinCode: pick(raw, 'primaryBinCode', 'PrimaryBinCode') ?? '',
};
}
async function openDetailWithOptionalFetch(
row: any,
opts?: { editBasic?: boolean; tab?: 'basic' | 'track' },
) {
let nextRow = row;
const id = row?.id;
if (id != null && id !== '') {
try {
const detail = await getOrderDetail(id);
nextRow = normalizeOrderRow({ ...row, ...detail });
} catch {
/* 保留列表行数*/
}
}
currentOrder.value = nextRow;
const drawer = await ensureDetailDrawer();
drawer?.openDrawer?.({ tab: opts?.tab || 'basic' });
if (opts?.editBasic) {
await nextTick();
drawer?.startBasicEdit?.();
}
}
function handleOrderDetailUpdated(row: any) {
currentOrder.value = normalizeOrderRow(row);
const idx = orderList.value.findIndex((it) => Number(it.id) === Number(row?.id));
if (idx >= 0) {
orderList.value[idx] = normalizeOrderRow({ ...orderList.value[idx], ...row });
}
}
const handleOrderDetailClick = (row: number) => {
if (row >= 0 && row < orderList.value.length) {
openDetailWithOptionalFetch(orderList.value[row]);
}
};
// 当前激活的标签页(我的订单=订单状态;代发订单=代发进度)
const validStatusSet = new Set(ORDER_STATUS_TABS.map((meta) => meta.value));
function resolveActiveTabFromQuery(): string {
if (isFulfillList.value) {
const raw = route.query.progress;
const progress = Array.isArray(raw) ? raw[0] : raw;
if (typeof progress === 'string' && FULFILL_PROGRESS_TAB_SET.has(progress)) {
return progress;
}
return FULFILL_PROGRESS_ALL;
}
const raw = route.query.status;
const status = Array.isArray(raw) ? raw[0] : raw;
if (typeof status === 'string' && validStatusSet.has(status as any)) {
return status;
}
return ORDER_STATUS_ALL;
}
const activeTab = ref<string>(resolveActiveTabFromQuery());
const activeHandleTab = ref<OrderHandleStatusCode>(ORDER_HANDLE_STATUS_ALL);
const tabCounts = ref<Record<string, number>>({});
const handleCounts = ref<Record<string, { pending: number; processed: number }>>({});
const showHandleSubTabs = computed(
() => !isFulfillList.value && isOrderHandleSubTabParent(activeTab.value),
);
const showExceptionCreateActions = computed(
() =>
!isFulfillList.value && !['problematic', 'claimed', 'deleted'].includes(activeTab.value),
);
const showMarkProcessedAction = computed(
() => showHandleSubTabs.value && activeHandleTab.value === 'pending',
);
function isActiveTab(...keys: string[]) {
return keys.includes(activeTab.value);
}
function isFulfillProgressTab(...keys: string[]) {
return isFulfillList.value && keys.includes(activeTab.value);
}
/** Tab 下动作优先级(越靠前越优先外露,最4 个) */
const FULFILL_TAB_TOOLBAR_ACTION_ORDER: Record<string, ToolbarActionKey[]> = {
all: ['stockBind', 'pay', 'predeclare', 'batchPrint', 'modifyOrder', 'delete', 'export'],
pendingBind: ['stockBind', 'modifyOrder', 'predeclare', 'delete', 'pay', 'export'],
domesticInTransit: ['batchPrint', 'export'],
arrivedPendingPick: ['batchPrint', 'export'],
outboundDone: ['batchPrint', 'export'],
};
/** 按当前状态收敛工具栏,避免客户在无关 Tab 看到一排无效按*/
const showPayAction = computed(() =>
isFulfillList.value
? isFulfillProgressTab('all', 'pendingBind')
: isActiveTab('all', 'pendingPayment'),
);
const showPredeclareAction = computed(() =>
isFulfillList.value
? isFulfillProgressTab('all', 'pendingBind')
: isActiveTab('all', 'draft', 'predeclared'),
);
const showPrintAction = computed(() =>
isFulfillList.value
? isFulfillProgressTab('all', 'domesticInTransit', 'arrivedPendingPick', 'outboundDone')
: isActiveTab(
'all',
'predeclared',
'pendingPayment',
'pendingShip',
'pendingOnline',
'shipping',
'deliverySuccess',
'deliveryFailed',
),
);
const showModifyOrderAction = computed(() =>
isFulfillList.value
? isFulfillProgressTab('all', 'pendingBind', 'domesticInTransit')
: isActiveTab('all', 'draft', 'predeclared', 'pendingAllocation', 'pendingPayment', 'pendingShip'),
);
const showInterceptActions = computed(() =>
!isFulfillList.value
&& isActiveTab('all', 'predeclared', 'pendingAllocation', 'pendingPayment', 'pendingShip'),
);
const showDeleteAction = computed(() =>
isFulfillList.value
? isFulfillProgressTab('pendingBind')
: isActiveTab('all', 'draft', 'predeclared'),
);
const showCreatePickupAction = computed(
() => !isFulfillList.value && isActiveTab('predeclared') && hasPermission('Order.Pickup.Create'),
);
const TOOLBAR_MAX_PRIMARY = 4;
type ToolbarActionKey =
| 'markProcessed'
| 'pay'
| 'predeclare'
| 'batchPrint'
| 'createPickup'
| 'stockBind'
| 'createProblematic'
| 'createClaimed'
| 'intercept'
| 'cancelIntercept'
| 'delete'
| 'export'
| 'modifyOrder';
const TOOLBAR_ACTION_LABEL_KEYS: Record<ToolbarActionKey, string> = {
markProcessed: 'order.myOrders.actions.markProcessed',
pay: 'order.myOrders.actions.pay',
predeclare: 'order.myOrders.actions.predeclare',
batchPrint: 'order.myOrders.actions.batchPrint',
createPickup: 'order.myOrders.actions.createPickup',
stockBind: 'order.myOrders.actions.stockBind',
createProblematic: 'order.myOrders.actions.createProblematic',
createClaimed: 'order.myOrders.actions.createClaimed',
intercept: 'order.myOrders.actions.intercept',
cancelIntercept: 'order.myOrders.actions.cancelIntercept',
delete: 'order.myOrders.actions.delete',
export: 'order.myOrders.actions.export',
modifyOrder: 'order.myOrders.actions.modifyOrder',
};
/** Tab 下动作优先级(越靠前越优先外露,最4 个) */
const TAB_TOOLBAR_ACTION_ORDER: Record<string, ToolbarActionKey[]> = {
all: [
'pay',
'predeclare',
'batchPrint',
'modifyOrder',
'delete',
'stockBind',
'createProblematic',
'createClaimed',
'intercept',
'cancelIntercept',
'export',
],
draft: ['predeclare', 'modifyOrder', 'delete', 'batchPrint', 'export', 'stockBind', 'createProblematic', 'createClaimed'],
predeclared: ['createPickup', 'batchPrint', 'modifyOrder', 'delete', 'intercept', 'cancelIntercept', 'export', 'stockBind'],
pendingAllocation: [
'modifyOrder',
'batchPrint',
'stockBind',
'intercept',
'cancelIntercept',
'createProblematic',
'createClaimed',
'export',
],
pendingPayment: [
'pay',
'batchPrint',
'modifyOrder',
'stockBind',
'intercept',
'cancelIntercept',
'export',
],
pendingShip: ['batchPrint', 'modifyOrder', 'intercept', 'cancelIntercept', 'stockBind', 'export'],
pendingOnline: ['batchPrint', 'export', 'stockBind'],
shipping: ['batchPrint', 'export', 'stockBind'],
deliverySuccess: ['batchPrint', 'export', 'stockBind'],
deliveryFailed: ['batchPrint', 'export', 'stockBind', 'createProblematic', 'createClaimed'],
problematic: ['markProcessed', 'export', 'stockBind'],
claimed: ['markProcessed', 'export', 'stockBind'],
deleted: ['export'],
};
const ALL_TOOLBAR_ACTION_KEYS: ToolbarActionKey[] = [
'markProcessed',
'pay',
'predeclare',
'batchPrint',
'createPickup',
'stockBind',
'createProblematic',
'createClaimed',
'intercept',
'cancelIntercept',
'delete',
'export',
'modifyOrder',
];
function isToolbarActionVisible(key: ToolbarActionKey): boolean {
switch (key) {
case 'markProcessed':
return showMarkProcessedAction.value;
case 'pay':
return showPayAction.value;
case 'predeclare':
return showPredeclareAction.value;
case 'batchPrint':
return showPrintAction.value;
case 'createPickup':
return showCreatePickupAction.value;
case 'stockBind':
return hasPermission(
isFulfillList.value ? 'Order.FulfillOrders.StockBind' : 'Order.MyOrders.StockBind',
);
case 'createProblematic':
case 'createClaimed':
return showExceptionCreateActions.value;
case 'intercept':
case 'cancelIntercept':
return showInterceptActions.value;
case 'delete':
return showDeleteAction.value;
case 'export':
return true;
case 'modifyOrder':
return showModifyOrderAction.value;
default:
return false;
}
}
const listColumnStorageKey = computed(() =>
isFulfillList.value ? FULFILL_ORDERS_COLUMN_STORAGE_KEY : MY_ORDERS_COLUMN_STORAGE_KEY,
);
function getToolbarActionLabelKey(key: ToolbarActionKey) {
if (key === 'stockBind') {
return isFulfillList.value
? 'order.fulfillOrders.actions.manageBind'
: 'order.myOrders.actions.stockBindConvert';
}
return TOOLBAR_ACTION_LABEL_KEYS[key];
}
const orderedVisibleToolbarActions = computed(() => {
const order = isFulfillList.value
? FULFILL_TAB_TOOLBAR_ACTION_ORDER[activeTab.value] ?? FULFILL_TAB_TOOLBAR_ACTION_ORDER.all
: TAB_TOOLBAR_ACTION_ORDER[activeTab.value] ?? TAB_TOOLBAR_ACTION_ORDER.all;
const seen = new Set<ToolbarActionKey>();
const result: ToolbarActionKey[] = [];
for (const key of order) {
if (seen.has(key) || !isToolbarActionVisible(key)) continue;
seen.add(key);
result.push(key);
}
for (const key of ALL_TOOLBAR_ACTION_KEYS) {
if (!seen.has(key) && isToolbarActionVisible(key)) {
result.push(key);
}
}
return result;
});
const primaryToolbarActions = computed(() =>
orderedVisibleToolbarActions.value.slice(0, TOOLBAR_MAX_PRIMARY),
);
const overflowToolbarActions = computed(() =>
orderedVisibleToolbarActions.value.slice(TOOLBAR_MAX_PRIMARY),
);
const showToolbarMore = computed(() => overflowToolbarActions.value.length > 0);
function toolbarActionNeedsSelection(key: ToolbarActionKey): boolean {
return key !== 'export';
}
function getToolbarActionLoadingKey(key: ToolbarActionKey): string | null {
const map: Partial<Record<ToolbarActionKey, string>> = {
markProcessed: 'markProcessed',
pay: 'pay',
predeclare: 'predeclare',
batchPrint: 'batchPrint',
export: 'export',
};
return map[key] ?? null;
}
function isToolbarActionDisabled(key: ToolbarActionKey): boolean {
if (toolbarActionNeedsSelection(key) && selectedRowCount.value === 0) {
return true;
}
const loadingKey = getToolbarActionLoadingKey(key);
if (loadingKey) {
return isActionBusy(loadingKey);
}
if (key === 'createProblematic') {
return isActionBusy('markProblematic');
}
if (key === 'createClaimed') {
return isActionBusy('markClaimed');
}
return !!actionLoadingKey.value;
}
function handleToolbarAction(key: ToolbarActionKey) {
if (isToolbarActionDisabled(key)) return;
if (key === 'markProcessed') return handleMarkProcessed();
if (key === 'pay') return handlePay();
if (key === 'predeclare') return handlePreDeclare();
if (key === 'batchPrint') return handleBatchPrint();
if (key === 'createPickup') return handleCreatePickup();
if (key === 'stockBind') return openStockBindModal();
if (key === 'createProblematic') return openProblematicModal();
if (key === 'createClaimed') return openClaimedModal();
if (key === 'intercept') return handleIntercept();
if (key === 'cancelIntercept') return handleCancelIntercept();
if (key === 'delete') return handleDelete();
if (key === 'export') return handleExport();
if (key === 'modifyOrder') return handleModifyOrder();
}
const problematicModalVisible = ref(false);
const claimedModalVisible = ref(false);
const claimContext = ref<{
hasInsurance: boolean | null;
declaredSum: number | null;
declaredCurrency: string | null;
}>({
hasInsurance: null,
declaredSum: null,
declaredCurrency: null,
});
const stockBindModalVisible = ref(false);
const stockBindOrderIds = ref<number[]>([]);
const exceptionOrderIds = ref<number[]>([]);
const payConfirmVisible = ref(false);
const payConfirmOrders = ref<Array<{ id: number | string; waybillNo?: string; serviceNo?: string }>>([]);
const handleContextLabel = computed(() => {
if (activeTab.value === 'problematic') {
return t('order.myOrders.handleStatus.context.problematic');
}
if (activeTab.value === 'claimed') {
return t('order.myOrders.handleStatus.context.claimed');
}
return '';
});
const handleSegments = computed(() => {
if (!showHandleSubTabs.value) return [];
const bucket = handleCounts.value[activeTab.value] ?? { pending: 0, processed: 0 };
const total = (tabCounts.value[activeTab.value] ?? 0) || bucket.pending + bucket.processed;
return ORDER_HANDLE_STATUS_LIST.map((meta) => {
let count = total;
if (meta.value === 'pending') count = bucket.pending;
if (meta.value === 'processed') count = bucket.processed;
return {
key: meta.value,
labelKey: meta.labelKey,
count,
tagColor: meta.tagColor,
tagBgColor: meta.tagBgColor,
};
});
});
const tabs = computed(() => {
if (isFulfillList.value) {
return FULFILL_PROGRESS_TABS.map((meta) => ({
key: meta.value,
labelKey: meta.labelKey,
showCount: meta.showTabCount !== false,
count: tabCounts.value[meta.value] ?? null,
}));
}
return ORDER_STATUS_TABS.map((meta) => ({
key: meta.value,
labelKey: meta.labelKey,
showCount: meta.showTabCount !== false,
count: tabCounts.value[meta.value] ?? null,
}));
});
const slidingTabItems = computed(() =>
tabs.value.map((tab) => ({
key: tab.key,
label: t(tab.labelKey),
badge: tab.showCount && tab.count != null ? tab.count : undefined,
}))
);
async function loadTabCounts() {
try {
const { createTimeStart, createTimeEnd } = buildListFilterParams();
const {
total,
counts,
handleCounts: handleCountsRaw,
fulfillProgressCounts,
} = await getOrderStatusCounts({
createTimeStart: createTimeStart || undefined,
createTimeEnd: createTimeEnd || undefined,
fulfillmentType: listFulfillmentTypeFilter.value,
});
if (isFulfillList.value) {
const next: Record<string, number> = {};
for (const meta of FULFILL_PROGRESS_TABS) {
if (meta.value === FULFILL_PROGRESS_ALL) {
next[meta.value] =
Number(fulfillProgressCounts?.all ?? total) || 0;
} else {
next[meta.value] = Number(fulfillProgressCounts?.[meta.value] ?? 0) || 0;
}
}
tabCounts.value = next;
handleCounts.value = {};
return;
}
const next: Record<string, number> = {
[ORDER_STATUS_ALL]: total,
};
for (const meta of ORDER_STATUS_TABS) {
if (meta.value === ORDER_STATUS_ALL) continue;
next[meta.value] = counts[meta.value] ?? 0;
}
tabCounts.value = next;
handleCounts.value = handleCountsRaw ?? {};
} catch {
/* 角标失败不影响列*/
}
}
async function refreshListAndTabCounts() {
await Promise.all([loadOrderList(), loadTabCounts()]);
}
// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(50);
const totalCount = ref(0);
/** 列表筛选:单号关键+ 创建时间(默认近 90 天) */
const listKeyword = ref('');
const createTimeRange = ref<(Date | string)[] | undefined>([
...buildDefaultCreateTimeRange(),
]);
/** 用户明确放宽时间窗(清空)后,不再自动填回默*/
const timeWindowRelaxed = ref(false);
const dateFilterExpanded = ref(false);
const headerSearchParams = reactive<Record<string, string>>({});
const listSortField = ref<string | null>(null);
const listSortOrder = ref<'asc' | 'desc' | null>(null);
const ORDER_SERVER_FILTER_KEYS = [
'waybillNo',
'customerOrderNo',
'trackingNo',
'createTime',
'serviceNo',
'clientNo',
'trackNo',
'orderStatus',
'shippingMethod',
'isPaid',
'receivableAmount',
'predeclareFailReason',
'payTime',
'shipTime',
'receiveTime',
'signTime',
] as const;
const ORDER_SORTABLE_KEYS = [
'createTime',
'payTime',
'shipTime',
'receiveTime',
'signTime',
'waybillNo',
'customerOrderNo',
'trackingNo',
'receivableAmount',
] as const;
function mapSortFieldToApi(field: string | null | undefined): string | undefined {
if (!field) return undefined;
const map: Record<string, string> = {
waybillNo: 'serviceNo',
customerOrderNo: 'clientNo',
trackingNo: 'trackNo',
receivableAmount: 'payableAmount',
};
return map[field] || field;
}
function buildListFilterParams() {
const adapted = adaptOrderListHeaderFilters(headerSearchParams);
let createTimeStart = adapted.createTimeStart || '';
let createTimeEnd = adapted.createTimeEnd || '';
if (!createTimeStart && !createTimeEnd) {
const fromToolbar = formatCreateTimeRangeParam(createTimeRange.value);
if (fromToolbar) {
createTimeStart = fromToolbar.createTimeStart;
createTimeEnd = fromToolbar.createTimeEnd;
} else if (!timeWindowRelaxed.value && !adapted.filters.some((f) =>
['serviceNo', 'clientNo', 'trackNo'].includes(f.field),
) && !(adapted.keyword || listKeyword.value.trim())) {
const [s, e] = buildDefaultCreateTimeRange();
createTimeRange.value = [s, e];
createTimeStart = s.format('YYYY-MM-DD HH:mm:ss');
createTimeEnd = e.format('YYYY-MM-DD HH:mm:ss');
}
}
const keyword = (adapted.keyword || listKeyword.value.trim() || '').trim();
return {
keyword,
createTimeStart,
createTimeEnd,
filters: adapted.filters.length ? adapted.filters : undefined,
sortField: mapSortFieldToApi(listSortField.value),
sortOrder: listSortOrder.value || undefined,
};
}
const usingDefaultTimeWindow = computed(
() => !timeWindowRelaxed.value && isDefaultCreateTimeRange(createTimeRange.value),
);
const timeWindowHelp = computed(() => {
if (timeWindowRelaxed.value && !createTimeRange.value?.length) {
return '';
}
return `默认仅展示近 ${ORDER_LIST_DEFAULT_DAYS} 天订单;按单号精确查询时可清空时间。`;
});
function restoreDefaultTimeWindow() {
createTimeRange.value = [...buildDefaultCreateTimeRange()];
timeWindowRelaxed.value = false;
}
async function onCreateTimeRangeChange(val: any) {
if (val?.length === 2 && val[0] && val[1]) {
timeWindowRelaxed.value = false;
createTimeRange.value = val;
handleSearch();
return;
}
// 清空时间:有精确单号则允许;否则确认
const adapted = adaptOrderListHeaderFilters(headerSearchParams);
const hasNo =
!!(adapted.keyword || listKeyword.value.trim()) ||
adapted.filters.some((f) =>
['serviceNo', 'clientNo', 'trackNo'].includes(f.field),
);
if (hasNo) {
timeWindowRelaxed.value = true;
createTimeRange.value = undefined;
handleSearch();
return;
}
Modal.confirm({
title: '清空时间范围?',
content: `未指定单号时查询全部历史可能较慢。建议保留近 ${ORDER_LIST_DEFAULT_DAYS} 天,或先输入单号再清空时间。`,
okText: '仍要清空',
cancelText: '保留近90天',
onOk: () => {
timeWindowRelaxed.value = true;
createTimeRange.value = undefined;
handleSearch();
},
onCancel: () => {
restoreDefaultTimeWindow();
},
});
}
function handleHeaderSearch() {
currentPage.value = 1;
selectedOrderRows.value = [];
selectedRowCount.value = 0;
loadOrderList();
loadTabCounts();
}
function handleSortChange(payload: { field: string | null; order: 'asc' | 'desc' | null }) {
listSortField.value = payload.field;
listSortOrder.value = payload.order;
currentPage.value = 1;
loadOrderList();
}
const orderList = ref<any[]>([]);
const listLoading = ref(false);
let listRequestSeq = 0;
function escapeHtml(text: string) {
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
const selectedRowCount = ref(0);
/** 表格选中行(用于批量操作*/
const selectedOrderRows = ref<any[]>([]);
/** 当前正在执行的 toolbar 操作(仅对应按钮显示 loading,避免全部按钮联动) */
const actionLoadingKey = ref<string | null>(null);
function isActionLoading(key: string) {
return actionLoadingKey.value === key;
}
function isActionBusy(exceptKey?: string) {
const current = actionLoadingKey.value;
return current != null && current !== exceptKey;
}
async function withOrderActionLoading<T>(key: string, fn: () => Promise<T>): Promise<T> {
if (actionLoadingKey.value) {
return Promise.reject(new Error('busy'));
}
actionLoadingKey.value = key;
try {
return await fn();
} finally {
if (actionLoadingKey.value === key) {
actionLoadingKey.value = null;
}
}
}
const printConnectionState = useHiprintClientState();
const singlePrintVisible = ref(false);
const batchPrintVisible = ref(false);
const batchPrintPreparing = ref(false);
const singlePrintItems = ref<Array<{ id: number | string; label: string; url: string }>>([]);
const batchPrintItems = ref<Array<{ id: number | string; label: string; url: string }>>([]);
watch(batchPrintVisible, (visible) => {
if (!visible) batchPrintPreparing.value = false;
});
async function runSelectedOrderBatch(options: {
action: string;
rows: any[];
payload?: Record<string, unknown>;
loadingKey: string;
syncRunner: () => Promise<void>;
successMessage?: string;
onAsyncComplete?: (ctx: {
job: { successCount: number; failCount: number };
items: Array<{ orderId: number; serviceNo?: string; status: string; failReason?: string; resultJson?: string }>;
rows: any[];
}) => void | Promise<void>;
}) {
const orderIds = options.rows.map((row) => Number(getOrderRowId(row)!));
try {
const job = await postOrderBatchJob({
action: options.action,
orderIds,
payloadJson: options.payload ? JSON.stringify(options.payload) : undefined,
});
const result = await waitOrderBatchJob(job.jobId);
if (result.timedOut) {
Message.warning(formatBatchJobSummaryMessage(result.job, { timedOut: true, jobId: job.jobId }));
await refreshListAndTabCounts();
return;
}
if (options.onAsyncComplete) {
await options.onAsyncComplete({ ...result, rows: options.rows });
} else if (result.job.failCount > 0) {
Message.warning(
formatBatchJobFailureMessage(result.job, result.items, options.rows, (row, item) =>
resolveBatchJobItemRowLabel(row, item)
)
);
} else if (options.successMessage) {
Message.success(options.successMessage);
}
await refreshListAndTabCounts();
return;
} catch (e: any) {
if (!isOrderBatchQueueDisabledError(e)) {
throw e;
}
}
await options.syncRunner();
}
function getOrderRowId(row: any): number | string | undefined {
if (row == null) return undefined;
const id = row.id ?? row.Id;
if (id === undefined || id === null || id === '') return undefined;
return id;
}
function requireSelectedRows(): any[] {
const rows = selectedOrderRows.value.filter((r) => getOrderRowId(r) != null);
if (!rows.length) {
Message.warning('请先选择订单');
return [];
}
return rows;
}
const loadOrderList = async () => {
const requestSeq = ++listRequestSeq;
const status = isFulfillList.value
? ORDER_STATUS_ALL
: activeTab.value === ORDER_STATUS_ALL
? ORDER_STATUS_ALL
: activeTab.value;
const fulfillProgress =
isFulfillList.value && activeTab.value !== FULFILL_PROGRESS_ALL
? activeTab.value
: undefined;
const handleStatus =
showHandleSubTabs.value && activeHandleTab.value !== ORDER_HANDLE_STATUS_ALL
? activeHandleTab.value
: undefined;
const { keyword, createTimeStart, createTimeEnd, filters, sortField, sortOrder } =
buildListFilterParams();
listLoading.value = true;
try {
const { items, total } = await postOrderList({
page: currentPage.value,
pageSize: pageSize.value,
status,
handleStatus,
fulfillmentType: listFulfillmentTypeFilter.value,
fulfillProgress,
keyword: keyword || undefined,
createTimeStart: createTimeStart || undefined,
createTimeEnd: createTimeEnd || undefined,
filters,
sortField,
sortOrder,
});
if (requestSeq !== listRequestSeq) {
return;
}
orderList.value = (items || []).map((row) => normalizeOrderRow(row));
totalCount.value = total;
tabCounts.value[status] = total;
} catch (e: any) {
if (requestSeq !== listRequestSeq) {
return;
}
orderList.value = [];
totalCount.value = 0;
Message.error(e?.message || '加载订单列表失败');
} finally {
if (requestSeq === listRequestSeq) {
listLoading.value = false;
}
}
};
const handleSearch = () => {
currentPage.value = 1;
selectedOrderRows.value = [];
selectedRowCount.value = 0;
loadOrderList();
loadTabCounts();
};
const handleResetSearch = () => {
listKeyword.value = '';
restoreDefaultTimeWindow();
Object.keys(headerSearchParams).forEach((k) => {
headerSearchParams[k] = '';
});
listSortField.value = null;
listSortOrder.value = null;
currentPage.value = 1;
selectedOrderRows.value = [];
selectedRowCount.value = 0;
loadOrderList();
loadTabCounts();
};
// 当前页数据(HandsontablePro 用)
const processedTableData = computed(() => orderList.value);
// 标签页切)
const handleTabChange = (key: string) => {
if (activeTab.value === key) {
return;
}
activeTab.value = key;
activeHandleTab.value = ORDER_HANDLE_STATUS_ALL;
currentPage.value = 1;
orderList.value = [];
selectedOrderRows.value = [];
selectedRowCount.value = 0;
loadOrderList();
};
const handleHandleTabChange = (key: OrderHandleStatusCode) => {
if (activeHandleTab.value === key) {
return;
}
activeHandleTab.value = key;
currentPage.value = 1;
orderList.value = [];
selectedOrderRows.value = [];
selectedRowCount.value = 0;
loadOrderList();
};
// 操作按钮处理(依赖表格多选行;导出按当前 tab 条件,无需选行)
function openPayConfirm(rows: any[]) {
payConfirmOrders.value = rows
.filter((row) => getOrderRowId(row) != null)
.map((row) => ({
id: getOrderRowId(row)!,
waybillNo: row.waybillNo || row.serviceNo,
serviceNo: row.serviceNo,
}));
if (!payConfirmOrders.value.length) return;
payConfirmVisible.value = true;
}
const handlePay = () => {
const rows = requireSelectedRows();
if (!rows.length) return;
openPayConfirm(rows);
};
async function handleCreatePickup() {
const rows = requireSelectedRows();
if (!rows.length) return;
const notPredeclared = rows.filter((r) => resolveOrderStatusCode(r) !== 'predeclared');
if (notPredeclared.length) {
Message.warning(t('order.myOrders.createPickup.predeclaredOnly'));
return;
}
const bound = rows.filter((r) => r?.pickupOrderId || r?.PickupOrderId);
if (bound.length) {
Message.warning(t('order.myOrders.createPickup.alreadyBound'));
return;
}
createPickupMounted.value = true;
const modal = await waitForRef(
() => createPickupModalRef.value,
(v) => typeof v.open === 'function',
);
modal?.open?.(
rows.map((r) => ({
id: getOrderRowId(r)!,
serviceNo: r?.serviceNo || r?.ServiceNo,
warehouseId: r?.warehouseId ?? r?.WarehouseId,
customerId: r?.customerId ?? r?.CustomerId,
})),
);
}
async function handleCreatePickupSuccess() {
await refreshListAndTabCounts();
}
const handleRowPay = (row: any) => {
if (!getOrderRowId(row)) return;
openPayConfirm([row]);
};
async function handlePayConfirmSuccess() {
notifyCustomerBalanceChanged();
await refreshListAndTabCounts();
}
const handlePreDeclare = async () => {
const rows = requireSelectedRows();
if (!rows.length) return;
try {
await withOrderActionLoading('predeclare', async () => {
await runSelectedOrderBatch({
action: 'pre-declare',
rows,
loadingKey: 'predeclare',
successMessage: '预报已提交',
syncRunner: async () => {
for (const row of rows) {
await postOrderPreDeclare({ id: getOrderRowId(row)! });
}
Message.success('预报已提交');
await refreshListAndTabCounts();
},
});
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || '操作失败');
}
}
};
function requireNotShippedRows(rows: any[]): any[] | null {
const blocked = rows.filter((row) => !isOrderNotShipped(row));
if (!blocked.length) return rows;
Message.warning(t('order.myOrders.intercept.notShippedOnly'));
return null;
}
async function executeInterceptBatch(rows: any[]) {
try {
await withOrderActionLoading('intercept', async () => {
await runSelectedOrderBatch({
action: 'intercept',
rows,
loadingKey: 'intercept',
successMessage: t('order.myOrders.intercept.submitSuccess'),
syncRunner: async () => {
for (const row of rows) {
await postOrderIntercept({ id: getOrderRowId(row)! });
}
Message.success(t('order.myOrders.intercept.submitSuccess'));
await refreshListAndTabCounts();
},
});
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || t('order.myOrders.intercept.submitFailed'));
}
}
}
async function executeCancelInterceptBatch(rows: any[]) {
try {
await withOrderActionLoading('cancelIntercept', async () => {
await runSelectedOrderBatch({
action: 'cancel-intercept',
rows,
loadingKey: 'cancelIntercept',
successMessage: t('order.myOrders.intercept.cancelSuccess'),
syncRunner: async () => {
for (const row of rows) {
await postOrderCancelIntercept({ id: getOrderRowId(row)! });
}
Message.success(t('order.myOrders.intercept.cancelSuccess'));
await refreshListAndTabCounts();
},
});
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || t('order.myOrders.intercept.cancelFailed'));
}
}
}
const handleIntercept = () => {
const rows = requireSelectedRows();
if (!rows.length) return;
const eligible = requireNotShippedRows(rows);
if (!eligible) return;
Modal.confirm({
title: t('order.myOrders.intercept.confirmTitle'),
content: t('order.myOrders.intercept.confirmContent'),
okText: t('order.myOrders.intercept.confirmOk'),
cancelText: t('common.cancel'),
onOk: () => executeInterceptBatch(eligible),
});
};
const handleCancelIntercept = () => {
const rows = requireSelectedRows();
if (!rows.length) return;
const eligible = requireNotShippedRows(rows);
if (!eligible) return;
Modal.confirm({
title: t('order.myOrders.intercept.cancelConfirmTitle'),
content: t('order.myOrders.intercept.cancelConfirmContent'),
okText: t('order.myOrders.intercept.cancelConfirmOk'),
cancelText: t('common.cancel'),
onOk: () => executeCancelInterceptBatch(eligible),
});
};
const handleDelete = () => {
const rows = requireSelectedRows();
if (!rows.length) return;
const blocked = rows.filter((row) => !isOrderDeletable(resolveOrderStatusCode(row)));
if (blocked.length) {
Message.warning('仅草稿或已预报订单可删除');
return;
}
Modal.confirm({
title: '确认删除',
content: `确定删除选中的 ${rows.length} 条订单吗?`,
onOk: async () => {
try {
await withOrderActionLoading('delete', async () => {
await runSelectedOrderBatch({
action: 'delete',
rows,
loadingKey: 'delete',
successMessage: '已删除',
syncRunner: async () => {
for (const row of rows) {
await postOrderDelete({ id: getOrderRowId(row)! });
}
Message.success('已删除');
await refreshListAndTabCounts();
},
});
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || '删除失败');
}
throw e;
}
},
});
};
function buildPrintItem(row: any, printUrl: string) {
const id = getOrderRowId(row)!;
const label = row?.waybillNo || row?.trackingNo || row?.customerOrderNo || String(id);
return { id, label, url: printUrl };
}
function isUsablePrintUrl(raw: unknown) {
const value = String(raw ?? '').trim();
if (!value) return false;
if (value.includes('获取中')) return false;
return true;
}
const handleRowPrint = async (row: any) => {
singlePrintVisible.value = false;
singlePrintItems.value = [];
if (!row || !getOrderRowId(row)) {
Message.warning('请选择要打印的订单');
return;
}
try {
await withOrderActionLoading('singlePrint', async () => {
const { printUrl } = await postOrderPrint({ id: getOrderRowId(row)! });
if (!isUsablePrintUrl(printUrl)) {
Message.info('未获取到打印文件,已打开打印弹窗供预览布局');
singlePrintVisible.value = true;
return;
}
singlePrintItems.value = [buildPrintItem(row, printUrl)];
singlePrintVisible.value = true;
if (!printConnectionState.enabled || !printConnectionState.connected) {
Message.info('已打开面单预览;静默打印需先在顶部连接打印开关');
}
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || '打印失败');
}
}
};
const handleBatchPrint = async () => {
const rows = requireSelectedRows();
if (!rows.length) return;
if (batchPrintPreparing.value || isActionLoading('batchPrint')) return;
batchPrintItems.value = rows.map((row) => {
const orderId = getOrderRowId(row)!;
const cached = getCachedPrintUrl(orderId);
return buildPrintItem(row, isUsablePrintUrl(cached) ? cached! : '');
});
batchPrintVisible.value = true;
batchPrintPreparing.value = true;
try {
await withOrderActionLoading('batchPrint', async () => {
const urlMap = await fetchPrintUrlsForOrders(rows.map((row) => getOrderRowId(row)!));
const printItems = rows
.map((row) => {
const orderId = String(getOrderRowId(row)!);
const printUrl = urlMap.get(orderId);
return printUrl ? buildPrintItem(row, printUrl) : null;
})
.filter(Boolean) as Array<{ id: number | string; label: string; url: string }>;
batchPrintItems.value = printItems.length
? printItems
: rows.map((row) => buildPrintItem(row, ''));
if (!printItems.length) {
Message.info('未获取到可打印文件');
return;
}
if (printItems.length < rows.length) {
Message.warning(`已获取 ${printItems.length}/${rows.length} 张面单,其余失败可重试`);
}
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || '批量打印失败');
}
} finally {
batchPrintPreparing.value = false;
}
};
const handleExport = async () => {
try {
await withOrderActionLoading('export', async () => {
const status = isFulfillList.value
? ORDER_STATUS_ALL
: activeTab.value === ORDER_STATUS_ALL
? ORDER_STATUS_ALL
: activeTab.value;
const fulfillProgress =
isFulfillList.value && activeTab.value !== FULFILL_PROGRESS_ALL
? activeTab.value
: undefined;
const { keyword, createTimeStart, createTimeEnd, filters, sortField, sortOrder } =
buildListFilterParams();
const { downloadUrl } = await postOrderExport({
status,
fulfillmentType: listFulfillmentTypeFilter.value,
fulfillProgress,
keyword,
createTimeStart,
createTimeEnd,
filters,
sortField,
sortOrder,
});
if (downloadUrl) window.open(downloadUrl, '_blank');
Message.success(downloadUrl ? '导出链接已打开' : '导出已提交');
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(
e?.message || `导出失败(单次最多 ${ORDER_EXPORT_MAX_ROWS.toLocaleString()} 条)`,
);
}
}
};
const handleModifyOrder = async () => {
const rows = requireSelectedRows();
if (!rows.length) return;
if (rows.length > 1) {
Message.warning(t('order.myOrders.modify.singleOnly'));
return;
}
await openDetailWithOptionalFetch(rows[0], { editBasic: true });
};
function isDirectFulfillmentRow(row: any) {
const ft = String(pick(row, 'fulfillmentType', 'FulfillmentType') || 'direct').trim();
return ft !== 'warehouse';
}
const openStockBindModal = () => {
const rows = requireSelectedRows();
if (!rows.length) return;
const open = () => {
stockBindOrderIds.value = rows.map((row) => Number(getOrderRowId(row)!));
stockBindModalVisible.value = true;
};
if (!isFulfillList.value && rows.some(isDirectFulfillmentRow)) {
Modal.confirm({
title: t('order.myOrders.stockBind.convertTitle'),
content: t('order.myOrders.stockBind.convertContent'),
// Defer past confirm teardown so StockBindModal can mount/open cleanly.
onOk: () =>
new Promise<void>((resolve) => {
window.setTimeout(() => {
open();
resolve();
}, 0);
}),
});
return;
}
open();
};
const openProblematicModal = () => {
const rows = requireSelectedRows();
if (!rows.length) return;
exceptionOrderIds.value = rows.map((row) => Number(getOrderRowId(row)!));
problematicModalVisible.value = true;
};
function resolveClaimContextFromRow(row: any) {
let hasInsurance: boolean | null = null;
const hi = row?.hasInsurance ?? row?.HasInsurance;
if (hi === true || hi === 1 || hi === '1') hasInsurance = true;
else if (hi === false || hi === 0 || hi === '0') hasInsurance = false;
else {
const services = row?.additionalServices ?? row?.AdditionalServices;
if (Array.isArray(services)) {
hasInsurance = services.some((x: any) => String(x).toLowerCase() === 'insurance');
} else if (typeof services === 'string' && services.trim()) {
hasInsurance = services.toLowerCase().includes('insurance');
}
}
const sumRaw = row?.declaredSum ?? row?.DeclaredSum;
const sum = sumRaw == null || sumRaw === '' ? null : Number(sumRaw);
return {
hasInsurance,
declaredSum: Number.isFinite(sum as number) ? (sum as number) : null,
declaredCurrency: String(row?.declaredCurrency ?? row?.DeclaredCurrency ?? '').trim() || null,
};
}
const openClaimedModal = async () => {
const rows = requireSelectedRows();
if (!rows.length) return;
exceptionOrderIds.value = rows.map((row) => Number(getOrderRowId(row)!));
let ctxRow = rows[0];
const id = getOrderRowId(ctxRow);
if (rows.length === 1 && id != null) {
try {
const detail = await getOrderDetail(id);
ctxRow = normalizeOrderRow({ ...ctxRow, ...detail });
} catch {
/* keep list row */
}
}
claimContext.value = resolveClaimContextFromRow(ctxRow);
claimedModalVisible.value = true;
};
const handleStockBindSuccess = async () => {
await refreshListAndTabCounts();
if (!isFulfillList.value) {
Message.info(t('order.myOrders.stockBind.convertedHint'));
}
};
const handleExceptionActionSuccess = async () => {
await refreshListAndTabCounts();
};
const handleMarkProcessed = async () => {
const rows = requireSelectedRows();
if (!rows.length) return;
try {
await withOrderActionLoading('markProcessed', async () => {
await runSelectedOrderBatch({
action: 'handle-status-update',
rows,
loadingKey: 'markProcessed',
payload: { handleStatus: 'processed' },
successMessage: t('order.myOrders.handleStatus.success'),
syncRunner: async () => {
const result = await postOrderHandleStatusUpdate({
orderIds: rows.map((row) => Number(getOrderRowId(row)!)),
handleStatus: 'processed',
});
if (result.failures?.length) {
const lines = result.failures
.slice(0, 5)
.map((f) => `${f.serviceNo || f.orderId}: ${f.reason}`)
.join('\n');
if (result.successCount > 0) {
Message.warning(
t('order.myOrders.batch.partialSuccess', {
success: result.successCount,
fail: result.failures.length,
detail: lines,
}),
);
} else {
Message.error(lines || t('order.myOrders.handleStatus.failed'));
return;
}
} else {
Message.success(t('order.myOrders.handleStatus.success'));
}
await refreshListAndTabCounts();
},
});
});
} catch (e: any) {
if (e?.message !== 'busy') {
Message.error(e?.message || t('order.myOrders.handleStatus.failed'));
}
}
};
// 分页处理函数
const handlePageChange = (page: number) => {
currentPage.value = page;
loadOrderList();
};
const handlePageSizeChange = (size: number) => {
pageSize.value = size;
currentPage.value = 1;
loadOrderList();
};
// HandsontablePro 列定义(支持命名方案配置,最多 30 列)
const initialIsFulfillList = route.meta.listMode === 'fulfill';
const columnConfigState = ref(
loadColumnConfigState(
initialIsFulfillList ? FULFILL_ORDERS_COLUMN_STORAGE_KEY : MY_ORDERS_COLUMN_STORAGE_KEY,
MY_ORDERS_COLUMN_CATALOG,
initialIsFulfillList ? FULFILL_ORDERS_DEFAULT_KEYS : MY_ORDERS_DEFAULT_KEYS,
t('order.myOrders.columnConfig.defaultScheme'),
),
);
const columnSchemeOptions = computed(() =>
columnConfigState.value.schemes.map((s) => ({ label: s.name, value: s.id })),
);
const activeColumnKeys = computed(() =>
filterMyOrdersFieldKeys(getActiveScheme(columnConfigState.value).keys),
);
const listColumnCatalog = computed(() => filterMyOrdersColumns(MY_ORDERS_COLUMN_CATALOG));
const hotColumns = computed(() => {
const statusOptions = ORDER_STATUS_LIST.map((meta) => ({
label: t(meta.labelKey),
value: meta.value,
}));
const numberKeys = new Set([
'waybillNo',
'customerOrderNo',
'trackingNo',
'serviceNo',
'clientNo',
'trackNo',
]);
const base = withServerFilterColumns(
buildHotColumns(listColumnCatalog.value, activeColumnKeys.value, t, te),
ORDER_SERVER_FILTER_KEYS,
(col) => {
if (numberKeys.has(col.key)) {
return {
defaultTextOp: 'equals' as const,
multiValue: true,
headerMode: 'inline' as const,
};
}
if (col.key === 'createTime' || col.key === 'payTime' || col.key === 'shipTime'
|| col.key === 'receiveTime' || col.key === 'signTime') {
return { filterType: 'date' as const, headerMode: 'icon' as const };
}
if (col.key === 'orderStatus') {
return {
filterType: 'enum' as const,
headerMode: 'icon' as const,
filterOptions: statusOptions,
};
}
if (col.key === 'isPaid') {
return {
filterType: 'enum' as const,
headerMode: 'icon' as const,
filterOptions: [
{ label: '已支付', value: '1' },
{ label: '已支付', value: '1' },
],
};
}
if (col.key === 'receivableAmount') {
return { filterType: 'number' as const, headerMode: 'icon' as const };
}
return {};
},
);
return withSortableColumns(base, ORDER_SORTABLE_KEYS);
});
const tableColumnsKey = computed(() => activeColumnKeys.value.join('|'));
function handleColumnSchemeChange(id: string) {
if (!columnConfigState.value.schemes.some((s) => s.id === id)) return;
columnConfigState.value = {
...columnConfigState.value,
activeId: id,
};
saveColumnConfigState(listColumnStorageKey.value, columnConfigState.value);
}
async function openColumnConfig() {
columnConfigMounted.value = true;
const modal = await waitForRef(
() => columnConfigModalRef.value,
(v) => typeof v.open === 'function',
);
modal?.open?.();
}
function handleColumnConfigApply(payload: { activeId: string; schemes: ColumnScheme[] }) {
columnConfigState.value = {
activeId: payload.activeId,
schemes: payload.schemes,
};
saveColumnConfigState(listColumnStorageKey.value, columnConfigState.value);
Message.success(t('order.myOrders.columnConfig.applySuccess'));
}
const showRowPayAction = computed(
() => activeTab.value === 'pendingPayment' && hasPermission('Order.MyOrders.Pay'),
);
const actionRenderer = (_rowData: any, rowIndex: number) => {
const parts = [
renderWarehouseActionBtn('view', t('common.viewDetail'), 'view'),
renderWarehouseActionBtn('track', t('order.myOrders.actions.viewTrack'), 'track'),
renderWarehouseActionBtn('advisor', t('nanaAssistant.actionAdvisor'), 'advisor'),
];
if (showPrintAction.value) {
parts.push(renderWarehouseActionBtn('print', t('order.myOrders.actions.print'), 'print'));
}
if (showRowPayAction.value) {
parts.push(renderWarehouseActionBtn('pay', t('order.myOrders.actions.pay'), 'pay'));
}
return wrapWarehouseActions(parts, rowIndex);
};
const customCellRenderer = (row: number, col: number, value: any, rowData: any) => {
const colOffset = 2; // action + serialNo
const dataColIndex = col - colOffset;
if (dataColIndex < 0 || dataColIndex >= hotColumns.value.length) return null;
const colKey = hotColumns.value[dataColIndex].key;
if (colKey === 'orderStatus') {
const code = resolveOrderStatusCode(rowData);
const meta = getOrderStatusMeta(code);
const statusText = meta ? t(meta.labelKey) : (rowData?.orderStatus || code || '--');
const handleCode = resolveOrderHandleStatusCode(rowData);
const handleMeta = getOrderHandleStatusMeta(handleCode);
const handleText =
rowData?.handleStatusName ||
(handleMeta ? t(handleMeta.labelKey) : '');
const showHandleTag = isOrderHandleSubTabParent(code) && handleText;
const handleTagHtml = showHandleTag
? buildOrderStatusSubTagHtml(String(handleText), handleMeta)
: '';
return `<span style="display:inline-flex;align-items:center;flex-wrap:wrap;gap:6px;max-width:100%;">${buildOrderStatusTagHtml(String(statusText), meta)}${handleTagHtml}</span>`;
}
if (colKey === 'predeclareFailReason') {
const reason = rowData?.predeclareFailReason || value || '';
if (!reason) return null;
const guide = buildFailGuideFromReason(String(reason));
const display = guide.reason || String(reason);
const escaped = escapeHtml(display);
const title = escapeHtml(guide.rawReason || String(reason));
return `<span title="${title}" style="display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#8a5c58;font-size:12px;">${escaped}</span>`;
}
if (colKey === 'isPaid') {
const paid = rowData?.isPaid === true || rowData?.isPaid === 1 || rowData?.IsPaid === true || rowData?.IsPaid === 1;
const paidText = paid ? t('order.myOrders.drawer.yes') : t('order.myOrders.drawer.no');
return buildBooleanTagHtml(paidText, paid);
}
if (colKey === 'cargoAttribute') {
const raw = String(rowData?.cargoAttribute || value || '').trim().toLowerCase();
if (!raw) return null;
const map: Record<string, string> = {
general: 'order.myOrders.drawer.cargoAttribute.general',
electronics: 'order.myOrders.drawer.cargoAttribute.electronics',
'3c': 'order.myOrders.drawer.cargoAttribute.electronics',
sensitive: 'order.myOrders.drawer.cargoAttribute.sensitive',
};
const labelKey = map[raw];
const text = labelKey ? t(labelKey) : String(rowData?.cargoAttribute || value);
const tone = raw === 'sensitive' ? 'wait' : raw === 'general' ? 'mute' : 'neutral';
return buildStatusTagHtml(text, tone);
}
if (colKey === 'consigneeCountry') {
const code = rowData?.consigneeCountry || value || '';
const name = rowData?.consigneeCountryName || '';
if (code && name) return `${code} ${name}`;
return name || code || null;
}
if (['chargeableWeight', 'receivableAmount'].includes(colKey)) {
return value != null && value !== '' ? Number(value).toLocaleString() : null;
}
if (colKey === 'trackingNo') {
const no = String(value || '').trim();
if (!no) return '--';
const escaped = escapeHtml(no);
return `<span title="${t('order.myOrders.table.copyHint')}: ${escaped}" style="font-family:ui-monospace,Consolas,monospace;font-size:12px;">${escaped}</span>`;
}
if (colKey === 'stockBindStatus') {
const code = String(rowData?.stockBindStatus || value || 'none').trim() || 'none';
const key = `order.myOrders.stockBind.status.${code}`;
const text = t(key);
const label = text === key ? code : text;
const tone =
code === 'deducted' ? 'alert' : code === 'bound' ? 'ok' : code === 'released' ? 'wait' : 'mute';
return buildStatusTagHtml(label, tone);
}
if (colKey === 'fulfillProgress') {
const code = String(rowData?.fulfillProgress || value || '').trim();
if (!code) return '--';
const key = `order.fulfillOrders.progress.${code}`;
const text = t(key);
const label = text === key ? code : text;
const tone =
code === 'outboundDone'
? 'ok'
: code === 'arrivedPendingPick'
? 'wait'
: code === 'domesticInTransit'
? 'neutral'
: 'mute';
return buildStatusTagHtml(label, tone);
}
if (colKey === 'primaryBinCode') {
const code = String(rowData?.primaryBinCode || value || '').trim();
return code || '--';
}
if (colKey === 'domesticTrackingNos') {
const nos = String(rowData?.domesticTrackingNos || value || '').trim();
if (!nos) return '--';
const escaped = escapeHtml(nos);
return `<span title="${escaped}" style="font-family:ui-monospace,Consolas,monospace;font-size:12px;">${escaped}</span>`;
}
if (colKey === 'fulfillmentSource') {
const code = String(rowData?.fulfillmentSource || value || '').trim();
if (!code) return '--';
const key = `order.fulfillOrders.source.${code}`;
const text = t(key);
return text === key ? code : text;
}
if (colKey === 'fulfillmentType') {
const code = String(rowData?.fulfillmentType || value || 'direct').trim() || 'direct';
if (code === 'warehouse') {
return buildStatusTagHtml(t('order.fulfillOrders.badge'), 'wait');
}
return buildStatusTagHtml(t('order.waybillManage.fulfillmentType.direct'), 'mute');
}
if (colKey === 'stockBindQtyTotal') {
const qty = Number(rowData?.stockBindQtyTotal ?? value ?? 0);
return qty > 0 ? String(qty) : '--';
}
// 首列添加 data-row-status 用于行背景样)
if (colKey === 'waybillNo') {
const statusCode = resolveOrderStatusCode(rowData);
const escaped = escapeHtml(String(value || '--'));
return `<span data-row-status="${statusCode}">${escaped}</span>`;
}
return null;
};
const handleActionClick = (row: any, _rowIndex: number, action?: string) => {
if (action === 'pay') {
handleRowPay(row);
return;
}
if (action === 'print') {
void handleRowPrint(row);
return;
}
if (action === 'advisor') {
openAskAdvisor(router, buildWaybillContextFromRow(row, 'myOrders'));
return;
}
if (action === 'track') {
void openDetailWithOptionalFetch(row, { tab: 'track' });
return;
}
openDetailWithOptionalFetch(row);
};
const handleSelectionChange = (rows: any[]) => {
selectedOrderRows.value = rows ?? [];
selectedRowCount.value = selectedOrderRows.value.length;
};
onMounted(() => {
nextTick(async () => {
await Promise.all([loadOrderList(), loadTabCounts()]);
await tryOpenOrderFromQuery();
});
});
async function tryOpenOrderFromQuery() {
const rawId = route.query.orderId;
const idStr = Array.isArray(rawId) ? rawId[0] : rawId;
const id = Number(idStr);
if (!Number.isFinite(id) || id <= 0) return;
const editRaw = route.query.edit;
const editStr = Array.isArray(editRaw) ? editRaw[0] : editRaw;
const editBasic = String(editStr || '') === '1';
try {
await openDetailWithOptionalFetch({ id }, { editBasic });
} finally {
const nextQuery = { ...route.query } as Record<string, any>;
delete nextQuery.orderId;
delete nextQuery.edit;
router.replace({ query: nextQuery });
}
}
watch(
() => (isFulfillList.value ? route.query.progress : route.query.status),
() => {
const next = resolveActiveTabFromQuery();
if (next === activeTab.value) return;
activeTab.value = next;
activeHandleTab.value = ORDER_HANDLE_STATUS_ALL;
currentPage.value = 1;
orderList.value = [];
selectedOrderRows.value = [];
selectedRowCount.value = 0;
loadOrderList();
loadTabCounts();
},
);
watch(
() => route.query.orderId,
(orderId) => {
if (!orderId) return;
void tryOpenOrderFromQuery();
},
);
</script>
<template>
<div class="my-orders-container">
<!-- 单一工作面:Tabs/筛+ 子状+ 工具+ 表格 -->
<div class="table-section">
<div class="tabs-actions-section">
<div class="tabs-slot">
<SlidingTabs
:model-value="activeTab"
:items="slidingTabItems"
@change="handleTabChange"
/>
</div>
<div class="toolbar-left">
<div class="list-filters">
<a-input
v-model="listKeyword"
allow-clear
:placeholder="t('order.myOrders.search.keywordPlaceholder')"
style="width: 240px"
@press-enter="handleSearch"
/>
<span class="list-date-filter">
<a-tooltip v-if="!dateFilterExpanded" content="日期筛选">
<a-button class="list-date-toggle" @click="dateFilterExpanded = true">
<template #icon>
<IconCalendar />
</template>
</a-button>
</a-tooltip>
<a-range-picker
v-else
:model-value="createTimeRange"
style="width: 260px"
allow-clear
:placeholder="[
t('order.myOrders.search.dateStart'),
t('order.myOrders.search.dateEnd'),
]"
@change="onCreateTimeRangeChange"
/>
<a-tooltip :content="timeWindowHelp" position="top">
<IconQuestionCircleFill
class="list-date-help"
:class="{ 'is-warn': timeWindowRelaxed && !createTimeRange?.length }"
/>
</a-tooltip>
<a-button
v-if="timeWindowRelaxed || !usingDefaultTimeWindow"
type="text"
size="mini"
class="list-date-restore"
@click="restoreDefaultTimeWindow(); handleSearch()"
>
恢复近{{ ORDER_LIST_DEFAULT_DAYS }}天
</a-button>
<a-button
v-if="dateFilterExpanded"
type="text"
size="mini"
class="list-date-restore"
@click="dateFilterExpanded = false"
>
收起
</a-button>
</span>
<a-button class="app-btn-search" @click="handleSearch">
{{ t('order.myOrders.search.actions.search') }}
</a-button>
<a-button @click="handleResetSearch" class="app-btn-reset">
{{ t('order.myOrders.search.actions.reset') }}
</a-button>
</div>
</div>
</div>
<div
v-if="showHandleSubTabs"
:class="['handle-status-bar', `handle-status-bar--${activeTab}`]"
>
<div class="handle-status-bar__intro">
<span class="handle-status-bar__dot" />
<span class="handle-status-bar__title">{{ handleContextLabel }}</span>
</div>
<div class="handle-status-segments" role="tablist">
<button
v-for="seg in handleSegments"
:key="seg.key"
type="button"
role="tab"
:class="['handle-status-segment', { active: activeHandleTab === seg.key }]"
:aria-selected="activeHandleTab === seg.key"
@click="handleHandleTabChange(seg.key)"
>
<span class="handle-status-segment__label">{{ t(seg.labelKey) }}</span>
<span class="handle-status-segment__count">{{ seg.count }}</span>
</button>
</div>
</div>
<!-- 表格操作按钮和分页控-->
<div class="table-toolbar">
<div class="actions-right">
<a-button
v-for="actionKey in primaryToolbarActions"
:key="actionKey"
class="app-btn-toolbar"
:loading="!!getToolbarActionLoadingKey(actionKey) && isActionLoading(getToolbarActionLoadingKey(actionKey)!)"
:disabled="isToolbarActionDisabled(actionKey)"
@click="handleToolbarAction(actionKey)"
>{{ t(getToolbarActionLabelKey(actionKey)) }}</a-button>
<a-dropdown
v-if="showToolbarMore"
trigger="click"
position="bl"
:disabled="!!actionLoadingKey"
>
<a-button class="app-btn-toolbar btn-more" :disabled="!!actionLoadingKey">
{{ t('order.myOrders.actions.more') }}
<icon-down class="btn-more-arrow" />
</a-button>
<template #content>
<a-doption
v-for="actionKey in overflowToolbarActions"
:key="actionKey"
:disabled="isToolbarActionDisabled(actionKey)"
@click="handleToolbarAction(actionKey)"
>{{ t(getToolbarActionLabelKey(actionKey)) }}</a-doption>
</template>
</a-dropdown>
</div>
<div class="toolbar-right">
<span class="selected-count">
<i18n-t keypath="order.myOrders.selectedCount" tag="span" scope="global">
<template #count>
<span class="count-number">{{ selectedRowCount }}</span>
</template>
</i18n-t>
</span>
<div class="column-config-controls">
<a-select
:model-value="columnConfigState.activeId"
:options="columnSchemeOptions"
:placeholder="t('order.myOrders.columnConfig.scheme')"
style="width: 140px"
@change="handleColumnSchemeChange"
/>
<a-button @click="openColumnConfig" class="app-btn-toolbar">
{{ t('order.myOrders.columnConfig.open') }}
</a-button>
</div>
<div class="pagination-controls">
<PaginationPro
:total-count="totalCount"
v-model:current-page="currentPage"
v-model:page-size="pageSize"
@page-change="handlePageChange"
@page-size-change="handlePageSizeChange"
/>
</div>
</div>
</div>
<div
v-if="!listLoading && totalCount === 0"
class="list-empty-hint"
>
<span>{{ t('order.myOrders.empty.hint') }}</span>
<a-button type="text" @click="router.push('/order/placeOrder')">
{{ t('order.myOrders.empty.goPlaceOrder') }}
</a-button>
<a-button type="text" @click="router.push('/order/priceCheck')">
{{ t('order.myOrders.empty.goPriceCheck') }}
</a-button>
</div>
<div ref="tableContainerRef" class="list-wrap">
<a-spin :loading="listLoading" class="table-spin">
<HandsontablePro
:key="`${activeTab}-${tableColumnsKey}`"
:columns="hotColumns"
:data="processedTableData"
:total="totalCount"
:current-page="currentPage"
:page-size="pageSize"
:show-action-column="true"
:action-renderer="actionRenderer"
:custom-cell-renderer="customCellRenderer"
:stretch-columns="true"
:height="tableHeight"
:search-params="headerSearchParams"
sort-mode="remote"
:sort-field="listSortField"
:sort-order="listSortOrder"
@search="handleHeaderSearch"
@sort-change="handleSortChange"
@action-click="handleActionClick"
@selection-change="handleSelectionChange"
/>
</a-spin>
</div>
</div>
<!-- 订单详情抽屉(左侧):首次打开再挂载 -->
<OrderDetailDrawer
v-if="detailDrawerMounted"
ref="detailDrawerRef"
:order="currentOrder"
@updated="handleOrderDetailUpdated"
/>
<ColumnConfigModal
v-if="columnConfigMounted"
ref="columnConfigModalRef"
:catalog="listColumnCatalog"
:schemes="columnConfigState.schemes"
:active-id="columnConfigState.activeId"
:default-keys="MY_ORDERS_DEFAULT_KEYS"
@apply="handleColumnConfigApply"
/>
<OrderPrintModal
v-if="singlePrintVisible"
v-model:visible="singlePrintVisible"
mode="single"
:items="singlePrintItems"
/>
<OrderPrintModal
v-if="batchPrintVisible"
v-model:visible="batchPrintVisible"
mode="batch"
:items="batchPrintItems"
:preparing="batchPrintPreparing"
/>
<MarkProblematicModal
v-if="problematicModalVisible"
v-model:visible="problematicModalVisible"
:order-ids="exceptionOrderIds"
@success="handleExceptionActionSuccess"
/>
<MarkClaimedModal
v-if="claimedModalVisible"
v-model:visible="claimedModalVisible"
:order-ids="exceptionOrderIds"
:has-insurance="claimContext.hasInsurance"
:declared-sum="claimContext.declaredSum"
:declared-currency="claimContext.declaredCurrency"
@success="handleExceptionActionSuccess"
/>
<StockBindModal
v-model:visible="stockBindModalVisible"
:order-ids="stockBindOrderIds"
@success="handleStockBindSuccess"
/>
<OrderPayConfirmModal
v-if="payConfirmVisible"
v-model:visible="payConfirmVisible"
:orders="payConfirmOrders"
@success="handlePayConfirmSuccess"
/>
<CreatePickupOrderModal
v-if="createPickupMounted"
ref="createPickupModalRef"
@success="handleCreatePickupSuccess"
/>
</div>
</template>
<style lang="less" scoped>
.my-orders-container {
width: 100%;
box-sizing: border-box;
padding: 16px 16px 24px;
background-color: var(--app-page-bg);
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: hidden;
display: flex;
flex-direction: column;
}
.page-header {
margin-bottom: 24px;
h2 {
margin: 0;
font-size: 24px;
font-weight: 600;
color: var(--color-text-1);
}
}
.tabs-actions-section {
background: transparent;
border-radius: 0;
padding: 10px 16px;
margin-bottom: 0;
border-bottom: 1px solid var(--color-border-2);
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: nowrap;
gap: 12px;
flex-shrink: 0;
min-height: 52px;
box-sizing: border-box;
.tabs-slot {
flex: 1 1 auto;
min-width: 0;
display: flex;
align-items: center;
overflow: hidden;
}
:deep(.t-tabs) {
flex: 0 1 auto;
min-width: 0;
max-width: 100%;
width: max-content;
}
}
.handle-status-bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 0;
padding: 12px 16px;
background: var(--app-card-bg);
border-radius: 0;
border: none;
border-bottom: 1px solid var(--color-border-2);
flex-shrink: 0;
&--problematic {
border-left: 3px solid #8a5c58;
background: linear-gradient(
90deg,
color-mix(in srgb, #8a5c58 10%, var(--app-card-bg)) 0%,
var(--app-card-bg) 28%
);
}
&--claimed {
border-left: 3px solid #5c656d;
background: linear-gradient(
90deg,
color-mix(in srgb, #5c656d 10%, var(--app-card-bg)) 0%,
var(--app-card-bg) 28%
);
}
&__intro {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
min-width: 120px;
}
&__dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--app-primary-color);
flex-shrink: 0;
}
&--problematic &__dot {
background: #8a5c58;
}
&--claimed &__dot {
background: #5c656d;
}
&__title {
font-size: 13px;
font-weight: 600;
color: var(--color-text-1);
white-space: nowrap;
}
}
.handle-status-segments {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 4px;
background: var(--color-fill-2);
border-radius: 8px;
flex-wrap: wrap;
justify-content: flex-end;
flex: 1;
}
.handle-status-segment {
display: inline-flex;
align-items: center;
gap: 8px;
height: 32px;
padding: 0 14px;
border: none;
border-radius: 6px;
background: transparent;
color: var(--color-text-2);
font-size: 13px;
cursor: pointer;
transition: all 0.2s ease;
&:hover {
color: var(--color-text-1);
background: var(--color-fill-1);
}
&.active {
color: var(--app-primary-color);
background: var(--app-card-bg);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
font-weight: 600;
}
&__count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 22px;
height: 20px;
padding: 0 6px;
border-radius: 10px;
background: var(--color-fill-3);
font-size: 12px;
line-height: 1;
color: inherit;
}
&.active &__count {
background: var(--app-primary-color-light);
color: var(--app-primary-color);
}
}
.actions-right {
display: flex;
flex-wrap: wrap;
gap: var(--app-button-gap, 8px);
align-items: center;
flex: 1;
min-width: 0;
:deep(.arco-btn) {
height: 32px;
padding: 0 12px;
border-radius: 4px;
font-size: 14px;
font-weight: 400;
line-height: 30px;
}
:deep(.arco-btn.btn-more) {
display: inline-flex;
align-items: center;
gap: 2px;
.btn-more-arrow {
font-size: 12px;
margin-left: 2px;
}
}
}
.toolbar-left {
flex: 0 0 auto;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: flex-end;
padding: 0;
max-width: 100%;
height: 32px;
.list-filters {
display: inline-flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
height: 32px;
:deep(.arco-input-wrapper),
:deep(.arco-btn) {
height: 32px;
}
:deep(.arco-input-wrapper) {
display: inline-flex;
align-items: center;
padding-top: 0;
padding-bottom: 0;
}
}
.list-date-toggle {
width: 32px;
padding: 0;
}
.list-date-filter {
display: inline-flex;
align-items: center;
gap: 4px;
height: 32px;
}
.list-date-help {
font-size: 14px;
color: var(--color-text-3);
cursor: help;
flex-shrink: 0;
&:hover {
color: var(--app-primary-color);
}
&.is-warn {
color: rgb(var(--warning-6));
}
}
.list-date-restore {
padding: 0 4px;
height: auto;
color: var(--app-primary-color);
}
}
.table-section {
background: var(--app-card-bg);
border-radius: 8px;
border: 1px solid var(--app-card-border);
padding: 0;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.table-toolbar {
padding: 12px 16px 0;
margin-bottom: 12px;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 12px;
.toolbar-right {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
.selected-count {
font-size: 13px;
color: var(--color-text-3);
white-space: nowrap;
line-height: 32px;
}
.column-config-controls {
display: flex;
align-items: center;
gap: 8px;
}
.pagination-controls {
display: flex;
align-items: center;
}
}
}
.list-empty-hint {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
margin: 0 16px 12px;
padding: 10px 12px;
border-radius: 8px;
background: var(--color-fill-2);
color: var(--color-text-2);
font-size: 13px;
}
.table-spin {
width: 100%;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
:deep(.arco-spin) {
width: 100%;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
:deep(.arco-spin-children) {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
}
.list-wrap {
width: 100%;
overflow: hidden;
flex: 1;
min-height: 0;
padding: 0 16px 16px;
box-sizing: border-box;
display: flex;
flex-direction: column;
overscroll-behavior: contain;
touch-action: pan-x pan-y;
:deep(.handsontable-pro-container) {
width: 100%;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.handsontable-wrapper {
width: 100%;
:deep(.handsontable) {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
border: none !important;
// 覆盖 Handsontable 默认的 table 边框
table {
border: none !important;
}
.ht_master,
.ht_clone_top,
.ht_clone_left,
.ht_clone_corner {
border: none !important;
}
.wtHolder {
border: none !important;
}
.htCore {
border-collapse: separate;
border-spacing: 0;
border: none !important;
td {
border-right: 0.5px solid var(--color-border-2) !important;
border-bottom: 0.5px solid var(--color-border-2) !important;
border-top: none !important;
border-left: none !important;
padding: 7px 16px;
font-size: 13px;
line-height: 1.4;
color: var(--color-text-1);
transition: all 0.2s ease;
background: var(--app-card-bg);
text-align: center !important;
vertical-align: middle !important;
&:hover {
background-color: var(--color-fill-2);
}
&:first-child {
padding-left: 8px;
padding-right: 8px;
}
}
tr {
transition: all 0.2s ease;
&:hover {
td {
// hover时,如果单元格已经有背景色(状态背景),则稍微加深
// 否则使用默认hover颜色
&:not([style*="background-color"]) {
background-color: var(--color-fill-2);
}
}
}
}
th {
background: var(--color-fill-2) !important;
border-right: 0.5px solid var(--color-border-2) !important;
border-bottom: 0.5px solid var(--color-border-2) !important;
border-top: none !important;
border-left: none !important;
}
// 根据订单状态设置行背景
tbody tr:has([data-row-status="problematic"]) td {
background-color: #fff1f0 !important;
}
tbody tr:has([data-row-status="pendingPayment"]) td {
background-color: #ffece8 !important;
}
tbody tr:has([data-row-status="pendingAllocation"]) td {
background-color: #fff7e6 !important;
}
// 隐藏筛选图标的边框
.changeType {
border: none !important;
box-shadow: none !important;
background: transparent !important;
}
// 隐藏筛选图标容器的边框
.ht_master .ht_clone_top th .changeType,
.ht_clone_top th .changeType,
.htCore th .changeType,
th .changeType {
border: none !important;
box-shadow: none !important;
background: transparent !important;
}
}
.ht_master .wtHolder {
overflow: auto;
}
.handsontableInput {
display: none;
}
}
}
}
// 响应式设计
@media (max-width: 768px) {
.actions-right {
flex-wrap: wrap;
gap: 4px;
}
.action-btn {
font-size: 12px;
padding: 0 8px;
height: 28px;
}
}
</style>