来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
304 lines
11 KiB
TypeScript
304 lines
11 KiB
TypeScript
/**
|
|
* 独立加工单:不依赖订单/验收,创建时即扣库存并按批次成本写入当天采购成本。
|
|
* 见 docs/design/20260822-standalone-processing-tasks.md
|
|
*/
|
|
import type { PoolClient } from 'pg';
|
|
import { pool } from '../db';
|
|
import { fifoDeductInventory, type InventoryDeductBatch as FIFODeductBatch } from './inventoryOutboundService';
|
|
import { postProcessingStandaloneMaterialCost, type InventoryDeductBatch } from './processingStandaloneCostService';
|
|
import { healOrphanIndependentInboundsAfterPass } from './selfPurchaseStockInboundService';
|
|
import { getClaimableStockQty } from './inventoryStockCoverService';
|
|
|
|
const PROCESS_STATUS = {
|
|
pending: 10,
|
|
inProgress: 20,
|
|
pendingInspection: 30,
|
|
completed: 40,
|
|
rejected: 50,
|
|
};
|
|
|
|
function trimText(v: unknown): string {
|
|
return String(v || '').trim();
|
|
}
|
|
|
|
function roundQty(n: number): number {
|
|
return Math.round(n * 1000) / 1000;
|
|
}
|
|
|
|
function roundMoney(n: number): number {
|
|
return Math.round(n * 100) / 100;
|
|
}
|
|
|
|
export interface CreateStandaloneProcessingInput {
|
|
skuCode: string;
|
|
qty: number;
|
|
processingMethod: string;
|
|
branchCode: string;
|
|
/** 加工单价:仅记录,不入账 */
|
|
processUnitPrice?: number | null;
|
|
operatorId?: string | null;
|
|
remark?: string | null;
|
|
}
|
|
|
|
export interface CreateStandaloneProcessingResult {
|
|
id: string;
|
|
task_code: string;
|
|
sku_code: string;
|
|
sku_name: string | null;
|
|
processing_method: string;
|
|
source_qty: number;
|
|
material_qty: number;
|
|
material_cost: number;
|
|
process_unit_price: number | null;
|
|
process_status: number;
|
|
branch_code: string;
|
|
created_at: string;
|
|
}
|
|
|
|
export async function createStandaloneProcessingTask(
|
|
input: CreateStandaloneProcessingInput
|
|
): Promise<CreateStandaloneProcessingResult> {
|
|
const skuCode = trimText(input.skuCode);
|
|
const branchCode = trimText(input.branchCode);
|
|
const processingMethod = trimText(input.processingMethod);
|
|
const qty = roundQty(Number(input.qty));
|
|
const unitPrice =
|
|
input.processUnitPrice == null
|
|
? null
|
|
: roundMoney(Number(input.processUnitPrice));
|
|
if (unitPrice != null && (unitPrice < 0 || !Number.isFinite(unitPrice))) {
|
|
throw Object.assign(new Error('加工单价不能为负数'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
|
|
if (!skuCode) {
|
|
throw Object.assign(new Error('请选择商品'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
if (!branchCode) {
|
|
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
|
}
|
|
if (!processingMethod) {
|
|
throw Object.assign(new Error('请选择加工方式'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
if (!Number.isFinite(qty) || qty <= 0) {
|
|
throw Object.assign(new Error('数量须大于 0'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
|
|
try {
|
|
await healOrphanIndependentInboundsAfterPass(branchCode);
|
|
} catch (healErr) {
|
|
console.warn('[standalone-processing] independent inbound heal skipped:', (healErr as Error)?.message);
|
|
}
|
|
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
|
|
const skuRow = await client.query(
|
|
`SELECT sku_code, sku_name, unit FROM skus WHERE sku_code = $1 LIMIT 1`,
|
|
[skuCode]
|
|
);
|
|
if (!skuRow.rowCount) {
|
|
throw Object.assign(new Error('商品不存在'), { status: 404, code: 'not_found' });
|
|
}
|
|
const skuName = String(skuRow.rows[0]?.sku_name || '');
|
|
|
|
// 与需求单领料同口径:只能领「毛可用 − 全部在用预留」
|
|
// 见 docs/design/20260922-processing-pick-respect-reservations.md
|
|
const availableQty = await getClaimableStockQty(client, skuCode, branchCode, null);
|
|
if (availableQty + 1e-9 < qty) {
|
|
throw Object.assign(
|
|
new Error(`库存不足:可用 ${availableQty},需要 ${qty}`),
|
|
{ status: 400, code: 'insufficient_stock' }
|
|
);
|
|
}
|
|
|
|
// task_code 为 MAX+1 取号,同日并发会撞唯一索引:SAVEPOINT + 换号重试
|
|
// (事务内普通 catch 后连接已 aborted,必须回滚到保存点)
|
|
let taskId = '';
|
|
let taskCodeReturn = '';
|
|
let lastErr: unknown = null;
|
|
for (let attempt = 0; attempt < 3 && !taskId; attempt += 1) {
|
|
const taskCode = await allocateStandaloneTaskCode(client);
|
|
await client.query('SAVEPOINT standalone_task_insert');
|
|
try {
|
|
const taskResult = await client.query(
|
|
`INSERT INTO processing_tasks (
|
|
order_code, inspection_id, task_code, source_type, sku_code, processing_method,
|
|
source_qty, process_status, branch_code, process_unit_price, remark, created_at, updated_at
|
|
) VALUES (NULL, NULL, $1, 'standalone', $2, $3, $4, $5, $6, $7, $8, NOW(), NOW())
|
|
RETURNING id, task_code`,
|
|
[taskCode, skuCode, processingMethod, qty, PROCESS_STATUS.pending, branchCode, unitPrice, trimText(input.remark) || null]
|
|
);
|
|
await client.query('RELEASE SAVEPOINT standalone_task_insert');
|
|
taskId = String(taskResult.rows[0].id);
|
|
taskCodeReturn = String(taskResult.rows[0].task_code || taskCode);
|
|
} catch (err) {
|
|
await client.query('ROLLBACK TO SAVEPOINT standalone_task_insert').catch(() => undefined);
|
|
if (String((err as { code?: string } | null)?.code || '') !== '23505') throw err;
|
|
lastErr = err;
|
|
}
|
|
}
|
|
if (!taskId) throw lastErr;
|
|
|
|
// 扣库存,同时采集批次成本
|
|
const deductedBatches: (FIFODeductBatch & { deductedQty: number })[] = [];
|
|
await fifoDeductInventory(
|
|
client,
|
|
{
|
|
skuCode,
|
|
qty,
|
|
branchCode,
|
|
orderCode: null,
|
|
pickCode: taskCodeReturn,
|
|
operatorId: input.operatorId || null,
|
|
itemName: skuName,
|
|
operationType: 'processing_out',
|
|
remark: `独立加工领料 ${taskCodeReturn}`,
|
|
},
|
|
(batch, deductedQty) => {
|
|
deductedBatches.push({ ...batch, deductedQty });
|
|
}
|
|
);
|
|
|
|
const materialCost = roundMoney(
|
|
deductedBatches.reduce((sum, b) => sum + b.deductedQty * b.costPrice, 0)
|
|
);
|
|
const costBatches: InventoryDeductBatch[] = deductedBatches.map((b) => ({
|
|
batchNo: b.batchNo,
|
|
deductedQty: b.deductedQty,
|
|
costPrice: b.costPrice,
|
|
}));
|
|
await client.query(
|
|
`UPDATE processing_tasks
|
|
SET material_qty = $2, material_cost = $3
|
|
WHERE id = $1`,
|
|
[taskId, qty, materialCost]
|
|
);
|
|
|
|
await postProcessingStandaloneMaterialCost(client, {
|
|
taskId,
|
|
skuCode,
|
|
branchCode,
|
|
materialCost,
|
|
deductedBatches: costBatches,
|
|
operatorId: input.operatorId || null,
|
|
});
|
|
|
|
await client.query('COMMIT');
|
|
|
|
return {
|
|
id: taskId,
|
|
task_code: taskCodeReturn,
|
|
sku_code: skuCode,
|
|
sku_name: skuName || null,
|
|
processing_method: processingMethod,
|
|
source_qty: qty,
|
|
material_qty: qty,
|
|
material_cost: materialCost,
|
|
process_unit_price: unitPrice,
|
|
process_status: PROCESS_STATUS.pending,
|
|
branch_code: branchCode,
|
|
created_at: new Date().toISOString(),
|
|
};
|
|
} catch (error) {
|
|
await client.query('ROLLBACK').catch(() => undefined);
|
|
throw error;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
async function allocateStandaloneTaskCode(client: PoolClient): Promise<string> {
|
|
const date = new Date();
|
|
const ymd = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
|
|
// 取当日最大序号 +1;没有时使用 1
|
|
const result = await client.query(
|
|
`SELECT COALESCE(MAX(NULLIF(REGEXP_REPLACE(task_code, '^SPG-\\d{8}-', ''), '')), '0')::int AS seq
|
|
FROM processing_tasks
|
|
WHERE task_code LIKE 'SPG-' || $1 || '-%'`,
|
|
[ymd]
|
|
);
|
|
const seq = (Number(result.rows[0]?.seq) || 0) + 1;
|
|
return `SPG-${ymd}-${String(seq).padStart(4, '0')}`;
|
|
}
|
|
|
|
export interface ListStandaloneSkuOptionInput {
|
|
branchCode: string;
|
|
search?: string | null;
|
|
limit?: number;
|
|
}
|
|
|
|
export async function listStandaloneProcessingSkuOptions(
|
|
input: ListStandaloneSkuOptionInput
|
|
): Promise<
|
|
Array<{
|
|
sku_code: string;
|
|
sku_name: string;
|
|
unit: string | null;
|
|
/** 真实可领 = 毛可用 − 在用预留 */
|
|
available_qty: number;
|
|
gross_available_qty: number;
|
|
reserved_qty: number;
|
|
cost_price: number | null;
|
|
}>
|
|
> {
|
|
const branchCode = trimText(input.branchCode);
|
|
const search = trimText(input.search);
|
|
const limit = Math.min(50, Math.max(1, Number(input.limit) || 20));
|
|
if (!branchCode) return [];
|
|
|
|
const params: unknown[] = [branchCode, limit];
|
|
const searchWhere = search
|
|
? `AND (
|
|
COALESCE(s.sku_code, '') ILIKE $3
|
|
OR COALESCE(s.sku_name, '') ILIKE $3
|
|
)`
|
|
: '';
|
|
if (search) params.push(`%${search.replace(/[%_]/g, '\\$&')}%`);
|
|
|
|
const result = await pool.query(
|
|
`SELECT s.sku_code,
|
|
COALESCE(s.sku_name, s.sku_code) AS sku_name,
|
|
s.unit,
|
|
-- 领料只能领「毛可用 − 全部在用预留」:预留是对别的明细(别的 SKU/别的行)的交付承诺,
|
|
-- 不能因为加工领料被吃掉。见 docs/design/20260922-processing-pick-respect-reservations.md
|
|
GREATEST(0, COALESCE(SUM(inv.available_qty), 0) - COALESCE(res.reserved_qty, 0))::float AS available_qty,
|
|
COALESCE(SUM(inv.available_qty), 0)::float AS gross_available_qty,
|
|
COALESCE(res.reserved_qty, 0)::float AS reserved_qty,
|
|
(
|
|
SELECT COALESCE(inv2.cost_price, 0)::float
|
|
FROM inventory inv2
|
|
WHERE inv2.sku_code = s.sku_code
|
|
AND inv2.branch_code = $1
|
|
AND inv2.available_qty > 0
|
|
AND inv2.cost_price > 0
|
|
ORDER BY inv2.created_at ASC NULLS LAST
|
|
LIMIT 1
|
|
) AS cost_price
|
|
FROM skus s
|
|
JOIN inventory inv ON inv.sku_code = s.sku_code AND inv.branch_code = $1
|
|
LEFT JOIN LATERAL (
|
|
SELECT COALESCE(SUM(r.qty), 0)::numeric AS reserved_qty
|
|
FROM inventory_reservations r
|
|
WHERE r.sku_code = s.sku_code
|
|
AND r.status = 10
|
|
AND (r.branch_code IS NULL OR r.branch_code = $1)
|
|
) res ON TRUE
|
|
WHERE inv.available_qty > 0 ${searchWhere}
|
|
GROUP BY s.sku_code, s.sku_name, s.unit, res.reserved_qty
|
|
ORDER BY s.sku_name
|
|
LIMIT $2`,
|
|
params
|
|
);
|
|
return result.rows.map((r) => ({
|
|
sku_code: String(r.sku_code),
|
|
sku_name: String(r.sku_name || r.sku_code),
|
|
unit: r.unit ? String(r.unit) : null,
|
|
// available_qty = 真实可领(已扣在用预留);另返回毛可用/占用量供展示或排查
|
|
available_qty: roundQty(Number(r.available_qty) || 0),
|
|
gross_available_qty: roundQty(Number(r.gross_available_qty) || 0),
|
|
reserved_qty: roundQty(Number(r.reserved_qty) || 0),
|
|
cost_price: Number(r.cost_price) || null,
|
|
}));
|
|
}
|