免入库(主系统骑手上门取货): - 50 展示「待取货」、副文案「待主系统骑手上门取货」、不建我方配送任务(守卫与开关解耦) - 我方 50 即回写备货完成;两开关(SKIP_INBOUND_AWAIT_PICKUP / FULFILLMENT_EVENTS)改默认开 核货事实镜像(「核货完毕」标记): - 按主系统 lookup 的 actual_qty 落台账,新增 GET/POST /orders/:orderCode/main-system-prep-facts[/refresh] - 详情行内显示「核货完毕」(含核货量),分配对账兜底刷新 实收数量/单位口径变更(对方先改 + 我方事后同步): - 台账加 applied_at;inbound 与 picking_check 同为事实登记(驳回不回滚) - 同意才落我方值:免入库改装车核货量、送仓改验收实收(已入库走既有库存调整)、已结算/已结案只留痕 - 计划量与金额一起改,并同步结算投影(syncStatementsForOrderSafe) - 审核页语义改「主系统实际值(已生效)/ 是否同步」+ 已处理历史(双方时间与落值结论) 台账对照与回写修复: - 行级对照改整单一次性(同名商品不再重复认领)+ 存量纠正 healOrderPrepMapping - 堵住客户绑定回填旁路(免入库单不再被派我方骑手) - 回写触发函数改对象参数(修 branch/order 传反导致的静默不回写) 文档:设计文档 4 篇 +《给主系统 AI 的对接改造清单》§2.9(第六批契约) 回归:服务端全量与 HEAD 基线一致(24 个失败文件同集合);前端 140 文件 / 699 测试全绿;tsc 双端干净
715 lines
27 KiB
TypeScript
715 lines
27 KiB
TypeScript
import { pool } from '../db';
|
||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||
import { fetchOrderInspectionStatesBatch, fetchUnresolvedFailedInspectionItemsBatch } from './orderInspectionStateService';
|
||
import { isPickingWorkflowEnabled } from './pickingConfigService';
|
||
import { normalizeDateOnly } from './orderDeliveryDate';
|
||
import {
|
||
buildProgressStatusHint,
|
||
fetchOrderProgressFactsBatch,
|
||
} from './orderStatusDisplayService';
|
||
import { orderNotDeletedSql } from './orderTrashScope';
|
||
import { fetchStockCoverItemLabelsBatch } from './stockCoverItemLabelsService';
|
||
import { customerCodeInSql } from '../utils/customerCodes';
|
||
import { isOrderCodeSearch } from '../utils/orderCodeQuery';
|
||
|
||
export type OrderManagementDateField = 'created_at' | 'delivery_date' | 'either';
|
||
export type OrderManagementStatusGroup = 'pending' | 'processing' | 'completed';
|
||
|
||
export interface ListOrdersForManagementInput {
|
||
page?: number;
|
||
pageSize?: number;
|
||
sortField?: string;
|
||
sortOrder?: 'asc' | 'desc';
|
||
statusFilter?: number | null;
|
||
statusGroup?: OrderManagementStatusGroup | string | null;
|
||
dateRangePreset?: 'today' | 'week' | 'month' | 'quarter' | 'year' | 'day' | 'all' | 'custom';
|
||
dateFilter?: string | null;
|
||
/** 自定义闭区间(YYYY-MM-DD);与 dateRangePreset=custom 联用 */
|
||
dateFrom?: string | null;
|
||
dateTo?: string | null;
|
||
dateField?: OrderManagementDateField;
|
||
customerCode?: string | null;
|
||
search?: string | null;
|
||
/** 仅返回「营收 < SUM(qty×unit_cost)」的负毛利订单(与商品毛利明细同口径) */
|
||
negativeMargin?: boolean;
|
||
cycleCode?: string | null;
|
||
/** 小程序等无分公司选择器场景:超级管理员可不选分公司,查看全部 */
|
||
allowMissingBranch?: boolean;
|
||
/** 仅看「待补录」(定时强推后配送完成挂起的订单) */
|
||
pendingBackfill?: boolean | null;
|
||
}
|
||
|
||
export function normalizeOrderManagementStatusGroup(
|
||
value: unknown
|
||
): OrderManagementStatusGroup | null {
|
||
const normalized = String(value || '').trim().toLowerCase();
|
||
if (normalized === 'pending' || normalized === 'processing' || normalized === 'completed') {
|
||
return normalized;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
export function getOrderStatusGroupCondition(value: unknown): string | null {
|
||
const statusGroup = normalizeOrderManagementStatusGroup(value);
|
||
if (statusGroup === 'pending') return 'o.order_status < 50';
|
||
if (statusGroup === 'processing') return 'o.order_status >= 50 AND o.order_status < 90';
|
||
if (statusGroup === 'completed') return 'o.order_status >= 90';
|
||
return null;
|
||
}
|
||
|
||
/** 与详情读口径一致:搜索只匹配未退货明细 */
|
||
const ORDER_ITEM_NOT_RETURNED_SQL = `COALESCE(oi.is_returned, false) = false`;
|
||
|
||
/** @internal exported for unit tests */
|
||
export function getOrderManagementSearchCondition(paramPlaceholder: string): string {
|
||
return `(
|
||
o.order_code ILIKE ${paramPlaceholder}
|
||
OR o.customer_code ILIKE ${paramPlaceholder}
|
||
OR c.company_name ILIKE ${paramPlaceholder}
|
||
OR EXISTS (
|
||
SELECT 1
|
||
FROM order_items oi
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
WHERE oi.order_code = o.order_code
|
||
AND ${ORDER_ITEM_NOT_RETURNED_SQL}
|
||
AND (
|
||
COALESCE(oi.item_name, '') ILIKE ${paramPlaceholder}
|
||
OR COALESCE(s.sku_name, '') ILIKE ${paramPlaceholder}
|
||
OR COALESCE(oi.sku_code, '') ILIKE ${paramPlaceholder}
|
||
)
|
||
)
|
||
OR EXISTS (
|
||
SELECT 1
|
||
FROM order_items oi
|
||
JOIN customer_skus cs
|
||
ON cs.customer_code = o.customer_code
|
||
AND cs.sku_code IS NOT DISTINCT FROM oi.sku_code
|
||
WHERE oi.order_code = o.order_code
|
||
AND ${ORDER_ITEM_NOT_RETURNED_SQL}
|
||
AND COALESCE(cs.customer_sku_name, '') ILIKE ${paramPlaceholder}
|
||
)
|
||
OR EXISTS (
|
||
SELECT 1
|
||
FROM order_items oi
|
||
JOIN customer_sku_aliases csa
|
||
ON csa.customer_code = o.customer_code
|
||
AND csa.sku_code IS NOT DISTINCT FROM oi.sku_code
|
||
WHERE oi.order_code = o.order_code
|
||
AND ${ORDER_ITEM_NOT_RETURNED_SQL}
|
||
AND COALESCE(csa.alias_name, '') ILIKE ${paramPlaceholder}
|
||
)
|
||
)`;
|
||
}
|
||
|
||
export interface OrderManagementListStats {
|
||
pending: number;
|
||
processing: number;
|
||
completed: number;
|
||
/** 待补录(定时强推后挂起)订单数 */
|
||
backfill: number;
|
||
}
|
||
|
||
export interface OrderManagementListRow {
|
||
order_code: string;
|
||
customer_code: string;
|
||
company_name: string | null;
|
||
branch_code: string | null;
|
||
branch_name: string | null;
|
||
order_status: number;
|
||
total_amount: number;
|
||
total_weight: number;
|
||
created_at: string;
|
||
updated_at: string | null;
|
||
delivery_date: string | null;
|
||
delivery_time_slot: string | null;
|
||
customer_delivery_time: string | null;
|
||
delivery_address: string | null;
|
||
cycle_code: string | null;
|
||
/** 主系统分配过来的订单(2026-10-10):界面隐藏「删除」、改用「缺货」 */
|
||
is_main_system_order: boolean;
|
||
inspection_state: 'none' | 'pending' | 'passed' | 'failed';
|
||
status_hint: string | null;
|
||
/** 未化解验收不合格商品名(与 inspection_state=failed 同口径) */
|
||
inspection_fail_items: string[];
|
||
/** 仍有库存抵扣的商品名 */
|
||
stock_cover_items: string[];
|
||
/** 定时强推标记:配送完成后挂起待补录 */
|
||
pending_backfill: boolean;
|
||
/** 强推前状态(30/40/45),未强推为 null */
|
||
auto_advanced_from_status: number | null;
|
||
}
|
||
|
||
const SORT_COLUMNS = new Set(['created_at', 'updated_at', 'order_code', 'total_amount', 'delivery_date']);
|
||
|
||
function chinaDayBounds(day: string): { start: string; end: string; day: string } {
|
||
const normalized = String(day || '').trim().slice(0, 10);
|
||
return {
|
||
day: normalized,
|
||
start: `${normalized}T00:00:00.000+08:00`,
|
||
end: `${normalized}T23:59:59.999+08:00`,
|
||
};
|
||
}
|
||
|
||
/** @internal exported for unit tests */
|
||
export function resolvePresetRange(
|
||
preset: ListOrdersForManagementInput['dateRangePreset'],
|
||
dayValue: string | null | undefined,
|
||
dateFrom?: string | null,
|
||
dateTo?: string | null
|
||
): { start: string; end: string; day: string | null } {
|
||
const from = String(dateFrom || '').trim().slice(0, 10);
|
||
const to = String(dateTo || '').trim().slice(0, 10);
|
||
if ((preset === 'custom' || (from && to)) && from && to) {
|
||
const startDay = from <= to ? from : to;
|
||
const endDay = from <= to ? to : from;
|
||
return {
|
||
start: `${startDay}T00:00:00.000+08:00`,
|
||
end: `${endDay}T23:59:59.999+08:00`,
|
||
day: startDay === endDay ? startDay : null,
|
||
};
|
||
}
|
||
|
||
const day = String(dayValue || '').trim().slice(0, 10);
|
||
if (preset === 'day' && day) {
|
||
const bounds = chinaDayBounds(day);
|
||
return { start: bounds.start, end: bounds.end, day: bounds.day };
|
||
}
|
||
|
||
const now = new Date();
|
||
const chinaToday = new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: 'Asia/Shanghai',
|
||
year: 'numeric',
|
||
month: '2-digit',
|
||
day: '2-digit',
|
||
}).format(now);
|
||
|
||
if (preset === 'all') {
|
||
return { start: '', end: '', day: null };
|
||
}
|
||
|
||
if (preset === 'today' || !preset) {
|
||
const bounds = chinaDayBounds(chinaToday);
|
||
return { start: bounds.start, end: bounds.end, day: bounds.day };
|
||
}
|
||
|
||
if (preset === 'week') {
|
||
const anchor = new Date(`${chinaToday}T12:00:00+08:00`);
|
||
const weekday = anchor.getUTCDay();
|
||
const diffToMonday = weekday === 0 ? 6 : weekday - 1;
|
||
anchor.setUTCDate(anchor.getUTCDate() - diffToMonday);
|
||
const weekStart = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(anchor);
|
||
anchor.setUTCDate(anchor.getUTCDate() + 6);
|
||
const weekEnd = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(anchor);
|
||
return {
|
||
start: `${weekStart}T00:00:00.000+08:00`,
|
||
end: `${weekEnd}T23:59:59.999+08:00`,
|
||
day: null,
|
||
};
|
||
}
|
||
|
||
const [y, m] = chinaToday.split('-').map(Number);
|
||
|
||
if (preset === 'month') {
|
||
const monthStart = `${y}-${String(m).padStart(2, '0')}-01`;
|
||
const nextMonth = m === 12 ? { y: y + 1, m: 1 } : { y, m: m + 1 };
|
||
const nextMonthStart = `${nextMonth.y}-${String(nextMonth.m).padStart(2, '0')}-01`;
|
||
const monthEndDate = new Date(`${nextMonthStart}T12:00:00+08:00`);
|
||
monthEndDate.setUTCDate(monthEndDate.getUTCDate() - 1);
|
||
const monthEnd = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(monthEndDate);
|
||
return {
|
||
start: `${monthStart}T00:00:00.000+08:00`,
|
||
end: `${monthEnd}T23:59:59.999+08:00`,
|
||
day: null,
|
||
};
|
||
}
|
||
|
||
if (preset === 'quarter') {
|
||
const quarterStartMonth = Math.floor((m - 1) / 3) * 3 + 1;
|
||
const quarterEndMonth = quarterStartMonth + 2;
|
||
const quarterStart = `${y}-${String(quarterStartMonth).padStart(2, '0')}-01`;
|
||
const nextAfterQuarter =
|
||
quarterEndMonth === 12 ? { y: y + 1, m: 1 } : { y, m: quarterEndMonth + 1 };
|
||
const quarterEndDate = new Date(
|
||
`${nextAfterQuarter.y}-${String(nextAfterQuarter.m).padStart(2, '0')}-01T12:00:00+08:00`
|
||
);
|
||
quarterEndDate.setUTCDate(quarterEndDate.getUTCDate() - 1);
|
||
const quarterEnd = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai' }).format(
|
||
quarterEndDate
|
||
);
|
||
return {
|
||
start: `${quarterStart}T00:00:00.000+08:00`,
|
||
end: `${quarterEnd}T23:59:59.999+08:00`,
|
||
day: null,
|
||
};
|
||
}
|
||
|
||
if (preset === 'year') {
|
||
return {
|
||
start: `${y}-01-01T00:00:00.000+08:00`,
|
||
end: `${y}-12-31T23:59:59.999+08:00`,
|
||
day: null,
|
||
};
|
||
}
|
||
|
||
const bounds = chinaDayBounds(chinaToday);
|
||
return { start: bounds.start, end: bounds.end, day: bounds.day };
|
||
}
|
||
|
||
/** @internal exported for unit tests */
|
||
export function appendDateFilter(
|
||
where: string[],
|
||
params: unknown[],
|
||
range: { start: string; end: string; day: string | null },
|
||
dateField: OrderManagementDateField
|
||
): void {
|
||
if (!range.start || !range.end) return;
|
||
|
||
const startDay = range.start.slice(0, 10);
|
||
const endDay = range.end.slice(0, 10);
|
||
const isSingleDay = Boolean(range.day) || startDay === endDay;
|
||
|
||
if (dateField === 'created_at') {
|
||
params.push(range.start, range.end);
|
||
where.push(`o.created_at >= $${params.length - 1} AND o.created_at <= $${params.length}`);
|
||
return;
|
||
}
|
||
|
||
if (dateField === 'delivery_date') {
|
||
if (isSingleDay) {
|
||
params.push(startDay);
|
||
where.push(`o.delivery_date::date = $${params.length}::date`);
|
||
} else {
|
||
params.push(startDay, endDay);
|
||
where.push(
|
||
`o.delivery_date::date >= $${params.length - 1}::date AND o.delivery_date::date <= $${params.length}::date`
|
||
);
|
||
}
|
||
return;
|
||
}
|
||
|
||
params.push(range.start, range.end);
|
||
const createdStartIdx = params.length - 1;
|
||
const createdEndIdx = params.length;
|
||
if (isSingleDay) {
|
||
params.push(startDay);
|
||
const deliveryIdx = params.length;
|
||
where.push(
|
||
`(
|
||
(o.created_at >= $${createdStartIdx} AND o.created_at <= $${createdEndIdx})
|
||
OR o.delivery_date::date = $${deliveryIdx}::date
|
||
)`
|
||
);
|
||
} else {
|
||
params.push(startDay, endDay);
|
||
const deliveryStartIdx = params.length - 1;
|
||
const deliveryEndIdx = params.length;
|
||
where.push(
|
||
`(
|
||
(o.created_at >= $${createdStartIdx} AND o.created_at <= $${createdEndIdx})
|
||
OR (o.delivery_date::date >= $${deliveryStartIdx}::date AND o.delivery_date::date <= $${deliveryEndIdx}::date)
|
||
)`
|
||
);
|
||
}
|
||
}
|
||
|
||
function buildStatusHint(
|
||
orderStatus: number,
|
||
inspectionState: string,
|
||
fulfillment?: { prepDone: number; prepTotal: number; purchaseDone: number; purchaseTotal: number },
|
||
pickingEnabled?: boolean
|
||
): string | null {
|
||
// 兼容旧调用;真实列表改用 buildProgressStatusHint
|
||
if (orderStatus === 30 && fulfillment) {
|
||
const parts: string[] = [];
|
||
if (fulfillment.prepTotal > 0) {
|
||
parts.push(`备货 ${fulfillment.prepDone}/${fulfillment.prepTotal}`);
|
||
}
|
||
if (fulfillment.purchaseTotal > 0) {
|
||
parts.push(`自采 ${fulfillment.purchaseDone}/${fulfillment.purchaseTotal}`);
|
||
}
|
||
if (parts.length) return parts.join(' · ');
|
||
}
|
||
if (orderStatus === 40 && inspectionState === 'pending') return '验收进行中';
|
||
if (orderStatus === 40 && inspectionState === 'passed') {
|
||
return pickingEnabled === false ? '验收已完成,待配送' : '验收已完成,待分拣';
|
||
}
|
||
if (orderStatus === 40 && inspectionState === 'failed') return '验收异常';
|
||
if (orderStatus === 40 && inspectionState === 'none') return '待仓管验收';
|
||
return null;
|
||
}
|
||
|
||
interface FulfillmentSummary {
|
||
prepDone: number;
|
||
prepTotal: number;
|
||
purchaseDone: number;
|
||
purchaseTotal: number;
|
||
}
|
||
|
||
async function fetchFulfillmentSummaries(orderCodes: string[]): Promise<Map<string, FulfillmentSummary>> {
|
||
const result = new Map<string, FulfillmentSummary>();
|
||
const codes = [...new Set(orderCodes.filter(Boolean))];
|
||
if (!codes.length) return result;
|
||
|
||
const [prepResult, purchaseResult] = await Promise.all([
|
||
pool.query(
|
||
`SELECT order_code,
|
||
COUNT(*)::int AS prep_total,
|
||
COUNT(*) FILTER (
|
||
WHERE COALESCE(is_stockout, false) = true
|
||
OR COALESCE(transferred_to_purchase, false) = true
|
||
OR COALESCE(prepare_status, 10) >= 30
|
||
OR EXISTS (
|
||
SELECT 1 FROM inspections i
|
||
WHERE i.order_code = supplier_preparations.order_code
|
||
AND i.sku_code IS NOT DISTINCT FROM supplier_preparations.sku_code
|
||
AND COALESCE(i.supplier_code, '') = COALESCE(supplier_preparations.supplier_code, '')
|
||
AND i.compliance_status >= 40
|
||
AND i.inbound_batch_no IS NOT NULL
|
||
)
|
||
OR EXISTS (
|
||
SELECT 1 FROM inspections i
|
||
WHERE i.order_code = supplier_preparations.order_code
|
||
AND i.sku_code IS NOT DISTINCT FROM supplier_preparations.sku_code
|
||
AND COALESCE(i.supplier_code, '') = COALESCE(supplier_preparations.supplier_code, '')
|
||
)
|
||
)::int AS prep_done
|
||
FROM supplier_preparations
|
||
WHERE order_code = ANY($1::text[])
|
||
GROUP BY order_code`,
|
||
[codes]
|
||
),
|
||
pool.query(
|
||
`SELECT order_code,
|
||
COUNT(*)::int AS purchase_total,
|
||
COUNT(*) FILTER (
|
||
WHERE COALESCE(purchase_status, 10) IN (20, 30, 40)
|
||
)::int AS purchase_done
|
||
FROM purchase_orders
|
||
WHERE order_code = ANY($1::text[])
|
||
GROUP BY order_code`,
|
||
[codes]
|
||
),
|
||
]);
|
||
|
||
for (const code of codes) {
|
||
result.set(code, { prepDone: 0, prepTotal: 0, purchaseDone: 0, purchaseTotal: 0 });
|
||
}
|
||
for (const row of prepResult.rows) {
|
||
const code = String(row.order_code);
|
||
const current = result.get(code) || { prepDone: 0, prepTotal: 0, purchaseDone: 0, purchaseTotal: 0 };
|
||
current.prepTotal = Number(row.prep_total) || 0;
|
||
current.prepDone = Number(row.prep_done) || 0;
|
||
result.set(code, current);
|
||
}
|
||
for (const row of purchaseResult.rows) {
|
||
const code = String(row.order_code);
|
||
const current = result.get(code) || { prepDone: 0, prepTotal: 0, purchaseDone: 0, purchaseTotal: 0 };
|
||
current.purchaseTotal = Number(row.purchase_total) || 0;
|
||
current.purchaseDone = Number(row.purchase_done) || 0;
|
||
result.set(code, current);
|
||
}
|
||
return result;
|
||
}
|
||
|
||
export async function listOrdersForManagement(
|
||
ctx: TenantContext | null,
|
||
operatingBranchCode: string | null | undefined,
|
||
input: ListOrdersForManagementInput
|
||
): Promise<{
|
||
rows: OrderManagementListRow[];
|
||
total: number;
|
||
totalAmount: number;
|
||
stats: OrderManagementListStats;
|
||
}> {
|
||
if (!ctx) {
|
||
throw Object.assign(new Error('未登录'), { status: 401 });
|
||
}
|
||
|
||
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
if (ctx.isSuperAdmin && !branchCode && !input.allowMissingBranch) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
|
||
const page = Math.max(1, Number(input.page) || 1);
|
||
const pageSize = Math.min(2000, Math.max(1, Number(input.pageSize) || 20));
|
||
const offset = (page - 1) * pageSize;
|
||
const sortField = SORT_COLUMNS.has(String(input.sortField || ''))
|
||
? String(input.sortField)
|
||
: 'updated_at';
|
||
const sortOrder = input.sortOrder === 'asc' ? 'ASC' : 'DESC';
|
||
const dateField: OrderManagementDateField = input.dateField || 'either';
|
||
const negativeMargin = Boolean(input.negativeMargin);
|
||
const cycleCode = String(input.cycleCode || '').trim();
|
||
// 负毛利下钻按账期筛选;按订单号搜索时订单号自身即唯一限定,忽略日期以免漏单
|
||
const skipDateFilter = negativeMargin || isOrderCodeSearch(input.search);
|
||
const range = resolvePresetRange(
|
||
skipDateFilter ? 'all' : input.dateRangePreset,
|
||
input.dateFilter,
|
||
skipDateFilter ? null : input.dateFrom,
|
||
skipDateFilter ? null : input.dateTo
|
||
);
|
||
|
||
const params: unknown[] = [];
|
||
const baseWhere: string[] = ['1=1', orderNotDeletedSql('o')];
|
||
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
baseWhere.push(`o.branch_code = $${params.length}`);
|
||
} else if (!ctx.isSuperAdmin && ctx.branchCode) {
|
||
params.push(ctx.branchCode);
|
||
baseWhere.push(`o.branch_code = $${params.length}`);
|
||
}
|
||
|
||
appendDateFilter(baseWhere, params, range, dateField);
|
||
|
||
if (cycleCode) {
|
||
params.push(cycleCode);
|
||
baseWhere.push(`o.cycle_code = $${params.length}`);
|
||
}
|
||
|
||
if (negativeMargin) {
|
||
// 与商品毛利分维一致:销售额 − SUM(qty×unit_cost) < 0(见 20260813-negative-margin-alert-unit-cost)
|
||
baseWhere.push(`o.order_status >= 20`);
|
||
baseWhere.push(`EXISTS (
|
||
SELECT 1
|
||
FROM order_items oi
|
||
WHERE oi.order_code = o.order_code
|
||
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
|
||
HAVING COALESCE(SUM(
|
||
COALESCE(oi.quantity, 0) * COALESCE(
|
||
NULLIF(oi.locked_price, 0),
|
||
NULLIF(oi.price, 0),
|
||
CASE WHEN COALESCE(oi.quantity, 0) > 0 THEN COALESCE(oi.amount, 0) / oi.quantity ELSE 0 END,
|
||
0
|
||
)
|
||
), 0) > 0
|
||
AND COALESCE(SUM(
|
||
COALESCE(oi.quantity, 0) * COALESCE(
|
||
NULLIF(oi.locked_price, 0),
|
||
NULLIF(oi.price, 0),
|
||
CASE WHEN COALESCE(oi.quantity, 0) > 0 THEN COALESCE(oi.amount, 0) / oi.quantity ELSE 0 END,
|
||
0
|
||
)
|
||
), 0) < COALESCE(SUM(COALESCE(oi.quantity, 0) * COALESCE(oi.unit_cost, 0)), 0)
|
||
)`);
|
||
}
|
||
|
||
const customerClause = customerCodeInSql('o', params, input.customerCode).replace(/^\s*AND\s+/, '').trim();
|
||
if (customerClause) {
|
||
baseWhere.push(customerClause);
|
||
}
|
||
|
||
const search = String(input.search || '').trim();
|
||
if (search) {
|
||
params.push(`%${search.replace(/[%_]/g, '\\$&')}%`);
|
||
const idx = params.length;
|
||
// 订单号 / 客户 / 订单商品名 / 标准品名 / 客户映射库名 / 客户别名
|
||
baseWhere.push(getOrderManagementSearchCondition(`$${idx}`));
|
||
}
|
||
|
||
const baseWhereSql = baseWhere.join(' AND ');
|
||
const statsResult = await pool.query(
|
||
`SELECT
|
||
COUNT(*) FILTER (WHERE o.order_status < 50)::int AS pending,
|
||
COUNT(*) FILTER (WHERE o.order_status >= 50 AND o.order_status < 90)::int AS processing,
|
||
COUNT(*) FILTER (WHERE o.order_status >= 90)::int AS completed,
|
||
COUNT(*) FILTER (WHERE COALESCE(o.pending_backfill, false))::int AS backfill
|
||
FROM orders o
|
||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||
WHERE ${baseWhereSql}`,
|
||
params
|
||
);
|
||
|
||
const where = [...baseWhere];
|
||
const listParams = [...params];
|
||
if (input.statusFilter !== null && input.statusFilter !== undefined && Number.isFinite(Number(input.statusFilter))) {
|
||
listParams.push(Number(input.statusFilter));
|
||
where.push(`o.order_status = $${listParams.length}`);
|
||
} else {
|
||
const statusGroupCondition = getOrderStatusGroupCondition(input.statusGroup);
|
||
if (statusGroupCondition) where.push(statusGroupCondition);
|
||
}
|
||
if (input.pendingBackfill === true) {
|
||
where.push(`COALESCE(o.pending_backfill, false) = true`);
|
||
}
|
||
|
||
const whereSql = where.join(' AND ');
|
||
|
||
const countResult = await pool.query(
|
||
`SELECT COUNT(*)::int AS cnt, COALESCE(SUM(o.total_amount), 0) AS total_amount
|
||
FROM orders o
|
||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||
WHERE ${whereSql}`,
|
||
listParams
|
||
);
|
||
|
||
listParams.push(pageSize, offset);
|
||
const listResult = await pool.query(
|
||
`SELECT o.order_code, o.customer_code, c.company_name, o.branch_code, b.branch_name,
|
||
o.order_status, o.total_amount, o.total_weight, o.created_at, o.updated_at,
|
||
COALESCE(o.pending_backfill, false) AS pending_backfill,
|
||
o.auto_advanced_from_status,
|
||
to_char(o.delivery_date::date, 'YYYY-MM-DD') AS delivery_date,
|
||
o.delivery_time_slot,
|
||
NULLIF(TRIM(c.delivery_time), '') AS customer_delivery_time,
|
||
COALESCE(
|
||
NULLIF(TRIM(o.delivery_address), ''),
|
||
(
|
||
SELECT NULLIF(TRIM(cr.address), '')
|
||
FROM customer_recipients cr
|
||
WHERE cr.customer_code = o.customer_code
|
||
ORDER BY cr.is_default DESC NULLS LAST, cr.created_at ASC
|
||
LIMIT 1
|
||
),
|
||
NULLIF(TRIM(c.address), '')
|
||
) AS delivery_address,
|
||
o.cycle_code,
|
||
-- 主系统分配过来的订单(2026-10-10):界面据此隐藏「删除」,改用「缺货」
|
||
EXISTS (
|
||
SELECT 1 FROM public.main_system_order_imports msi
|
||
WHERE msi.branch_code = o.branch_code AND msi.our_order_code = o.order_code
|
||
) AS is_main_system_order
|
||
FROM orders o
|
||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||
LEFT JOIN branches b ON b.branch_code = o.branch_code
|
||
WHERE ${whereSql}
|
||
ORDER BY o.${sortField} ${sortOrder} NULLS LAST, o.order_code DESC
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||
listParams
|
||
);
|
||
|
||
const orderCodes = listResult.rows.map((row) => String(row.order_code));
|
||
const [fulfillmentMap, inspectionStates, progressFacts, failItemsMap, stockCoverMap] = await Promise.all([
|
||
fetchFulfillmentSummaries(orderCodes),
|
||
fetchOrderInspectionStatesBatch(orderCodes),
|
||
fetchOrderProgressFactsBatch(orderCodes),
|
||
fetchUnresolvedFailedInspectionItemsBatch(orderCodes),
|
||
fetchStockCoverItemLabelsBatch(orderCodes),
|
||
]);
|
||
|
||
const pickingEnabledByBranch = new Map<string, boolean>();
|
||
const uniqueBranches = [
|
||
...new Set(
|
||
listResult.rows
|
||
.map((row) => (row.branch_code ? String(row.branch_code) : ''))
|
||
.filter(Boolean)
|
||
),
|
||
];
|
||
await Promise.all(
|
||
uniqueBranches.map(async (branchKey) => {
|
||
pickingEnabledByBranch.set(branchKey, await isPickingWorkflowEnabled(branchKey));
|
||
})
|
||
);
|
||
|
||
/**
|
||
* 2026-10-11 方案 A1:主系统「免入库」单在 50 时展示为「待取货」(**不改状态链**)。
|
||
*
|
||
* 判定 = 该单在**行级台账**里所有行 `skipInbound=true`(`bool_and`)。
|
||
* ⚠️ 用 `bool_and` 而非 `bool_or`:混合单(部分免入库/部分送仓)走发车流程,不得标成待取货。
|
||
* ⚠️ **自有单天然 false**:它们不在 `main_system_order_import_items` 里 ⇒ 永远显示「待配送」。
|
||
*/
|
||
const skipInboundMap = new Map<string, boolean>();
|
||
const orderCodesForSkip = listResult.rows
|
||
.map((r) => String((r as { order_code?: string }).order_code || ''))
|
||
.filter(Boolean);
|
||
if (orderCodesForSkip.length) {
|
||
const skipRes = await pool.query<{ our_order_code: string; all_skip: boolean }>(
|
||
`SELECT our_order_code,
|
||
bool_and(COALESCE(payload->>'skipInbound', 'false') = 'true') AS all_skip
|
||
FROM public.main_system_order_import_items
|
||
WHERE branch_code = $1 AND our_order_code = ANY($2::text[])
|
||
GROUP BY our_order_code`,
|
||
[branchCode, orderCodesForSkip]
|
||
);
|
||
for (const r of skipRes.rows) skipInboundMap.set(String(r.our_order_code), r.all_skip === true);
|
||
}
|
||
|
||
const rows: OrderManagementListRow[] = listResult.rows.map((row) => {
|
||
const orderCode = String(row.order_code);
|
||
const storedStatus = Number(row.order_status) || 20;
|
||
const inspectionState = inspectionStates.get(orderCode) || 'none';
|
||
const fulfillment = fulfillmentMap.get(orderCode);
|
||
const branchKey = row.branch_code ? String(row.branch_code) : '';
|
||
const pickingEnabled = branchKey ? Boolean(pickingEnabledByBranch.get(branchKey)) : true;
|
||
const facts = progressFacts.get(orderCode) || {
|
||
allocationFulfilled: false,
|
||
pendingPreps: 0,
|
||
pendingPurchases: 0,
|
||
itemCount: 0,
|
||
inspectionCount: 0,
|
||
pendingProcessing: 0,
|
||
unfinishedPicks: 0,
|
||
completedPicks: 0,
|
||
deliveryStarted: false,
|
||
deliveryEnded: false,
|
||
customerSigned: false,
|
||
pendingBackfill: row.pending_backfill === true,
|
||
};
|
||
return {
|
||
order_code: orderCode,
|
||
customer_code: String(row.customer_code || ''),
|
||
company_name: row.company_name ? String(row.company_name) : null,
|
||
branch_code: row.branch_code ? String(row.branch_code) : null,
|
||
branch_name: row.branch_name ? String(row.branch_name) : null,
|
||
order_status: storedStatus,
|
||
total_amount: Number(row.total_amount) || 0,
|
||
total_weight: Number(row.total_weight) || 0,
|
||
created_at: String(row.created_at),
|
||
updated_at: row.updated_at ? String(row.updated_at) : null,
|
||
delivery_date: normalizeDateOnly(row.delivery_date),
|
||
delivery_time_slot: row.delivery_time_slot ? String(row.delivery_time_slot) : null,
|
||
customer_delivery_time: row.customer_delivery_time ? String(row.customer_delivery_time) : null,
|
||
delivery_address: row.delivery_address ? String(row.delivery_address) : null,
|
||
cycle_code: row.cycle_code ? String(row.cycle_code) : null,
|
||
is_main_system_order: row.is_main_system_order === true,
|
||
// 主系统全免入库单 ⇒ 前端在 50 展示「待取货」(自建单恒为 false)
|
||
is_skip_inbound: skipInboundMap.get(orderCode) === true,
|
||
inspection_state: inspectionState,
|
||
status_hint:
|
||
buildProgressStatusHint(
|
||
storedStatus,
|
||
inspectionState,
|
||
facts,
|
||
fulfillment,
|
||
pickingEnabled,
|
||
// 免入库单副文案同口径「待主系统骑手上门取货」(见 orderStatusDisplayService)
|
||
skipInboundMap.get(orderCode) === true
|
||
) ||
|
||
buildStatusHint(storedStatus, inspectionState, fulfillment, pickingEnabled),
|
||
inspection_fail_items: failItemsMap.get(orderCode) || [],
|
||
stock_cover_items: stockCoverMap.get(orderCode) || [],
|
||
pending_backfill: row.pending_backfill === true,
|
||
auto_advanced_from_status:
|
||
row.auto_advanced_from_status == null ? null : Number(row.auto_advanced_from_status),
|
||
};
|
||
});
|
||
|
||
return {
|
||
rows,
|
||
total: Number(countResult.rows[0]?.cnt || 0),
|
||
totalAmount: Math.round(Number(countResult.rows[0]?.total_amount || 0) * 100) / 100,
|
||
stats: {
|
||
pending: Number(statsResult.rows[0]?.pending) || 0,
|
||
processing: Number(statsResult.rows[0]?.processing) || 0,
|
||
completed: Number(statsResult.rows[0]?.completed) || 0,
|
||
backfill: Number(statsResult.rows[0]?.backfill) || 0,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 订单列表首页角标:今天上海日 + 配送日轴的待处理订单数(order_status < 50,排除垃圾桶)。
|
||
* 与列表默认筛(今天、配送日、待处理)同口径;切本周/下单日不改此 COUNT。
|
||
* 租户隔离由 /api/mobile 的 tenantDbMiddleware 承担。
|
||
*/
|
||
export async function countPendingPickingOrders(): Promise<number> {
|
||
const result = await pool.query(
|
||
`SELECT COUNT(*)::int AS c
|
||
FROM orders o
|
||
WHERE o.order_status < 50
|
||
AND ${orderNotDeletedSql('o')}
|
||
AND o.delivery_date::date = (NOW() AT TIME ZONE 'Asia/Shanghai')::date`
|
||
);
|
||
return Number(result.rows[0]?.c) || 0;
|
||
}
|