Files
SupplierSystem/server/src/services/costAllocationService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库: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 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

459 lines
15 KiB
TypeScript

import { pool } from '../db';
export type AllocationMethod = 'amount' | 'weight' | 'mileage' | 'days' | 'days30';
export const ALLOCATION_METHODS: AllocationMethod[] = [
'amount',
'weight',
'mileage',
'days',
'days30',
];
/** 固定成本默认按「月历天数」日额分摊 */
export const FIXED_COST_ALLOCATION_METHOD: AllocationMethod = 'days30';
export function normalizeAllocationMethod(raw: unknown): AllocationMethod {
const method = String(raw || 'amount').trim().toLowerCase();
return (ALLOCATION_METHODS as string[]).includes(method)
? (method as AllocationMethod)
: 'amount';
}
/** 由核算周期码推算当月天数:YYYYMM→月天数,YYYYMMDD→1,其它→30 */
export function resolveAllocationDayCount(cycleCode: string): number {
return listCalendarDays(cycleCode).length;
}
/** 周期内每一天:YYYYMM→整月日历日;YYYYMMDD→仅该日;其它→占位 30 天 */
export function listCalendarDays(cycleCode: string): string[] {
const code = String(cycleCode || '').trim();
if (/^\d{8}$/.test(code)) {
return [`${code.slice(0, 4)}-${code.slice(4, 6)}-${code.slice(6, 8)}`];
}
if (/^\d{6}$/.test(code)) {
const year = Number(code.slice(0, 4));
const month = Number(code.slice(4, 6));
if (year >= 2000 && month >= 1 && month <= 12) {
const dayCount = new Date(Date.UTC(year, month, 0)).getUTCDate();
const days: string[] = [];
for (let day = 1; day <= dayCount; day += 1) {
days.push(`${code.slice(0, 4)}-${code.slice(4, 6)}-${String(day).padStart(2, '0')}`);
}
return days;
}
}
return Array.from({ length: 30 }, (_, index) => `day-${index + 1}`);
}
function buildDailyRates(poolAmount: number, dayCount: number): number[] {
if (dayCount <= 0) return [];
const base = round2(poolAmount / dayCount);
const rates = Array.from({ length: dayCount }, () => base);
if (rates.length) {
const sumExceptLast = round2(base * (dayCount - 1));
rates[rates.length - 1] = round2(poolAmount - sumExceptLast);
}
return rates;
}
export interface AllocationLine {
order_code: string;
sku_code?: string | null;
weight?: number;
amount?: number;
mileage?: number;
days?: number;
allocated: number;
}
export interface AllocationResult {
method: AllocationMethod;
poolAmount: number;
totalBasis: number;
dayCount: number;
activeDays: number;
lines: AllocationLine[];
residual: number;
}
function round2(n: number) {
return Math.round(n * 100) / 100;
}
/**
* 按订单维度分摊间接成本(金额 / 重量 / 里程 / 天 / 按天日额)。
* - days30(固定成本):日额 = 池 / 当月天数;逐日入账;有配送单的天摊到当日订单,无单日写当天期间成本
* - days:池额按有单配送日均分后摊到当日订单
* - 全程单事务;舍入补差保证订单行合计正确
*/
export async function allocateCostPool(input: {
cycleCode: string;
costType: string;
poolAmount: number;
method: AllocationMethod;
branchCode?: string | null;
/** 固定成本等来源主键,重跑时只清本条,避免同类互相覆盖 */
referenceType?: string | null;
referenceId?: string | null;
costSubtype?: string | null;
}): Promise<AllocationResult> {
const method = normalizeAllocationMethod(input.method);
const costType = String(input.costType || '').trim().toLowerCase();
if (costType === 'free_overhead') {
throw new Error('其他成本按录入日记入,不参与订单分摊');
}
const poolAmount = round2(Math.max(0, Number(input.poolAmount) || 0));
if (poolAmount <= 0) {
return {
method,
poolAmount: 0,
totalBasis: 0,
dayCount: 0,
activeDays: 0,
lines: [],
residual: 0,
};
}
const referenceType = input.referenceType ? String(input.referenceType) : null;
const referenceId = input.referenceId ? String(input.referenceId) : null;
const costSubtype = input.costSubtype != null ? String(input.costSubtype) : null;
const client = await pool.connect();
try {
await client.query('BEGIN');
const params: unknown[] = [input.cycleCode];
let branchSql = '';
if (input.branchCode) {
params.push(input.branchCode);
branchSql = `AND o.branch_code = $${params.length}`;
}
const ordersResult = await client.query(
`SELECT o.order_code,
o.branch_code,
COALESCE(o.total_amount, 0) AS amount,
COALESCE(o.total_weight, 0) AS weight,
COALESCE(dt.task_count, 0) AS mileage,
to_char(
(COALESCE(o.delivery_date, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date,
'YYYY-MM-DD'
) 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
) dt ON true
WHERE o.cycle_code = $1 ${branchSql}
AND o.order_status >= 20
AND o.deleted_at IS NULL
ORDER BY o.order_code ASC`,
params
);
const rows = ordersResult.rows.map((row) => ({
order_code: row.order_code as string,
branch_code: (row.branch_code as string | null) || null,
amount: Number(row.amount) || 0,
weight: Number(row.weight) || 0,
mileage: Number(row.mileage) || 0,
delivery_day: String(row.delivery_day || ''),
}));
// 重跑幂等:有 reference 时只清本条固定成本
if (referenceType && referenceId) {
await client.query(
`DELETE FROM cost_details
WHERE reference_type = $1 AND reference_id = $2`,
[referenceType, referenceId]
);
} else {
const delParams: unknown[] = [input.cycleCode, input.costType, method];
let delSql = `DELETE FROM cost_details
WHERE cycle_code = $1 AND cost_type = $2 AND allocation_method = $3`;
if (method === 'days30') {
delSql += ` AND (status = 10 OR status = 20)`;
} else {
delSql += ` AND status = 10`;
}
if (input.branchCode) {
delParams.push(input.branchCode);
delSql += ` AND branch_code = $${delParams.length}`;
}
delSql += ` AND (reference_id IS NULL OR reference_type IS DISTINCT FROM 'fixed_cost')`;
await client.query(delSql, delParams);
}
if (method === 'days30') {
const calendarDays = listCalendarDays(input.cycleCode);
const dayCount = calendarDays.length;
const dailyRates = buildDailyRates(poolAmount, dayCount);
const ordersByDay = new Map<string, typeof rows>();
for (const row of rows) {
const key = row.delivery_day;
if (!key || !calendarDays.includes(key)) continue;
const list = ordersByDay.get(key) || [];
list.push(row);
ordersByDay.set(key, list);
}
const lines: (AllocationLine & { branch_code: string | null; day: string })[] = [];
let activeDays = 0;
for (let index = 0; index < calendarDays.length; index += 1) {
const day = calendarDays[index];
const dailyAmount = dailyRates[index] || 0;
if (dailyAmount <= 0) continue;
const dayOrders = ordersByDay.get(day) || [];
if (dayOrders.length) {
activeDays += 1;
const shareBase = round2(dailyAmount / dayOrders.length);
let assigned = 0;
dayOrders.forEach((order, orderIndex) => {
const allocated =
orderIndex === dayOrders.length - 1
? round2(dailyAmount - assigned)
: shareBase;
assigned = round2(assigned + allocated);
lines.push({
order_code: order.order_code,
branch_code: order.branch_code,
amount: order.amount,
weight: order.weight,
mileage: order.mileage,
days: 1 / dayOrders.length,
allocated,
day,
});
});
} else {
await client.query(
`INSERT INTO cost_details (
cycle_code, cost_type, cost_subtype, order_code, amount, allocation_method,
allocated_amount, status, branch_code, reference_type, reference_id, created_at
) VALUES ($1,$2,$3,NULL,$4,'days30',$4,20,$5,$6,$7,$8::timestamptz)`,
[
input.cycleCode,
input.costType,
`day:${day}`,
dailyAmount,
input.branchCode || null,
referenceType,
referenceId,
`${day}T04:00:00+08:00`,
]
);
}
}
for (const line of lines) {
if (line.allocated <= 0) continue;
await client.query(
`INSERT INTO cost_details (
cycle_code, cost_type, cost_subtype, order_code, amount, allocation_method,
allocated_amount, status, branch_code, reference_type, reference_id, created_at
) VALUES ($1,$2,$3,$4,$5,'days30',$5,20,$6,$7,$8,$9::timestamptz)`,
[
input.cycleCode,
input.costType,
costSubtype ? `${costSubtype}|${line.day}` : `day:${line.day}`,
line.order_code,
line.allocated,
line.branch_code || input.branchCode || null,
referenceType,
referenceId,
`${line.day}T04:00:00+08:00`,
]
);
}
const orderAllocatedSum = round2(lines.reduce((sum, line) => sum + line.allocated, 0));
const residual = round2(poolAmount - orderAllocatedSum);
await client.query('COMMIT');
return {
method,
poolAmount,
totalBasis: dayCount,
dayCount,
activeDays,
lines: lines.map(({ branch_code: _b, day: _d, ...line }) => line),
residual,
};
}
const dayCounts = new Map<string, number>();
if (method === 'days') {
for (const row of rows) {
const key = row.delivery_day || row.order_code;
dayCounts.set(key, (dayCounts.get(key) || 0) + 1);
}
}
const distinctDays = dayCounts.size;
const pickBasis = (row: (typeof rows)[0]) => {
if (method === 'weight') return row.weight;
if (method === 'mileage') return row.mileage;
if (method === 'days') {
const key = row.delivery_day || row.order_code;
const sameDay = dayCounts.get(key) || 1;
return distinctDays > 0 ? 1 / sameDay : 1;
}
return row.amount;
};
const totalBasis = rows.reduce((sum, row) => sum + pickBasis(row), 0);
const lines: (AllocationLine & { branch_code: string | null })[] = rows.map((row) => {
const basis = pickBasis(row);
const allocated =
totalBasis > 0
? round2((poolAmount * basis) / totalBasis)
: round2(poolAmount / Math.max(rows.length, 1));
return {
order_code: row.order_code,
branch_code: row.branch_code,
amount: row.amount,
weight: row.weight,
mileage: row.mileage,
days: method === 'days' ? basis : undefined,
allocated,
};
});
if (lines.length) {
const allocatedSum = round2(lines.reduce((sum, line) => sum + line.allocated, 0));
const diff = round2(poolAmount - allocatedSum);
if (diff !== 0) {
const lastPositive = [...lines].reverse().find((line) => line.allocated > 0) || lines[lines.length - 1];
lastPositive.allocated = round2(lastPositive.allocated + diff);
}
}
for (const line of lines) {
if (line.allocated <= 0) continue;
await client.query(
`INSERT INTO cost_details (
cycle_code, cost_type, cost_subtype, order_code, amount, allocation_method,
allocated_amount, status, branch_code, reference_type, reference_id, created_at
) VALUES ($1,$2,$3,$4,$5,$6,$5,10,$7,$8,$9,NOW())`,
[
input.cycleCode,
input.costType,
costSubtype,
line.order_code,
line.allocated,
method,
line.branch_code || input.branchCode || null,
referenceType,
referenceId,
]
);
}
await client.query('COMMIT');
return {
method,
poolAmount,
totalBasis: round2(method === 'days' ? distinctDays : totalBasis),
dayCount: distinctDays,
activeDays: distinctDays,
lines: lines.map(({ branch_code: _branch, ...line }) => line),
residual: 0,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => undefined);
throw error;
} finally {
client.release();
}
}
export async function summarizeCycleAllocation(cycleCode: string) {
const result = await pool.query(
`SELECT allocation_method, cost_type, COUNT(*)::int AS line_count, COALESCE(SUM(allocated_amount), 0) AS total
FROM cost_details
WHERE cycle_code = $1 AND allocated_amount IS NOT NULL
GROUP BY allocation_method, cost_type
ORDER BY cost_type`,
[cycleCode]
);
return result.rows;
}
/** 按 fixed_costs 台账重算全部按天分摊(修复历史互相覆盖 / 未含完成单) */
export async function reallocateAllFixedCosts(input?: {
cycleCode?: string | null;
branchCode?: string | null;
}): Promise<{ processed: number; results: Array<Record<string, unknown>> }> {
const COST_TYPE_TO_LEDGER: Record<string, string> = {
rent: 'rent',
vehicle: 'transport',
salary: 'labor',
equipment: 'warehouse',
packaging: 'packaging',
other: 'fixed_overhead',
};
const params: unknown[] = [];
let where = `WHERE status = 20 AND COALESCE(actual_amount, 0) > 0`;
if (input?.cycleCode) {
params.push(input.cycleCode);
where += ` AND cycle_code = $${params.length}`;
}
if (input?.branchCode) {
params.push(input.branchCode);
where += ` AND branch_code = $${params.length}`;
}
const rows = await pool.query(
`SELECT * FROM fixed_costs ${where} ORDER BY created_at ASC`,
params
);
// 清掉历史无 reference 的 days30 残留,避免与重算结果重复
const wipeParams: unknown[] = [];
let wipeSql = `DELETE FROM cost_details
WHERE allocation_method = 'days30'
AND (reference_id IS NULL OR reference_type IS DISTINCT FROM 'fixed_cost')`;
if (input?.cycleCode) {
wipeParams.push(input.cycleCode);
wipeSql += ` AND cycle_code = $${wipeParams.length}`;
}
if (input?.branchCode) {
wipeParams.push(input.branchCode);
wipeSql += ` AND branch_code = $${wipeParams.length}`;
}
await pool.query(wipeSql, wipeParams);
const results: Array<Record<string, unknown>> = [];
for (const row of rows.rows) {
const ledgerType = COST_TYPE_TO_LEDGER[String(row.cost_type)] || 'fixed_overhead';
const amount = round2(Number(row.actual_amount) || 0);
const allocated = await allocateCostPool({
cycleCode: String(row.cycle_code),
costType: ledgerType,
poolAmount: amount,
method: FIXED_COST_ALLOCATION_METHOD,
branchCode: row.branch_code || null,
referenceType: 'fixed_cost',
referenceId: String(row.id),
costSubtype: String(row.cost_type || ''),
});
results.push({
id: row.id,
cost_type: row.cost_type,
amount,
active_days: allocated.activeDays,
day_count: allocated.dayCount,
order_lines: allocated.lines.length,
residual: allocated.residual,
});
}
return { processed: results.length, results };
}