来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
322 lines
12 KiB
TypeScript
322 lines
12 KiB
TypeScript
import { PoolClient } from 'pg';
|
|
import { pool } from '../db';
|
|
import { createSupplierInspectionIfNeeded } from './inspectionRejectFulfillmentService';
|
|
import {
|
|
ensureSkuAndBarcodeForInspection,
|
|
ensureSkuForPickingOutbound,
|
|
} from './skuProvisioningService';
|
|
import { findExistingPurchaseInboundBatch, isMergeGuestOrderSku } from './orderInspectionStateService';
|
|
import { isPassThroughSku } from './stockModeService';
|
|
import { isIndependentInboundDetails } from './independentInboundService';
|
|
import { isWarehouseProcessingFinishedSku } from './processingDemandSheetService';
|
|
import { WAREHOUSE_FINISHED_LEDGER_SKIP_REMARK } from './inventoryOutboundService';
|
|
|
|
function trimText(value: unknown): string {
|
|
return String(value || '').trim();
|
|
}
|
|
|
|
function newBatchNo() {
|
|
return `IN${Date.now().toString().slice(-9)}${Math.random().toString(36).slice(2, 6).toUpperCase()}`;
|
|
}
|
|
|
|
function readPurchaseCodesFromDetailsLocal(details: unknown): string[] {
|
|
if (!details || typeof details !== 'object') return [];
|
|
const d = details as Record<string, unknown>;
|
|
const codes: string[] = [];
|
|
const one = String(d.purchase_code || '').trim();
|
|
if (one) codes.push(one);
|
|
if (Array.isArray(d.purchase_codes)) {
|
|
for (const c of d.purchase_codes) {
|
|
const t = String(c || '').trim();
|
|
if (t) codes.push(t);
|
|
}
|
|
}
|
|
return [...new Set(codes)];
|
|
}
|
|
|
|
async function passPendingInspectionForRepair(client: PoolClient, inspectionId: string) {
|
|
const rowResult = await client.query(
|
|
`SELECT i.id, i.order_code, i.sku_code, i.supplier_code, i.prepare_qty, i.purchase_price,
|
|
i.branch_code, i.item_name, i.processing_details, i.inspection_time
|
|
FROM inspections i
|
|
WHERE i.id = $1
|
|
FOR UPDATE`,
|
|
[inspectionId]
|
|
);
|
|
const row = rowResult.rows[0];
|
|
if (!row || row.inspection_time) return { skipped: true, reason: 'already_inspected' };
|
|
|
|
const actualQty = Number(row.prepare_qty) || 0;
|
|
if (actualQty <= 0) return { skipped: true, reason: 'zero_qty' };
|
|
|
|
const purchaseCodes = new Set(readPurchaseCodesFromDetailsLocal(row.processing_details));
|
|
if (row.order_code && row.sku_code) {
|
|
const linkedPo = await client.query(
|
|
`SELECT DISTINCT f.purchase_code
|
|
FROM order_item_fulfillments f
|
|
JOIN order_items oi ON oi.id = f.order_item_id
|
|
WHERE oi.order_code = $1
|
|
AND oi.sku_code IS NOT DISTINCT FROM $2
|
|
AND f.purchase_code IS NOT NULL`,
|
|
[row.order_code, row.sku_code]
|
|
);
|
|
for (const r of linkedPo.rows) {
|
|
const code = String(r.purchase_code || '').trim();
|
|
if (code) purchaseCodes.add(code);
|
|
}
|
|
}
|
|
const existingBatch = await findExistingPurchaseInboundBatch(
|
|
{
|
|
purchaseCodes: [...purchaseCodes],
|
|
skuCode: row.sku_code,
|
|
excludeInspectionId: inspectionId,
|
|
},
|
|
client
|
|
);
|
|
const isGuest =
|
|
Boolean(row.order_code && row.sku_code) &&
|
|
(await isMergeGuestOrderSku(String(row.order_code), String(row.sku_code), client));
|
|
if (isGuest && !existingBatch) {
|
|
return { skipped: true, reason: 'merge_guest_await_host_inbound' };
|
|
}
|
|
const skipInventory = Boolean(isGuest && existingBatch);
|
|
const batchNo = skipInventory ? String(existingBatch) : newBatchNo();
|
|
const passThrough = await isPassThroughSku(
|
|
{ skuCode: row.sku_code, branchCode: row.branch_code },
|
|
client
|
|
);
|
|
const independentInbound = isIndependentInboundDetails(row.processing_details);
|
|
const warehouseFinishedNoStock =
|
|
!independentInbound &&
|
|
(await isWarehouseProcessingFinishedSku(row.order_code, row.sku_code, client));
|
|
const writeStockLedger = !skipInventory && !passThrough && !warehouseFinishedNoStock;
|
|
|
|
await client.query(
|
|
`UPDATE inspections
|
|
SET actual_qty = $2, quality_rating = 'A', loss_qty = 0, compliance_status = 40,
|
|
inspection_time = NOW(), inbound_batch_no = $3
|
|
WHERE id = $1`,
|
|
[inspectionId, actualQty, batchNo]
|
|
);
|
|
|
|
const skuProvision = await ensureSkuAndBarcodeForInspection(client, {
|
|
inspectionId,
|
|
orderCode: row.order_code,
|
|
skuCode: row.sku_code,
|
|
itemName: row.item_name,
|
|
supplierCode: row.supplier_code,
|
|
processingDetails: row.processing_details,
|
|
branchCode: row.branch_code,
|
|
purchasePrice: row.purchase_price,
|
|
});
|
|
const inboundSku = trimText(skuProvision?.skuCode || row.sku_code);
|
|
if (!inboundSku) {
|
|
throw new Error(`${row.item_name || inspectionId} 无法生成 SKU,验收入库修复失败`);
|
|
}
|
|
|
|
if (writeStockLedger) {
|
|
// 订单已完结后的迟到入库修复:不形成可用库存
|
|
let completedOrder = false;
|
|
if (row.order_code) {
|
|
const orderSt = await client.query(
|
|
`SELECT order_status FROM orders WHERE order_code = $1 LIMIT 1`,
|
|
[row.order_code]
|
|
);
|
|
completedOrder = Number(orderSt.rows[0]?.order_status) >= 90;
|
|
}
|
|
const ledgerAvailableQty = completedOrder ? 0 : actualQty;
|
|
await client.query(
|
|
`INSERT INTO inventory (batch_no, sku_code, quantity, available_qty, supplier_code, cost_price, status, branch_code, production_date)
|
|
VALUES ($1, $2, $3, $4, $5, $6, 10, $7, (NOW() AT TIME ZONE 'Asia/Shanghai')::date)`,
|
|
[
|
|
batchNo,
|
|
inboundSku,
|
|
actualQty,
|
|
ledgerAvailableQty,
|
|
row.supplier_code || null,
|
|
Number(row.purchase_price) || null,
|
|
row.branch_code || null,
|
|
]
|
|
);
|
|
await client.query(
|
|
`INSERT INTO inventory_logs (batch_no, sku_code, operation_type, quantity, before_qty, after_qty, related_order_code, remark)
|
|
VALUES ($1, $2, 'inspection_in', $3, 0, $4, $5, $6)`,
|
|
[
|
|
batchNo,
|
|
inboundSku,
|
|
actualQty,
|
|
ledgerAvailableQty,
|
|
row.order_code,
|
|
`验收入库修复 ${inspectionId}${completedOrder ? '(订单已完结,不形成可用库存)' : ''}`,
|
|
]
|
|
);
|
|
} else if ((passThrough || warehouseFinishedNoStock) && !skipInventory) {
|
|
await client.query(
|
|
`INSERT INTO inventory_logs (batch_no, sku_code, operation_type, quantity, before_qty, after_qty, related_order_code, remark)
|
|
VALUES ($1, $2, 'inspection_in', 0, 0, 0, $3, $4)`,
|
|
[
|
|
batchNo,
|
|
inboundSku,
|
|
row.order_code,
|
|
warehouseFinishedNoStock
|
|
? `${WAREHOUSE_FINISHED_LEDGER_SKIP_REMARK}(修复) ${inspectionId}`
|
|
: `过手履约跳过库存台账(修复) ${inspectionId}`,
|
|
]
|
|
);
|
|
}
|
|
|
|
return { skipped: false, skuCode: inboundSku, batchNo, actualQty };
|
|
}
|
|
|
|
/** 修复验收入库时 sku_code 为空的库存(自采等历史数据) */
|
|
export async function backfillNullSkuInventory(orderCode?: string | null) {
|
|
const client = await pool.connect();
|
|
const repaired: Array<{ orderCode: string; itemName: string; skuCode: string; batchNo: string }> = [];
|
|
try {
|
|
await client.query('BEGIN');
|
|
const rows = await client.query(
|
|
`SELECT i.id AS inspection_id, i.order_code, i.item_name, i.sku_code AS insp_sku,
|
|
i.branch_code, inv.id AS inv_id, inv.batch_no
|
|
FROM inspections i
|
|
JOIN inventory inv ON inv.batch_no = i.inbound_batch_no
|
|
WHERE i.inbound_batch_no IS NOT NULL
|
|
AND (inv.sku_code IS NULL OR TRIM(inv.sku_code) = '')
|
|
AND ($1::text IS NULL OR i.order_code = $1)
|
|
ORDER BY i.order_code, i.item_name`,
|
|
[orderCode || null]
|
|
);
|
|
|
|
for (const row of rows.rows) {
|
|
const pickItem = await client.query(
|
|
`SELECT pi.id FROM picking_items pi
|
|
JOIN picking_tasks pt ON pt.pick_code = pi.pick_code
|
|
WHERE pt.order_code = $1 AND TRIM(COALESCE(pi.item_name, '')) = TRIM($2)
|
|
LIMIT 1`,
|
|
[row.order_code, row.item_name]
|
|
);
|
|
const provision = await ensureSkuForPickingOutbound(client, {
|
|
pickItemId: pickItem.rows[0]?.id || null,
|
|
orderCode: row.order_code,
|
|
skuCode: row.insp_sku,
|
|
itemName: row.item_name,
|
|
branchCode: row.branch_code,
|
|
});
|
|
if (!provision?.skuCode) continue;
|
|
|
|
await client.query(`UPDATE inspections SET sku_code = $2 WHERE id = $1`, [
|
|
row.inspection_id,
|
|
provision.skuCode,
|
|
]);
|
|
await client.query(`UPDATE inventory SET sku_code = $2 WHERE id = $1`, [
|
|
row.inv_id,
|
|
provision.skuCode,
|
|
]);
|
|
await client.query(
|
|
`UPDATE inventory_logs SET sku_code = $2
|
|
WHERE batch_no = $1 AND (sku_code IS NULL OR TRIM(sku_code) = '')`,
|
|
[row.batch_no, provision.skuCode]
|
|
);
|
|
repaired.push({
|
|
orderCode: row.order_code,
|
|
itemName: row.item_name,
|
|
skuCode: provision.skuCode,
|
|
batchNo: row.batch_no,
|
|
});
|
|
}
|
|
await client.query('COMMIT');
|
|
return { repaired: repaired.length, items: repaired };
|
|
} catch (error) {
|
|
await client.query('ROLLBACK').catch(() => undefined);
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
/** 修复供应商备货未完成导致未验收、未入库的订单行 */
|
|
export async function repairMissingSupplierInspections(orderCode: string) {
|
|
const client = await pool.connect();
|
|
const passed: string[] = [];
|
|
const skipped: string[] = [];
|
|
try {
|
|
await client.query('BEGIN');
|
|
|
|
await client.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]
|
|
);
|
|
|
|
const orderResult = await client.query(`SELECT branch_code FROM orders WHERE order_code = $1`, [orderCode]);
|
|
const branchCode = orderResult.rows[0]?.branch_code || null;
|
|
|
|
const preps = await client.query(
|
|
`SELECT sp.order_code, sp.sku_code, sp.supplier_code, sp.prepare_qty, sp.purchase_price, sp.item_name
|
|
FROM supplier_preparations sp
|
|
WHERE sp.order_code = $1
|
|
AND COALESCE(sp.is_stockout, false) = false
|
|
AND COALESCE(sp.transferred_to_purchase, false) = false
|
|
AND COALESCE(sp.prepare_status, 10) >= 30
|
|
AND sp.sku_code IS NOT NULL
|
|
AND NOT EXISTS (
|
|
SELECT 1 FROM inspections i
|
|
WHERE i.order_code = sp.order_code
|
|
AND i.sku_code IS NOT DISTINCT FROM sp.sku_code
|
|
AND COALESCE(i.supplier_code, '') = COALESCE(sp.supplier_code, '')
|
|
AND i.compliance_status >= 40
|
|
AND i.inbound_batch_no IS NOT NULL
|
|
)`,
|
|
[orderCode]
|
|
);
|
|
|
|
for (const prep of preps.rows) {
|
|
await createSupplierInspectionIfNeeded(
|
|
{
|
|
orderCode: prep.order_code,
|
|
skuCode: prep.sku_code,
|
|
supplierCode: prep.supplier_code,
|
|
prepareQty: Number(prep.prepare_qty) || 0,
|
|
purchasePrice: prep.purchase_price,
|
|
branchCode,
|
|
},
|
|
client
|
|
);
|
|
}
|
|
|
|
const pending = await client.query(
|
|
`SELECT id, item_name FROM inspections
|
|
WHERE order_code = $1
|
|
AND inspection_time IS NULL
|
|
AND inbound_batch_no IS NULL`,
|
|
[orderCode]
|
|
);
|
|
|
|
for (const row of pending.rows) {
|
|
const result = await passPendingInspectionForRepair(client, row.id);
|
|
if (result.skipped) {
|
|
skipped.push(`${row.item_name || row.id}:${result.reason}`);
|
|
} else {
|
|
passed.push(`${row.item_name}:${result.skuCode}`);
|
|
}
|
|
}
|
|
|
|
await client.query('COMMIT');
|
|
return { passedCount: passed.length, passed, skippedCount: skipped.length, skipped };
|
|
} catch (error) {
|
|
await client.query('ROLLBACK').catch(() => undefined);
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
export async function repairOrderInboundGaps(orderCode: string) {
|
|
const skuBackfill = await backfillNullSkuInventory(orderCode);
|
|
const supplierRepair = await repairMissingSupplierInspections(orderCode);
|
|
return { orderCode, skuBackfill, supplierRepair };
|
|
}
|