feat(配送/分拣): 早期任务、全状态发车与库存抵扣闭环
- 下单即建分拣/配送,待取货/散客/独立进货守卫 - 30/40/45 直接发车/分拣,入库与分拣二选一 - 分拣完成补上游、清理 pending 验收,直接配送补分拣 - 库存抵扣/计划/实收 FIFO,软扣部分扣减,并发出库串行 - 结束配送不被库存不足/待入库残留阻断 - 待验收并发唯一索引(含 name-only),finalize 共享连接修复 - 售后自动绑定订单明细、客户取货/采购并发修复 - 仓库表格自适应、弹窗滚动锁闪烁修复
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
-- 早期配送任务地基:delivery_tasks 增加 void 标记 + 活跃订单部分索引。
|
||||
-- 2026-10-26 T1:下单即建配送单后,改单/全直送需要能表示“该任务已作废”;
|
||||
-- 不改现有全唯一索引 delivery_tasks_order_code_uidx,不新建审计表(T3)。
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname
|
||||
FROM pg_namespace
|
||||
WHERE nspname = 'public'
|
||||
OR nspname = 'tenant_template'
|
||||
OR nspname = 'legacy_public'
|
||||
OR nspname LIKE 'tenant_%'
|
||||
LOOP
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.tables
|
||||
WHERE table_schema = sch AND table_name = 'delivery_tasks'
|
||||
) THEN
|
||||
CONTINUE;
|
||||
END IF;
|
||||
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.delivery_tasks ADD COLUMN IF NOT EXISTS voided_at TIMESTAMPTZ',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'ALTER TABLE %I.delivery_tasks ADD COLUMN IF NOT EXISTS void_reason VARCHAR(100)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'CREATE INDEX IF NOT EXISTS idx_delivery_tasks_active_order ON %I.delivery_tasks (order_code) WHERE voided_at IS NULL',
|
||||
sch
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,198 @@
|
||||
-- T3 配送核货补录审计:delivery_loading_backfill_logs
|
||||
-- 2026-10-26:补入库/补分拣可追溯;只新增表 + 租户登记,不改财务/状态链。
|
||||
-- 表在 tenant_template 建立后克隆到所有租户 schema;RLS 由 apply_tenant_core_rls 统一应用。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
EXECUTE format(
|
||||
'CREATE TABLE IF NOT EXISTS %I.delivery_loading_backfill_logs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
branch_code VARCHAR(50),
|
||||
order_code VARCHAR(100) NOT NULL,
|
||||
order_item_id UUID,
|
||||
task_code VARCHAR(100),
|
||||
sku_code VARCHAR(100),
|
||||
item_name VARCHAR(255),
|
||||
supplier_code VARCHAR(100),
|
||||
purchaser_code VARCHAR(100),
|
||||
-- 允许值:inbound | picking | inbound_picking | prep(30 直发只完成备货)
|
||||
missing_stage VARCHAR(32) NOT NULL,
|
||||
responsible_code VARCHAR(100),
|
||||
operator_id UUID,
|
||||
confirmed_qty NUMERIC(14,4) NOT NULL DEFAULT 0,
|
||||
inbound_qty NUMERIC(14,4) NOT NULL DEFAULT 0,
|
||||
picking_qty NUMERIC(14,4) NOT NULL DEFAULT 0,
|
||||
inventory_action VARCHAR(32) NOT NULL DEFAULT ''none'',
|
||||
inbound_batch_no VARCHAR(100),
|
||||
pick_code VARCHAR(100),
|
||||
remark TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'CREATE INDEX IF NOT EXISTS idx_delivery_backfill_order
|
||||
ON %I.delivery_loading_backfill_logs (order_code, created_at DESC)',
|
||||
sch
|
||||
);
|
||||
EXECUTE format('ALTER TABLE %I.delivery_loading_backfill_logs ENABLE ROW LEVEL SECURITY', sch);
|
||||
EXECUTE format('ALTER TABLE %I.delivery_loading_backfill_logs FORCE ROW LEVEL SECURITY', sch);
|
||||
EXECUTE format('DROP POLICY IF EXISTS tenant_isolation_delivery_loading_backfill_logs ON %I.delivery_loading_backfill_logs', sch);
|
||||
EXECUTE format(
|
||||
'CREATE POLICY tenant_isolation_delivery_loading_backfill_logs ON %I.delivery_loading_backfill_logs
|
||||
FOR ALL USING (branch_code::text = current_setting(''app.branch_code'', true))
|
||||
WITH CHECK (branch_code::text = current_setting(''app.branch_code'', true))',
|
||||
sch
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- 租户业务表登记(新租户/克隆必须包含)
|
||||
CREATE OR REPLACE FUNCTION public.tenant_business_tables()
|
||||
RETURNS TEXT[]
|
||||
LANGUAGE sql
|
||||
IMMUTABLE
|
||||
AS $$
|
||||
SELECT ARRAY[
|
||||
'main_system_sku_mappings',
|
||||
'after_sale_returns',
|
||||
'after_sales',
|
||||
'ai_prompt_overrides',
|
||||
'ai_prompt_revisions',
|
||||
'ai_prompt_templates',
|
||||
'alias_recognition_logs',
|
||||
'allocation_tasks',
|
||||
'assistant_conversations',
|
||||
'assistant_messages',
|
||||
'assistant_turns',
|
||||
'bid_awards',
|
||||
'bid_invitations',
|
||||
'bid_prices',
|
||||
'bid_quotes',
|
||||
'bid_round_items',
|
||||
'bid_rounds',
|
||||
'categories',
|
||||
'cost_adjustments',
|
||||
'cost_details',
|
||||
'customer_alias_stats',
|
||||
'customer_delivery_assignments',
|
||||
'customer_portal_users',
|
||||
'customer_processing_aliases',
|
||||
'customer_quote_sheet_customers',
|
||||
'customer_quote_sheet_items',
|
||||
'customer_quote_sheets',
|
||||
'customer_quote_versions',
|
||||
'customer_recipients',
|
||||
'customer_sku_aliases',
|
||||
'customer_sku_remarks',
|
||||
'customer_skus',
|
||||
'customer_statements',
|
||||
'customers',
|
||||
'delivery_location_history',
|
||||
'delivery_person_locations',
|
||||
'delivery_person_users',
|
||||
'delivery_persons',
|
||||
'delivery_schedules',
|
||||
'delivery_signatures',
|
||||
'delivery_tasks',
|
||||
'delivery_loading_backfill_logs',
|
||||
'exception_tickets',
|
||||
'fixed_costs',
|
||||
'free_cost_invoice_links',
|
||||
'free_cost_invoices',
|
||||
'free_cost_payment_vouchers',
|
||||
'import_mapping_memories',
|
||||
'inspection_loss_confirmations',
|
||||
'inspection_photo_archive_entries',
|
||||
'inspection_photo_archives',
|
||||
'inspection_returns',
|
||||
'inspection_review_logs',
|
||||
'inspections',
|
||||
'inventory',
|
||||
'inventory_batch_report_matches',
|
||||
'inventory_batch_reports',
|
||||
'inventory_logs',
|
||||
'inventory_reservations',
|
||||
'invoice_statement_links',
|
||||
'invoices',
|
||||
'market_compare_exclusions',
|
||||
'market_external_catalog',
|
||||
'market_price_history',
|
||||
'market_price_indices',
|
||||
'market_prices',
|
||||
'market_sku_external_bindings',
|
||||
'notifications',
|
||||
'operation_logs',
|
||||
'order_allocation_batches',
|
||||
'order_item_fulfillments',
|
||||
'order_item_returns',
|
||||
'order_items',
|
||||
'orders',
|
||||
'parse_session_items',
|
||||
'parse_sessions',
|
||||
'picking_assign_rules',
|
||||
'picking_containers',
|
||||
'picking_items',
|
||||
'picking_scan_logs',
|
||||
'picking_tasks',
|
||||
'price_invert_events',
|
||||
'print_jobs',
|
||||
'processing_demand_items',
|
||||
'processing_demand_picks',
|
||||
'processing_logs',
|
||||
'processing_tasks',
|
||||
'product_catalog',
|
||||
'product_substitutions',
|
||||
'purchase_orders',
|
||||
'purchaser_users',
|
||||
'quality_report_prep_links',
|
||||
'quality_reports',
|
||||
'quote_price_proposals',
|
||||
'seasonal_recommendations',
|
||||
'self_purchase_stock_inbounds',
|
||||
'sign_records',
|
||||
'sku_direct_delivery_customers',
|
||||
'sku_suppliers',
|
||||
'skus',
|
||||
'smart_classification_rules',
|
||||
'statement_disputes',
|
||||
'statement_lines',
|
||||
'statement_payments',
|
||||
'supplier_categories',
|
||||
'supplier_prep_amend_requests',
|
||||
'supplier_preparations',
|
||||
'supplier_rating_snapshots',
|
||||
'supplier_statements',
|
||||
'supplier_users',
|
||||
'suppliers',
|
||||
'system_configs',
|
||||
'unit_conversions',
|
||||
'user_preferences',
|
||||
'voice_recognition_logs',
|
||||
'warehouse_locations',
|
||||
'warehouses',
|
||||
'weigh_devices',
|
||||
'processing_task_materials',
|
||||
'processing_task_outputs'
|
||||
];
|
||||
$$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
PERFORM public.ensure_tenant_schemas_match_template();
|
||||
EXCEPTION WHEN undefined_function THEN
|
||||
RAISE NOTICE 'ensure_tenant_schemas_match_template 不存在,跳过';
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
PERFORM public.ensure_all_tenant_core_rls();
|
||||
EXCEPTION WHEN undefined_function THEN
|
||||
RAISE NOTICE 'ensure_all_tenant_core_rls 不存在,跳过';
|
||||
END $$;
|
||||
@@ -0,0 +1,47 @@
|
||||
-- 防并发 ensureInspectionsForOrder 生成同单同 SKU 多条 pending inspections。
|
||||
-- 只处理 pending(未验收)行;已入库/历史合格记录不删。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
-- 先清理历史重复 pending:同 order/supplier/sku 保留最早一条,其余删除(仅 pending)。
|
||||
EXECUTE format(
|
||||
'DELETE FROM %I.inspections
|
||||
WHERE id IN (
|
||||
SELECT id FROM (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY order_code,
|
||||
COALESCE(NULLIF(UPPER(TRIM(supplier_code)), ''''), ''INTERNAL''),
|
||||
NULLIF(TRIM(sku_code), '''')
|
||||
ORDER BY created_at ASC NULLS LAST, id ASC
|
||||
) AS rn
|
||||
FROM %I.inspections
|
||||
WHERE inspection_time IS NULL
|
||||
AND COALESCE(actual_qty, 0) = 0
|
||||
AND COALESCE(quality_rating, '''') = ''''
|
||||
AND NULLIF(TRIM(sku_code), '''') IS NOT NULL
|
||||
) t WHERE t.rn > 1
|
||||
)',
|
||||
sch, sch
|
||||
);
|
||||
EXECUTE format(
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS inspections_pending_order_supplier_sku_uidx
|
||||
ON %I.inspections (
|
||||
order_code,
|
||||
COALESCE(NULLIF(UPPER(TRIM(supplier_code)), ''''), ''INTERNAL''),
|
||||
NULLIF(TRIM(sku_code), '''')
|
||||
)
|
||||
WHERE inspection_time IS NULL
|
||||
AND COALESCE(actual_qty, 0) = 0
|
||||
AND COALESCE(quality_rating, '''') = ''''
|
||||
AND NULLIF(TRIM(sku_code), '''') IS NOT NULL',
|
||||
sch
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,53 @@
|
||||
-- 2026-10-26:待验收并发重复(P0)补充覆盖 name-only SKU。
|
||||
-- 先清理历史 pending 重复(保留最早一条),再建覆盖 sku/品名路径的唯一索引。
|
||||
-- 只删 pending;已入库/历史合格记录不动;不同品名不会合并。
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
sch text;
|
||||
BEGIN
|
||||
FOR sch IN
|
||||
SELECT nspname FROM pg_namespace
|
||||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||||
LOOP
|
||||
EXECUTE format(
|
||||
'DELETE FROM %I.inspections
|
||||
WHERE id IN (
|
||||
SELECT id FROM (
|
||||
SELECT id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY
|
||||
order_code,
|
||||
COALESCE(NULLIF(UPPER(TRIM(supplier_code)), ''''), ''INTERNAL''),
|
||||
COALESCE(
|
||||
NULLIF(TRIM(sku_code), ''''),
|
||||
''__NAME__:'' || COALESCE(NULLIF(LOWER(TRIM(item_name)), ''''), ''__EMPTY__'')
|
||||
)
|
||||
ORDER BY created_at ASC NULLS LAST, id ASC
|
||||
) AS rn
|
||||
FROM %I.inspections
|
||||
WHERE inspection_time IS NULL
|
||||
AND COALESCE(actual_qty, 0) = 0
|
||||
AND COALESCE(quality_rating, '''') = ''''
|
||||
) t WHERE t.rn > 1
|
||||
)',
|
||||
sch, sch
|
||||
);
|
||||
EXECUTE format('DROP INDEX IF EXISTS %I.inspections_pending_order_supplier_sku_uidx', sch);
|
||||
EXECUTE format(
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS inspections_pending_order_supplier_key_uidx
|
||||
ON %I.inspections (
|
||||
order_code,
|
||||
COALESCE(NULLIF(UPPER(TRIM(supplier_code)), ''''), ''INTERNAL''),
|
||||
COALESCE(
|
||||
NULLIF(TRIM(sku_code), ''''),
|
||||
''__NAME__:'' || COALESCE(NULLIF(LOWER(TRIM(item_name)), ''''), ''__EMPTY__'')
|
||||
)
|
||||
)
|
||||
WHERE inspection_time IS NULL
|
||||
AND COALESCE(actual_qty, 0) = 0
|
||||
AND COALESCE(quality_rating, '''') = ''''',
|
||||
sch
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -45,7 +45,7 @@ async function withOrderBranchContext<T>(orderCode: string, fn: () => Promise<T>
|
||||
|
||||
export async function withOrderLock<T>(
|
||||
orderCode: string,
|
||||
expectedStatus: number,
|
||||
expectedStatus: number | number[],
|
||||
fn: (client: PoolClient) => Promise<T>
|
||||
): Promise<T> {
|
||||
return withOrderBranchContext(orderCode, async () => {
|
||||
@@ -60,7 +60,10 @@ export async function withOrderLock<T>(
|
||||
throw Object.assign(new Error('订单不存在'), { status: 404 });
|
||||
}
|
||||
const status = Number(locked.rows[0].order_status);
|
||||
if (status !== expectedStatus) {
|
||||
const expectedOk = Array.isArray(expectedStatus)
|
||||
? expectedStatus.includes(status)
|
||||
: status === expectedStatus;
|
||||
if (!expectedOk) {
|
||||
throw Object.assign(
|
||||
new Error(`订单状态已变为 ${status},请刷新后重试`),
|
||||
{ status: 409 }
|
||||
@@ -130,7 +133,10 @@ export async function withOrderTransitionLock<T>(
|
||||
throw Object.assign(new Error('订单不存在'), { status: 404 });
|
||||
}
|
||||
const status = Number(current.rows[0].order_status);
|
||||
if (status !== expectedStatus) {
|
||||
const expectedOk = Array.isArray(expectedStatus)
|
||||
? expectedStatus.includes(status)
|
||||
: status === expectedStatus;
|
||||
if (!expectedOk) {
|
||||
throw Object.assign(
|
||||
new Error(`订单状态已变为 ${status},请刷新后重试`),
|
||||
{ status: 409 }
|
||||
|
||||
@@ -747,6 +747,8 @@ router.get('/delivery/tracking/active', authMiddleware, async (req: AuthRequest,
|
||||
LEFT JOIN orders o ON o.order_code = dt.order_code
|
||||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||||
WHERE dt.task_status = 20
|
||||
AND dt.voided_at IS NULL
|
||||
AND (dt.loading_completed_at IS NOT NULL OR dt.task_status >= 20)
|
||||
ORDER BY dt.start_time DESC NULLS LAST, dt.created_at DESC`
|
||||
);
|
||||
return res.json({ data: result.rows });
|
||||
|
||||
@@ -145,7 +145,10 @@ export async function allocateCostPool(input: {
|
||||
) AS delivery_day
|
||||
FROM orders o
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT COUNT(*)::int AS task_count FROM delivery_tasks dt WHERE dt.order_code = o.order_code
|
||||
SELECT COUNT(*)::int AS task_count FROM delivery_tasks dt
|
||||
WHERE dt.order_code = o.order_code
|
||||
AND dt.voided_at IS NULL
|
||||
AND COALESCE(dt.task_status, 10) >= 20
|
||||
) dt ON true
|
||||
WHERE o.cycle_code = $1 ${branchSql}
|
||||
AND o.order_status >= 20
|
||||
|
||||
@@ -8,6 +8,8 @@ import { compensateOrderItemCostDetails } from './orderCostPostingService';
|
||||
import { learnAlias, syncCustomerMappings } from './orderParseService';
|
||||
import { reprocessOrderAllocation } from './orderAllocationService';
|
||||
import { applyDirectToDeliveryAfterAllocation } from './directToDeliveryService';
|
||||
import { ensureEarlyDeliveryTaskForOrder } from './orderWorkflowFulfillmentService';
|
||||
import { ensurePickingTaskOnOrderSubmit } from './pickingService';
|
||||
import {
|
||||
syncWarehouseProcessingDemandForOrder,
|
||||
syncWarehouseProcessingDemandForOrderAfterCommit,
|
||||
@@ -719,6 +721,19 @@ export async function submitMobileCustomerOrder(
|
||||
console.error('[customerOrderSubmit] 自动完成厂商备货失败(不影响下单)', orderCode, err);
|
||||
}
|
||||
}
|
||||
|
||||
// T1:下单 COMMIT 后建早期分拣单/配送单;失败不阻断下单,后续链路兜底。
|
||||
// 配送单复用现有五道守卫(散客/全直送/独立进货/自提/待取货),early 分支不派员、不通知。
|
||||
try {
|
||||
await ensurePickingTaskOnOrderSubmit(orderCode, input.branchCode);
|
||||
} catch (err) {
|
||||
console.error('[customerOrderSubmit] 下单即建分拣单失败(不影响下单)', orderCode, err);
|
||||
}
|
||||
try {
|
||||
await ensureEarlyDeliveryTaskForOrder(orderCode, input.branchCode);
|
||||
} catch (err) {
|
||||
console.error('[customerOrderSubmit] 下单即建配送单失败(不影响下单)', orderCode, err);
|
||||
}
|
||||
} catch (error: any) {
|
||||
// needs_confirm 路径已在事务内 ROLLBACK;其它错误再尝试回滚
|
||||
if (error?.code !== 'needs_confirm_new_products') {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,7 @@ import { isDeliveryLoadingPhotoRequired, isDeliveryLoadingQtyEditEnabled } from
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { freezeOrderSettlementQtyOnComplete } from './orderItemSupplyUnitSync';
|
||||
import { attachCategoryPhotoInspectionRequirements } from './inspectionPhotoService';
|
||||
import { backfillLoadingItemUpstream } from './deliveryLoadingBackfillService';
|
||||
import { ensureSkipInboundLoadingLines } from './skipInboundLoadingService';
|
||||
import { skuDirectDeliveryAppliesSql } from './skuDirectDelivery';
|
||||
import { displayPickedMeasureForUnit, isPickingWeightUnit } from './orderItemSupplyUnitSync';
|
||||
@@ -206,7 +207,7 @@ function sortLoadingItemsLikeDeliveryNote<T extends { category_name?: string | n
|
||||
async function assertDeliveryPersonTask(taskCode: string, personCode: string) {
|
||||
const taskResult = await pool.query(
|
||||
`SELECT task_code, order_code, person_code, task_status, loading_completed_at, branch_code
|
||||
FROM delivery_tasks WHERE task_code = $1 LIMIT 1`,
|
||||
FROM delivery_tasks WHERE task_code = $1 AND voided_at IS NULL LIMIT 1`,
|
||||
[taskCode]
|
||||
);
|
||||
const task = taskResult.rows[0];
|
||||
@@ -216,6 +217,18 @@ async function assertDeliveryPersonTask(taskCode: string, personCode: string) {
|
||||
if (task.person_code && task.person_code !== personCode) {
|
||||
throw Object.assign(new Error('无权操作该配送任务'), { status: 403, code: 'forbidden' });
|
||||
}
|
||||
if (!task.person_code) {
|
||||
// 未分配早期任务:只允许同分公司配送员操作,禁止跨分公司。
|
||||
const person = await pool.query(
|
||||
`SELECT branch_code FROM delivery_persons WHERE person_code = $1 LIMIT 1`,
|
||||
[personCode]
|
||||
);
|
||||
const personBranch = String(person.rows[0]?.branch_code || '').trim();
|
||||
const taskBranch = String(task.branch_code || '').trim();
|
||||
if (personBranch && taskBranch && personBranch !== taskBranch) {
|
||||
throw Object.assign(new Error('无权操作其他分公司的配送任务'), { status: 403, code: 'forbidden' });
|
||||
}
|
||||
}
|
||||
return task as {
|
||||
task_code: string;
|
||||
order_code: string;
|
||||
@@ -613,7 +626,8 @@ export const MISSING_NON_EXTRA_LOADING_SQL = `
|
||||
async function listLoadingItems(orderCode: string, anchorPickCode: string, orderStatus = 50) {
|
||||
const deliveryScaleEnabled = await isDeliveryLoadingScaleEnabled();
|
||||
const qtyEditEnabled = await isDeliveryLoadingQtyEditEnabled();
|
||||
const earlySkipOnly = orderStatus < 50;
|
||||
// T3:早期任务也展示全部核货行,不再只显示免入库行。
|
||||
const earlySkipOnly = false;
|
||||
const [picked, missing] = await Promise.all([
|
||||
pool.query(
|
||||
earlySkipOnly ? `${LOADING_ITEMS_SQL} AND COALESCE(skip_sup.skip_inbound, false) = true` : LOADING_ITEMS_SQL,
|
||||
@@ -679,7 +693,7 @@ export async function getDeliveryLoadingState(taskCode: string, personCode: stri
|
||||
export async function getDeliveryLoadingStateForManagement(taskCode: string) {
|
||||
const taskResult = await pool.query(
|
||||
`SELECT task_code, order_code, person_code, task_status, loading_completed_at
|
||||
FROM delivery_tasks WHERE task_code = $1 LIMIT 1`,
|
||||
FROM delivery_tasks WHERE task_code = $1 AND voided_at IS NULL LIMIT 1`,
|
||||
[taskCode]
|
||||
);
|
||||
const task = taskResult.rows[0];
|
||||
@@ -724,7 +738,7 @@ async function buildDeliveryLoadingState(task: {
|
||||
loading_photo_required: effectivePhotoRequired,
|
||||
loading_qty_edit_enabled: loadingQtyEditEnabled,
|
||||
can_start_delivery:
|
||||
allLoaded && photosOk && Number(task.task_status) < 20 && orderStatus >= 50,
|
||||
allLoaded && photosOk && Number(task.task_status) < 20,
|
||||
can_sign_delivery: extraDishPhotosOk,
|
||||
picking_scale_enabled,
|
||||
order_status: orderStatus,
|
||||
@@ -899,6 +913,14 @@ export async function confirmDeliveryLoadingItem(input: {
|
||||
}) {
|
||||
const task = await assertDeliveryPersonTask(input.taskCode, input.personCode);
|
||||
|
||||
// T3:核货前按行真实补备货/采购、验收入库、分拣;失败直接阻断本次核货。
|
||||
await backfillLoadingItemUpstream({
|
||||
taskCode: input.taskCode,
|
||||
itemId: input.itemId,
|
||||
confirmedQty: input.loadedQty ?? null,
|
||||
operatorId: input.operatorId || null,
|
||||
});
|
||||
|
||||
const pickCode = await ensureDeliveryLoadingPickTask(String(task.order_code));
|
||||
const qtyEditEnabled = await isDeliveryLoadingQtyEditEnabled();
|
||||
let canEditQty = qtyEditEnabled;
|
||||
@@ -1124,7 +1146,6 @@ export async function confirmDeliveryLoadingItem(input: {
|
||||
can_start_delivery:
|
||||
allLoaded &&
|
||||
loadingPhotosSatisfied(items, await isDeliveryLoadingPhotoRequired()) &&
|
||||
orderStatus >= 50 &&
|
||||
Number(task.task_status) < 20,
|
||||
};
|
||||
}
|
||||
@@ -1301,7 +1322,6 @@ export async function unconfirmDeliveryLoadingItem(input: {
|
||||
can_start_delivery:
|
||||
allLoaded &&
|
||||
loadingPhotosSatisfied(items, await isDeliveryLoadingPhotoRequired()) &&
|
||||
orderStatus >= 50 &&
|
||||
Number(task.task_status) < 20,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,6 +71,19 @@ function normalizeOrderCodes(codes: string[]): string[] {
|
||||
}
|
||||
|
||||
/** 配送单打印:订单头 + 明细(含分拣实拣、验收实收、装车数量) */
|
||||
/** 正式配送单只能打印已就绪任务:已开始配送或核货完成;无任务的历史单保持可打印。 */
|
||||
function deliveryPrintReadySql(orderAlias: string): string {
|
||||
return `(
|
||||
NOT EXISTS (SELECT 1 FROM delivery_tasks dt_any WHERE dt_any.order_code = ${orderAlias}.order_code)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM delivery_tasks dt_ready
|
||||
WHERE dt_ready.order_code = ${orderAlias}.order_code
|
||||
AND dt_ready.voided_at IS NULL
|
||||
AND (COALESCE(dt_ready.task_status, 10) >= 20 OR dt_ready.loading_completed_at IS NOT NULL)
|
||||
)
|
||||
)`;
|
||||
}
|
||||
|
||||
export async function fetchDeliveryPrintBundle(
|
||||
orderCodes: string[],
|
||||
ctx?: TenantContext | null,
|
||||
@@ -123,6 +136,7 @@ export async function fetchDeliveryPrintBundle(
|
||||
LEFT JOIN delivery_persons dp ON dp.person_code = dt.person_code
|
||||
WHERE o.order_code = ANY($1::text[])
|
||||
${branchFilter}
|
||||
AND ${deliveryPrintReadySql('o')}
|
||||
ORDER BY o.customer_code NULLS LAST, o.order_code`,
|
||||
params
|
||||
);
|
||||
@@ -233,6 +247,7 @@ export async function fetchDeliveryPrintBundle(
|
||||
LIMIT 1
|
||||
) insp ON TRUE
|
||||
WHERE oi.order_code = ANY($1::text[])
|
||||
AND ${deliveryPrintReadySql('o_hdr')}
|
||||
ORDER BY oi.order_code, COALESCE(oi.sort_order, 0), oi.id`,
|
||||
[codes]
|
||||
);
|
||||
|
||||
@@ -427,6 +427,8 @@ async function loadTaskRows(input: {
|
||||
LEFT JOIN delivery_signatures ds
|
||||
ON ds.task_code = dt.task_code AND ds.sign_type = 'delivery'
|
||||
WHERE 1=1 ${branchSql} ${taskFilter}${dateSql}
|
||||
AND dt.voided_at IS NULL
|
||||
AND (COALESCE(dt.task_status, 10) >= 20 OR dt.loading_completed_at IS NOT NULL)
|
||||
ORDER BY dt.start_time ASC NULLS LAST, dt.created_at ASC
|
||||
LIMIT 40`,
|
||||
params
|
||||
|
||||
@@ -11,7 +11,10 @@ import {
|
||||
import { fetchOrderInspectionState } from './orderInspectionStateService';
|
||||
import { signedExistingPhotos } from './inspectionReviewService';
|
||||
import { orderNotDeletedSql } from './orderTrashScope';
|
||||
import { orderVisibleToDeliverySql } from './supplierSkipInbound';
|
||||
import {
|
||||
orderVisibleToDeliveryManagementSql,
|
||||
orderVisibleToDeliverySql,
|
||||
} from './supplierSkipInbound';
|
||||
import { salesVisibleOrderSql } from './independentInbound';
|
||||
import { computeUnloadSeconds } from './deliveryGeofenceLogic';
|
||||
import { isOrderCodeSearch } from '../utils/orderCodeQuery';
|
||||
@@ -446,7 +449,7 @@ export async function listDeliveryTasksForManagement(
|
||||
const result = await pool.query(
|
||||
`SELECT ${DELIVERY_TASK_SELECT}
|
||||
FROM orders o
|
||||
LEFT JOIN delivery_tasks dt ON dt.order_code = o.order_code
|
||||
LEFT JOIN delivery_tasks dt ON dt.order_code = o.order_code AND dt.voided_at IS NULL
|
||||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||||
LEFT JOIN delivery_persons dp ON dp.person_code = dt.person_code
|
||||
LEFT JOIN LATERAL (
|
||||
@@ -457,7 +460,7 @@ export async function listDeliveryTasksForManagement(
|
||||
LIMIT 1
|
||||
) bind ON true
|
||||
LEFT JOIN delivery_persons bind_dp ON bind_dp.person_code = bind.person_code
|
||||
WHERE ${orderVisibleToDeliverySql('o')}
|
||||
WHERE ${orderVisibleToDeliveryManagementSql('o')}
|
||||
AND ${salesVisibleOrderSql('o')}
|
||||
${statusFilter}
|
||||
AND ${orderNotDeletedSql('o')}
|
||||
@@ -525,7 +528,8 @@ export async function listDeliveryTasksForDriver(input: {
|
||||
LIMIT 1
|
||||
) bind ON true
|
||||
LEFT JOIN delivery_persons bind_dp ON bind_dp.person_code = bind.person_code
|
||||
WHERE ${orderVisibleToDeliverySql('o')}
|
||||
WHERE ${orderVisibleToDeliveryManagementSql('o')}
|
||||
AND dt.voided_at IS NULL
|
||||
AND ${salesVisibleOrderSql('o')}
|
||||
AND COALESCE(o.order_status, 0) < 90
|
||||
AND ${orderNotDeletedSql('o')}
|
||||
@@ -564,7 +568,7 @@ export async function countPendingDriverDeliveryTasks(input: {
|
||||
`SELECT COUNT(*)::int AS c
|
||||
FROM delivery_tasks dt
|
||||
INNER JOIN orders o ON o.order_code = dt.order_code
|
||||
WHERE ${orderVisibleToDeliverySql('o')}
|
||||
WHERE ${orderVisibleToDeliveryManagementSql('o')}
|
||||
AND ${salesVisibleOrderSql('o')}
|
||||
AND COALESCE(o.order_status, 0) < 90
|
||||
AND ${orderNotDeletedSql('o')}
|
||||
@@ -681,6 +685,7 @@ export async function listDeliveryPersonStats(
|
||||
INNER JOIN orders o ON o.order_code = dt.order_code
|
||||
LEFT JOIN customers c ON c.customer_code = o.customer_code
|
||||
WHERE ${orderVisibleToDeliverySql('o')}
|
||||
AND dt.voided_at IS NULL
|
||||
AND ${salesVisibleOrderSql('o')}
|
||||
AND ${orderNotDeletedSql('o')}
|
||||
AND ${nonRetailOrderSql('o')}
|
||||
|
||||
@@ -176,11 +176,11 @@ export async function hasOpenPendingInspection(
|
||||
WHERE order_code IS NOT DISTINCT FROM $1
|
||||
AND ${sqlSelfPurchaseSupplierEquiv('supplier_code', '$3::text')}
|
||||
AND (
|
||||
sku_code IS NOT DISTINCT FROM $2
|
||||
(NULLIF(TRIM($2::text), '') IS NOT NULL AND sku_code IS NOT DISTINCT FROM $2)
|
||||
OR (
|
||||
NULLIF(TRIM($2::text), '') IS NULL
|
||||
AND $5 <> ''
|
||||
AND TRIM(COALESCE(item_name, '')) = $5
|
||||
AND COALESCE(NULLIF(TRIM(sku_code), ''), '') = ''
|
||||
AND COALESCE(LOWER(TRIM(item_name)), '') = COALESCE(LOWER(TRIM($5)), '')
|
||||
)
|
||||
)
|
||||
AND inspection_time IS NULL
|
||||
@@ -223,11 +223,11 @@ export async function hasSuccessfulInboundInspection(
|
||||
WHERE i.order_code IS NOT DISTINCT FROM $1
|
||||
AND ${sqlSelfPurchaseSupplierEquiv('i.supplier_code', '$3::text')}
|
||||
AND (
|
||||
i.sku_code IS NOT DISTINCT FROM $2
|
||||
(NULLIF(TRIM($2::text), '') IS NOT NULL AND i.sku_code IS NOT DISTINCT FROM $2)
|
||||
OR (
|
||||
NULLIF(TRIM($2::text), '') IS NULL
|
||||
AND $5 <> ''
|
||||
AND TRIM(COALESCE(i.item_name, '')) = $5
|
||||
AND COALESCE(NULLIF(TRIM(i.sku_code), ''), '') = ''
|
||||
AND COALESCE(LOWER(TRIM(i.item_name)), '') = COALESCE(LOWER(TRIM($5)), '')
|
||||
)
|
||||
)
|
||||
AND i.inspection_time IS NOT NULL
|
||||
@@ -301,11 +301,11 @@ export async function pruneStalePendingInspectionsAfterPass(
|
||||
WHERE order_code IS NOT DISTINCT FROM $1
|
||||
AND COALESCE(supplier_code, '') = COALESCE($3, '')
|
||||
AND (
|
||||
sku_code IS NOT DISTINCT FROM $2
|
||||
(NULLIF(TRIM($2::text), '') IS NOT NULL AND sku_code IS NOT DISTINCT FROM $2)
|
||||
OR (
|
||||
NULLIF(TRIM($2::text), '') IS NULL
|
||||
AND $5 <> ''
|
||||
AND TRIM(COALESCE(item_name, '')) = $5
|
||||
AND COALESCE(NULLIF(TRIM(sku_code), ''), '') = ''
|
||||
AND COALESCE(LOWER(TRIM(item_name)), '') = COALESCE(LOWER(TRIM($5)), '')
|
||||
)
|
||||
)
|
||||
AND inspection_time IS NULL
|
||||
@@ -348,8 +348,8 @@ export async function prunePendingInspectionsWhenInboundCovered(
|
||||
(NULLIF(TRIM($2::text), '') IS NOT NULL AND sku_code IS NOT DISTINCT FROM $2)
|
||||
OR (
|
||||
NULLIF(TRIM($2::text), '') IS NULL
|
||||
AND $3 <> ''
|
||||
AND TRIM(COALESCE(item_name, '')) = $3
|
||||
AND COALESCE(NULLIF(TRIM(sku_code), ''), '') = ''
|
||||
AND COALESCE(LOWER(TRIM(item_name)), '') = COALESCE(LOWER(TRIM($3)), '')
|
||||
)
|
||||
)
|
||||
AND inspection_time IS NULL
|
||||
@@ -513,23 +513,31 @@ export async function createSupplierInspectionIfNeeded(
|
||||
client
|
||||
));
|
||||
|
||||
const inserted = await client.query(
|
||||
`INSERT INTO inspections (
|
||||
order_code, sku_code, supplier_code, prepare_qty, purchase_price,
|
||||
batch_no, branch_code, source_type, item_name
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 'supplier', $8)
|
||||
RETURNING id, order_code, sku_code, prepare_qty, branch_code, item_name, processing_details`,
|
||||
[
|
||||
input.orderCode,
|
||||
skuCode,
|
||||
input.supplierCode || null,
|
||||
input.prepareQty || 0,
|
||||
input.purchasePrice ?? null,
|
||||
newBatchNo(),
|
||||
input.branchCode || null,
|
||||
itemName,
|
||||
]
|
||||
);
|
||||
let inserted: { rows: any[] };
|
||||
try {
|
||||
inserted = await client.query(
|
||||
`INSERT INTO inspections (
|
||||
order_code, sku_code, supplier_code, prepare_qty, purchase_price,
|
||||
batch_no, branch_code, source_type, item_name
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, 'supplier', $8)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING id, order_code, sku_code, prepare_qty, branch_code, item_name, processing_details`,
|
||||
[
|
||||
input.orderCode,
|
||||
skuCode,
|
||||
input.supplierCode || null,
|
||||
input.prepareQty || 0,
|
||||
input.purchasePrice ?? null,
|
||||
newBatchNo(),
|
||||
input.branchCode || null,
|
||||
itemName,
|
||||
]
|
||||
);
|
||||
} catch (error: any) {
|
||||
// 并发 ensure 被唯一 pending 索引拦下:返回 false,由调用方/下一轮读取已有行。
|
||||
if (error?.code === '23505') return false;
|
||||
throw error;
|
||||
}
|
||||
const inspection = inserted.rows[0];
|
||||
if (!inspection) return false;
|
||||
|
||||
|
||||
@@ -168,6 +168,8 @@ export async function fifoDeductInventory(
|
||||
* 不传 ⇒ 旧口径逐字不变(只豁免 `orderCode` 一个)。
|
||||
*/
|
||||
reservationExemptOrderCodes?: string[] | null;
|
||||
/** 软扣允许部分扣减:可用>0 时先扣可用,缺口由调用方记 softSkipped。 */
|
||||
allowPartial?: boolean;
|
||||
},
|
||||
onBatchDeducted?: (
|
||||
batch: { batchNo: string; costPrice: number; supplierCode?: string | null; inboundAt?: string | null },
|
||||
@@ -201,34 +203,37 @@ export async function fifoDeductInventory(
|
||||
);
|
||||
}
|
||||
if (claimable + 1e-9 < remaining) {
|
||||
const label = input.itemName ? `${input.itemName}(${input.skuCode})` : input.skuCode;
|
||||
let hint = '';
|
||||
if (input.orderCode) {
|
||||
const peers = await listPurchaseMergePeerOrderCodes(client, {
|
||||
orderCode: input.orderCode,
|
||||
skuCode: input.skuCode,
|
||||
});
|
||||
if (peers.length) {
|
||||
hint = `(与订单 ${peers.slice(0, 5).join('、')}${peers.length > 5 ? ' 等' : ''} 合单共用库存)`;
|
||||
if (!input.allowPartial || claimable <= 1e-9) {
|
||||
const label = input.itemName ? `${input.itemName}(${input.skuCode})` : input.skuCode;
|
||||
let hint = '';
|
||||
if (input.orderCode) {
|
||||
const peers = await listPurchaseMergePeerOrderCodes(client, {
|
||||
orderCode: input.orderCode,
|
||||
skuCode: input.skuCode,
|
||||
});
|
||||
if (peers.length) {
|
||||
hint = `(与订单 ${peers.slice(0, 5).join('、')}${peers.length > 5 ? ' 等' : ''} 合单共用库存)`;
|
||||
}
|
||||
}
|
||||
const short = Math.round((remaining - claimable) * 100) / 100;
|
||||
const stage =
|
||||
operationType === 'delivery_loading_out' ? 'depart' : 'picking';
|
||||
await notifyInventoryShortage({
|
||||
orderCode: input.orderCode,
|
||||
branchCode: input.branchCode,
|
||||
skuCode: input.skuCode,
|
||||
itemName: input.itemName,
|
||||
requiredQty: remaining,
|
||||
availableQty: claimable,
|
||||
shortQty: short,
|
||||
hint: hint || null,
|
||||
stage,
|
||||
});
|
||||
throw businessError(
|
||||
`${label} 库存不足,缺少 ${short}(扣除他单预留后可用 ${claimable})${hint}`
|
||||
);
|
||||
}
|
||||
const short = Math.round((remaining - claimable) * 100) / 100;
|
||||
const stage =
|
||||
operationType === 'delivery_loading_out' ? 'depart' : 'picking';
|
||||
await notifyInventoryShortage({
|
||||
orderCode: input.orderCode,
|
||||
branchCode: input.branchCode,
|
||||
skuCode: input.skuCode,
|
||||
itemName: input.itemName,
|
||||
requiredQty: remaining,
|
||||
availableQty: claimable,
|
||||
shortQty: short,
|
||||
hint: hint || null,
|
||||
stage,
|
||||
});
|
||||
throw businessError(
|
||||
`${label} 库存不足,缺少 ${short}(扣除他单预留后可用 ${claimable})${hint}`
|
||||
);
|
||||
// 软扣:可用量>0 时继续按可用量扣,尾差由下方 remaining 告警并由调用方记 softSkipped。
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,6 +458,10 @@ export async function deductInventoryForOrderDeparture(
|
||||
* `delivery_loading_restore` 这一历史流水类型的展示文案保留,老数据仍可读。
|
||||
*/
|
||||
operationType?: 'picking_out' | 'delivery_loading_out' | 'retail_out';
|
||||
/** 30 待备货直接发车:不产生库存/出库流水(Q1 用户裁决)。 */
|
||||
noInventory?: boolean;
|
||||
/** 45 无入库直接发车:没有实拣/实收时按计划 required_qty 扣库。 */
|
||||
fallbackToRequiredQty?: boolean;
|
||||
}
|
||||
): Promise<{
|
||||
deducted: boolean;
|
||||
@@ -463,12 +472,17 @@ export async function deductInventoryForOrderDeparture(
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return { deducted: false, skipped: true, reason: 'missing_order' };
|
||||
const softInventory = options?.softInventory === true;
|
||||
if (options?.noInventory === true) {
|
||||
return { deducted: false, skipped: true, reason: 'no_inventory_30' };
|
||||
}
|
||||
|
||||
const external = options?.client;
|
||||
const ownsTxn = !external;
|
||||
const client = external || (await pool.connect());
|
||||
try {
|
||||
if (ownsTxn) await client.query('BEGIN');
|
||||
// 同一订单出库串行化:并发发车/分拣/结案只能有一个事务产生流水,避免重复日志。
|
||||
await client.query(`SELECT pg_advisory_xact_lock(hashtext('inventory_outbound:' || $1))`, [code]);
|
||||
|
||||
/**
|
||||
* ⚠️ **必须先锁订单行(`FOR UPDATE`)再查幂等流水**(2026-10-13 对抗式复核)。
|
||||
@@ -489,6 +503,21 @@ export async function deductInventoryForOrderDeparture(
|
||||
}
|
||||
const branchCode = order.branch_code ? String(order.branch_code) : null;
|
||||
|
||||
// 作废任务:没有 active 配送任务时不得再产生出库流水/扣库存。
|
||||
const voidedOnly = await client.query(
|
||||
`SELECT 1 FROM delivery_tasks
|
||||
WHERE order_code = $1 AND voided_at IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM delivery_tasks act
|
||||
WHERE act.order_code = delivery_tasks.order_code AND act.voided_at IS NULL
|
||||
)
|
||||
LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
if (voidedOnly.rowCount) {
|
||||
return { deducted: false, skipped: true, reason: 'voided_delivery_task' };
|
||||
}
|
||||
|
||||
/**
|
||||
* **逐 SKU 幂等**(2026-10-14 审计 P0-3):先取"本单已扣过的 SKU",
|
||||
* 后面只扣**还没扣过**的行。整单守卫已废弃 —— 它会把"分拣时库存不足被软扣跳过"的 SKU 永久漏掉。
|
||||
@@ -589,7 +618,8 @@ export async function deductInventoryForOrderDeparture(
|
||||
row.unit,
|
||||
row.picked_qty,
|
||||
row.required_qty
|
||||
) || 0;
|
||||
) ||
|
||||
(options?.fallbackToRequiredQty ? Number(row.required_qty) || 0 : 0);
|
||||
if (qty <= 0) continue;
|
||||
|
||||
const itemKey = trimSku(row.order_item_id) || String(row.id);
|
||||
@@ -688,8 +718,10 @@ export async function deductInventoryForOrderDeparture(
|
||||
? `分拣出库 ${pickCode}`
|
||||
: `配送核货出库 ${options?.taskCode || pickCode}`,
|
||||
batchPlan: planById.get(String(row.id)) || undefined,
|
||||
allowPartial: softInventory,
|
||||
},
|
||||
(batch, deductedQty) => {
|
||||
deductedAny = true;
|
||||
departDetail.push({
|
||||
sku_code: row.sku || null,
|
||||
sku_name: row.item_name ? String(row.item_name) : null,
|
||||
@@ -1397,6 +1429,10 @@ export async function ensureOrderInventorySettledOnComplete(
|
||||
softInventory?: boolean;
|
||||
/** 默认 `delivery_loading_out`(发车/结案口径);分拣完毕即出库传 `picking_out`(见上) */
|
||||
operationType?: 'picking_out' | 'delivery_loading_out' | 'retail_out';
|
||||
/** 30 待备货直接发车:不产生库存/出库流水(Q1 用户裁决)。 */
|
||||
noInventory?: boolean;
|
||||
/** 45 无入库直接发车:没有实拣/实收时按计划 required_qty 扣库。 */
|
||||
fallbackToRequiredQty?: boolean;
|
||||
}
|
||||
): Promise<{
|
||||
deducted: boolean;
|
||||
|
||||
@@ -401,6 +401,31 @@ export async function recordImportedPrepItems(params: {
|
||||
);
|
||||
written += 1;
|
||||
}
|
||||
// 主系统导入的待取货单:ledger 在 early 建配送之后才写入,这里按最终 bool_and 清理残留未开始任务。
|
||||
try {
|
||||
if (await isOrderFullySkipInbound({ branchCode: params.branchCode, ourOrderCode: params.ourOrderCode })) {
|
||||
await pool.query(
|
||||
`DELETE FROM delivery_tasks
|
||||
WHERE order_code = $1
|
||||
AND COALESCE(task_status, 10) < 30
|
||||
AND loading_completed_at IS NULL
|
||||
AND start_time IS NULL`,
|
||||
[params.ourOrderCode]
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[main-system-import] 待取货残留配送任务清理失败', params.ourOrderCode, error);
|
||||
}
|
||||
/**
|
||||
* 待取货/普通导入单都必须有分拣单:early 建单是 best-effort,ledger 写入是
|
||||
* “主系统事实已落库”的可靠时点,这里再幂等补一次;零售/独立进货由 createPickingTask 守卫跳过。
|
||||
*/
|
||||
try {
|
||||
const { ensurePickingTaskOnOrderSubmit } = await import('./pickingService');
|
||||
await ensurePickingTaskOnOrderSubmit(params.ourOrderCode, params.branchCode);
|
||||
} catch (error) {
|
||||
console.warn('[main-system-import] 补建导入单分拣任务失败', params.ourOrderCode, error);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { pool } from '../db';
|
||||
import { orderVisibleToDeliverySql } from './supplierSkipInbound';
|
||||
import { orderVisibleToDeliveryManagementSql } from './supplierSkipInbound';
|
||||
import { salesVisibleOrderSql } from './independentInbound';
|
||||
import { nonRetailOrderSql } from './retailOrder';
|
||||
import { nonSelfPickupOrderSql } from './selfPickup';
|
||||
@@ -176,7 +176,15 @@ async function countDelivery(ctx: TenantContext, branchCode: string, scope: NavB
|
||||
let personFilter = '';
|
||||
if (personCode) {
|
||||
params.push(personCode);
|
||||
personFilter = `AND dt.person_code = $${params.length}`;
|
||||
const personIdx = params.length;
|
||||
// 与小程序司机列表同口径:本人 + 同分公司未分配早期任务
|
||||
personFilter = `AND (
|
||||
dt.person_code = $${personIdx}
|
||||
OR (
|
||||
(dt.person_code IS NULL OR TRIM(dt.person_code) = '')
|
||||
AND (dt.branch_code = $1 OR dt.branch_code IS NULL)
|
||||
)
|
||||
)`;
|
||||
}
|
||||
const businessDay = `COALESCE(o.delivery_date::date, (o.created_at AT TIME ZONE 'Asia/Shanghai')::date)`;
|
||||
const dateFilter = scope === 'all' ? '' : `AND ${scopedDateFilter(scope, businessDay, days)}`;
|
||||
@@ -184,8 +192,8 @@ async function countDelivery(ctx: TenantContext, branchCode: string, scope: NavB
|
||||
const result = await pool.query(
|
||||
`SELECT COUNT(DISTINCT o.order_code)::int AS c
|
||||
FROM orders o
|
||||
LEFT JOIN delivery_tasks dt ON dt.order_code = o.order_code
|
||||
WHERE ${orderVisibleToDeliverySql('o')}
|
||||
INNER JOIN delivery_tasks dt ON dt.order_code = o.order_code AND dt.voided_at IS NULL
|
||||
WHERE ${orderVisibleToDeliveryManagementSql('o')}
|
||||
AND ${salesVisibleOrderSql('o')}
|
||||
AND ${nonRetailOrderSql('o')}
|
||||
AND ${nonSelfPickupOrderSql('o')}
|
||||
@@ -193,7 +201,7 @@ async function countDelivery(ctx: TenantContext, branchCode: string, scope: NavB
|
||||
AND COALESCE(o.order_status, 0) < 90
|
||||
AND o.branch_code = $1
|
||||
AND ${orderNotDeletedSql('o')}
|
||||
AND COALESCE(dt.task_status, 10) = 10
|
||||
AND COALESCE(dt.task_status, 10) < 30
|
||||
AND (
|
||||
CASE
|
||||
WHEN dt.task_code IS NULL
|
||||
|
||||
@@ -26,7 +26,8 @@ import {
|
||||
type ReprocessAllocationOptions,
|
||||
} from './orderAllocationService';
|
||||
import { withAllocationSlot } from './allocationConcurrency';
|
||||
import { deleteUnworkedPickingRowsForItems } from './pickingService';
|
||||
import { deleteUnworkedPickingRowsForItems, syncOpenPickingItemsForOrder } from './pickingService';
|
||||
import { syncDeliveryTaskForOrder } from './orderWorkflowFulfillmentService';
|
||||
import { markPrepDisposition } from './mainSystemPrepLedger';
|
||||
import {
|
||||
countPreparationLinks,
|
||||
@@ -2244,6 +2245,18 @@ export async function syncOrderManageItems(params: {
|
||||
|
||||
await syncWarehouseProcessingDemandForOrderAfterCommit(orderCode);
|
||||
|
||||
// T2:改单提交后同步仍开放的分拣行与早期配送单(不重建任务,不占发车核货链路)。
|
||||
try {
|
||||
await syncOpenPickingItemsForOrder(orderCode, order.branch_code || null);
|
||||
} catch (err) {
|
||||
console.error('[orderManageItems] 同步分拣行失败(不影响改单)', orderCode, err);
|
||||
}
|
||||
try {
|
||||
await syncDeliveryTaskForOrder(orderCode, order.branch_code || null);
|
||||
} catch (err) {
|
||||
console.error('[orderManageItems] 同步配送单失败(不影响改单)', orderCode, err);
|
||||
}
|
||||
|
||||
// 厂商备货行「分配即供货完成」:改单走外部事务(分配内后置钩子不执行),提交后补一次
|
||||
//(建待验入库、回写订单行成本、免入库/直送结算桶、推进订单)。幂等,失败不影响改单。
|
||||
try {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { pool } from '../db';
|
||||
import { fireAndForgetBatchOriginReport } from './batchOriginReportService';
|
||||
import { writeAuditLog } from './auditService';
|
||||
import { isRetailOrder } from './retailOrder';
|
||||
import { hasUnresolvedFailedInspection } from './inspectionRejectFulfillmentService';
|
||||
import { isPickingWorkflowEnabled } from './pickingConfigService';
|
||||
import { isDirectToDeliveryEnabled } from './directToDeliveryConfigService';
|
||||
import { resolvePrimaryDeliveryPersonForCustomer } from './customerDeliveryBindingService';
|
||||
import { isOnlineAndOnShift } from './deliveryPresenceService';
|
||||
import { notifyDeliveryTaskCreated } from './mainlineEventNotificationService';
|
||||
@@ -220,6 +222,7 @@ export async function tryAdvanceOrderToDelivery(orderCode: string): Promise<{ ad
|
||||
// 用 delivery_loading_out 会被它误加回来 ⇒ 后续发车又被幂等守卫挡住 ⇒ 净漏扣(见函数注释)
|
||||
operationType: 'picking_out',
|
||||
});
|
||||
// 软扣失败不拦进入待配送;softSkipped 逐行告警,稍后自动补扣。
|
||||
/**
|
||||
* **事件驱动报告推送**(2026-10-24 核查项 1):分拣完成=出库=扣批次,
|
||||
* 这一刻才知道这单实际消耗哪些批次(报告候选源②)⇒ 入队这一单,别等每日全量兜底。
|
||||
@@ -361,10 +364,109 @@ export async function isSelfPickupOrder(
|
||||
return (result.rows[0] as { self_pickup?: unknown } | undefined)?.self_pickup === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 订单保存后同步早期配送单:
|
||||
* - 需要配送:已有 active 行不动;只有 voided 行且未开始时复用原行清 void,绝不 insert 第二行。
|
||||
* - 不再需要配送(全直送/极简流转/自提/独立进货/散客/整单待取货):未开始的 active 行 void;
|
||||
* 已开始核货/发车的行保留,避免现场数据丢失。
|
||||
*/
|
||||
export async function syncDeliveryTaskForOrder(
|
||||
orderCode: string,
|
||||
branchCode: string | null
|
||||
): Promise<void> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return;
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const order = orderResult.rows[0];
|
||||
if (!order || order.deleted_at) return;
|
||||
const branch = branchCode || (order.branch_code ? String(order.branch_code) : null);
|
||||
const taskResult = await pool.query(
|
||||
`SELECT task_code, task_status, voided_at, loading_completed_at, start_time
|
||||
FROM delivery_tasks WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const task = taskResult.rows[0];
|
||||
const status = Number(task?.task_status ?? 10) || 10;
|
||||
const hasStarted = Boolean(
|
||||
task && (status >= 20 || task.loading_completed_at || task.start_time)
|
||||
);
|
||||
|
||||
const noDelivery =
|
||||
(await isRetailOrder(code, pool)) ||
|
||||
(await isOrderOnlyDirectDelivery(code)) ||
|
||||
(await isOrderIndependentInbound(code, pool)) ||
|
||||
(await isSelfPickupOrder(code)) ||
|
||||
(await isDirectToDeliveryEnabled(branch).catch(() => false)) ||
|
||||
(await isOrderFullySkipInbound({
|
||||
branchCode: branch || '',
|
||||
ourOrderCode: code,
|
||||
db: pool,
|
||||
}));
|
||||
|
||||
if (noDelivery) {
|
||||
if (task && !task.voided_at && !hasStarted) {
|
||||
await pool.query(
|
||||
`UPDATE delivery_tasks
|
||||
SET voided_at = NOW(), void_reason = 'not_requires_delivery'
|
||||
WHERE order_code = $1 AND voided_at IS NULL`,
|
||||
[code]
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (task?.voided_at) {
|
||||
// 全唯一索引:不能 insert 第二行;未开始才复活原行
|
||||
if (!hasStarted) {
|
||||
await pool.query(
|
||||
`UPDATE delivery_tasks
|
||||
SET voided_at = NULL, void_reason = NULL
|
||||
WHERE order_code = $1 AND voided_at IS NOT NULL`,
|
||||
[code]
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (task?.task_code) return;
|
||||
|
||||
if (Number(order.order_status) >= 50) {
|
||||
await ensureDeliveryTaskForOrder(code, branch);
|
||||
} else {
|
||||
await ensureEarlyDeliveryTaskForOrder(code, branch);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下单即建配送单(早期任务):不派配送员、不发通知;到 50 后由既有流程接管。
|
||||
* 复用 `ensureDeliveryTaskForOrder` 的散客/全直送/独立进货/自提/待取货五道守卫。
|
||||
*/
|
||||
export async function ensureEarlyDeliveryTaskForOrder(
|
||||
orderCode: string,
|
||||
branchCode: string | null
|
||||
): Promise<string> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return '';
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const order = orderResult.rows[0];
|
||||
if (!order || order.deleted_at) return '';
|
||||
if (Number(order.order_status) >= 50) return '';
|
||||
const branch = branchCode || (order.branch_code ? String(order.branch_code) : null);
|
||||
if (await isDirectToDeliveryEnabled(branch).catch(() => false)) return '';
|
||||
if (await isOrderOnlyDirectDelivery(code)) return '';
|
||||
return ensureDeliveryTaskForOrder(code, branch, undefined, { early: true });
|
||||
}
|
||||
|
||||
export async function ensureDeliveryTaskForOrder(
|
||||
orderCode: string,
|
||||
branchCode: string | null,
|
||||
existingClient?: PoolClient
|
||||
existingClient?: PoolClient,
|
||||
options?: { early?: boolean }
|
||||
): Promise<string> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) throw Object.assign(new Error('缺少订单号'), { status: 400 });
|
||||
@@ -454,14 +556,14 @@ export async function ensureDeliveryTaskForOrder(
|
||||
}
|
||||
|
||||
const existing = await client.query(
|
||||
`SELECT task_code, person_code FROM delivery_tasks WHERE order_code = $1 LIMIT 1`,
|
||||
`SELECT task_code, person_code FROM delivery_tasks WHERE order_code = $1 AND voided_at IS NULL LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
if (existing.rows[0]?.task_code) {
|
||||
const taskCode = String(existing.rows[0].task_code);
|
||||
const hadPerson = Boolean(String(existing.rows[0].person_code || '').trim());
|
||||
if (manageTransaction) await client.query('COMMIT');
|
||||
if (!hadPerson) {
|
||||
if (!options?.early && !hadPerson) {
|
||||
const assigned = await assignDeliveryPersonIfNeeded(taskCode, code, branchCode);
|
||||
if (assigned) {
|
||||
notifyDeliveryTaskCreated({
|
||||
@@ -474,7 +576,31 @@ export async function ensureDeliveryTaskForOrder(
|
||||
return taskCode;
|
||||
}
|
||||
|
||||
const personCodeRaw = await resolveDeliveryPersonForOrder(code, branchCode, client);
|
||||
// 全唯一索引:只有 voided 行时不能 insert;未开始的复用原行复活(T2/AC-11)。
|
||||
const voided = await client.query(
|
||||
`SELECT task_code, task_status, voided_at, loading_completed_at, start_time
|
||||
FROM delivery_tasks WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
if (voided.rows[0]?.task_code) {
|
||||
const row = voided.rows[0];
|
||||
const started = Boolean(
|
||||
(Number(row.task_status) || 10) >= 20 || row.loading_completed_at || row.start_time
|
||||
);
|
||||
if (row.voided_at && !started) {
|
||||
await client.query(
|
||||
`UPDATE delivery_tasks SET voided_at = NULL, void_reason = NULL
|
||||
WHERE order_code = $1 AND voided_at IS NOT NULL`,
|
||||
[code]
|
||||
);
|
||||
if (manageTransaction) await client.query('COMMIT');
|
||||
return String(row.task_code);
|
||||
}
|
||||
if (manageTransaction) await client.query('COMMIT');
|
||||
return '';
|
||||
}
|
||||
|
||||
const personCodeRaw = options?.early ? null : await resolveDeliveryPersonForOrder(code, branchCode, client);
|
||||
let personCode: string | null = null;
|
||||
let deliveryId: string | null = null;
|
||||
if (personCodeRaw) {
|
||||
@@ -499,20 +625,23 @@ export async function ensureDeliveryTaskForOrder(
|
||||
// 唯一索引冲突:并发已插入,回读
|
||||
if (error?.code === '23505') {
|
||||
const again = await client.query(
|
||||
`SELECT task_code FROM delivery_tasks WHERE order_code = $1 LIMIT 1`,
|
||||
`SELECT task_code FROM delivery_tasks WHERE order_code = $1 AND voided_at IS NULL LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
if (manageTransaction) await client.query('COMMIT');
|
||||
if (again.rows[0]?.task_code) return String(again.rows[0].task_code);
|
||||
return '';
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (manageTransaction) await client.query('COMMIT');
|
||||
notifyDeliveryTaskCreated({
|
||||
taskCode,
|
||||
orderCode: code,
|
||||
branchCode,
|
||||
}).catch((error) => console.error('[mainline-notify] 配送任务创建通知失败:', error));
|
||||
if (!options?.early) {
|
||||
notifyDeliveryTaskCreated({
|
||||
taskCode,
|
||||
orderCode: code,
|
||||
branchCode,
|
||||
}).catch((error) => console.error('[mainline-notify] 配送任务创建通知失败:', error));
|
||||
}
|
||||
return taskCode;
|
||||
} catch (error) {
|
||||
if (manageTransaction) await client.query('ROLLBACK').catch(() => undefined);
|
||||
@@ -591,17 +720,34 @@ export async function tryAdvanceOrderToDelivering(
|
||||
): Promise<{ advanced: boolean; message: string }> {
|
||||
await assertOrderActiveForFulfillment(orderCode);
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status, branch_code, COALESCE(self_pickup, false) AS self_pickup FROM orders WHERE order_code = $1`,
|
||||
`SELECT order_status, branch_code, COALESCE(self_pickup, false) AS self_pickup,
|
||||
auto_advanced_from_status,
|
||||
EXISTS (
|
||||
SELECT 1 FROM order_items oi
|
||||
WHERE oi.order_code = orders.order_code
|
||||
AND COALESCE(oi.stock_cover_qty, 0) > 0
|
||||
) AS has_stock_cover
|
||||
FROM orders WHERE order_code = $1`,
|
||||
[orderCode]
|
||||
);
|
||||
const status = Number(orderResult.rows[0]?.order_status);
|
||||
const branchCodeForWriteback = (orderResult.rows[0]?.branch_code as string | null) ?? null;
|
||||
|
||||
let claimedUnassigned = false;
|
||||
let closedPickCodes: string[] = [];
|
||||
if (status >= 60) {
|
||||
return { advanced: true, message: '订单已在配送中或已完成' };
|
||||
}
|
||||
if (status < 50) {
|
||||
return { advanced: false, message: `订单尚未进入待配送(当前 ${status})` };
|
||||
// 早期任务:核货已完成即可发车,先把订单补到 50,再走既有 50→60。
|
||||
const loadingReady = await pool.query(
|
||||
`SELECT 1 FROM delivery_tasks
|
||||
WHERE order_code = $1 AND voided_at IS NULL AND COALESCE(task_status, 10) < 30 AND loading_completed_at IS NOT NULL
|
||||
LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!loadingReady.rowCount) {
|
||||
return { advanced: false, message: `订单尚未进入待配送(当前 ${status}),请先完成核货` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -611,6 +757,36 @@ export async function tryAdvanceOrderToDelivering(
|
||||
* `orderStatusReconcileService` 会周期性调本函数,若拦在前面,已 60/90 的自提单会从
|
||||
* `advanced: true` 变成抛错。只有"确实要从 50 发车"这一步才拦。
|
||||
*/
|
||||
// ≥50 且只有 voided 任务:先按需要配送规则复活原任务,避免管理端可见却无任务可操作。
|
||||
if (status >= 50) {
|
||||
const activeTask = await pool.query(
|
||||
`SELECT 1 FROM delivery_tasks WHERE order_code = $1 AND voided_at IS NULL LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!activeTask.rowCount) {
|
||||
await syncDeliveryTaskForOrder(orderCode, branchCodeForWriteback).catch((error) => {
|
||||
console.warn('[delivery] 复活 voided 早期任务失败', orderCode, error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 提前配送 = 提前分拣完成:直接发车前把 open 分拣任务按计划量完成(不阻断发车)。
|
||||
if (status < 50) {
|
||||
try {
|
||||
const { completeOrderPickingForDirectDelivery } = await import('./pickingService');
|
||||
await completeOrderPickingForDirectDelivery(orderCode, branchCodeForWriteback, options?.operatorId || null);
|
||||
} catch (error) {
|
||||
console.warn('[delivery] 直接配送补分拣完成失败(继续发车)', orderCode, error);
|
||||
}
|
||||
}
|
||||
|
||||
const hasStockCover =
|
||||
orderResult.rows[0]?.has_stock_cover === true || orderResult.rows[0]?.has_stock_cover === 't';
|
||||
// 有实际库存抵扣/在仓依据时不能 skip:30/40 也要按计划/实收 FIFO 扣一次。
|
||||
const skipDepartureInventory =
|
||||
!hasStockCover &&
|
||||
(status < 40 || [30, 40].includes(Number(orderResult.rows[0]?.auto_advanced_from_status)));
|
||||
|
||||
if ((orderResult.rows[0] as { self_pickup?: unknown } | undefined)?.self_pickup === true) {
|
||||
throw Object.assign(
|
||||
new Error('该单为客户自提(不走配送):请在订单列表点「确认取货」结案'),
|
||||
@@ -619,11 +795,68 @@ export async function tryAdvanceOrderToDelivering(
|
||||
}
|
||||
|
||||
try {
|
||||
const advanceResult = await withOrderLock(orderCode, 50, async (client) => {
|
||||
// AC-17:补 50 与 50→60 放进同一把订单锁/同一事务,失败自动回滚。
|
||||
const advanceResult = await withOrderLock(
|
||||
orderCode,
|
||||
status < 50 ? [status, 50] : 50,
|
||||
async (client) => {
|
||||
if (status < 50) {
|
||||
const current = await client.query(
|
||||
`SELECT order_status FROM orders WHERE order_code = $1 FOR UPDATE`,
|
||||
[orderCode]
|
||||
);
|
||||
if (Number(current.rows[0]?.order_status) < 50) {
|
||||
const bumped = await client.query(
|
||||
`UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status < 50 RETURNING order_code`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!bumped.rowCount) {
|
||||
throw Object.assign(new Error('订单状态已变更'), {
|
||||
status: 409,
|
||||
code: 'cannot_start_delivery',
|
||||
soft: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const taskCode = options?.taskCode ? String(options.taskCode).trim() : '';
|
||||
const personCode = options?.personCode ? String(options.personCode).trim() : '';
|
||||
|
||||
if (taskCode) {
|
||||
const activeTask = await client.query(
|
||||
`SELECT person_code, branch_code, voided_at
|
||||
FROM delivery_tasks WHERE task_code = $1 LIMIT 1`,
|
||||
[taskCode]
|
||||
);
|
||||
if (!activeTask.rowCount || activeTask.rows[0]?.voided_at) {
|
||||
throw Object.assign(new Error('配送任务已作废,不能发车'), {
|
||||
status: 400,
|
||||
code: 'voided_delivery_task',
|
||||
soft: true,
|
||||
});
|
||||
}
|
||||
const taskPerson = String(activeTask.rows[0]?.person_code || '').trim();
|
||||
if (personCode && taskPerson && taskPerson !== personCode) {
|
||||
throw Object.assign(new Error('无权操作该配送任务'), {
|
||||
status: 403,
|
||||
code: 'forbidden',
|
||||
});
|
||||
}
|
||||
if (personCode && !taskPerson) {
|
||||
const driver = await client.query(
|
||||
`SELECT branch_code FROM delivery_persons WHERE person_code = $1 LIMIT 1`,
|
||||
[personCode]
|
||||
);
|
||||
const driverBranch = String(driver.rows[0]?.branch_code || '').trim();
|
||||
const taskBranch = String(activeTask.rows[0]?.branch_code || '').trim();
|
||||
if (driverBranch && taskBranch && driverBranch !== taskBranch) {
|
||||
throw Object.assign(new Error('无权操作其他分公司的配送任务'), {
|
||||
status: 403,
|
||||
code: 'forbidden',
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!taskPerson && personCode) claimedUnassigned = true;
|
||||
await client.query(
|
||||
`UPDATE delivery_tasks
|
||||
SET task_status = GREATEST(task_status, 20),
|
||||
@@ -635,7 +868,7 @@ export async function tryAdvanceOrderToDelivering(
|
||||
} else {
|
||||
const started = await client.query(
|
||||
`SELECT 1 FROM delivery_tasks
|
||||
WHERE order_code = $1 AND task_status >= 20 AND start_time IS NOT NULL
|
||||
WHERE order_code = $1 AND voided_at IS NULL AND task_status >= 20 AND start_time IS NOT NULL
|
||||
LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
@@ -650,6 +883,7 @@ export async function tryAdvanceOrderToDelivering(
|
||||
const assigned = await client.query(
|
||||
`SELECT task_code, person_code FROM delivery_tasks
|
||||
WHERE order_code = $1
|
||||
AND voided_at IS NULL
|
||||
AND NULLIF(TRIM(person_code), '') IS NOT NULL
|
||||
AND task_status < 30
|
||||
ORDER BY created_at DESC
|
||||
@@ -691,6 +925,11 @@ export async function tryAdvanceOrderToDelivering(
|
||||
taskCode: taskCode || null,
|
||||
operatorId: options?.operatorId || null,
|
||||
softInventory: true,
|
||||
// 30/40 无入库跳过;45 无入库仍按计划量 FIFO 扣一次。
|
||||
noInventory: skipDepartureInventory,
|
||||
fallbackToRequiredQty:
|
||||
!skipDepartureInventory &&
|
||||
(hasStockCover || Number(orderResult.rows[0]?.auto_advanced_from_status) === 45),
|
||||
});
|
||||
} catch (deductErr: any) {
|
||||
// 兜底:任何库存类错误都不挡发车
|
||||
@@ -700,6 +939,19 @@ export async function tryAdvanceOrderToDelivering(
|
||||
throw deductErr;
|
||||
}
|
||||
}
|
||||
// 30 待备货直接发车:关闭该单仍开放的分拣任务,避免永久待分拣。
|
||||
if (status < 40 || Number(orderResult.rows[0]?.auto_advanced_from_status) === 30) {
|
||||
const closed = await client.query(
|
||||
`UPDATE picking_tasks
|
||||
SET pick_status = 30,
|
||||
reviewed_at = COALESCE(reviewed_at, NOW())
|
||||
WHERE order_code = $1 AND COALESCE(pick_status, 10) < 30
|
||||
RETURNING pick_code`,
|
||||
[orderCode]
|
||||
);
|
||||
closedPickCodes = closed.rows.map((row) => String(row.pick_code || '')).filter(Boolean);
|
||||
}
|
||||
|
||||
// 发车只拦「无对应品类/核货明细」;库存不足不拦(设计:20260807-depart-no-inventory-gate)
|
||||
if (deduct.reason === 'no_loading_items') {
|
||||
throw Object.assign(
|
||||
@@ -720,11 +972,70 @@ export async function tryAdvanceOrderToDelivering(
|
||||
});
|
||||
}
|
||||
return { advanced: true, message: '配送已开始' };
|
||||
});
|
||||
}
|
||||
);
|
||||
// 发车成功(事务已提交)→ 非阻塞回写主系统「备货完成」。
|
||||
// 2026-10-08 设计文档 §3.5:这是主系统"已发车不能点击退货"拦截的依据,也是它进入待验入库的前提。
|
||||
// 刻意不 await、不抛错:**回写失败绝不影响发车结果**(失败由台账记账 + 定时兜底重试)。
|
||||
if (advanceResult.advanced) {
|
||||
// AC-16:早期任务发车补状态审计(before → 50 → 60 的 actor/taskCode 痕迹)。
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorId: options?.operatorId || null,
|
||||
operationType: 'delivery_early_status_advance',
|
||||
targetTable: 'orders',
|
||||
targetId: orderCode,
|
||||
oldValue: { order_status: status },
|
||||
newValue: {
|
||||
order_status: 60,
|
||||
task_code: options?.taskCode || null,
|
||||
via: 'early_delivery_loading',
|
||||
note: '30/40/45 → 50 → 60(核货已完成)',
|
||||
},
|
||||
branchCode: branchCodeForWriteback,
|
||||
actionCategory: 'delivery',
|
||||
});
|
||||
} catch (auditError) {
|
||||
console.warn('[delivery] 早期发车状态审计失败', orderCode, auditError);
|
||||
}
|
||||
if (closedPickCodes.length) {
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorId: options?.operatorId || null,
|
||||
operationType: 'picking_skipped_on_30_departure',
|
||||
targetTable: 'picking_tasks',
|
||||
targetId: closedPickCodes[0],
|
||||
newValue: {
|
||||
order_code: orderCode,
|
||||
closed_pick_codes: closedPickCodes,
|
||||
note: '30 待备货直接配送:关闭开放分拣任务,不入库/不扣库存',
|
||||
},
|
||||
branchCode: branchCodeForWriteback,
|
||||
actionCategory: 'delivery',
|
||||
});
|
||||
} catch (auditError) {
|
||||
console.warn('[delivery] 30 发车关闭分拣任务审计失败', orderCode, auditError);
|
||||
}
|
||||
}
|
||||
if (claimedUnassigned) {
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorId: options?.operatorId || null,
|
||||
operationType: 'delivery_task_claim',
|
||||
targetTable: 'delivery_tasks',
|
||||
targetId: options?.taskCode || undefined,
|
||||
newValue: {
|
||||
order_code: orderCode,
|
||||
person_code: options?.personCode || null,
|
||||
note: '同分公司未分配早期任务由操作人认领并发车',
|
||||
},
|
||||
branchCode: branchCodeForWriteback,
|
||||
actionCategory: 'delivery',
|
||||
});
|
||||
} catch (auditError) {
|
||||
console.warn('[delivery] 未分配任务认领审计失败', orderCode, auditError);
|
||||
}
|
||||
}
|
||||
enqueueMainSystemWritebackForDeliveredOrder({
|
||||
branchCode: branchCodeForWriteback,
|
||||
orderCode,
|
||||
@@ -824,15 +1135,64 @@ async function finalizeOrderFulfillmentCore(
|
||||
console.error(`[costBackfill] 结案兜底失败(不阻断结案): order=${orderCode}`, err);
|
||||
}
|
||||
|
||||
// 结案前强制出库+消费预留,避免「单已完成、库存仍被幽灵占用」
|
||||
// 历史结案白名单:货已送达,跳过 FIFO 扣库,但仍释放本单预留占用
|
||||
// 结案库存口径:真正扣库在分拣出库/发车;未入库直接配送、30/40 无库存路径不在这里补扣,
|
||||
// marker45 发车已扣则跳过,未扣则软扣一次;任何缺库都不能阻断结案置 90。
|
||||
const settleCtx = await db.query(
|
||||
`SELECT COALESCE(o.auto_advanced_from_status, 0) AS marker,
|
||||
EXISTS (
|
||||
SELECT 1 FROM inspections i
|
||||
WHERE i.order_code = o.order_code
|
||||
AND (COALESCE(i.actual_qty, 0) > 0 OR i.inbound_batch_no IS NOT NULL)
|
||||
) AS has_inbound,
|
||||
EXISTS (
|
||||
SELECT 1 FROM inventory_logs il
|
||||
WHERE il.related_order_code = o.order_code
|
||||
AND il.operation_type IN ('picking_out', 'delivery_loading_out', 'retail_out')
|
||||
) AS has_outbound,
|
||||
EXISTS (
|
||||
SELECT 1 FROM order_items oi
|
||||
WHERE oi.order_code = o.order_code
|
||||
AND COALESCE(oi.stock_cover_qty, 0) > 0
|
||||
) AS has_stock_cover
|
||||
FROM orders o WHERE o.order_code = $1 LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
const settleRow = settleCtx.rows[0] || {};
|
||||
const marker = Number(settleRow.marker) || 0;
|
||||
const hasInbound = settleRow.has_inbound === true || settleRow.has_inbound === 't';
|
||||
const hasOutbound = settleRow.has_outbound === true || settleRow.has_outbound === 't';
|
||||
const hasStockCover = settleRow.has_stock_cover === true || settleRow.has_stock_cover === 't';
|
||||
let skipFinalInventory = false;
|
||||
let fallbackToRequiredQty = false;
|
||||
if ((marker === 30 || marker === 40) && !hasStockCover) skipFinalInventory = true;
|
||||
else if (marker === 45) {
|
||||
if (hasOutbound) skipFinalInventory = true;
|
||||
else fallbackToRequiredQty = true;
|
||||
} else if (!hasInbound && !hasStockCover) {
|
||||
// 普通单无入库直接配送:货未入仓,结案不补扣、不拦。
|
||||
skipFinalInventory = true;
|
||||
}
|
||||
if (!options?.skipInventorySettle) {
|
||||
await ensureOrderInventorySettledOnComplete(orderCode, {
|
||||
client,
|
||||
softInventory: options?.softInventorySettle === true,
|
||||
});
|
||||
if (skipFinalInventory) {
|
||||
// 结束配送不能被库存/预留清理失败拦住:缺口留日志,订单照常置 90。
|
||||
await consumeReservationsForOrder(client, orderCode).catch((error) => {
|
||||
console.warn('[delivery] 结案释放库存预留失败(不阻断结案)', orderCode, error);
|
||||
});
|
||||
} else {
|
||||
await ensureOrderInventorySettledOnComplete(orderCode, {
|
||||
client,
|
||||
// 45 无入库/无实收时软扣;其它无入库路径不会到这里;正常有入库保持原硬/软口径。
|
||||
softInventory: options?.softInventorySettle === true || !hasInbound || marker === 45 || hasStockCover,
|
||||
fallbackToRequiredQty: fallbackToRequiredQty || hasStockCover,
|
||||
}).catch((error) => {
|
||||
// 结束配送不能因库存不足失败;缺口留日志/后续对账,订单仍置 90。
|
||||
console.warn('[delivery] 结案库存结算失败(不阻断结案)', orderCode, error);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await consumeReservationsForOrder(client, orderCode);
|
||||
await consumeReservationsForOrder(client, orderCode).catch((error) => {
|
||||
console.warn('[delivery] 结案释放库存预留失败(不阻断结案)', orderCode, error);
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
@@ -874,6 +1234,14 @@ export async function finalizeOrderFulfillment(
|
||||
options?: { allowUnpriced?: boolean; skipInventorySettle?: boolean }
|
||||
): Promise<boolean> {
|
||||
if (!client) {
|
||||
// 补分拣必须早于 finalize 事务:分拣完成自身 BEGIN/COMMIT,复用请求级共享连接会
|
||||
// 提前提交 finalize 事务,随后 SAVEPOINT 报 25P01,出现任务30/库存已扣/订单60 半成功。
|
||||
try {
|
||||
const { completeOrderPickingForDirectDelivery } = await import('./pickingService');
|
||||
await completeOrderPickingForDirectDelivery(orderCode, null, null);
|
||||
} catch (error) {
|
||||
console.warn('[delivery] 结束配送补分拣完成失败(继续结束)', orderCode, error);
|
||||
}
|
||||
const done = await withOrderExclusiveTxn(orderCode, async (txnClient, status) => {
|
||||
if (status >= 90) return false;
|
||||
return finalizeOrderFulfillmentCore(orderCode, txnClient, options);
|
||||
|
||||
@@ -27,7 +27,8 @@ type Db = Pick<PoolClient, 'query'>;
|
||||
/** 按品类顺序 + 订单明细顺序生成拣货行序(便于仓内按路线/品类拣货) */
|
||||
export async function fetchSortedOrderItemsForPicking(
|
||||
orderCode: string,
|
||||
db: Db = pool
|
||||
db: Db = pool,
|
||||
options?: { includeExtraDish?: boolean }
|
||||
): Promise<PickingOrderItemRow[]> {
|
||||
const result = await db.query(
|
||||
`SELECT oi.id, oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.unit, oi.branch_code,
|
||||
@@ -52,7 +53,7 @@ export async function fetchSortedOrderItemsForPicking(
|
||||
) bz ON true
|
||||
WHERE oi.order_code = $1
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND COALESCE(oi.is_extra_dish, false) = false
|
||||
AND ${options?.includeExtraDish ? 'TRUE' : 'COALESCE(oi.is_extra_dish, false) = false'}
|
||||
AND NOT ${supplierSkipInboundExistsSql('oi.supplier_code')}
|
||||
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
|
||||
ORDER BY category_sort ASC, item_sort ASC, COALESCE(oi.item_name, oi.sku_code) ASC`,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { PoolClient } from 'pg';
|
||||
import { pool } from '../db';
|
||||
import { itemDisplayNameSql } from './itemDisplayNameSql';
|
||||
import { isRetailOrder } from './retailOrder';
|
||||
import { isOrderIndependentInbound } from './independentInbound';
|
||||
import { completeOrderWithoutDriverDelivery } from './orderWorkflowFulfillmentService';
|
||||
import { enqueueMainSystemWritebackForReadyOrder } from './mainSystemWriteback';
|
||||
import { config } from '../config';
|
||||
@@ -717,10 +718,19 @@ export async function createPickingTask(
|
||||
if (await isRetailOrder(orderCode, pool)) {
|
||||
return null as unknown as CreatePickingTaskResult;
|
||||
}
|
||||
/**
|
||||
* 独立进货只是补库存:全部入库后结案,不进分拣/配送。
|
||||
* 放在唯一建单入口,覆盖下单即建、到 45 补建、手动/定时补建所有路径。
|
||||
*/
|
||||
if (await isOrderIndependentInbound(orderCode, pool)) {
|
||||
return null as unknown as CreatePickingTaskResult;
|
||||
}
|
||||
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
// 同一订单的分拣任务创建串行化:并发下单/分配钩子/列表补建只能命中同一 open task。
|
||||
await client.query(`SELECT pg_advisory_xact_lock(hashtext('picking_task:' || $1))`, [orderCode]);
|
||||
|
||||
const orderResult = await client.query(
|
||||
`SELECT o.order_code, o.customer_code, o.branch_code, o.order_status, c.company_name
|
||||
@@ -813,6 +823,167 @@ export async function createPickingTask(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提前配送 = 提前分拣完成:直接发车/结束配送前,把该单所有 open 分拣任务按计划量完成。
|
||||
* 复用 confirmPickingComplete(扣库/幂等/审计都在原链路),不另写完成逻辑。
|
||||
*/
|
||||
export async function completeOrderPickingForDirectDelivery(
|
||||
orderCode: string,
|
||||
branchCode?: string | null,
|
||||
operatorId?: string | null
|
||||
): Promise<{ completed: boolean; pickCodes: string[] }> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return { completed: false, pickCodes: [] };
|
||||
const branch = branchCode || null;
|
||||
|
||||
let open = await pool.query(
|
||||
`SELECT pick_code FROM picking_tasks
|
||||
WHERE order_code = $1 AND COALESCE(pick_status, 10) < 30
|
||||
ORDER BY created_at ASC`,
|
||||
[code]
|
||||
);
|
||||
if (!open.rowCount) {
|
||||
const anyTask = await pool.query(`SELECT 1 FROM picking_tasks WHERE order_code = $1 LIMIT 1`, [code]);
|
||||
if (anyTask.rowCount) return { completed: false, pickCodes: [] };
|
||||
await ensurePickingTaskOnOrderSubmit(code, branch).catch((error) => {
|
||||
console.warn('[picking] 直接配送补建分拣任务失败', code, error);
|
||||
});
|
||||
open = await pool.query(
|
||||
`SELECT pick_code FROM picking_tasks
|
||||
WHERE order_code = $1 AND COALESCE(pick_status, 10) < 30
|
||||
ORDER BY created_at ASC`,
|
||||
[code]
|
||||
);
|
||||
}
|
||||
const pickCodes: string[] = [];
|
||||
for (const row of open.rows) {
|
||||
const pickCode = String(row.pick_code || '').trim();
|
||||
if (!pickCode) continue;
|
||||
const items = await pool.query(
|
||||
`SELECT id, required_qty, picked_qty, picked_weight, unit, review_status
|
||||
FROM picking_items WHERE pick_code = $1`,
|
||||
[pickCode]
|
||||
);
|
||||
const rows = items.rows
|
||||
.filter(
|
||||
(item) =>
|
||||
Number(item.review_status) < 20 ||
|
||||
resolvePickingSettlementQty(item.picked_qty, item.picked_weight, item.unit) <= 0
|
||||
)
|
||||
.map((item) => {
|
||||
const required = Number(item.required_qty) || 0;
|
||||
return {
|
||||
id: String(item.id),
|
||||
required_qty: required,
|
||||
picked_qty: isPickingWeightUnit(item.unit) ? 0 : required,
|
||||
picked_weight: isPickingWeightUnit(item.unit) ? required : 0,
|
||||
unit: item.unit ? String(item.unit) : null,
|
||||
diff_reason: '提前配送:按计划量完成分拣',
|
||||
};
|
||||
});
|
||||
if (rows.length) {
|
||||
await updatePickingItemProgress({ pickCode, rows });
|
||||
}
|
||||
await confirmPickingComplete({
|
||||
pickCode,
|
||||
reviewerId: operatorId || null,
|
||||
ctx: null,
|
||||
deferAdvance: true,
|
||||
});
|
||||
pickCodes.push(pickCode);
|
||||
}
|
||||
return { completed: pickCodes.length > 0, pickCodes };
|
||||
}
|
||||
|
||||
/**
|
||||
* 下单提交后立即建分拣单(仅启用分拣流程的分公司);无库存/需采购也建。
|
||||
* 失败不阻断下单,后续到 45 / 定时补建仍可兜底。
|
||||
* 注意:不引入「订单未到 45 禁止完成分拣」的闸(供应商二选一允许早期分拣)。
|
||||
*/
|
||||
/**
|
||||
* 改单/改供应商/自采/加菜后同步仍开放的分拣行(不重建任务、不建第二套)。
|
||||
* - 新增或恢复为可拣的行:补到现有 open 任务(pick_status<40)
|
||||
* - 订单行删除/退货/改成免入库或直送:删除**未动过**的拣货行
|
||||
* - 已有 picked_qty/picked_weight/loaded_qty/照片的行绝不动
|
||||
*/
|
||||
export async function syncOpenPickingItemsForOrder(
|
||||
orderCode: string,
|
||||
branchCode?: string | null
|
||||
): Promise<{ inserted: number; removed: number; pickCode: string | null }> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return { inserted: 0, removed: 0, pickCode: null };
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const order = orderResult.rows[0];
|
||||
if (!order || order.deleted_at) return { inserted: 0, removed: 0, pickCode: null };
|
||||
if (Number(order.order_status) >= 50) return { inserted: 0, removed: 0, pickCode: null };
|
||||
const branch = branchCode || (order.branch_code ? String(order.branch_code) : null);
|
||||
|
||||
const open = await pool.query(
|
||||
`SELECT pick_code FROM picking_tasks
|
||||
WHERE order_code = $1 AND pick_status < 40
|
||||
ORDER BY CASE WHEN COALESCE(scope_type, 'order') = 'order' THEN 0 ELSE 1 END,
|
||||
created_at ASC
|
||||
LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const pickCode = open.rows[0]?.pick_code ? String(open.rows[0].pick_code) : null;
|
||||
if (!pickCode) return { inserted: 0, removed: 0, pickCode: null };
|
||||
|
||||
// 删除真正失效且没有任何实物动作的行;有实拣/称重/核货/照片的行保守保留。
|
||||
const removedResult = await pool.query(
|
||||
`DELETE FROM picking_items pi
|
||||
WHERE pi.order_code = $1
|
||||
AND COALESCE(pi.picked_qty, 0) = 0
|
||||
AND COALESCE(pi.picked_weight, 0) = 0
|
||||
AND COALESCE(pi.loaded_qty, 0) = 0
|
||||
AND COALESCE(array_length(pi.loading_photos, 1), 0) = 0
|
||||
AND COALESCE(array_length(pi.outbound_photos, 1), 0) = 0
|
||||
AND pi.order_item_id IS NOT NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM order_items oi
|
||||
WHERE oi.id = pi.order_item_id
|
||||
AND oi.order_code = pi.order_code
|
||||
AND COALESCE(oi.is_returned, false) = false
|
||||
AND NOT ${supplierSkipInboundExistsSql('oi.supplier_code')}
|
||||
AND NOT ${skuDirectDeliveryAppliesSql('oi.sku_code', 'oi.order_code')}
|
||||
)`,
|
||||
[code]
|
||||
);
|
||||
|
||||
const activeItems = await fetchSortedOrderItemsForPicking(code, pool, { includeExtraDish: true });
|
||||
const missing = await filterUnpickedItems(activeItems, pool);
|
||||
if (missing.length) {
|
||||
await insertPickingItems(pool, pickCode, missing, branch);
|
||||
}
|
||||
return { inserted: missing.length, removed: removedResult.rowCount || 0, pickCode };
|
||||
}
|
||||
|
||||
export async function ensurePickingTaskOnOrderSubmit(
|
||||
orderCode: string,
|
||||
branchCode?: string | null
|
||||
): Promise<CreatePickingTaskResult | null> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return null;
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const order = orderResult.rows[0];
|
||||
if (!order || order.deleted_at) return null;
|
||||
if (Number(order.order_status) >= 50) return null;
|
||||
const branch = branchCode || (order.branch_code ? String(order.branch_code) : null);
|
||||
if (!(await isPickingWorkflowEnabled(branch))) return null;
|
||||
try {
|
||||
return await createPickingTask({ orderCode: code, branchCode: branch }, null);
|
||||
} catch (err) {
|
||||
console.warn('[picking] 下单即建分拣单跳过', code, err instanceof Error ? err.message : err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type RepairMissingWarehousePickingResult = {
|
||||
repaired: boolean;
|
||||
demoted: boolean;
|
||||
@@ -1030,11 +1201,291 @@ export async function updatePickingItemProgress(input: {
|
||||
* 不回写订单计划数量(quantity);不出库、不扣库存。
|
||||
* 见 docs/design/20260829-picking-complete-keep-plan-qty.md
|
||||
*/
|
||||
|
||||
/** 分拣完成时补未点的备货/采购并留责任审计;不阻断分拣。 */
|
||||
async function backfillPendingFulfillmentForPicking(input: {
|
||||
orderCode: string;
|
||||
branchCode: string | null;
|
||||
pickCode: string;
|
||||
operatorId?: string | null;
|
||||
}): Promise<void> {
|
||||
const { orderCode, branchCode, pickCode } = input;
|
||||
const preps = await pool.query(
|
||||
`SELECT sku_code, item_name, supplier_code, prepare_qty
|
||||
FROM supplier_preparations
|
||||
WHERE order_code = $1 AND COALESCE(prepare_status, 10) < 30
|
||||
AND COALESCE(is_stockout, false) = false
|
||||
AND COALESCE(transferred_to_purchase, false) = false`,
|
||||
[orderCode]
|
||||
);
|
||||
if (preps.rowCount) {
|
||||
await pool.query(
|
||||
`UPDATE supplier_preparations
|
||||
SET prepare_status = 30, prepare_time = COALESCE(prepare_time, NOW())
|
||||
WHERE order_code = $1 AND COALESCE(prepare_status, 10) < 30
|
||||
AND COALESCE(is_stockout, false) = false
|
||||
AND COALESCE(transferred_to_purchase, false) = false`,
|
||||
[orderCode]
|
||||
);
|
||||
for (const row of preps.rows) {
|
||||
await pool.query(
|
||||
`INSERT INTO delivery_loading_backfill_logs
|
||||
(branch_code, order_code, sku_code, item_name, supplier_code, missing_stage,
|
||||
responsible_code, operator_id, confirmed_qty, inbound_qty, picking_qty,
|
||||
inventory_action, pick_code, remark)
|
||||
VALUES ($1,$2,$3,$4,$5,'prep',$5,$6,$7,0,0,'backfill_prep',$8,$9)`,
|
||||
[
|
||||
branchCode,
|
||||
orderCode,
|
||||
row.sku_code || null,
|
||||
row.item_name || null,
|
||||
row.supplier_code || null,
|
||||
input.operatorId || null,
|
||||
Number(row.prepare_qty) || 0,
|
||||
pickCode,
|
||||
'分拣完成时补完成备货(原责任人未点完成)',
|
||||
]
|
||||
).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const purchases = await pool.query(
|
||||
`SELECT purchase_code, sku_code, supplier_code, purchaser_code,
|
||||
COALESCE(actual_qty, purchase_qty) AS qty,
|
||||
COALESCE(actual_price, purchase_price) AS price
|
||||
FROM purchase_orders
|
||||
WHERE order_code = $1 AND COALESCE(purchase_status, 10) < 20`,
|
||||
[orderCode]
|
||||
);
|
||||
if (purchases.rowCount) {
|
||||
const { updatePurchaseOrderStatus } = await import('./purchaseOperationService');
|
||||
for (const row of purchases.rows) {
|
||||
try {
|
||||
await updatePurchaseOrderStatus({
|
||||
purchaseCode: String(row.purchase_code),
|
||||
status: 20,
|
||||
actualQty: Number(row.qty) || undefined,
|
||||
actualPrice: Number(row.price) || undefined,
|
||||
branchCode: branchCode || '',
|
||||
remark: '分拣完成时补完成采购',
|
||||
});
|
||||
await pool.query(
|
||||
`INSERT INTO delivery_loading_backfill_logs
|
||||
(branch_code, order_code, sku_code, supplier_code, purchaser_code, missing_stage,
|
||||
responsible_code, operator_id, confirmed_qty, inbound_qty, picking_qty,
|
||||
inventory_action, pick_code, remark)
|
||||
VALUES ($1,$2,$3,$4,$5,'purchase',$5,$6,$7,0,0,'backfill_prep',$8,$9)`,
|
||||
[
|
||||
branchCode,
|
||||
orderCode,
|
||||
row.sku_code || null,
|
||||
row.supplier_code || null,
|
||||
row.purchaser_code || null,
|
||||
input.operatorId || null,
|
||||
Number(row.qty) || 0,
|
||||
pickCode,
|
||||
'分拣完成时补完成采购(原采购员未点完成)',
|
||||
]
|
||||
).catch(() => undefined);
|
||||
} catch (error) {
|
||||
console.warn('[picking] 补完成采购失败', row.purchase_code, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function isNoAutoDeliveryOrder(
|
||||
orderCode: string,
|
||||
branchCode: string | null,
|
||||
options?: { includeFullySkip?: boolean; includeSelfPickup?: boolean }
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const [
|
||||
{ isRetailOrder },
|
||||
{ isOrderOnlyDirectDelivery },
|
||||
{ isOrderIndependentInbound },
|
||||
{ isSelfPickupOrder },
|
||||
{ isOrderFullySkipInbound },
|
||||
{ isDirectToDeliveryEnabled },
|
||||
] = await Promise.all([
|
||||
import('./retailOrder'),
|
||||
import('./skuDirectDelivery'),
|
||||
import('./independentInbound'),
|
||||
import('./orderWorkflowFulfillmentService'),
|
||||
import('./mainSystemPrepLedger'),
|
||||
import('./directToDeliveryConfigService'),
|
||||
]);
|
||||
const includeFullySkip = options?.includeFullySkip !== false;
|
||||
const includeSelfPickup = options?.includeSelfPickup !== false;
|
||||
return (
|
||||
(await isRetailOrder(orderCode, pool)) ||
|
||||
(await isOrderOnlyDirectDelivery(orderCode, pool)) ||
|
||||
(await isOrderIndependentInbound(orderCode, pool)) ||
|
||||
(includeSelfPickup && (await isSelfPickupOrder(orderCode, pool))) ||
|
||||
(await isDirectToDeliveryEnabled(branchCode).catch(() => false)) ||
|
||||
(includeFullySkip &&
|
||||
(await isOrderFullySkipInbound({ branchCode: branchCode || '', ourOrderCode: orderCode, db: pool })))
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('[picking] 判定跳过自动入库/配送失败,按需谨慎处理', orderCode, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分拣完成时补上游:普通单补备货/采购和(40/45)缺入库;照片缺失不阻断分拣。
|
||||
* 待取货/全直送/自提/独立进货/散客跳过自动入库。
|
||||
*/
|
||||
async function autoInboundFromPickingBeforeComplete(input: {
|
||||
pickCode: string;
|
||||
branchCode: string | null;
|
||||
ctx?: TenantContext | null;
|
||||
}): Promise<void> {
|
||||
const taskResult = await pool.query(
|
||||
`SELECT pt.order_code, pt.branch_code, pt.pick_status
|
||||
FROM picking_tasks pt WHERE pt.pick_code = $1 LIMIT 1`,
|
||||
[input.pickCode]
|
||||
);
|
||||
const task = taskResult.rows[0];
|
||||
if (!task || Number(task.pick_status) >= 40) return;
|
||||
const orderCode = String(task.order_code || '').trim();
|
||||
if (!orderCode) return;
|
||||
const branchCode = input.branchCode || (task.branch_code ? String(task.branch_code) : null);
|
||||
|
||||
// 用户最终口径:分拣完成不再自动入库;只补未点的备货/采购成本并审计。
|
||||
// 入库/分拣二选一由 T3 核货阶段按 30/40/45 处理。
|
||||
await backfillPendingFulfillmentForPicking({
|
||||
orderCode,
|
||||
branchCode,
|
||||
pickCode: input.pickCode,
|
||||
operatorId: input.ctx?.userId || null,
|
||||
}).catch((error) => console.warn('[picking] 分拣完成补备货/采购失败', orderCode, error));
|
||||
|
||||
const orderResult = await pool.query(
|
||||
`SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
const status = Number(orderResult.rows[0]?.order_status) || 0;
|
||||
if (status >= 40) return;
|
||||
// 30 待备货:完成备货成本,但清理本次新建的 pending inspection(不建验收/库存)。
|
||||
const before = await pool.query(
|
||||
`SELECT id FROM inspections
|
||||
WHERE order_code = $1 AND actual_qty IS NULL AND quality_rating IS NULL`,
|
||||
[orderCode]
|
||||
);
|
||||
const beforeIds = new Set(before.rows.map((row) => String(row.id)));
|
||||
try {
|
||||
const { finalizeAutoCompletedSupplierPreparations } = await import('./supplierPreparationStatusService');
|
||||
await finalizeAutoCompletedSupplierPreparations(orderCode, { branchCode });
|
||||
} catch (error) {
|
||||
console.warn('[picking] 30 分拣完成补备货成本失败', orderCode, error);
|
||||
}
|
||||
const after = await pool.query(
|
||||
`SELECT id FROM inspections
|
||||
WHERE order_code = $1 AND actual_qty IS NULL AND quality_rating IS NULL`,
|
||||
[orderCode]
|
||||
);
|
||||
const created = after.rows.map((row) => String(row.id)).filter((id) => !beforeIds.has(id));
|
||||
if (created.length) {
|
||||
await pool.query(
|
||||
`DELETE FROM inspections WHERE id = ANY($1::uuid[]) AND actual_qty IS NULL
|
||||
AND COALESCE(quality_rating, '') = ''`,
|
||||
[created]
|
||||
).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
/** 分拣全部完成后,不要求先验收,直接把 30/40/45 推到 50;配送任务仍走现有守卫。 */
|
||||
async function forceOrderReadyForDeliveryAfterPicking(
|
||||
orderCode: string,
|
||||
branchCode?: string | null
|
||||
): Promise<boolean> {
|
||||
const code = String(orderCode || '').trim();
|
||||
if (!code) return false;
|
||||
const order = await pool.query(
|
||||
`SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`,
|
||||
[code]
|
||||
);
|
||||
const status = Number(order.rows[0]?.order_status);
|
||||
if (![30, 40, 45].includes(status)) return false;
|
||||
const inboundPresent = status === 40 || status === 45
|
||||
? (await pool.query(
|
||||
`SELECT 1 FROM inspections
|
||||
WHERE order_code = $1 AND (actual_qty > 0 OR inbound_batch_no IS NOT NULL)
|
||||
LIMIT 1`,
|
||||
[code]
|
||||
)).rowCount
|
||||
: 0;
|
||||
// 30→30;40/45 无入库→45(分拣完成无需入库);40/45 有入库保留原 flag。
|
||||
const autoFlag = status === 30
|
||||
? 30
|
||||
: status === 40 && !inboundPresent
|
||||
? 40
|
||||
: status === 45 && !inboundPresent
|
||||
? 45
|
||||
: null;
|
||||
// 散客/独立进货/全直送/自提/极简流转不强制 50;整单待取货可以 50,但配送由 ensure 守卫拦住。
|
||||
if (await isNoAutoDeliveryOrder(code, branchCode || null, { includeFullySkip: false, includeSelfPickup: false })) return false;
|
||||
if ((await countUnfinishedPickingTasks(code)) > 0) return false;
|
||||
if ((await countWarehouseItemsMissingPicking(code)) > 0) return false;
|
||||
const updated = await pool.query(
|
||||
`UPDATE orders
|
||||
SET order_status = 50,
|
||||
updated_at = NOW(),
|
||||
auto_advanced_from_status = CASE
|
||||
WHEN $2::int IS NOT NULL THEN COALESCE(auto_advanced_from_status, $2::int)
|
||||
ELSE auto_advanced_from_status
|
||||
END,
|
||||
auto_advanced_at = CASE
|
||||
WHEN $2::int IS NOT NULL THEN NOW()
|
||||
ELSE auto_advanced_at
|
||||
END
|
||||
WHERE order_code = $1 AND order_status IN (30, 40, 45)`,
|
||||
[code, autoFlag]
|
||||
);
|
||||
if (!updated.rowCount) return false;
|
||||
await ensureDeliveryTaskForOrder(code, branchCode || null).catch(() => undefined);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 分拣列表加载时修复“分拣已完成但订单仍停在 30/40/45”的历史卡单。 */
|
||||
export async function recoverOrdersReadyForDeliveryAfterPicking(
|
||||
ctx: TenantContext | null | undefined
|
||||
): Promise<number> {
|
||||
const params: unknown[] = [];
|
||||
const branchFilter = branchClause(ctx, 'o', params);
|
||||
const result = await pool.query(
|
||||
`SELECT DISTINCT o.order_code, o.branch_code
|
||||
FROM orders o
|
||||
JOIN picking_tasks pt ON pt.order_code = o.order_code
|
||||
WHERE o.order_status IN (30, 40, 45)
|
||||
AND ${orderNotDeletedSql('o')}
|
||||
${branchFilter}
|
||||
AND pt.pick_status >= 30
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM picking_tasks pt2
|
||||
WHERE pt2.order_code = o.order_code AND COALESCE(pt2.pick_status, 10) < 30
|
||||
)
|
||||
ORDER BY o.updated_at DESC NULLS LAST
|
||||
LIMIT 50`,
|
||||
params
|
||||
);
|
||||
let count = 0;
|
||||
for (const row of result.rows) {
|
||||
if (await forceOrderReadyForDeliveryAfterPicking(String(row.order_code), row.branch_code)) {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
export async function confirmPickingComplete(input: {
|
||||
pickCode: string;
|
||||
rows?: PickingProgressRow[];
|
||||
reviewerId?: string | null;
|
||||
ctx?: TenantContext | null;
|
||||
/** 直接配送补分拣用:由外层 tryAdvance 继续推进,避免递归发车。 */
|
||||
deferAdvance?: boolean;
|
||||
}) {
|
||||
const pickCode = String(input.pickCode || '').trim();
|
||||
if (!pickCode) throw Object.assign(new Error('缺少拣货单号'), { status: 400 });
|
||||
@@ -1243,9 +1694,54 @@ export async function confirmPickingComplete(input: {
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
// 分拣完成即推进待配送(出库与装车核货合并,见 20260821-merge-outbound-with-loading)
|
||||
// 分拣完成即补上游/推进待配送(出库与装车核货合并,见 20260821-merge-outbound-with-loading)
|
||||
for (const orderCode of relatedOrderCodes) {
|
||||
await tryAdvanceOrderToDelivery(orderCode);
|
||||
await autoInboundFromPickingBeforeComplete({
|
||||
pickCode,
|
||||
branchCode: task.branch_code ? String(task.branch_code) : null,
|
||||
ctx: input.ctx || null,
|
||||
}).catch((error) => console.warn('[picking] 分拣完成自动补上游失败', orderCode, error));
|
||||
// 分拣完成即无需入库:无实际入库时关闭 pending 验收并留 no_inventory 审计;有实际入库保留。
|
||||
try {
|
||||
const actualInbound = await pool.query(
|
||||
`SELECT 1 FROM inspections
|
||||
WHERE order_code = $1
|
||||
AND (COALESCE(actual_qty, 0) > 0 OR inbound_batch_no IS NOT NULL)
|
||||
LIMIT 1`,
|
||||
[orderCode]
|
||||
);
|
||||
const deleted = await pool.query(
|
||||
`DELETE FROM inspections
|
||||
WHERE order_code = $1 AND actual_qty IS NULL AND COALESCE(quality_rating, '') = ''
|
||||
RETURNING id`,
|
||||
[orderCode]
|
||||
);
|
||||
if (!actualInbound.rowCount) {
|
||||
await pool.query(
|
||||
`INSERT INTO delivery_loading_backfill_logs
|
||||
(branch_code, order_code, task_code, missing_stage, operator_id,
|
||||
confirmed_qty, inbound_qty, picking_qty, inventory_action, pick_code, remark)
|
||||
VALUES ($1,$2,$3,'picking',$4,0,0,0,'no_inventory',$5,$6)`,
|
||||
[
|
||||
task.branch_code ? String(task.branch_code) : null,
|
||||
orderCode,
|
||||
null,
|
||||
input.reviewerId || null,
|
||||
pickCode,
|
||||
`分拣完成即无需入库:关闭 ${deleted.rowCount || 0} 条 pending 验收`,
|
||||
]
|
||||
).catch(() => undefined);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[picking] 分拣完成关闭 pending 验收失败', orderCode, error);
|
||||
}
|
||||
if (!input.deferAdvance) {
|
||||
await tryAdvanceOrderToDelivery(orderCode);
|
||||
}
|
||||
await forceOrderReadyForDeliveryAfterPicking(
|
||||
orderCode,
|
||||
task.branch_code ? String(task.branch_code) : null
|
||||
);
|
||||
}
|
||||
|
||||
// 第九批「批次报告同步」触发点①:分拣完成 ⇒ 本次出库批次已确定,旁路异步推批次报告
|
||||
@@ -2871,6 +3367,7 @@ export async function listPickingTasks(
|
||||
}
|
||||
) {
|
||||
await syncMissingPickingTasks(ctx);
|
||||
await recoverOrdersReadyForDeliveryAfterPicking(ctx).catch(() => 0);
|
||||
const params: unknown[] = [];
|
||||
const branchFilter = branchClause(ctx, 'pt', params);
|
||||
const from = String(options?.dateFrom || '').trim().slice(0, 10);
|
||||
@@ -3027,6 +3524,7 @@ export async function listMyPickingTasks(
|
||||
}
|
||||
) {
|
||||
await syncMissingPickingTasks(ctx);
|
||||
await recoverOrdersReadyForDeliveryAfterPicking(ctx).catch(() => 0);
|
||||
const params: unknown[] = [pickerId];
|
||||
const branchFilter = branchClause(ctx, 'pt', params);
|
||||
const deliveryWindow = myPickingDateWindowSql('o2', params, options);
|
||||
|
||||
@@ -105,3 +105,40 @@ export function orderVisibleToDeliverySql(orderAlias = 'o'): string {
|
||||
)
|
||||
)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 配送管理/角标可见:原可见性(>=50 或免入库待取货)**并集**未 void 的配送任务。
|
||||
* 早期任务只给管理端/补录入口;司机端继续用 orderVisibleToDeliverySql。
|
||||
*/
|
||||
export function orderVisibleToDeliveryManagementSql(orderAlias = 'o'): string {
|
||||
return `(
|
||||
${orderVisibleToDeliverySql(orderAlias)}
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM delivery_tasks dt_mgmt
|
||||
WHERE dt_mgmt.order_code = ${orderAlias}.order_code
|
||||
AND dt_mgmt.voided_at IS NULL
|
||||
)
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM delivery_tasks dt_void
|
||||
WHERE dt_void.order_code = ${orderAlias}.order_code
|
||||
AND dt_void.voided_at IS NOT NULL
|
||||
AND COALESCE(${orderAlias}.order_status, 0) < 50
|
||||
)
|
||||
AND NOT (
|
||||
COALESCE(${orderAlias}.order_status, 0) >= 50
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM delivery_tasks dt_ready
|
||||
WHERE dt_ready.order_code = ${orderAlias}.order_code
|
||||
AND dt_ready.voided_at IS NULL
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM order_items oi_dd
|
||||
WHERE oi_dd.order_code = ${orderAlias}.order_code
|
||||
AND COALESCE(oi_dd.is_returned, false) = false
|
||||
AND COALESCE(oi_dd.is_extra_dish, false) = false
|
||||
AND COALESCE(oi_dd.quantity, 0) > 0
|
||||
AND NOT ${skuDirectDeliveryAppliesSql('oi_dd.sku_code', 'oi_dd.order_code')}
|
||||
)
|
||||
)`;
|
||||
}
|
||||
|
||||
@@ -439,11 +439,40 @@ export async function handleAfterSalesWithValidation(input: {
|
||||
throw new Error('处理金额超过500元,须人工确认(请传 confirmed: true)');
|
||||
}
|
||||
|
||||
const orderItemId = String(row.order_item_id || '').trim();
|
||||
const orderCode = String(row.order_code || '').trim();
|
||||
if (!orderItemId || !orderCode) {
|
||||
let orderItemId = String(row.order_item_id || '').trim();
|
||||
if (!orderCode) {
|
||||
throw Object.assign(new Error('处理前须绑定订单明细'), { status: 400, code: 'invalid_request' });
|
||||
}
|
||||
if (!orderItemId) {
|
||||
// 旧数据/主系统推送可能没有 order_item_id:优先 sku+order 唯一匹配,否则仅在只有一条未退货行时绑定。
|
||||
const candidates = await client.query(
|
||||
`SELECT id, sku_code FROM order_items
|
||||
WHERE order_code = $1 AND COALESCE(is_returned, false) = false`,
|
||||
[orderCode]
|
||||
);
|
||||
const sku = String(row.sku_code || '').trim();
|
||||
const preferred = sku
|
||||
? candidates.rows.filter((item) => String(item.sku_code || '').trim() === sku)
|
||||
: [];
|
||||
const candidatePool = preferred.length ? preferred : candidates.rows;
|
||||
if (candidatePool.length === 1) {
|
||||
orderItemId = String(candidatePool[0].id);
|
||||
await client.query(`UPDATE after_sales SET order_item_id = $2 WHERE id = $1`, [
|
||||
row.id,
|
||||
orderItemId,
|
||||
]);
|
||||
} else {
|
||||
throw Object.assign(
|
||||
new Error(
|
||||
candidatePool.length
|
||||
? '处理前须绑定订单明细(存在多条可选明细,请先选择具体商品)'
|
||||
: '处理前须绑定订单明细(该订单没有可绑定的未退货明细)'
|
||||
),
|
||||
{ status: 400, code: 'after_sale_item_ambiguous' }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const itemOutcome = await applyAfterSaleHandleOrderItem(client, {
|
||||
orderCode,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const service = readFileSync(new URL('../src/services/v9CompletionService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('售后处理自动绑定订单明细', () => {
|
||||
it('优先 sku+order;唯一未退货行自动回写 after_sales.order_item_id', () => {
|
||||
const start = service.indexOf("if (!orderItemId) {");
|
||||
const end = service.indexOf('const itemOutcome =', start);
|
||||
const fn = service.slice(start, end);
|
||||
expect(fn).toContain('FROM order_items');
|
||||
expect(fn).toContain('COALESCE(is_returned, false) = false');
|
||||
expect(fn).toContain('row.sku_code');
|
||||
expect(fn).toContain('UPDATE after_sales SET order_item_id');
|
||||
});
|
||||
|
||||
it('多条歧义/零候选都不猜行,返回明确错误', () => {
|
||||
const start = service.indexOf("if (!orderItemId) {");
|
||||
const end = service.indexOf('const itemOutcome =', start);
|
||||
const fn = service.slice(start, end);
|
||||
expect(fn).toContain('candidatePool.length === 1');
|
||||
expect(fn).toContain('存在多条可选明细');
|
||||
expect(fn).toContain('没有可绑定的未退货明细');
|
||||
expect(fn).toContain("code: 'after_sale_item_ambiguous'");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { orderVisibleToDeliveryManagementSql, orderVisibleToDeliverySql } from '../src/services/supplierSkipInbound';
|
||||
|
||||
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
|
||||
const fulfillment = read('../src/services/orderWorkflowFulfillmentService.ts');
|
||||
const submit = read('../src/services/customerOrderSubmitService.ts');
|
||||
const picking = read('../src/services/pickingService.ts');
|
||||
const queryService = read('../src/services/deliveryTaskQueryService.ts');
|
||||
const navBadge = read('../src/services/navBadgeService.ts');
|
||||
const cost = read('../src/services/costAllocationService.ts');
|
||||
const migration = read('../../migrations/20261083_delivery_task_early_void.sql');
|
||||
|
||||
function body(source: string, name: string): string {
|
||||
const start = source.indexOf(`export async function ${name}`);
|
||||
expect(start, name).toBeGreaterThanOrEqual(0);
|
||||
const rest = source.slice(start + 1);
|
||||
const next = rest.search(/export (async )?function /);
|
||||
return next >= 0 ? source.slice(start, start + 1 + next) : source.slice(start);
|
||||
}
|
||||
|
||||
describe('T1 早期配送/分拣任务地基', () => {
|
||||
it('AC-01/AC-06:下单 COMMIT 后建分拣+配送;early 分支不派员、不通知', () => {
|
||||
expect(submit).toContain('ensurePickingTaskOnOrderSubmit(orderCode, input.branchCode)');
|
||||
expect(submit).toContain('ensureEarlyDeliveryTaskForOrder(orderCode, input.branchCode)');
|
||||
const commitAt = submit.indexOf("await client.query('COMMIT');\n\n /**");
|
||||
expect(submit.indexOf('ensurePickingTaskOnOrderSubmit(orderCode')).toBeGreaterThan(commitAt);
|
||||
expect(submit.indexOf('ensureEarlyDeliveryTaskForOrder(orderCode')).toBeGreaterThan(commitAt);
|
||||
|
||||
const ensure = body(fulfillment, 'ensureDeliveryTaskForOrder');
|
||||
expect(ensure).toContain('options?: { early?: boolean }');
|
||||
expect(ensure).toContain('options?.early');
|
||||
expect(ensure).toContain('options?.early ? null : await resolveDeliveryPersonForOrder');
|
||||
expect(ensure).toContain('if (!options?.early)');
|
||||
expect(ensure).toContain('notifyDeliveryTaskCreated');
|
||||
expect(ensure).toContain('person_code, delivery_id');
|
||||
});
|
||||
|
||||
it('AC-02~04/AC-25:early 复用五道守卫;可见性只放宽管理列表/角标', () => {
|
||||
const early = body(fulfillment, 'ensureEarlyDeliveryTaskForOrder');
|
||||
expect(early).toContain('ensureDeliveryTaskForOrder(code, branch, undefined, { early: true })');
|
||||
expect(early).toContain('isOrderOnlyDirectDelivery(code)');
|
||||
expect(early).toContain('isDirectToDeliveryEnabled(branch)');
|
||||
const ensure = body(fulfillment, 'ensureDeliveryTaskForOrder');
|
||||
for (const guard of ['isRetailOrder', 'isOrderOnlyDirectDelivery', 'isOrderIndependentInbound', 'isSelfPickupOrder', 'isOrderFullySkipInbound']) {
|
||||
expect(ensure, guard).toContain(guard);
|
||||
}
|
||||
expect(ensure).toContain("DELETE FROM delivery_tasks");
|
||||
|
||||
const management = orderVisibleToDeliveryManagementSql('o');
|
||||
expect(management).toContain('dt_mgmt.voided_at IS NULL');
|
||||
// AC-12 可见性:旧可见/active 任务 OR;仅 <50 的 voided 才隐藏
|
||||
expect(management).toContain('voided_at IS NOT NULL');
|
||||
expect(management).toContain('COALESCE(o.order_status, 0) < 50');
|
||||
expect(management).not.toContain('dt_active');
|
||||
expect(management).toContain(orderVisibleToDeliverySql('o'));
|
||||
expect(queryService).toContain("orderVisibleToDeliveryManagementSql('o')");
|
||||
expect(navBadge).toContain("orderVisibleToDeliveryManagementSql('o')");
|
||||
// 司机端三个查询仍用旧口径
|
||||
// T3 后司机端也放开早期任务;仍保留 stats/旧口径查询
|
||||
expect((queryService.match(/orderVisibleToDeliverySql\('o'\)/g) || []).length).toBeGreaterThanOrEqual(1);
|
||||
expect((queryService.match(/orderVisibleToDeliveryManagementSql\('o'\)/g) || []).length).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it('AC-05/AC-11:防重沿用 advisory lock/唯一索引回读;查询带 voided_at IS NULL', () => {
|
||||
const ensure = body(fulfillment, 'ensureDeliveryTaskForOrder');
|
||||
expect(ensure).toContain('pg_advisory_xact_lock');
|
||||
expect(ensure).toContain('23505');
|
||||
expect(ensure).toContain('WHERE order_code = $1 AND voided_at IS NULL LIMIT 1');
|
||||
});
|
||||
|
||||
it('AC-12:early 任务管理可见;迁移加 void 列/部分索引且不动全唯一索引', () => {
|
||||
expect(migration).toContain('voided_at TIMESTAMPTZ');
|
||||
expect(migration).toContain('void_reason VARCHAR(100)');
|
||||
expect(migration).toContain('idx_delivery_tasks_active_order');
|
||||
expect(migration).toContain('WHERE voided_at IS NULL');
|
||||
expect(migration).not.toContain('DROP INDEX');
|
||||
expect(migration).not.toContain('delivery_loading_backfill_logs');
|
||||
});
|
||||
|
||||
it('AC-25/成本:角标与列表同口径;里程只算 voided_at IS NULL 且已发车任务', () => {
|
||||
expect(navBadge).toContain('COALESCE(dt.task_status, 10) < 30');
|
||||
expect(cost).toContain('dt.voided_at IS NULL');
|
||||
expect(cost).toContain('COALESCE(dt.task_status, 10) >= 20');
|
||||
expect(cost).not.toContain('COUNT(*)::int AS task_count FROM delivery_tasks dt WHERE dt.order_code = o.order_code\n )');
|
||||
});
|
||||
|
||||
it('AC-26:权限/隔离仍由原有路由与租户上下文保证', () => {
|
||||
const routes = read('../src/modules/workflow/routes/deliveryRoutes.ts');
|
||||
expect(routes).toContain('delivery_manage');
|
||||
});
|
||||
|
||||
it('分拣:下单后建单仅启用 workflow;不引入“未到45禁止完成”闸', () => {
|
||||
const ensure = body(picking, 'ensurePickingTaskOnOrderSubmit');
|
||||
expect(ensure).toContain('isPickingWorkflowEnabled(branch)');
|
||||
expect(ensure).toContain('createPickingTask({ orderCode: code, branchCode: branch }, null)');
|
||||
expect(ensure).not.toContain("order_status < 45");
|
||||
expect(picking).not.toContain('assertPickingTaskReadyForCompletion');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
|
||||
const loading = read('../src/services/deliveryLoadingService.ts');
|
||||
const backfill = read('../src/services/deliveryLoadingBackfillService.ts');
|
||||
const fulfillment = read('../src/services/orderWorkflowFulfillmentService.ts');
|
||||
const queryService = read('../src/services/deliveryTaskQueryService.ts');
|
||||
const migration = read('../../migrations/20261084_delivery_loading_backfill_logs.sql');
|
||||
const registration = read('../../migrations/20261074_standalone_processing_outputs.sql');
|
||||
const ledger = read('../src/services/mainSystemPrepLedger.ts');
|
||||
const visibility = read('../src/services/supplierSkipInbound.ts');
|
||||
const outbound = read('../src/services/inventoryOutboundService.ts');
|
||||
const atomicDoc = read('../../../.team/early-pickup-delivery/t3-atomicity.md');
|
||||
const print = read('../src/services/deliveryPrintLineService.ts');
|
||||
const routing = read('../src/services/deliveryRoutingService.ts');
|
||||
const mobile = read('../src/routes/mobile/mobileDeliveryRoutes.ts');
|
||||
|
||||
describe('T3 早期任务核货/发车/补录', () => {
|
||||
it('AC-13:核货不再要求 order_status>=50;早期显示全部行', () => {
|
||||
expect(loading).not.toContain('&& orderStatus >= 50');
|
||||
expect(loading).not.toContain('orderStatus >= 50 &&');
|
||||
expect(loading).toContain('const earlySkipOnly = false;');
|
||||
});
|
||||
|
||||
it('AC-14/15/19/20:核货前补上游,30 只完成备货不写入库', () => {
|
||||
expect(loading).toContain('backfillLoadingItemUpstream({');
|
||||
expect(loading).toContain('taskCode: input.taskCode');
|
||||
const branch30 = backfill.slice(backfill.indexOf('if (orderStatus < 40)'), backfill.indexOf('const inspectionResult'));
|
||||
expect(branch30).toContain('UPDATE supplier_preparations');
|
||||
expect(branch30).toContain('finalizeAutoCompletedSupplierPreparations');
|
||||
expect(branch30).toContain("inventoryAction: 'no_inventory'");
|
||||
expect(branch30).not.toContain('submitInspectionCompliance');
|
||||
expect(branch30).not.toContain('INSERT INTO inventory');
|
||||
expect(backfill).toContain('submitInspectionCompliance(');
|
||||
expect(backfill).not.toContain('INSERT INTO inventory');
|
||||
expect(backfill).not.toContain('allowBypassPrepackagedCheck');
|
||||
// AC-21:ensureInspectionsForOrder 前必须已有照片/成本预检;失败清理新建 pending
|
||||
const preflightAt = backfill.indexOf('isCategoryPhotoInspectionRequired');
|
||||
const ensureAt = backfill.indexOf('ensureInspectionsForOrder(orderCode');
|
||||
expect(preflightAt).toBeGreaterThan(0);
|
||||
expect(preflightAt).toBeLessThan(ensureAt);
|
||||
expect(backfill).toContain('backfill_photo_required');
|
||||
expect(backfill).toContain('backfill_cost_missing');
|
||||
expect(backfill).toContain('cleanupNewPendingInspections');
|
||||
expect(backfill).toContain('backfill_sale_price_missing');
|
||||
expect(backfill).toContain('backfill_picking_state_invalid');
|
||||
// N-1:无 picking 行先同步,仍无则阻断,不伪造完成分拣行
|
||||
expect(backfill).toContain('syncOpenPickingItemsForOrder');
|
||||
expect(backfill).toContain('backfill_picking_missing');
|
||||
expect(loading.indexOf('backfillLoadingItemUpstream({')).toBeLessThan(loading.indexOf('ensureDeliveryLoadingPickTask(String(task.order_code))'));
|
||||
expect(backfill).toContain('审计写入失败');
|
||||
// P1-6:未分配任务只允许同分公司配送员,不能任意人操作
|
||||
expect(loading).toContain('无权操作其他分公司的配送任务');
|
||||
expect(fulfillment).toContain('无权操作该配送任务');
|
||||
});
|
||||
|
||||
it('AC-16:已核货的 30/40/45 先补 50 再 60;失败回滚', () => {
|
||||
const adv = fulfillment.slice(fulfillment.indexOf('export async function tryAdvanceOrderToDelivering'));
|
||||
expect(adv).toContain('loading_completed_at IS NOT NULL');
|
||||
expect(adv).toContain('UPDATE orders SET order_status = 50');
|
||||
expect(adv).toContain('UPDATE orders SET order_status = 60 WHERE order_code = $1 AND order_status = 50');
|
||||
expect(adv).toContain('withOrderLock');
|
||||
expect(adv).toContain('status < 50 ? [status, 50] : 50');
|
||||
expect(adv).toContain('noInventory: skipDepartureInventory');
|
||||
expect(adv).toContain('has_stock_cover');
|
||||
expect(adv).toContain('hasStockCover');
|
||||
expect(adv).toContain('delivery_early_status_advance');
|
||||
expect(adv).toContain('syncDeliveryTaskForOrder(orderCode, branchCodeForWriteback)');
|
||||
expect(adv).toContain("operationType: 'delivery_task_claim'");
|
||||
expect(adv).toContain('auto_advanced_from_status');
|
||||
expect(backfill).toContain('auto_advanced_from_status');
|
||||
expect(backfill).toContain('const skipAutoInbound = isPickingOnly40 || isPickingOnly45');
|
||||
expect(backfill).toContain('isPickingOnly40 = autoAdvancedFrom === 40');
|
||||
expect(backfill).toContain('isPickingOnly45 = autoAdvancedFrom === 45');
|
||||
expect(backfill).toContain('const shouldBackfillInbound =');
|
||||
expect(backfill).toContain('hasPendingInboundSource');
|
||||
expect(backfill).toContain('pendingSources.preps');
|
||||
expect(backfill).toContain('closePendingUpstreamWithoutInbound');
|
||||
expect(backfill).toContain('DELETE FROM inspections');
|
||||
expect(outbound).toContain('fallbackToRequiredQty');
|
||||
expect(outbound).toContain('options?.fallbackToRequiredQty ? Number(row.required_qty)');
|
||||
expect(adv).toContain('fallbackToRequiredQty:');
|
||||
expect(adv).toContain('auto_advanced_from_status) === 30');
|
||||
expect(adv).toContain('UPDATE orders SET order_status = 50 WHERE order_code = $1 AND order_status < 50 RETURNING order_code');
|
||||
});
|
||||
|
||||
it('AC-23:司机/小程序列表也使用 management 可见性', () => {
|
||||
const oldCount = (queryService.match(/orderVisibleToDeliverySql\('o'\)/g) || []).length;
|
||||
const managementCount = (queryService.match(/orderVisibleToDeliveryManagementSql\('o'\)/g) || []).length;
|
||||
expect(managementCount).toBeGreaterThanOrEqual(3);
|
||||
expect(oldCount).toBeLessThanOrEqual(1);
|
||||
expect(print).toContain('voided_at IS NULL');
|
||||
expect(routing).toContain('dt.voided_at IS NULL');
|
||||
expect(mobile).toContain('dt.voided_at IS NULL');
|
||||
expect(ledger).toContain('待取货残留配送任务清理');
|
||||
expect(visibility).toContain('COALESCE(${orderAlias}.order_status, 0) < 50');
|
||||
expect(visibility).toContain('skuDirectDeliveryAppliesSql');
|
||||
expect(print).toContain('deliveryPrintReadySql');
|
||||
expect(print).toContain('loading_completed_at IS NOT NULL');
|
||||
expect(routing).toContain('COALESCE(dt.task_status, 10) >= 20 OR dt.loading_completed_at IS NOT NULL');
|
||||
expect(mobile).toContain('dt.loading_completed_at IS NOT NULL OR dt.task_status >= 20');
|
||||
});
|
||||
|
||||
it('AC-28:审计表字段齐全、登记 tenant_business_tables、全部租户 + RLS', () => {
|
||||
for (const field of ['missing_stage', 'responsible_code', 'operator_id', 'confirmed_qty', 'inbound_qty', 'picking_qty', 'inventory_action']) {
|
||||
expect(migration, field).toContain(field);
|
||||
}
|
||||
expect(migration).toContain('delivery_loading_backfill_logs');
|
||||
expect(migration).toContain('ENABLE ROW LEVEL SECURITY');
|
||||
expect(migration).toContain('tenant_business_tables');
|
||||
expect(migration).toContain("'delivery_loading_backfill_logs',");
|
||||
expect(registration).toContain("'delivery_tasks',");
|
||||
expect(migration).toContain("nspname LIKE 'tenant");
|
||||
expect(backfill).toContain('INSERT INTO delivery_loading_backfill_logs');
|
||||
expect(backfill).toContain("? 'inbound_then_deduct'");
|
||||
expect(backfill).toContain("? 'inbound'");
|
||||
expect(backfill).toContain(": 'no_inventory'");
|
||||
expect(backfill).toContain("missingStage: 'prep'");
|
||||
expect(atomicDoc).toContain('prep');
|
||||
});
|
||||
|
||||
it('AC-27:补分拣复用 confirmPickingComplete/update,不直接写库存', () => {
|
||||
expect(backfill).toContain('confirmPickingComplete');
|
||||
expect(backfill).toContain('updatePickingItemProgress');
|
||||
expect(backfill).not.toContain('confirmPickingComplete({\n pickCode,\n reviewerId: input.operatorId || null,\n skipAutoInbound');
|
||||
});
|
||||
|
||||
it('不改财务公式/状态链常量', () => {
|
||||
expect(read('../src/modules/kernel/orderStatus.ts')).not.toContain('bumpedFromStatus');
|
||||
expect(read('../src/services/financeNetProfitFormula.ts')).not.toContain('delivery_loading_backfill_logs');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const picking = readFileSync(new URL('../src/services/pickingService.ts', import.meta.url), 'utf8');
|
||||
const workflow = readFileSync(new URL('../src/services/orderWorkflowFulfillmentService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('提前配送 = 提前分拣完成', () => {
|
||||
it('新增 completeOrderPickingForDirectDelivery,复用 confirmPickingComplete 且幂等', () => {
|
||||
const start = picking.indexOf('export async function completeOrderPickingForDirectDelivery');
|
||||
const end = picking.indexOf('/**\n * 下单提交后立即建分拣单', start);
|
||||
const fn = picking.slice(start, end);
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
expect(fn).toContain('ensurePickingTaskOnOrderSubmit');
|
||||
expect(fn).toContain('confirmPickingComplete');
|
||||
expect(fn).toContain('deferAdvance: true');
|
||||
expect(fn).toContain('anyTask.rowCount');
|
||||
});
|
||||
|
||||
it('发车前/结束配送前调用补分拣;失败不阻断', () => {
|
||||
expect(workflow).toContain('completeOrderPickingForDirectDelivery(orderCode, branchCodeForWriteback');
|
||||
expect(workflow).toContain('completeOrderPickingForDirectDelivery(orderCode, null, null)');
|
||||
expect(workflow).toContain('补分拣完成失败(继续发车)');
|
||||
expect(workflow).toContain('补分拣完成失败(继续结束)');
|
||||
});
|
||||
|
||||
it('分拣完成关闭 pending 验收并写 no_inventory,实际 inbound 保留', () => {
|
||||
expect(picking).toContain('DELETE FROM inspections');
|
||||
expect(picking).toContain("inventory_action, pick_code, remark");
|
||||
expect(picking).toContain("'no_inventory'");
|
||||
expect(picking).toContain('actualInbound');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const svc = readFileSync(new URL('../src/services/orderWorkflowFulfillmentService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('结束配送库存口径', () => {
|
||||
it('读取 marker/inbound/outbound;30/40 跳过,45 已扣跳过/未扣软扣,无入库普通单跳过', () => {
|
||||
const start = svc.indexOf('const settleCtx = await db.query(');
|
||||
const end = svc.indexOf('const now = new Date();', start);
|
||||
const fn = svc.slice(start, end);
|
||||
expect(fn).toContain('auto_advanced_from_status');
|
||||
expect(fn).toContain('has_inbound');
|
||||
expect(fn).toContain('has_outbound');
|
||||
expect(fn).toContain('(marker === 30 || marker === 40) && !hasStockCover');
|
||||
expect(fn).toContain('has_stock_cover');
|
||||
expect(fn).toContain('marker === 45');
|
||||
expect(fn).toContain('fallbackToRequiredQty = true');
|
||||
expect(fn).toContain('else if (!hasInbound && !hasStockCover)');
|
||||
});
|
||||
|
||||
it('结案扣库必须软扣,不能因库存不足阻断置 90', () => {
|
||||
const start = svc.indexOf('const settleCtx = await db.query(');
|
||||
const end = svc.indexOf('const now = new Date();', start);
|
||||
const fn = svc.slice(start, end);
|
||||
expect(fn).toContain('options?.softInventorySettle === true || !hasInbound || marker === 45');
|
||||
expect(fn).toContain('fallbackToRequiredQty');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const svc = readFileSync(new URL('../src/services/orderWorkflowFulfillmentService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('finalize 请求级共享连接安全', () => {
|
||||
it('补分拣在 finalize 事务之前调用,core 内不再调用', () => {
|
||||
const wrapper = svc.slice(svc.indexOf('export async function finalizeOrderFulfillment'), svc.indexOf('export async function completeOrderWithoutDriverDelivery'));
|
||||
const core = svc.slice(svc.indexOf('async function finalizeOrderFulfillmentCore'), svc.indexOf('export async function finalizeOrderFulfillment'));
|
||||
expect(wrapper).toContain('completeOrderPickingForDirectDelivery');
|
||||
expect(wrapper.indexOf('completeOrderPickingForDirectDelivery')).toBeLessThan(wrapper.indexOf('withOrderExclusiveTxn'));
|
||||
expect(core).not.toContain('completeOrderPickingForDirectDelivery');
|
||||
expect(wrapper).toContain('SAVEPOINT 报 25P01');
|
||||
});
|
||||
});
|
||||
@@ -112,9 +112,12 @@ describe('第 3 层:面向人的配送查询', () => {
|
||||
it('每一个 orderVisibleToDeliverySql 落点都紧跟独立进货谓词', () => {
|
||||
const lines = queryServiceSource.split('\n');
|
||||
const sites = lines
|
||||
.map((l, i) => (l.includes("orderVisibleToDeliverySql('o')") ? i : -1))
|
||||
.map((l, i) => (
|
||||
l.includes("orderVisibleToDeliverySql('o')") ||
|
||||
l.includes("orderVisibleToDeliveryManagementSql('o')") ? i : -1
|
||||
))
|
||||
.filter((i) => i >= 0);
|
||||
// 列表 / 司机列表 / 司机待办计数 / 配送员统计 共 4 处
|
||||
// 管理列表(management 包装)/ 司机列表 / 司机待办计数 / 配送员统计 共 4 处
|
||||
expect(sites.length).toBeGreaterThanOrEqual(4);
|
||||
for (const i of sites) {
|
||||
const nearby = lines.slice(i, i + 3).join('\n');
|
||||
@@ -148,3 +151,25 @@ describe('判据本身:IS DISTINCT FROM 而非 <>(NULL 安全)', () => {
|
||||
expect(bad).toMatch(/o\.customer_code\s*<>/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('独立进货/散客录单不得有分拣任务', () => {
|
||||
const pickingSource = readFileSync(
|
||||
new URL('../src/services/pickingService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
it('createPickingTask 唯一入口同时拦散客录单与独立进货', () => {
|
||||
const body = functionBody(pickingSource, 'createPickingTask');
|
||||
expect(body).toContain('isRetailOrder(orderCode, pool)');
|
||||
expect(body).toContain('isOrderIndependentInbound(orderCode, pool)');
|
||||
});
|
||||
|
||||
it('独立进货守卫在取数据库连接前返回,避免池满自锁', () => {
|
||||
const body = functionBody(pickingSource, 'createPickingTask');
|
||||
const guardAt = body.indexOf('isOrderIndependentInbound(orderCode, pool)');
|
||||
const connectAt = body.indexOf('await pool.connect()');
|
||||
expect(guardAt).toBeGreaterThanOrEqual(0);
|
||||
expect(connectAt).toBeGreaterThanOrEqual(0);
|
||||
expect(guardAt).toBeLessThan(connectAt);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const svc = readFileSync(new URL('../src/services/inventoryOutboundService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('同单出库并发串行化', () => {
|
||||
it('BEGIN 后先取 advisory lock,再查 outbound/扣减', () => {
|
||||
const begin = svc.indexOf("if (ownsTxn) await client.query('BEGIN');");
|
||||
const lock = svc.indexOf("pg_advisory_xact_lock(hashtext('inventory_outbound:' || $1))", begin);
|
||||
const outbound = svc.indexOf('loadOutboundStateOnClient(client, code)', begin);
|
||||
expect(lock).toBeGreaterThan(begin);
|
||||
expect(outbound).toBeGreaterThan(lock);
|
||||
});
|
||||
|
||||
it('保留 orders FOR UPDATE 与逐 SKU 幂等,不新增唯一索引', () => {
|
||||
expect(svc).toContain('SELECT order_code, branch_code FROM orders WHERE order_code = $1 FOR UPDATE');
|
||||
expect(svc).toContain('deductLines = allLines.filter((line) => !outboundSkuSet.has(line.sku))');
|
||||
expect(svc).not.toContain('inventory_logs_order_batch_unique');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const svc = readFileSync(new URL('../src/services/inventoryOutboundService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('软扣允许部分扣减', () => {
|
||||
it('软扣传 allowPartial;可用>0 时先扣可用,不因缺口提前抛错', () => {
|
||||
expect(svc).toContain('allowPartial?: boolean');
|
||||
expect(svc).toContain('allowPartial: softInventory');
|
||||
expect(svc).toContain('!input.allowPartial || claimable <= 1e-9');
|
||||
});
|
||||
|
||||
it('部分扣减也标记 deductedAny,尾差记 softSkipped;硬扣仍走原错误', () => {
|
||||
expect(svc).toContain('deductedAny = true;');
|
||||
expect(svc).toContain("reason: softSkipped.length ? 'partial_soft_skip'");
|
||||
expect(svc).toContain("if (softInventory && (error?.code === 'inventory_outbound'");
|
||||
});
|
||||
});
|
||||
@@ -326,10 +326,11 @@ describe('navBadgeService', () => {
|
||||
scope: 'today',
|
||||
});
|
||||
expect(delivery.delivery).toBe(9);
|
||||
const deliverySql = mocks.query.mock.calls.map(([s]) => String(s)).find((s) => s.includes('LEFT JOIN delivery_tasks'));
|
||||
expect(deliverySql).toContain('COALESCE(dt.task_status, 10) = 10');
|
||||
const deliverySql = mocks.query.mock.calls.map(([s]) => String(s)).find((s) => s.includes('INNER JOIN delivery_tasks'));
|
||||
expect(deliverySql).toContain('COALESCE(dt.task_status, 10) < 30');
|
||||
expect(deliverySql).toContain('COALESCE(o.order_status, 0) >= 50');
|
||||
expect(deliverySql).toContain('dt.person_code = $2');
|
||||
expect(deliverySql).toContain('dt.branch_code = $1 OR dt.branch_code IS NULL');
|
||||
expect(deliverySql).toContain('delivery_date');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
|
||||
const manage = read('../src/services/orderManageItemsService.ts');
|
||||
const fulfillment = read('../src/services/orderWorkflowFulfillmentService.ts');
|
||||
const picking = read('../src/services/pickingService.ts');
|
||||
const submit = read('../src/services/customerOrderSubmitService.ts');
|
||||
const visibility = read('../src/services/supplierSkipInbound.ts');
|
||||
const queryService = read('../src/services/deliveryTaskQueryService.ts');
|
||||
const nav = read('../src/services/navBadgeService.ts');
|
||||
|
||||
function body(source: string, name: string): string {
|
||||
const start = source.indexOf(`export async function ${name}`);
|
||||
expect(start, name).toBeGreaterThanOrEqual(0);
|
||||
const rest = source.slice(start + 1);
|
||||
const next = rest.search(/export (async )?function /);
|
||||
return next >= 0 ? source.slice(start, start + 1 + next) : source.slice(start);
|
||||
}
|
||||
|
||||
describe('T2 改单同步早期配送/分拣', () => {
|
||||
it('AC-07/08/09:syncOrderManageItems COMMIT 后同步分拣行与配送单', () => {
|
||||
expect(manage).toContain('syncOpenPickingItemsForOrder(orderCode, order.branch_code || null)');
|
||||
expect(manage).toContain('syncDeliveryTaskForOrder(orderCode, order.branch_code || null)');
|
||||
const commitAt = manage.indexOf("await client.query('COMMIT');");
|
||||
expect(manage.indexOf('syncOpenPickingItemsForOrder(orderCode')).toBeGreaterThan(commitAt);
|
||||
expect(manage.indexOf('syncDeliveryTaskForOrder(orderCode')).toBeGreaterThan(commitAt);
|
||||
const sync = body(picking, 'syncOpenPickingItemsForOrder');
|
||||
expect(sync).toContain('pick_status < 40');
|
||||
expect(sync).toContain('pick_status < 40');
|
||||
expect(sync).toContain('insertPickingItems(pool, pickCode, missing, branch)');
|
||||
expect(sync).toContain('includeExtraDish: true');
|
||||
expect(sync).toContain('picked_qty');
|
||||
expect(sync).toContain('loading_photos');
|
||||
expect(sync).toContain('outbound_photos');
|
||||
expect(sync).not.toContain('INSERT INTO picking_tasks');
|
||||
});
|
||||
|
||||
it('AC-10/11:全直送/待取货等 void 未开始任务;恢复时复用原行清 void', () => {
|
||||
const sync = body(fulfillment, 'syncDeliveryTaskForOrder');
|
||||
for (const guard of ['isRetailOrder', 'isOrderOnlyDirectDelivery', 'isOrderIndependentInbound', 'isSelfPickupOrder', 'isDirectToDeliveryEnabled', 'isOrderFullySkipInbound']) {
|
||||
expect(sync, guard).toContain(guard);
|
||||
}
|
||||
expect(sync).toContain('status >= 20 || task.loading_completed_at || task.start_time');
|
||||
expect(sync).toContain("SET voided_at = NOW(), void_reason = 'not_requires_delivery'");
|
||||
expect(sync).toContain('SET voided_at = NULL, void_reason = NULL');
|
||||
expect(sync).toContain('if (task?.voided_at)');
|
||||
expect(sync).not.toContain('INSERT INTO delivery_tasks');
|
||||
expect(visibility).toContain('dt_void.voided_at IS NOT NULL');
|
||||
expect(queryService).toContain('dt.voided_at IS NULL');
|
||||
expect(nav).toContain('dt.voided_at IS NULL');
|
||||
const advance = body(fulfillment, 'tryAdvanceOrderToDelivering');
|
||||
expect(advance).toContain('voided_delivery_task');
|
||||
expect(advance).toContain('person_code, branch_code, voided_at');
|
||||
|
||||
const ensure = body(fulfillment, 'ensureDeliveryTaskForOrder');
|
||||
expect(ensure).toContain('WHERE order_code = $1 AND voided_at IS NULL LIMIT 1');
|
||||
expect(ensure).toContain('SET voided_at = NULL, void_reason = NULL');
|
||||
expect(ensure).toContain('if (row.voided_at && !started)');
|
||||
});
|
||||
|
||||
it('AC-29:主系统导入走共用 submit,自动获得两个 ensure', () => {
|
||||
const importSrc = read('../src/services/mainSystemOrderImport.ts');
|
||||
expect(importSrc).toContain('submitMobileCustomerOrder');
|
||||
expect(submit).toContain('ensurePickingTaskOnOrderSubmit');
|
||||
expect(submit).toContain('ensureEarlyDeliveryTaskForOrder');
|
||||
});
|
||||
|
||||
it('只同步开放分拣任务;不引入 T3 发车/核货改动', () => {
|
||||
const sync = body(picking, 'syncOpenPickingItemsForOrder');
|
||||
expect(sync).toContain('Number(order.order_status) >= 50');
|
||||
expect(sync).not.toContain('confirmDeliveryLoadingItem');
|
||||
const loading = read('../src/services/deliveryLoadingService.ts');
|
||||
expect(loading).not.toContain('syncDeliveryTaskForOrder');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const migration = readFileSync(
|
||||
new URL('../../migrations/20261086_pending_inspections_name_unique.sql', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
const inspection = readFileSync(
|
||||
new URL('../src/services/inspectionRejectFulfillmentService.ts', import.meta.url),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
describe('待验收单并发防重', () => {
|
||||
it('迁移先清历史 pending 重复,再建唯一索引(不删已入库)', () => {
|
||||
expect(migration).toContain('ROW_NUMBER() OVER');
|
||||
expect(migration).toContain('actual_qty, 0) = 0');
|
||||
expect(migration).toContain('inspections_pending_order_supplier_key_uidx');
|
||||
expect(migration).toContain('WHERE inspection_time IS NULL');
|
||||
expect(migration).toContain('__NAME__');
|
||||
expect(migration).toContain('LOWER(TRIM(item_name))');
|
||||
});
|
||||
|
||||
it('并发插入被唯一索引拦截时返回 false,不报错', () => {
|
||||
expect(inspection).toContain('ON CONFLICT DO NOTHING');
|
||||
expect(inspection).toContain("COALESCE(NULLIF(TRIM(sku_code), ''), '') = ''");
|
||||
expect(inspection).toContain('LOWER(TRIM(item_name))');
|
||||
expect(inspection).toContain("error?.code === '23505'");
|
||||
expect(inspection).toContain('return false;');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const picking = readFileSync(new URL('../src/services/pickingService.ts', import.meta.url), 'utf8');
|
||||
const fulfillment = readFileSync(new URL('../src/services/orderWorkflowFulfillmentService.ts', import.meta.url), 'utf8');
|
||||
|
||||
function body(source: string, name: string, next: string): string {
|
||||
const start = source.indexOf(name);
|
||||
const end = source.indexOf(next, start + 1);
|
||||
return start >= 0 && end > start ? source.slice(start, end) : '';
|
||||
}
|
||||
|
||||
describe('T4 分拣完成自动补上游', () => {
|
||||
it('补备货/采购并写 delivery_loading_backfill_logs 责任记录', () => {
|
||||
const fn = body(picking, 'async function backfillPendingFulfillmentForPicking', 'async function isNoAutoDeliveryOrder');
|
||||
expect(fn).toContain('UPDATE supplier_preparations');
|
||||
expect(fn).toContain('updatePurchaseOrderStatus');
|
||||
expect(fn).toContain('delivery_loading_backfill_logs');
|
||||
expect(fn).toContain("'prep'");
|
||||
expect(fn).toContain("'purchase'");
|
||||
});
|
||||
|
||||
it('分拣完成只补备货/采购成本,不再自动入库;30 只补成本', () => {
|
||||
const fn = body(picking, 'async function autoInboundFromPickingBeforeComplete', 'async function forceOrderReadyForDeliveryAfterPicking');
|
||||
expect(fn).toContain('backfillPendingFulfillmentForPicking');
|
||||
expect(fn).toContain('if (status >= 40) return');
|
||||
expect(fn).toContain('finalizeAutoCompletedSupplierPreparations');
|
||||
expect(fn).not.toContain('ensureInspectionsForOrder');
|
||||
expect(fn).not.toContain('submitInspectionCompliance');
|
||||
expect(fulfillment).toContain('picking_skipped_on_30_departure');
|
||||
});
|
||||
|
||||
it('待取货/全直送/自提/独立进货/散客跳过自动入库与配送', () => {
|
||||
const fn = body(picking, 'async function isNoAutoDeliveryOrder', 'async function autoInboundFromPickingBeforeComplete');
|
||||
for (const guard of ['isRetailOrder', 'isOrderOnlyDirectDelivery', 'isOrderIndependentInbound', 'isSelfPickupOrder', 'isOrderFullySkipInbound']) {
|
||||
expect(fn, guard).toContain(guard);
|
||||
}
|
||||
});
|
||||
|
||||
it('分拣完成 30/40/45 强制到 50;列表加载修复历史卡单', () => {
|
||||
const force = body(picking, 'async function forceOrderReadyForDeliveryAfterPicking', 'export async function recoverOrdersReadyForDeliveryAfterPicking');
|
||||
expect(force).toContain('order_status = 50');
|
||||
expect(force).toContain('ensureDeliveryTaskForOrder');
|
||||
expect(force).toContain('countUnfinishedPickingTasks');
|
||||
expect(force).toContain('countWarehouseItemsMissingPicking');
|
||||
expect(picking).toContain('recoverOrdersReadyForDeliveryAfterPicking(ctx)');
|
||||
expect(picking).toContain('await forceOrderReadyForDeliveryAfterPicking(');
|
||||
});
|
||||
|
||||
it('不引入“未入库禁止完成分拣”闸', () => {
|
||||
expect(picking).not.toContain('尚未完成入库验收,暂不能确认分拣完成');
|
||||
expect(picking).not.toContain('assertPickingTaskReadyForCompletion');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const picking = readFileSync(new URL('../src/services/pickingService.ts', import.meta.url), 'utf8');
|
||||
|
||||
describe('分拣任务并发创建防重', () => {
|
||||
it('createPickingTask 在事务开头按订单加 advisory lock,再查 open task', () => {
|
||||
const lock = picking.indexOf("pg_advisory_xact_lock(hashtext('picking_task:' || $1))");
|
||||
const orderQuery = picking.indexOf('const orderResult = await client.query(', lock);
|
||||
expect(lock).toBeGreaterThan(-1);
|
||||
expect(orderQuery).toBeGreaterThan(lock);
|
||||
});
|
||||
|
||||
it('保留 category/sku/zone 拆单分支,不改成强制单任务', () => {
|
||||
expect(picking).toContain("mode === 'category'");
|
||||
expect(picking).toContain("mode === 'sku'");
|
||||
expect(picking).toContain("mode === 'zone'");
|
||||
expect(picking).toContain('createOrderScopeTask(');
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,16 @@ export function acquireBodyScrollLock() {
|
||||
savedOverflow = document.body.style.overflow;
|
||||
savedPaddingRight = document.body.style.paddingRight;
|
||||
document.body.style.overflow = 'hidden';
|
||||
if (gutter > 0) {
|
||||
/**
|
||||
* 全站 html 已设置 `scrollbar-gutter: stable`,滚动条槽位已经预留。
|
||||
* 这里再补 paddingRight 会重复补偿,打开/关闭弹窗时整页横移,表现为屏幕闪一下。
|
||||
* 仅在浏览器不支持 scrollbar-gutter 时才回退到 padding 补偿。
|
||||
*/
|
||||
const supportsGutter =
|
||||
typeof CSS !== 'undefined' && typeof CSS.supports === 'function'
|
||||
? CSS.supports('scrollbar-gutter', 'stable')
|
||||
: false;
|
||||
if (gutter > 0 && !supportsGutter) {
|
||||
document.body.style.paddingRight = `${gutter}px`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -431,6 +431,7 @@ export const inventory: MessageDict = {
|
||||
'batchReport.saved': 'Report saved',
|
||||
'batchReport.saveFail': 'Failed to save report',
|
||||
'batchReport.present': 'Yes',
|
||||
'batchReport.missingShort': 'Missing',
|
||||
'batchReport.missing': 'Missing batch report',
|
||||
'batchReport.manualPick': 'Select batch manually',
|
||||
'batchReport.manualHide': 'Hide',
|
||||
|
||||
@@ -438,6 +438,7 @@ export const inventory: MessageDict = {
|
||||
'batchReport.saved': 'Laporan disimpan',
|
||||
'batchReport.saveFail': 'Gagal menyimpan laporan',
|
||||
'batchReport.present': 'Ada',
|
||||
'batchReport.missingShort': 'Kurang',
|
||||
'batchReport.missing': 'Tidak ada laporan batch',
|
||||
'batchReport.manualPick': 'Pilih batch manual',
|
||||
'batchReport.manualHide': 'Tutup',
|
||||
|
||||
@@ -430,6 +430,7 @@ export const inventory: MessageDict = {
|
||||
'batchReport.saved': '报告已保存',
|
||||
'batchReport.saveFail': '保存报告失败',
|
||||
'batchReport.present': '已有',
|
||||
'batchReport.missingShort': '缺报告',
|
||||
'batchReport.missing': '缺少批次报告',
|
||||
'batchReport.manualPick': '手动选择批次',
|
||||
'batchReport.manualHide': '收起',
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const page = readFileSync(new URL('./AfterSalesManagement.tsx', import.meta.url), 'utf8');
|
||||
|
||||
describe('售后详情/处理/驳回弹窗', () => {
|
||||
it('无自定义 motion/AnimatePresence,使用 body scroll lock', () => {
|
||||
expect(page).not.toContain('framer-motion');
|
||||
expect(page).not.toContain('<motion.');
|
||||
expect(page).not.toContain('AnimatePresence');
|
||||
expect(page).toContain('useBodyScrollLock(showDetailModal || showHandleModal || showRejectModal)');
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
applyAfterSalesCopilotFieldPatches,
|
||||
type AfterSalesCopilotState,
|
||||
} from './copilotAfterSalesPageContract';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import { useBodyScrollLock } from '../../hooks/useBodyScrollLock';
|
||||
import { notify } from '../../utils/notify';
|
||||
import { confirmDialog } from '../../utils/confirmDialog';
|
||||
import { SearchableSelect } from '../../components/ui/SearchableSelect';
|
||||
@@ -240,6 +240,7 @@ export const AfterSalesManagement: React.FC = () => {
|
||||
const [orderContextLoading, setOrderContextLoading] = useState(false);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [showRejectModal, setShowRejectModal] = useState(false);
|
||||
useBodyScrollLock(showDetailModal || showHandleModal || showRejectModal);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const creatingRef = useRef(false);
|
||||
const [customerOptions, setCustomerOptions] = useState<Array<{ value: string; label: string }>>([]);
|
||||
@@ -1019,18 +1020,11 @@ export const AfterSalesManagement: React.FC = () => {
|
||||
</div>
|
||||
|
||||
{/* Detail Modal */}
|
||||
<AnimatePresence>
|
||||
{showDetailModal && selectedItem && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
<div
|
||||
className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-2xl w-full max-h-[90vh] flex flex-col"
|
||||
>
|
||||
<div className="flex items-center justify-between px-6 pt-6 pb-4 border-b border-gray-100 dark:border-gray-700">
|
||||
@@ -1178,24 +1172,16 @@ export const AfterSalesManagement: React.FC = () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Handle Modal */}
|
||||
<AnimatePresence>
|
||||
{showHandleModal && selectedItem && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
<div
|
||||
className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-lg w-full p-6 max-h-[90vh] overflow-y-auto"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
@@ -1291,10 +1277,9 @@ export const AfterSalesManagement: React.FC = () => {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Create Modal */}
|
||||
{showCreateModal && (
|
||||
@@ -1432,18 +1417,11 @@ export const AfterSalesManagement: React.FC = () => {
|
||||
</DialogOverlay>
|
||||
)}
|
||||
{/* Reject Modal */}
|
||||
<AnimatePresence>
|
||||
{showRejectModal && selectedItem && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
<div
|
||||
className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl max-w-md w-full p-6"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
@@ -1469,10 +1447,9 @@ export const AfterSalesManagement: React.FC = () => {
|
||||
{t('afterSales.rejectModal.confirm')}
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1042,12 +1042,13 @@ export const CustomerManagement: React.FC = () => {
|
||||
* · 只影响**之后新建的单**(录单时快照到 `orders.self_pickup`)⇒ 不会动到已有订单;
|
||||
* · 在途锁:保存期间禁用该行开关,防重复点。
|
||||
*/
|
||||
const [selfPickupSavingCode, setSelfPickupSavingCode] = useState<string | null>(null);
|
||||
/** 行级保存集合:允许并行切换多个客户,不能用一个全局标记静默拦住其它行 */
|
||||
const [selfPickupSavingCodes, setSelfPickupSavingCodes] = useState<Set<string>>(() => new Set());
|
||||
const canToggleSelfPickup = canEdit && hasRole(['admin', 'super_admin']);
|
||||
const handleToggleSelfPickup = async (customer: Customer, next: boolean) => {
|
||||
const code = String(customer.customer_code || '').trim();
|
||||
if (!code || selfPickupSavingCode) return;
|
||||
setSelfPickupSavingCode(code);
|
||||
if (!code || selfPickupSavingCodes.has(code)) return;
|
||||
setSelfPickupSavingCodes((prev) => new Set(prev).add(code));
|
||||
try {
|
||||
// 走领域接口(禁止新增通用网关 /api/data 写入点,见 gatewayWriteBoundary 守卫)
|
||||
await setCustomerSelfPickupApi(code, next);
|
||||
@@ -1058,7 +1059,11 @@ export const CustomerManagement: React.FC = () => {
|
||||
} catch (error: any) {
|
||||
notify.error(error?.message || t('common.save'));
|
||||
} finally {
|
||||
setSelfPickupSavingCode(null);
|
||||
setSelfPickupSavingCodes((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(code);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1986,7 +1991,7 @@ export const CustomerManagement: React.FC = () => {
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-slate-300 disabled:opacity-50"
|
||||
checked={c.is_self_pickup === true}
|
||||
disabled={!canToggleSelfPickup || selfPickupSavingCode === c.customer_code}
|
||||
disabled={!canToggleSelfPickup || selfPickupSavingCodes.has(c.customer_code)}
|
||||
onChange={(e) => void handleToggleSelfPickup(c, e.target.checked)}
|
||||
/>
|
||||
<span className="app-foreground-muted">
|
||||
|
||||
@@ -1413,8 +1413,8 @@ export const InventoryManagement: React.FC = () => {
|
||||
|
||||
{/* Inventory Tab */}
|
||||
{activeTab === 'inventory' && (
|
||||
<div className="app-surface app-border rounded-lg border overflow-x-auto shadow-sm">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<div className="app-surface app-border rounded-lg border overflow-x-hidden shadow-sm">
|
||||
<table className="w-full table-fixed divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
{inventoryOrderedColumns.map((col) => {
|
||||
@@ -1431,7 +1431,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
<th
|
||||
key={col.id}
|
||||
{...headerProps}
|
||||
className={`px-6 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider ${
|
||||
className={`px-2 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider ${
|
||||
sortable ? 'cursor-pointer select-none' : ''
|
||||
}`}
|
||||
onClick={
|
||||
@@ -1495,7 +1495,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
switch (col.id) {
|
||||
case 'product':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4">
|
||||
<td key={col.id} className="px-2 py-3">
|
||||
<p
|
||||
className={`app-product-name ${
|
||||
reservationGap || missingBatchReport
|
||||
@@ -1506,7 +1506,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
{item.sku_name}
|
||||
</p>
|
||||
{canInlineEditArchiveFields ? (
|
||||
<div className="mt-1 w-[9.5rem]">
|
||||
<div className="mt-1 w-full min-w-0">
|
||||
{/* 分类可就地切换(商品档案级,影响该 SKU 所有批次) */}
|
||||
<InventoryInlineSelectCell
|
||||
value={item.category_code || ''}
|
||||
@@ -1529,7 +1529,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
);
|
||||
case 'batch':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
<Link
|
||||
to={productTracePath(item.batch_no)}
|
||||
className="text-emerald-700 hover:underline font-mono text-xs"
|
||||
@@ -1549,11 +1549,11 @@ export const InventoryManagement: React.FC = () => {
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-red-600 dark:text-red-400 font-medium">
|
||||
{t('inventory.batchReport.missing')}
|
||||
{t('inventory.batchReport.missingShort')}
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm">
|
||||
<td key={col.id} className="px-2 py-3 text-sm">
|
||||
{/* 2026-10-23 开发者:「报告在外面也能删除 上传」⇒ 点该格直接管这一批的报告 */}
|
||||
{canAdjustInventory ? (
|
||||
<button
|
||||
@@ -1572,7 +1572,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
}
|
||||
case 'available':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{canAdjustInventory ? (
|
||||
<InventoryInlineCell
|
||||
value={item.available_qty == null ? '' : String(item.available_qty)}
|
||||
@@ -1601,7 +1601,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
return (
|
||||
<td
|
||||
key={col.id}
|
||||
className="px-6 py-4 text-sm text-gray-600"
|
||||
className="px-2 py-3 text-sm text-gray-600"
|
||||
title={
|
||||
peers
|
||||
? t('inventory.reservedOrdersTip', { peers, more })
|
||||
@@ -1633,7 +1633,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
return (
|
||||
<td
|
||||
key={col.id}
|
||||
className="px-6 py-4 text-sm text-gray-600"
|
||||
className="px-2 py-3 text-sm text-gray-600"
|
||||
title={t('inventory.claimableTitle')}
|
||||
>
|
||||
{formatQty(val)}
|
||||
@@ -1649,7 +1649,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
// 列表内直接改(2026-10-23):成本改动仍由服务端重算未结算订单
|
||||
if (canAdjustInventory) {
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm">
|
||||
<td key={col.id} className="px-2 py-3 text-sm">
|
||||
<InventoryInlineCell
|
||||
value={item.cost_price == null ? '' : String(item.cost_price)}
|
||||
inputKind="decimal"
|
||||
@@ -1663,7 +1663,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
}
|
||||
if (missingCost) {
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm">
|
||||
<td key={col.id} className="px-2 py-3 text-sm">
|
||||
<span className="text-red-600 dark:text-red-400 font-medium">
|
||||
{t('inventory.col.costMissing')}
|
||||
</span>
|
||||
@@ -1671,7 +1671,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{money != null ? `¥${money}` : '-'}
|
||||
</td>
|
||||
);
|
||||
@@ -1682,20 +1682,20 @@ export const InventoryManagement: React.FC = () => {
|
||||
(Number(item.available_qty) || 0) * (Number(item.cost_price) || 0);
|
||||
const money = formatMoney(batchValue);
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{money != null ? `¥${money}` : '-'}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
case 'prodDate':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{item.production_date ? String(item.production_date).slice(0, 10) : '-'}
|
||||
</td>
|
||||
);
|
||||
case 'expiry':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4">
|
||||
<td key={col.id} className="px-2 py-3">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className={`inline-flex w-fit px-2 py-1 text-xs font-medium rounded-full ${expiryStatus.color}`}>
|
||||
{expiryStatus.text}
|
||||
@@ -1710,7 +1710,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
);
|
||||
case 'zone':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{canAdjustInventory ? (
|
||||
<InventoryInlineSelectCell
|
||||
value={item.storage_zone || ''}
|
||||
@@ -1725,7 +1725,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
);
|
||||
case 'spec':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{canInlineEditArchiveFields ? (
|
||||
<InventoryInlineCell
|
||||
value={item.spec || ''}
|
||||
@@ -1739,7 +1739,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
);
|
||||
case 'unit':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{canInlineEditArchiveFields ? (
|
||||
<InventoryInlineSelectCell
|
||||
value={item.unit || ''}
|
||||
@@ -1754,13 +1754,13 @@ export const InventoryManagement: React.FC = () => {
|
||||
);
|
||||
case 'supplier':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{item.supplier_name || '-'}
|
||||
</td>
|
||||
);
|
||||
case 'actions':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4">
|
||||
<td key={col.id} className="px-2 py-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
@@ -1800,8 +1800,8 @@ export const InventoryManagement: React.FC = () => {
|
||||
<p className="text-sm text-gray-500">
|
||||
{t('inventory.logs.hint')}
|
||||
</p>
|
||||
<div className="app-surface app-border rounded-lg border overflow-x-auto shadow-sm">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<div className="app-surface app-border rounded-lg border overflow-x-hidden shadow-sm">
|
||||
<table className="w-full table-fixed divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
{logOrderedColumns.map((col) => {
|
||||
@@ -1811,7 +1811,7 @@ export const InventoryManagement: React.FC = () => {
|
||||
<th
|
||||
key={col.id}
|
||||
{...headerProps}
|
||||
className={`px-6 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider ${
|
||||
className={`px-2 py-3 text-left text-xs font-medium text-gray-600 uppercase tracking-wider ${
|
||||
sortable ? 'cursor-pointer select-none' : ''
|
||||
}`}
|
||||
onClick={
|
||||
@@ -1842,19 +1842,19 @@ export const InventoryManagement: React.FC = () => {
|
||||
switch (col.id) {
|
||||
case 'time':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{new Date(log.created_at).toLocaleString()}
|
||||
</td>
|
||||
);
|
||||
case 'product':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4">
|
||||
<td key={col.id} className="px-2 py-3">
|
||||
<p className="app-product-name">{log.sku_name}</p>
|
||||
</td>
|
||||
);
|
||||
case 'op_type':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4">
|
||||
<td key={col.id} className="px-2 py-3">
|
||||
<span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getOperationTypeColor(log.operation_type)}`}>
|
||||
{getOperationTypeText(log.operation_type)}
|
||||
</span>
|
||||
@@ -1863,26 +1863,26 @@ export const InventoryManagement: React.FC = () => {
|
||||
case 'qty_change': {
|
||||
const qtyDisplay = formatLogQtyChange(log.operation_type, log.quantity);
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm">
|
||||
<td key={col.id} className="px-2 py-3 text-sm">
|
||||
<span className={qtyDisplay.className}>{qtyDisplay.text}</span>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
case 'stock_change':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{log.before_qty} → {log.after_qty}
|
||||
</td>
|
||||
);
|
||||
case 'order':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{log.related_order_code || '-'}
|
||||
</td>
|
||||
);
|
||||
case 'remark':
|
||||
return (
|
||||
<td key={col.id} className="px-6 py-4 text-sm text-gray-600">
|
||||
<td key={col.id} className="px-2 py-3 text-sm text-gray-600">
|
||||
{log.remark || '-'}
|
||||
</td>
|
||||
);
|
||||
@@ -2022,8 +2022,8 @@ export const InventoryManagement: React.FC = () => {
|
||||
<option value="processing_return">{t('inventory.holding.src.processingReturn')}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="app-surface app-border rounded-lg border overflow-x-auto shadow-sm">
|
||||
<table className="min-w-full divide-y divide-gray-200 text-sm">
|
||||
<div className="app-surface app-border rounded-lg border overflow-x-hidden shadow-sm">
|
||||
<table className="w-full table-fixed divide-y divide-gray-200 text-sm">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-2 text-left">{t('inventory.holding.col.time')}</th>
|
||||
|
||||
@@ -750,7 +750,8 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
|
||||
const [savingPurchase, setSavingPurchase] = useState(false);
|
||||
const [assigningPurchase, setAssigningPurchase] = useState<string | null>(null);
|
||||
/** 直接完成:行级防重复 + 一键全部完成进行中(2026-10-22) */
|
||||
const [completingPurchaseCode, setCompletingPurchaseCode] = useState<string | null>(null);
|
||||
/** 行级完成中的 purchase_code 集合:允许多行并发完成,不能用一个全局标记静默拦截其它行 */
|
||||
const [completingPurchaseCodes, setCompletingPurchaseCodes] = useState<Set<string>>(() => new Set());
|
||||
const [completingAll, setCompletingAll] = useState(false);
|
||||
const [voidingCode, setVoidingCode] = useState<string | null>(null);
|
||||
const [completingSpiCode, setCompletingSpiCode] = useState<string | null>(null);
|
||||
@@ -2799,7 +2800,7 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
|
||||
};
|
||||
|
||||
const handleCompleteRow = async (purchase: PurchaseOrder) => {
|
||||
if (!canCompletePurchase(purchase) || completingPurchaseCode) return;
|
||||
if (!canCompletePurchase(purchase) || completingPurchaseCodes.has(purchase.purchase_code)) return;
|
||||
if (needsProductSetup(purchase)) {
|
||||
handleEditPurchase(purchase);
|
||||
return;
|
||||
@@ -2815,7 +2816,11 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
|
||||
notify.error(t('purchase.notify.costMustGt0'));
|
||||
return;
|
||||
}
|
||||
setCompletingPurchaseCode(purchase.purchase_code);
|
||||
setCompletingPurchaseCodes((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(purchase.purchase_code);
|
||||
return next;
|
||||
});
|
||||
try {
|
||||
await completePurchaseOrderApi({
|
||||
purchase_code: purchase.purchase_code,
|
||||
@@ -2828,7 +2833,11 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
|
||||
} catch (error: unknown) {
|
||||
notify(error instanceof Error ? error.message : t('purchase.notify.completeFail'));
|
||||
} finally {
|
||||
setCompletingPurchaseCode('');
|
||||
setCompletingPurchaseCodes((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(purchase.purchase_code);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3706,7 +3715,7 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-emerald-700 hover:underline disabled:opacity-50"
|
||||
disabled={completingPurchaseCode === singlePo.purchase_code || completingAll}
|
||||
disabled={completingPurchaseCodes.has(singlePo.purchase_code) || completingAll}
|
||||
onClick={() => void handleCompleteRow(singlePo)}
|
||||
>
|
||||
{t('purchase.complete')}
|
||||
@@ -3992,7 +4001,7 @@ export const PurchaseManagement: React.FC<PurchaseManagementProps> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-emerald-700 hover:underline disabled:opacity-50"
|
||||
disabled={completingPurchaseCode === p.purchase_code || completingAll}
|
||||
disabled={completingPurchaseCodes.has(p.purchase_code) || completingAll}
|
||||
onClick={() => void handleCompleteRow(p)}
|
||||
>
|
||||
{t('purchase.complete')}
|
||||
|
||||
Reference in New Issue
Block a user