- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14) - T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9) - T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4) - T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8) - T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15) - T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8) - T7 前后端测试与 lint 门禁清零 - T8 应付卡片按关联订单日(口径 A) - T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
669 lines
24 KiB
TypeScript
669 lines
24 KiB
TypeScript
import { pool } from '../db';
|
||
import type { TenantContext } from './tenantScope';
|
||
import { allocateCostPool, FIXED_COST_ALLOCATION_METHOD } from './costAllocationService';
|
||
import {
|
||
assertOwnedStoragePaths,
|
||
buildSignedStoragePathForCtx,
|
||
type StorageOwnerCtx,
|
||
} from './storageObjectOwnership';
|
||
import { safeStorageFileName } from './storageBucketConfig';
|
||
import { withDistributedLock } from './distributedLock';
|
||
import { runWithTenantDbContext } from './tenantDbContext';
|
||
|
||
const COST_TYPE_TO_LEDGER: Record<string, string> = {
|
||
rent: 'rent',
|
||
vehicle: 'transport',
|
||
salary: 'labor',
|
||
equipment: 'warehouse',
|
||
packaging: 'packaging',
|
||
other: 'fixed_overhead',
|
||
};
|
||
|
||
function branchFilter(ctx: TenantContext | null | undefined, alias: string, params: unknown[]) {
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
params.push(ctx.branchCode);
|
||
return `AND ${alias}.branch_code = $${params.length}`;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
/** YYYYMM → 上月 YYYYMM */
|
||
export function previousCycleCode(cycleCode: string): string | null {
|
||
const c = String(cycleCode || '').trim();
|
||
if (!/^\d{6}$/.test(c)) return null;
|
||
const y = Number(c.slice(0, 4));
|
||
const m = Number(c.slice(4, 6));
|
||
if (!(y > 2000) || m < 1 || m > 12) return null;
|
||
if (m <= 1) return `${y - 1}12`;
|
||
return `${y}${String(m - 1).padStart(2, '0')}`;
|
||
}
|
||
|
||
/** 本月 1 日 04:00+08,供账本入账日归属 */
|
||
export function cycleMonthLedgerCreatedAt(cycleCode: string): string | null {
|
||
const c = String(cycleCode || '').trim();
|
||
if (!/^\d{6}$/.test(c)) return null;
|
||
const y = c.slice(0, 4);
|
||
const m = c.slice(4, 6);
|
||
return `${y}-${m}-01T04:00:00+08:00`;
|
||
}
|
||
|
||
/** 归一化 fixed_costs.voucher_urls(历史为外链,现也可存 invoices 桶内存储路径) */
|
||
export function normalizeFixedCostVoucherPaths(raw: unknown): string[] {
|
||
const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
|
||
const out: string[] = [];
|
||
for (const item of arr) {
|
||
const value = String(item || '').trim();
|
||
if (value && !out.includes(value)) out.push(value);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 凭证/发票展示 URL:外链原样返回;invoices 桶内存储路径签名为临时可读链接。
|
||
* 无法识别的历史字符串原样返回,保持改动前行为。
|
||
*/
|
||
export function toFixedCostVoucherDisplayUrl(value: string): string {
|
||
const text = String(value || '').trim();
|
||
if (!text) return text;
|
||
if (/^(https?:)?\/\//i.test(text) || text.startsWith('/')) return text;
|
||
try {
|
||
return buildSignedStoragePathForCtx(undefined, 'invoices', safeStorageFileName(text));
|
||
} catch {
|
||
return text;
|
||
}
|
||
}
|
||
|
||
/** 挂载固定成本的展示字段(voucher_paths 原文 + voucher_urls 展示链接),不改数据库 */
|
||
export function decorateFixedCostVoucherFields<T extends { voucher_urls?: unknown }>(row: T) {
|
||
const paths = normalizeFixedCostVoucherPaths(row.voucher_urls);
|
||
return {
|
||
...row,
|
||
voucher_paths: paths,
|
||
voucher_urls: paths.map(toFixedCostVoucherDisplayUrl),
|
||
};
|
||
}
|
||
|
||
export async function listFixedCosts(
|
||
ctx?: TenantContext | null,
|
||
opts?: { cycleCode?: string | null }
|
||
) {
|
||
const params: unknown[] = [];
|
||
const branchSql = branchFilter(ctx, 'fixed_costs', params);
|
||
const cycleCode = String(opts?.cycleCode || '').trim();
|
||
let cycleSql = '';
|
||
if (/^\d{6}$/.test(cycleCode)) {
|
||
params.push(cycleCode);
|
||
cycleSql = ` AND cycle_code = $${params.length}`;
|
||
}
|
||
const sql = `SELECT * FROM fixed_costs WHERE 1=1 ${branchSql}${cycleSql}
|
||
ORDER BY created_at DESC LIMIT 500`;
|
||
const result = await pool.query(sql, params);
|
||
return result.rows.map((row) => decorateFixedCostVoucherFields(row));
|
||
}
|
||
|
||
/**
|
||
* 录入固定成本:直接入账(成本模块仅管理员/财务使用,无需审核)。
|
||
* 分摊固定为「金额 ÷ 当月天数」逐日入账:有配送日摊到当日订单,无单日写当天期间成本。
|
||
*/
|
||
export async function createFixedCost(input: {
|
||
cycleCode: string;
|
||
costType: string;
|
||
budgetAmount: number;
|
||
actualAmount: number;
|
||
allocationMethod?: string;
|
||
remark?: string | null;
|
||
voucherUrls?: string[];
|
||
branchCode?: string | null;
|
||
inputterId?: string | null;
|
||
allocate?: boolean;
|
||
/** 非分摊入账时覆盖 cost_details.created_at(沿用上月用) */
|
||
ledgerCreatedAt?: string | null;
|
||
/** 写入口归属校验用租户上下文(route 传入;缺省按 branchCode fail-closed) */
|
||
ownerCtx?: StorageOwnerCtx | null;
|
||
}) {
|
||
const cycleCode = String(input.cycleCode || '').trim();
|
||
if (!cycleCode) throw Object.assign(new Error('请填写核算周期'), { status: 400 });
|
||
const costType = String(input.costType || 'other');
|
||
const actual = Math.max(0, Number(input.actualAmount) || 0);
|
||
if (actual <= 0) throw Object.assign(new Error('实际金额须大于 0'), { status: 400 });
|
||
const method = FIXED_COST_ALLOCATION_METHOD;
|
||
const ledgerType = COST_TYPE_TO_LEDGER[costType] || 'fixed_overhead';
|
||
const wantAllocate = input.allocate !== false;
|
||
const ledgerAt = input.ledgerCreatedAt ? String(input.ledgerCreatedAt).trim() : '';
|
||
const voucherPaths = normalizeFixedCostVoucherPaths(input.voucherUrls);
|
||
// T9:写库前校验 voucher_urls 归属(跨分支 key ⇒ 403,不落库)
|
||
await assertOwnedStoragePaths(
|
||
input.ownerCtx ?? { branchCode: input.branchCode || null },
|
||
'invoices',
|
||
voucherPaths
|
||
);
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const inserted = await client.query(
|
||
`INSERT INTO fixed_costs (
|
||
cycle_code, cost_type, budget_amount, actual_amount, allocation_method,
|
||
voucher_urls, inputter_id, status, branch_code, remark, approver_id, approved_at
|
||
) VALUES ($1,$2,$3,$4,$5,$6,$7,20,$8,$9,$7,NOW())
|
||
RETURNING *`,
|
||
[
|
||
cycleCode,
|
||
costType,
|
||
Math.max(0, Number(input.budgetAmount) || 0),
|
||
actual,
|
||
method,
|
||
voucherPaths.length ? voucherPaths : null,
|
||
input.inputterId || null,
|
||
input.branchCode || null,
|
||
input.remark || null,
|
||
]
|
||
);
|
||
const row = inserted.rows[0];
|
||
|
||
if (!wantAllocate && actual > 0) {
|
||
if (ledgerAt) {
|
||
await client.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id, created_at
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7,$8::timestamptz)`,
|
||
[cycleCode, ledgerType, costType, actual, method, input.branchCode || null, row.id, ledgerAt]
|
||
);
|
||
} else {
|
||
await client.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7)`,
|
||
[cycleCode, ledgerType, costType, actual, method, input.branchCode || null, row.id]
|
||
);
|
||
}
|
||
}
|
||
|
||
await client.query('COMMIT');
|
||
|
||
let allocated = false;
|
||
if (wantAllocate && actual > 0) {
|
||
try {
|
||
await allocateCostPool({
|
||
cycleCode,
|
||
costType: ledgerType,
|
||
poolAmount: actual,
|
||
method,
|
||
branchCode: input.branchCode || null,
|
||
referenceType: 'fixed_cost',
|
||
referenceId: String(row.id),
|
||
costSubtype: costType,
|
||
});
|
||
allocated = true;
|
||
} catch {
|
||
if (ledgerAt) {
|
||
await pool.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id, created_at
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7,$8::timestamptz)`,
|
||
[cycleCode, ledgerType, costType, actual, method, input.branchCode || null, row.id, ledgerAt]
|
||
);
|
||
} else {
|
||
await pool.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7)`,
|
||
[cycleCode, ledgerType, costType, actual, method, input.branchCode || null, row.id]
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
return { fixedCost: row, ledgerType, amount: actual, allocated };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 对本月已入账但缺少按天(day:)账本的固定成本,重跑 days30 分摊。
|
||
* 用于:历史整笔入账、早期沿用未分摊。
|
||
*/
|
||
export async function ensureFixedCostsDayAllocated(input: {
|
||
cycleCode: string;
|
||
branchCode: string;
|
||
}): Promise<{ repaired: number }> {
|
||
const cycleCode = String(input.cycleCode || '').trim();
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!/^\d{6}$/.test(cycleCode) || !branchCode) return { repaired: 0 };
|
||
|
||
const need = await pool.query(
|
||
`SELECT fc.id, fc.cost_type, fc.actual_amount, fc.branch_code
|
||
FROM fixed_costs fc
|
||
WHERE fc.cycle_code = $1 AND fc.branch_code = $2 AND fc.status >= 20
|
||
AND COALESCE(fc.actual_amount, 0) > 0
|
||
AND COALESCE((
|
||
SELECT COUNT(*)::int FROM cost_details cd
|
||
WHERE cd.reference_type = 'fixed_cost' AND cd.reference_id = fc.id::text
|
||
), 0) <= 1
|
||
AND NOT EXISTS (
|
||
SELECT 1 FROM cost_details cd
|
||
WHERE cd.reference_type = 'fixed_cost'
|
||
AND cd.reference_id = fc.id::text
|
||
AND (
|
||
cd.cost_subtype LIKE 'day:%'
|
||
OR position('|' in coalesce(cd.cost_subtype, '')) > 0
|
||
)
|
||
)`,
|
||
[cycleCode, branchCode]
|
||
);
|
||
|
||
let repaired = 0;
|
||
for (const row of need.rows) {
|
||
const amount = Math.max(0, Number(row.actual_amount) || 0);
|
||
if (!(amount > 0)) continue;
|
||
const ledgerType = COST_TYPE_TO_LEDGER[String(row.cost_type)] || 'fixed_overhead';
|
||
try {
|
||
await allocateCostPool({
|
||
cycleCode,
|
||
costType: ledgerType,
|
||
poolAmount: amount,
|
||
method: FIXED_COST_ALLOCATION_METHOD,
|
||
branchCode: row.branch_code || branchCode,
|
||
referenceType: 'fixed_cost',
|
||
referenceId: String(row.id),
|
||
costSubtype: String(row.cost_type || ''),
|
||
});
|
||
repaired += 1;
|
||
} catch {
|
||
// 分摊失败则保留原账本,不阻断 ensure
|
||
}
|
||
}
|
||
return { repaired };
|
||
}
|
||
|
||
/**
|
||
* 本月尚无固定成本时,沿用上月已入账科目与金额,并按天分摊。
|
||
* 见 docs/design/20260806-fixed-cost-carry-forward.md
|
||
*/
|
||
export async function ensureFixedCostsCarriedForward(input: {
|
||
cycleCode: string;
|
||
branchCode: string | null | undefined;
|
||
inputterId?: string | null;
|
||
}): Promise<{ carried: number; skipped: boolean; reason?: string; repaired?: number }> {
|
||
const cycleCode = String(input.cycleCode || '').trim();
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!/^\d{6}$/.test(cycleCode)) {
|
||
return { carried: 0, skipped: true, reason: 'invalid_cycle' };
|
||
}
|
||
if (!branchCode) {
|
||
return { carried: 0, skipped: true, reason: 'no_branch' };
|
||
}
|
||
|
||
const prev = previousCycleCode(cycleCode);
|
||
if (!prev) return { carried: 0, skipped: true, reason: 'invalid_cycle' };
|
||
|
||
let carried = 0;
|
||
let reason: string | undefined;
|
||
|
||
const existing = await pool.query(
|
||
`SELECT COUNT(*)::int AS c FROM fixed_costs
|
||
WHERE cycle_code = $1 AND branch_code = $2`,
|
||
[cycleCode, branchCode]
|
||
);
|
||
if ((Number(existing.rows[0]?.c) || 0) > 0) {
|
||
reason = 'already_has_rows';
|
||
} else {
|
||
const prevRows = await pool.query(
|
||
`SELECT cost_type, budget_amount, actual_amount, remark
|
||
FROM fixed_costs
|
||
WHERE cycle_code = $1 AND branch_code = $2 AND status >= 20
|
||
AND COALESCE(actual_amount, 0) > 0
|
||
ORDER BY created_at ASC`,
|
||
[prev, branchCode]
|
||
);
|
||
if (!prevRows.rowCount) {
|
||
reason = 'no_prev_rows';
|
||
} else {
|
||
for (const row of prevRows.rows) {
|
||
const actual = Math.max(0, Number(row.actual_amount) || 0);
|
||
if (!(actual > 0)) continue;
|
||
const prevRemark = String(row.remark || '').trim();
|
||
const remark = prevRemark
|
||
? `沿用上月;${prevRemark}`.slice(0, 500)
|
||
: '沿用上月';
|
||
await createFixedCost({
|
||
cycleCode,
|
||
costType: String(row.cost_type || 'other'),
|
||
budgetAmount: Math.max(0, Number(row.budget_amount) || 0),
|
||
actualAmount: actual,
|
||
remark,
|
||
voucherUrls: undefined,
|
||
branchCode,
|
||
inputterId: input.inputterId || null,
|
||
allocate: true,
|
||
});
|
||
carried += 1;
|
||
}
|
||
if (carried === 0) reason = 'no_prev_rows';
|
||
}
|
||
}
|
||
|
||
const { repaired } = await ensureFixedCostsDayAllocated({ cycleCode, branchCode });
|
||
return {
|
||
carried,
|
||
skipped: carried === 0,
|
||
reason,
|
||
repaired,
|
||
};
|
||
}
|
||
|
||
/** 当月 YYYYMM(Asia/Shanghai,口径同 getFinanceOverviewStats,不依赖进程时区) */
|
||
export function currentCycleCodeChina(now: Date = new Date()): string {
|
||
const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit' }).formatToParts(now);
|
||
const y = parts.find((p) => p.type === 'year')?.value || '';
|
||
const m = parts.find((p) => p.type === 'month')?.value || '';
|
||
return `${y}${m}`;
|
||
}
|
||
|
||
/** 登录兜底的单次超时(毫秒):宁可少补一次,也不长期占着连接与锁 */
|
||
const LOGIN_CARRY_TIMEOUT_MS = 8000;
|
||
/** 锁 TTL(秒):覆盖一次真写(实测 <2s),进程被kill后也能自动解锁 */
|
||
const LOGIN_CARRY_LOCK_TTL_SEC = 120;
|
||
|
||
/**
|
||
* 登录成功后兜底:只为「登录者所属分公司」补当月固定成本(沿用上月)。
|
||
*
|
||
* 为什么需要:现有触发点只有「打开固定成本界面」与「财务概览」,两者都要有人操作;
|
||
* 生产实测 10 月的沿用在 10-07 才发生,10 月 1–6 日看板/归因/预算预警/毛利净利全都少了这笔钱。
|
||
*
|
||
* 三条硬约束(见 docs/design/20261007-fixed-cost-carry-forward-on-login.md):
|
||
* 1. `branchCode` 为空(超管/平台)**直接跳过** —— 分公司可能大量增加,不做全量遍历;
|
||
* 2. 套 `withDistributedLock` —— 沿用函数是「查空再插」且 `fixed_costs` 无唯一约束,
|
||
* 同一分公司多人同时登录会各插一套导致当月固定成本翻倍;
|
||
* 3. 全程 best-effort:任何失败/超时只记日志,**绝不抛给调用方**(不阻塞登录、不影响登录结果)。
|
||
*/
|
||
export async function carryForwardFixedCostsOnLogin(input: {
|
||
branchCode: string | null | undefined;
|
||
userId?: string | null;
|
||
}): Promise<{ carried: number; skipped: boolean; reason?: string }> {
|
||
const branchCode = String(input.branchCode || '').trim();
|
||
if (!branchCode) return { carried: 0, skipped: true, reason: 'no_branch' };
|
||
const cycleCode = currentCycleCodeChina();
|
||
if (!/^\d{6}$/.test(cycleCode)) return { carried: 0, skipped: true, reason: 'invalid_cycle' };
|
||
|
||
const lockKey = `fixed-cost-carry:${cycleCode}:${branchCode}`;
|
||
const run = async (): Promise<{ carried: number; skipped: boolean; reason?: string }> => {
|
||
let timer: NodeJS.Timeout | undefined;
|
||
const timeout = new Promise<never>((_, reject) => {
|
||
timer = setTimeout(() => reject(new Error(`carry timeout ${LOGIN_CARRY_TIMEOUT_MS}ms`)), LOGIN_CARRY_TIMEOUT_MS);
|
||
timer.unref?.();
|
||
});
|
||
try {
|
||
// 登录请求本身没有租户上下文,必须自己套一层(否则 search_path 没切到该分公司 schema)
|
||
const result = await Promise.race([
|
||
runWithTenantDbContext(branchCode, () =>
|
||
ensureFixedCostsCarriedForward({ cycleCode, branchCode, inputterId: input.userId ?? null })
|
||
),
|
||
timeout,
|
||
]);
|
||
if (result.carried > 0) {
|
||
console.log(`[fixed-cost-carry] 登录兜底沿用 ${cycleCode} ${branchCode}: ${result.carried} 项`);
|
||
}
|
||
return result;
|
||
} finally {
|
||
if (timer) clearTimeout(timer);
|
||
}
|
||
};
|
||
|
||
try {
|
||
const locked = await withDistributedLock(lockKey, LOGIN_CARRY_LOCK_TTL_SEC, run);
|
||
// 没抢到锁 = 另一个请求正在补同一家:跳过属于正常路径,不是错误
|
||
return locked ?? { carried: 0, skipped: true, reason: 'lock_held' };
|
||
} catch (error) {
|
||
console.warn('[fixed-cost-carry] 登录兜底沿用失败(不影响登录):', error instanceof Error ? error.message : error);
|
||
return { carried: 0, skipped: true, reason: 'error' };
|
||
}
|
||
}
|
||
|
||
/** @deprecated 成本模块已取消审核;保留供历史「待入账」记录补记 */
|
||
export async function approveFixedCost(input: {
|
||
id: string;
|
||
approverId?: string | null;
|
||
ctx?: TenantContext | null;
|
||
allocate?: boolean;
|
||
}) {
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const params: unknown[] = [input.id];
|
||
const branchSql = branchFilter(input.ctx, 'fc', params);
|
||
const locked = await client.query(
|
||
`SELECT * FROM fixed_costs fc WHERE fc.id = $1 AND fc.status = 10 ${branchSql} FOR UPDATE`,
|
||
params
|
||
);
|
||
const row = locked.rows[0];
|
||
if (!row) throw Object.assign(new Error('固定成本不存在或已入账'), { status: 404 });
|
||
|
||
const ledgerType = COST_TYPE_TO_LEDGER[String(row.cost_type)] || 'fixed_overhead';
|
||
const amount = Math.max(0, Number(row.actual_amount) || 0);
|
||
const method = FIXED_COST_ALLOCATION_METHOD;
|
||
|
||
if (!input.allocate) {
|
||
await client.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7)`,
|
||
[
|
||
row.cycle_code,
|
||
ledgerType,
|
||
row.cost_type,
|
||
amount,
|
||
method,
|
||
row.branch_code,
|
||
row.id,
|
||
]
|
||
);
|
||
}
|
||
|
||
const updated = await client.query(
|
||
`UPDATE fixed_costs
|
||
SET status = 20, approver_id = $2, approved_at = NOW()
|
||
WHERE id = $1
|
||
RETURNING *`,
|
||
[row.id, input.approverId || null]
|
||
);
|
||
|
||
await client.query('COMMIT');
|
||
return {
|
||
fixedCost: updated.rows[0],
|
||
ledgerType,
|
||
amount,
|
||
allocateHint: Boolean(input.allocate),
|
||
method,
|
||
};
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 修改固定成本主表,并重建该条 cost_details(删旧 + 按天分摊),与录入/删除闭环一致。
|
||
*/
|
||
export async function updateFixedCost(input: {
|
||
id: string;
|
||
cycleCode: string;
|
||
costType: string;
|
||
budgetAmount: number;
|
||
actualAmount: number;
|
||
remark?: string | null;
|
||
allocate?: boolean;
|
||
ctx?: TenantContext | null;
|
||
}) {
|
||
const entryId = String(input.id || '').trim();
|
||
if (!entryId) throw Object.assign(new Error('缺少记录 id'), { status: 400 });
|
||
const cycleCode = String(input.cycleCode || '').trim();
|
||
if (!/^\d{6}$/.test(cycleCode)) {
|
||
throw Object.assign(new Error('核算月份须为 YYYYMM'), { status: 400 });
|
||
}
|
||
const costType = String(input.costType || 'other').trim() || 'other';
|
||
const actual = Math.max(0, Number(input.actualAmount) || 0);
|
||
if (actual <= 0) throw Object.assign(new Error('实际金额须大于 0'), { status: 400 });
|
||
const budget = Math.max(0, Number(input.budgetAmount) || 0);
|
||
const method = FIXED_COST_ALLOCATION_METHOD;
|
||
const ledgerType = COST_TYPE_TO_LEDGER[costType] || 'fixed_overhead';
|
||
const wantAllocate = input.allocate !== false;
|
||
const remark = input.remark != null ? String(input.remark) : null;
|
||
|
||
const client = await pool.connect();
|
||
let row: Record<string, unknown>;
|
||
try {
|
||
await client.query('BEGIN');
|
||
const params: unknown[] = [entryId];
|
||
const branchSql = branchFilter(input.ctx, 'fc', params);
|
||
const locked = await client.query(
|
||
`SELECT * FROM fixed_costs fc WHERE fc.id = $1 ${branchSql} FOR UPDATE`,
|
||
params
|
||
);
|
||
if (!locked.rowCount) {
|
||
throw Object.assign(new Error('固定成本记录不存在'), { status: 404 });
|
||
}
|
||
const prev = locked.rows[0];
|
||
if (Number(prev.status) >= 30) {
|
||
throw Object.assign(new Error('已锁定的固定成本不可修改'), { status: 400 });
|
||
}
|
||
|
||
const updated = await client.query(
|
||
`UPDATE fixed_costs
|
||
SET cycle_code = $2,
|
||
cost_type = $3,
|
||
budget_amount = $4,
|
||
actual_amount = $5,
|
||
allocation_method = $6,
|
||
remark = $7,
|
||
status = GREATEST(COALESCE(status, 10), 20),
|
||
approved_at = COALESCE(approved_at, NOW())
|
||
WHERE id = $1
|
||
RETURNING *`,
|
||
[entryId, cycleCode, costType, budget, actual, method, remark]
|
||
);
|
||
row = updated.rows[0];
|
||
|
||
await client.query(
|
||
`DELETE FROM cost_details
|
||
WHERE reference_type = 'fixed_cost' AND reference_id = $1`,
|
||
[entryId]
|
||
);
|
||
await client.query('COMMIT');
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
|
||
let allocated = false;
|
||
if (wantAllocate && actual > 0) {
|
||
try {
|
||
await allocateCostPool({
|
||
cycleCode,
|
||
costType: ledgerType,
|
||
poolAmount: actual,
|
||
method,
|
||
branchCode: (row.branch_code as string | null) || null,
|
||
referenceType: 'fixed_cost',
|
||
referenceId: entryId,
|
||
costSubtype: costType,
|
||
});
|
||
allocated = true;
|
||
} catch {
|
||
await pool.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7)`,
|
||
[
|
||
cycleCode,
|
||
ledgerType,
|
||
costType,
|
||
actual,
|
||
method,
|
||
row.branch_code || null,
|
||
entryId,
|
||
]
|
||
);
|
||
}
|
||
} else if (actual > 0) {
|
||
await pool.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, cost_type, cost_subtype, amount, allocation_method,
|
||
allocated_amount, status, branch_code, reference_type, reference_id
|
||
) VALUES ($1,$2,$3,$4,$5,$4,20,$6,'fixed_cost',$7)`,
|
||
[
|
||
cycleCode,
|
||
ledgerType,
|
||
costType,
|
||
actual,
|
||
method,
|
||
row.branch_code || null,
|
||
entryId,
|
||
]
|
||
);
|
||
}
|
||
|
||
return { fixedCost: row, ledgerType, amount: actual, allocated };
|
||
}
|
||
|
||
export async function updateFixedCostVouchers(id: string, urls: string[], ctx?: TenantContext | null) {
|
||
// T9:UPDATE 前校验归属(跨分支 key ⇒ 403,原值保持不变)
|
||
await assertOwnedStoragePaths(ctx ?? null, 'invoices', urls);
|
||
const params: unknown[] = [urls, id];
|
||
const branchSql = branchFilter(ctx, 'fixed_costs', params);
|
||
const result = await pool.query(
|
||
`UPDATE fixed_costs SET voucher_urls = $1 WHERE id = $2 ${branchSql} RETURNING *`,
|
||
params
|
||
);
|
||
if (!result.rows.length) throw Object.assign(new Error('记录不存在'), { status: 404 });
|
||
return result.rows[0];
|
||
}
|
||
|
||
/** 删除固定成本,并清理其入账 reference(fixed_cost) */
|
||
export async function deleteFixedCost(id: string, ctx?: TenantContext | null) {
|
||
const entryId = String(id || '').trim();
|
||
if (!entryId) throw Object.assign(new Error('缺少记录 id'), { status: 400 });
|
||
|
||
const client = await pool.connect();
|
||
try {
|
||
await client.query('BEGIN');
|
||
const params: unknown[] = [entryId];
|
||
const branchSql = branchFilter(ctx, 'fc', params);
|
||
const locked = await client.query(
|
||
`SELECT id FROM fixed_costs fc WHERE fc.id = $1 ${branchSql} FOR UPDATE`,
|
||
params
|
||
);
|
||
if (!locked.rowCount) {
|
||
throw Object.assign(new Error('固定成本记录不存在'), { status: 404 });
|
||
}
|
||
|
||
await client.query(
|
||
`DELETE FROM cost_details
|
||
WHERE reference_type = 'fixed_cost' AND reference_id = $1`,
|
||
[entryId]
|
||
);
|
||
await client.query(`DELETE FROM fixed_costs WHERE id = $1`, [entryId]);
|
||
await client.query('COMMIT');
|
||
return { id: entryId, deleted: true as const };
|
||
} catch (error) {
|
||
await client.query('ROLLBACK');
|
||
throw error;
|
||
} finally {
|
||
client.release();
|
||
}
|
||
}
|