- 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 超长修复
907 lines
33 KiB
TypeScript
907 lines
33 KiB
TypeScript
import { pool } from '../db';
|
||
import { ORDER_ITEM_REVENUE_SQL, salesLinePredicateSql } from './orderItemRevenueSql';
|
||
import type { TenantContext } from './tenantScope';
|
||
import {
|
||
listNegativeMarginFromLedger,
|
||
normalizeFinanceDateField,
|
||
orderFinanceJoinSql,
|
||
orderFinanceRangeCondSql,
|
||
} from './marginQueryService';
|
||
import {
|
||
assertOwnedStoragePaths,
|
||
tryBuildSignedStoragePathForCtx,
|
||
type StorageOwnerCtx,
|
||
} from './storageObjectOwnership';
|
||
import { safeStorageFileName, stripStorageBranchPrefix } from './storageBucketConfig';
|
||
import { getStorageProvider } from './storageProvider';
|
||
import {
|
||
buildFreeCostAuditSnapshot,
|
||
writeFreeCostAuditLog,
|
||
type FreeCostAuditSource,
|
||
} from './freeCostAudit';
|
||
|
||
export interface FreeCostTypeItem {
|
||
code: string;
|
||
label: string;
|
||
}
|
||
|
||
/** 默认科目;库内 system_configs.free_cost_types 可覆盖并增删 */
|
||
export const DEFAULT_FREE_COST_TYPES: FreeCostTypeItem[] = [
|
||
{ code: 'maintenance', label: '维修' },
|
||
{ code: 'emergency', label: '应急' },
|
||
{ code: 'labor_misc', label: '人工' },
|
||
{ code: 'misc', label: '杂费' },
|
||
];
|
||
|
||
/** @deprecated 兼容旧引用,等同 DEFAULT_FREE_COST_TYPES */
|
||
export const FREE_COST_SUBTYPES = DEFAULT_FREE_COST_TYPES;
|
||
|
||
export function labelForFreeSubtype(
|
||
code: string | null | undefined,
|
||
types: FreeCostTypeItem[]
|
||
): string {
|
||
const key = String(code || 'misc').trim().toLowerCase() || 'misc';
|
||
const hit = types.find((t) => t.code === key);
|
||
if (hit?.label) return hit.label;
|
||
const builtin = DEFAULT_FREE_COST_TYPES.find((t) => t.code === key);
|
||
if (builtin) return builtin.label;
|
||
if (/^fc_[a-z0-9_]+$/i.test(key)) return '自定义科目';
|
||
return key;
|
||
}
|
||
|
||
export type FreeCostSubtype = string;
|
||
|
||
const FREE_COST_TYPE = 'free_overhead';
|
||
const FREE_COST_TYPES_KEY = 'free_cost_types';
|
||
const WARN_RATIO = 0.05;
|
||
/** 其他成本仅已入账计入合计;待审 10、驳回 30 不计(其它类型 status=30 仍为已归档) */
|
||
export const FREE_COST_POSTED_CD_SQL = `COALESCE(cd.status, 20) = 20`;
|
||
|
||
export const FREE_COST_STATUS = {
|
||
pending: 10,
|
||
posted: 20,
|
||
rejected: 30,
|
||
} as const;
|
||
|
||
export type FreeCostListStatus =
|
||
| typeof FREE_COST_STATUS.pending
|
||
| typeof FREE_COST_STATUS.posted
|
||
| typeof FREE_COST_STATUS.rejected;
|
||
|
||
export type FreeCostStatusCounts = {
|
||
pending: number;
|
||
posted: number;
|
||
rejected: number;
|
||
};
|
||
|
||
export type FreeCostStatusAmounts = {
|
||
pending: number;
|
||
posted: number;
|
||
rejected: number;
|
||
};
|
||
|
||
export function roundFreeCostMoney(value: unknown): number {
|
||
return Math.round((Number(value) || 0) * 100) / 100;
|
||
}
|
||
|
||
export function parseFreeCostStatusAmounts(row: {
|
||
pending_amount?: unknown;
|
||
posted_amount?: unknown;
|
||
rejected_amount?: unknown;
|
||
} | null | undefined): FreeCostStatusAmounts {
|
||
return {
|
||
pending: roundFreeCostMoney(row?.pending_amount),
|
||
posted: roundFreeCostMoney(row?.posted_amount),
|
||
rejected: roundFreeCostMoney(row?.rejected_amount),
|
||
};
|
||
}
|
||
|
||
export function parseFreeCostListStatus(raw: unknown): FreeCostListStatus | undefined {
|
||
if (raw == null || raw === '') return undefined;
|
||
const n = Number(Array.isArray(raw) ? raw[0] : raw);
|
||
if (n === FREE_COST_STATUS.pending || n === FREE_COST_STATUS.posted || n === FREE_COST_STATUS.rejected) {
|
||
return n;
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
const FREE_COST_SUBTYPE_CODE_RE = /^[a-zA-Z0-9_]{1,64}$/;
|
||
const FREE_COST_UUID_RE =
|
||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||
|
||
export function parseFreeCostListSubtype(raw: unknown): string | undefined {
|
||
const value = String(Array.isArray(raw) ? raw[0] : raw || '').trim();
|
||
return FREE_COST_SUBTYPE_CODE_RE.test(value) ? value : undefined;
|
||
}
|
||
|
||
export function parseFreeCostListApplicantId(raw: unknown): string | undefined {
|
||
const value = String(Array.isArray(raw) ? raw[0] : raw || '').trim();
|
||
return FREE_COST_UUID_RE.test(value) ? value : undefined;
|
||
}
|
||
|
||
export type FreeCostListSortKey = 'amount' | 'subtype';
|
||
|
||
export function parseFreeCostListSort(raw: unknown): FreeCostListSortKey | undefined {
|
||
const value = String(Array.isArray(raw) ? raw[0] : raw || '').trim().toLowerCase();
|
||
return value === 'amount' || value === 'subtype' ? value : undefined;
|
||
}
|
||
|
||
export function parseFreeCostListSortDir(raw: unknown): 'ASC' | 'DESC' {
|
||
const value = String(Array.isArray(raw) ? raw[0] : raw || '').trim().toLowerCase();
|
||
return value === 'asc' ? 'ASC' : 'DESC';
|
||
}
|
||
|
||
export function parseFreeCostVoucherPaths(raw: unknown): string[] {
|
||
if (Array.isArray(raw)) {
|
||
return raw.map((item) => String(item || '').trim()).filter(Boolean);
|
||
}
|
||
const text = String(raw || '').trim();
|
||
if (!text) return [];
|
||
if (text.startsWith('[')) {
|
||
try {
|
||
const parsed = JSON.parse(text);
|
||
if (Array.isArray(parsed)) {
|
||
return parsed.map((item) => String(item || '').trim()).filter(Boolean);
|
||
}
|
||
} catch {
|
||
/* fall through */
|
||
}
|
||
}
|
||
return [text];
|
||
}
|
||
|
||
export function normalizeFreeCostVoucherPaths(raw: unknown): string[] {
|
||
const out: string[] = [];
|
||
for (const item of parseFreeCostVoucherPaths(raw)) {
|
||
try {
|
||
const safe = safeStorageFileName(item);
|
||
if (safe) out.push(safe);
|
||
} catch {
|
||
/* skip invalid */
|
||
}
|
||
}
|
||
return [...new Set(out)].slice(0, 20);
|
||
}
|
||
|
||
/** 识图用:仅允许 invoices 桶 free-cost/ 下已上传凭证 */
|
||
export function assertFreeCostVoucherStoragePath(raw: string): string {
|
||
const text = String(raw || '').trim();
|
||
if (!text) {
|
||
throw Object.assign(new Error('缺少凭证路径'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
let safe: string;
|
||
try {
|
||
safe = safeStorageFileName(text);
|
||
} catch {
|
||
throw Object.assign(new Error('凭证路径无效'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
// SEC-5:允许新 key 的 `<branch>/` 前缀
|
||
const withoutBranch = stripStorageBranchPrefix(safe);
|
||
if (!withoutBranch.startsWith('free-cost/') || withoutBranch.startsWith('free-cost-invoice/')) {
|
||
throw Object.assign(new Error('仅支持 free-cost 凭证'), { status: 400, code: 'invalid_request' });
|
||
}
|
||
return safe;
|
||
}
|
||
|
||
export async function loadFreeCostVoucherImageBase64(voucherPath: string): Promise<string> {
|
||
const safe = assertFreeCostVoucherStoragePath(voucherPath);
|
||
const obj = await getStorageProvider().getObject('invoices', safe);
|
||
if (!obj?.buffer?.length) {
|
||
throw Object.assign(new Error('凭证文件不存在或无法读取'), { status: 404, code: 'not_found' });
|
||
}
|
||
return obj.buffer.toString('base64');
|
||
}
|
||
|
||
function signFreeCostVoucherUrls(paths: string[]): string[] {
|
||
// T9F-5:无前缀旧 key 不再同步签发;未迁移时给空串,列表不 500。
|
||
return paths.map((path) => tryBuildSignedStoragePathForCtx(undefined, 'invoices', path) ?? '');
|
||
}
|
||
|
||
function normalizeTypeList(raw: unknown): FreeCostTypeItem[] {
|
||
const arr = Array.isArray(raw)
|
||
? raw
|
||
: typeof raw === 'string'
|
||
? (() => {
|
||
try {
|
||
return JSON.parse(raw);
|
||
} catch {
|
||
return null;
|
||
}
|
||
})()
|
||
: raw && typeof raw === 'object' && Array.isArray((raw as { types?: unknown }).types)
|
||
? (raw as { types: unknown[] }).types
|
||
: null;
|
||
if (!Array.isArray(arr) || !arr.length) return [...DEFAULT_FREE_COST_TYPES];
|
||
const seen = new Set<string>();
|
||
const list: FreeCostTypeItem[] = [];
|
||
for (const item of arr) {
|
||
const code = String((item as FreeCostTypeItem)?.code || '')
|
||
.trim()
|
||
.toLowerCase()
|
||
.replace(/[^a-z0-9_]/g, '_')
|
||
.slice(0, 40);
|
||
const label = String((item as FreeCostTypeItem)?.label || '').trim().slice(0, 40);
|
||
if (!code || !label || seen.has(code)) continue;
|
||
seen.add(code);
|
||
list.push({ code, label });
|
||
}
|
||
return list.length ? list : [...DEFAULT_FREE_COST_TYPES];
|
||
}
|
||
|
||
function codeFromLabel(label: string): string {
|
||
const ascii = label
|
||
.trim()
|
||
.toLowerCase()
|
||
.replace(/[^a-z0-9]+/g, '_')
|
||
.replace(/^_|_$/g, '')
|
||
.slice(0, 32);
|
||
if (ascii && /[a-z]/.test(ascii)) return ascii;
|
||
return `fc_${Date.now().toString(36)}`;
|
||
}
|
||
|
||
export async function listFreeCostTypes(branchCode?: string | null): Promise<FreeCostTypeItem[]> {
|
||
const branch = String(branchCode || '').trim();
|
||
if (branch) {
|
||
const byBranch = await pool.query(
|
||
`SELECT config_value FROM system_configs
|
||
WHERE config_key = $1 AND branch_code = $2 LIMIT 1`,
|
||
[FREE_COST_TYPES_KEY, branch]
|
||
);
|
||
if (byBranch.rowCount) return normalizeTypeList(byBranch.rows[0].config_value);
|
||
}
|
||
const global = await pool.query(
|
||
`SELECT config_value FROM system_configs
|
||
WHERE config_key = $1 AND (branch_code IS NULL OR TRIM(branch_code) = '')
|
||
ORDER BY updated_at DESC NULLS LAST
|
||
LIMIT 1`,
|
||
[FREE_COST_TYPES_KEY]
|
||
);
|
||
if (global.rowCount) return normalizeTypeList(global.rows[0].config_value);
|
||
return [...DEFAULT_FREE_COST_TYPES];
|
||
}
|
||
|
||
async function saveFreeCostTypes(types: FreeCostTypeItem[], branchCode?: string | null) {
|
||
const branch = String(branchCode || '').trim() || null;
|
||
const value = JSON.stringify(types);
|
||
if (branch) {
|
||
const updated = await pool.query(
|
||
`UPDATE system_configs
|
||
SET config_value = $2::jsonb, updated_at = NOW()
|
||
WHERE config_key = $1 AND branch_code = $3`,
|
||
[FREE_COST_TYPES_KEY, value, branch]
|
||
);
|
||
if (updated.rowCount) return;
|
||
await pool.query(
|
||
`INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code)
|
||
VALUES ($1, $2::jsonb, 'finance', '其他成本科目类型列表(可增删)', $3)`,
|
||
[FREE_COST_TYPES_KEY, value, branch]
|
||
);
|
||
return;
|
||
}
|
||
const updated = await pool.query(
|
||
`UPDATE system_configs
|
||
SET config_value = $2::jsonb, updated_at = NOW()
|
||
WHERE config_key = $1 AND (branch_code IS NULL OR TRIM(branch_code) = '')`,
|
||
[FREE_COST_TYPES_KEY, value]
|
||
);
|
||
if (updated.rowCount) return;
|
||
await pool.query(
|
||
`INSERT INTO system_configs (config_key, config_value, config_group, description, branch_code)
|
||
VALUES ($1, $2::jsonb, 'finance', '其他成本科目类型列表(可增删)', NULL)`,
|
||
[FREE_COST_TYPES_KEY, value]
|
||
);
|
||
}
|
||
|
||
export async function addFreeCostType(
|
||
label: string,
|
||
branchCode?: string | null
|
||
): Promise<FreeCostTypeItem[]> {
|
||
const name = String(label || '').trim().slice(0, 40);
|
||
if (!name) throw new Error('请填写类型名称');
|
||
const types = await listFreeCostTypes(branchCode);
|
||
if (types.some((t) => t.label === name)) throw new Error('该类型已存在');
|
||
let code = codeFromLabel(name);
|
||
if (types.some((t) => t.code === code)) {
|
||
code = `${code}_${Date.now().toString(36).slice(-4)}`;
|
||
}
|
||
const next = [...types, { code, label: name }];
|
||
await saveFreeCostTypes(next, branchCode);
|
||
return next;
|
||
}
|
||
|
||
export async function renameFreeCostType(
|
||
code: string,
|
||
label: string,
|
||
branchCode?: string | null
|
||
): Promise<FreeCostTypeItem[]> {
|
||
const key = String(code || '')
|
||
.trim()
|
||
.toLowerCase();
|
||
const name = String(label || '').trim().slice(0, 40);
|
||
if (!key) throw new Error('缺少类型编码');
|
||
if (!name) throw new Error('请填写类型名称');
|
||
const types = await listFreeCostTypes(branchCode);
|
||
if (types.some((t) => t.code !== key && t.label === name)) throw new Error('该类型名称已存在');
|
||
if (types.some((t) => t.code === key)) {
|
||
const next = types.map((t) => (t.code === key ? { ...t, label: name } : t));
|
||
await saveFreeCostTypes(next, branchCode);
|
||
return next;
|
||
}
|
||
const next = [...types, { code: key, label: name }];
|
||
await saveFreeCostTypes(next, branchCode);
|
||
return next;
|
||
}
|
||
|
||
export async function deleteFreeCostType(
|
||
code: string,
|
||
branchCode?: string | null
|
||
): Promise<FreeCostTypeItem[]> {
|
||
const key = String(code || '')
|
||
.trim()
|
||
.toLowerCase();
|
||
if (!key) throw new Error('缺少类型编码');
|
||
const types = await listFreeCostTypes(branchCode);
|
||
if (types.length <= 1) throw new Error('至少保留一个成本类型');
|
||
if (!types.some((t) => t.code === key)) throw new Error('类型不存在');
|
||
const next = types.filter((t) => t.code !== key);
|
||
await saveFreeCostTypes(next, branchCode);
|
||
return next;
|
||
}
|
||
|
||
/** 录入日 → 日周期码 YYYYMMDD(其他成本归属录入当天,不分摊) */
|
||
export function freeCostDayCycleCode(date = new Date()) {
|
||
const y = date.getFullYear();
|
||
const m = String(date.getMonth() + 1).padStart(2, '0');
|
||
const d = String(date.getDate()).padStart(2, '0');
|
||
return `${y}${m}${d}`;
|
||
}
|
||
|
||
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 '';
|
||
}
|
||
|
||
/** 按录入日筛选:YYYYMMDD_YYYYMMDD → 区间;YYYYMM / YYYY-MM → 整月;YYYYMMDD → 当天;否则回落 cycle_code 精确匹配 */
|
||
function entryDateFilter(
|
||
periodCode: string | undefined,
|
||
alias: string,
|
||
params: unknown[]
|
||
): string {
|
||
if (!periodCode) return '';
|
||
const original = String(periodCode).trim();
|
||
// 自定义区间 YYYYMMDD_YYYYMMDD(注意:raw 去 '-' 但保留下划线)
|
||
const rangeMatch = /^(\d{8})_(\d{8})$/.exec(original.replace(/-/g, ''));
|
||
if (rangeMatch) {
|
||
const from = `${rangeMatch[1].slice(0, 4)}-${rangeMatch[1].slice(4, 6)}-${rangeMatch[1].slice(6, 8)}`;
|
||
const to = `${rangeMatch[2].slice(0, 4)}-${rangeMatch[2].slice(4, 6)}-${rangeMatch[2].slice(6, 8)}`;
|
||
params.push(from, to);
|
||
return ` AND (${alias}.created_at AT TIME ZONE 'Asia/Shanghai')::date >= $${params.length - 1}::date
|
||
AND (${alias}.created_at AT TIME ZONE 'Asia/Shanghai')::date <= $${params.length}::date`;
|
||
}
|
||
const raw = original.replace(/-/g, '');
|
||
if (/^\d{8}$/.test(raw)) {
|
||
const day = `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`;
|
||
params.push(day);
|
||
return ` AND (${alias}.created_at AT TIME ZONE 'Asia/Shanghai')::date = $${params.length}::date`;
|
||
}
|
||
if (/^\d{6}$/.test(raw)) {
|
||
const monthStart = `${raw.slice(0, 4)}-${raw.slice(4, 6)}-01`;
|
||
params.push(monthStart);
|
||
return ` AND ${alias}.created_at >= ($${params.length}::date)
|
||
AND ${alias}.created_at < ($${params.length}::date + INTERVAL '1 month')`;
|
||
}
|
||
params.push(periodCode);
|
||
return ` AND ${alias}.cycle_code = $${params.length}`;
|
||
}
|
||
|
||
/** 关键词归类其他成本科目(对照当前类型列表) */
|
||
export function categorizeFreeCostText(
|
||
text: string,
|
||
types: FreeCostTypeItem[] = DEFAULT_FREE_COST_TYPES
|
||
): FreeCostSubtype {
|
||
const raw = text.trim();
|
||
const fallback =
|
||
types.find((t) => t.code === 'misc')?.code || types[types.length - 1]?.code || 'misc';
|
||
if (!raw) return fallback;
|
||
|
||
const byBuiltin: Array<{ re: RegExp; code: string }> = [
|
||
{ re: /维修|修理|维保|设备/, code: 'maintenance' },
|
||
{ re: /应急|紧急|突发/, code: 'emergency' },
|
||
{ re: /人工|劳务|加班|临时工/, code: 'labor_misc' },
|
||
];
|
||
for (const rule of byBuiltin) {
|
||
if (rule.re.test(raw) && types.some((t) => t.code === rule.code)) return rule.code;
|
||
}
|
||
for (const t of types) {
|
||
if (t.label && raw.includes(t.label)) return t.code;
|
||
}
|
||
return fallback;
|
||
}
|
||
|
||
function decorateFreeCostRow(row: Record<string, unknown> | null | undefined, types: FreeCostTypeItem[]) {
|
||
if (!row) return row;
|
||
const subtype = String(row.cost_subtype || '');
|
||
const voucherPaths = normalizeFreeCostVoucherPaths(row.voucher_url);
|
||
return {
|
||
...row,
|
||
subtype_label: labelForFreeSubtype(subtype, types),
|
||
voucher_paths: voucherPaths,
|
||
voucher_urls: signFreeCostVoucherUrls(voucherPaths),
|
||
inputter_name: row.inputter_name ? String(row.inputter_name) : null,
|
||
auditor_name: row.auditor_name ? String(row.auditor_name) : null,
|
||
};
|
||
}
|
||
|
||
export async function createFreeCostEntry(input: {
|
||
cycleCode: string;
|
||
amount: number;
|
||
description: string;
|
||
subtype?: FreeCostSubtype;
|
||
orderCode?: string | null;
|
||
branchCode?: string | null;
|
||
inputterId?: string | null;
|
||
voucherUrls?: unknown;
|
||
requireVoucher?: boolean;
|
||
/** 本条将挂发票图,发票不算进 voucher_url,但仍满足必传照片 */
|
||
invoicePhoto?: boolean;
|
||
status?: number;
|
||
source?: FreeCostAuditSource;
|
||
/** 写入口归属校验用租户上下文(route 传入;缺省按 branchCode fail-closed) */
|
||
ownerCtx?: StorageOwnerCtx | null;
|
||
}) {
|
||
const types = await listFreeCostTypes(input.branchCode);
|
||
let subtype = String(input.subtype || '').trim().toLowerCase();
|
||
if (!subtype || !types.some((t) => t.code === subtype)) {
|
||
if (input.requireVoucher) {
|
||
throw Object.assign(new Error('请选择有效的成本类型'), { status: 400 });
|
||
}
|
||
subtype = categorizeFreeCostText(input.description, types);
|
||
}
|
||
const label = types.find((item) => item.code === subtype)?.label || subtype || '杂费';
|
||
const description = String(input.description || '').trim().slice(0, 200);
|
||
const amountRaw = Number(input.amount);
|
||
if (!Number.isFinite(amountRaw) || amountRaw <= 0) {
|
||
throw Object.assign(new Error('金额必须大于 0'), { status: 400 });
|
||
}
|
||
const amount = Math.round(amountRaw * 100) / 100;
|
||
const voucherPaths = normalizeFreeCostVoucherPaths(input.voucherUrls);
|
||
if (input.requireVoucher && voucherPaths.length < 1 && !input.invoicePhoto) {
|
||
throw Object.assign(new Error('请上传凭证照片'), { status: 400 });
|
||
}
|
||
const status =
|
||
Number(input.status) === FREE_COST_STATUS.pending
|
||
? FREE_COST_STATUS.pending
|
||
: FREE_COST_STATUS.posted;
|
||
const dayCycle = freeCostDayCycleCode();
|
||
// T9 写入口:跨分支/无归属凭证 key 必须在 INSERT 之前 403,不能先落库再在装饰层才拦
|
||
await assertOwnedStoragePaths(
|
||
input.ownerCtx ?? { branchCode: input.branchCode || null },
|
||
'invoices',
|
||
voucherPaths
|
||
);
|
||
const result = await pool.query(
|
||
`INSERT INTO cost_details (
|
||
cycle_code, order_code, cost_type, cost_subtype, amount,
|
||
allocation_method, allocated_amount, status, branch_code, reference_type, reference_id,
|
||
inputter_id, voucher_url
|
||
) VALUES ($1, NULL, $2, $3, $4, 'none', $4, $5, $6, 'free_cost', $7, $8, $9)
|
||
RETURNING *`,
|
||
[
|
||
dayCycle,
|
||
FREE_COST_TYPE,
|
||
subtype,
|
||
amount,
|
||
status,
|
||
input.branchCode || null,
|
||
description || null,
|
||
input.inputterId || null,
|
||
voucherPaths.length ? JSON.stringify(voucherPaths) : null,
|
||
]
|
||
);
|
||
const row = result.rows[0];
|
||
const decorated = decorateFreeCostRow(row, types);
|
||
const snap = buildFreeCostAuditSnapshot({
|
||
id: row?.id,
|
||
amount,
|
||
costSubtype: subtype,
|
||
subtypeLabel: label,
|
||
status,
|
||
remark: description || null,
|
||
voucherCount: voucherPaths.length,
|
||
source: input.source === 'mp' ? 'mp' : 'web',
|
||
});
|
||
await writeFreeCostAuditLog({
|
||
operatorId: input.inputterId,
|
||
operationType: 'free_cost_create',
|
||
targetId: String(row?.id || ''),
|
||
branchCode: input.branchCode || null,
|
||
newValue: snap,
|
||
});
|
||
return { row: decorated, subtype, label };
|
||
}
|
||
|
||
const FREE_COST_PAGE_SIZES = new Set([10, 20, 50, 100]);
|
||
|
||
export async function listFreeCostEntries(
|
||
ctx?: TenantContext | null,
|
||
options?: {
|
||
cycleCode?: string;
|
||
page?: number;
|
||
pageSize?: number;
|
||
limit?: number;
|
||
inputterId?: string | null;
|
||
status?: unknown;
|
||
subtype?: unknown;
|
||
applicantId?: unknown;
|
||
sort?: unknown;
|
||
sortDir?: unknown;
|
||
}
|
||
) {
|
||
const pageSizeRaw = Number(options?.pageSize ?? options?.limit) || 10;
|
||
const pageSize = FREE_COST_PAGE_SIZES.has(pageSizeRaw) ? pageSizeRaw : 10;
|
||
const page = Math.max(1, Number(options?.page) || 1);
|
||
const offset = (page - 1) * pageSize;
|
||
const types = await listFreeCostTypes(ctx?.branchCode || null);
|
||
|
||
const params: unknown[] = [FREE_COST_TYPE];
|
||
const branchSql = branchFilter(ctx, 'cd', params);
|
||
const dateSql = entryDateFilter(options?.cycleCode, 'cd', params);
|
||
let scopeSql = '';
|
||
const inputterId = String(options?.inputterId || '').trim();
|
||
if (inputterId) {
|
||
params.push(inputterId);
|
||
scopeSql += ` AND cd.inputter_id = $${params.length}::uuid`;
|
||
}
|
||
const subtype = parseFreeCostListSubtype(options?.subtype);
|
||
if (subtype) {
|
||
params.push(subtype);
|
||
scopeSql += ` AND cd.cost_subtype = $${params.length}`;
|
||
}
|
||
|
||
const applicantParams = [...params];
|
||
const applicantScopeSql = scopeSql;
|
||
let listScopeSql = scopeSql;
|
||
const applicantId = inputterId ? undefined : parseFreeCostListApplicantId(options?.applicantId);
|
||
if (applicantId) {
|
||
params.push(applicantId);
|
||
listScopeSql += ` AND cd.inputter_id = $${params.length}::uuid`;
|
||
}
|
||
|
||
const statusFilter = parseFreeCostListStatus(options?.status);
|
||
let statusSql = '';
|
||
let totalExpr = 'COUNT(*)::int';
|
||
let amountExpr = 'COALESCE(SUM(cd.amount), 0)::numeric';
|
||
if (statusFilter != null) {
|
||
params.push(statusFilter);
|
||
statusSql = ` AND COALESCE(cd.status, 20) = $${params.length}`;
|
||
totalExpr = `COUNT(*) FILTER (WHERE COALESCE(cd.status, 20) = $${params.length})::int`;
|
||
amountExpr = `COALESCE(SUM(cd.amount) FILTER (WHERE COALESCE(cd.status, 20) = $${params.length}), 0)::numeric`;
|
||
}
|
||
|
||
const countResult = await pool.query(
|
||
`SELECT
|
||
${totalExpr} AS total,
|
||
${amountExpr} AS amount_total,
|
||
COUNT(*) FILTER (WHERE COALESCE(cd.status, 20) = 10)::int AS pending,
|
||
COUNT(*) FILTER (WHERE COALESCE(cd.status, 20) = 20)::int AS posted,
|
||
COUNT(*) FILTER (WHERE COALESCE(cd.status, 20) = 30)::int AS rejected,
|
||
COALESCE(SUM(cd.amount) FILTER (WHERE COALESCE(cd.status, 20) = 10), 0)::numeric AS pending_amount,
|
||
COALESCE(SUM(cd.amount) FILTER (WHERE COALESCE(cd.status, 20) = 20), 0)::numeric AS posted_amount,
|
||
COALESCE(SUM(cd.amount) FILTER (WHERE COALESCE(cd.status, 20) = 30), 0)::numeric AS rejected_amount,
|
||
-- 付款凭证核销情况(2026-10-08 新增):已入账里「已付款 / 未付款」的笔数与金额。
|
||
-- 只读聚合,不影响金额/状态口径;表由 migrations/20261008_free_cost_payment_vouchers.sql 建。
|
||
COUNT(*) FILTER (WHERE COALESCE(cd.status, 20) = 20 AND EXISTS (
|
||
SELECT 1 FROM free_cost_payment_vouchers v WHERE v.matched_cost_detail_id = cd.id
|
||
))::int AS paid_count,
|
||
COUNT(*) FILTER (WHERE COALESCE(cd.status, 20) = 20 AND NOT EXISTS (
|
||
SELECT 1 FROM free_cost_payment_vouchers v WHERE v.matched_cost_detail_id = cd.id
|
||
))::int AS unpaid_count,
|
||
COALESCE(SUM(cd.amount) FILTER (WHERE COALESCE(cd.status, 20) = 20 AND EXISTS (
|
||
SELECT 1 FROM free_cost_payment_vouchers v WHERE v.matched_cost_detail_id = cd.id
|
||
)), 0)::numeric AS paid_amount,
|
||
COALESCE(SUM(cd.amount) FILTER (WHERE COALESCE(cd.status, 20) = 20 AND NOT EXISTS (
|
||
SELECT 1 FROM free_cost_payment_vouchers v WHERE v.matched_cost_detail_id = cd.id
|
||
)), 0)::numeric AS unpaid_amount
|
||
FROM cost_details cd
|
||
WHERE cd.cost_type = $1 ${branchSql}${dateSql}${listScopeSql}`,
|
||
params
|
||
);
|
||
|
||
const total = Number(countResult.rows[0]?.total) || 0;
|
||
const amountTotal = roundFreeCostMoney(countResult.rows[0]?.amount_total);
|
||
const statusCounts: FreeCostStatusCounts = {
|
||
pending: Number(countResult.rows[0]?.pending) || 0,
|
||
posted: Number(countResult.rows[0]?.posted) || 0,
|
||
rejected: Number(countResult.rows[0]?.rejected) || 0,
|
||
};
|
||
const statusAmounts = parseFreeCostStatusAmounts(countResult.rows[0]);
|
||
// 已入账拆成「已付款 / 未付款」(付款凭证核销口径;未付款合计给页面用)
|
||
const paymentAmounts = {
|
||
paidAmount: roundFreeCostMoney(countResult.rows[0]?.paid_amount),
|
||
unpaidAmount: roundFreeCostMoney(countResult.rows[0]?.unpaid_amount),
|
||
paidCount: Number(countResult.rows[0]?.paid_count) || 0,
|
||
unpaidCount: Number(countResult.rows[0]?.unpaid_count) || 0,
|
||
};
|
||
|
||
const applicantResult = await pool.query(
|
||
`SELECT DISTINCT cd.inputter_id::text AS id,
|
||
COALESCE(NULLIF(TRIM(p.full_name), ''), NULLIF(TRIM(p.username), ''), '') AS name
|
||
FROM cost_details cd
|
||
LEFT JOIN public.profiles p ON p.id = cd.inputter_id
|
||
WHERE cd.cost_type = $1 ${branchSql}${dateSql}${applicantScopeSql}
|
||
AND cd.inputter_id IS NOT NULL
|
||
ORDER BY 2 ASC, 1 ASC`,
|
||
applicantParams
|
||
);
|
||
const applicants = applicantResult.rows
|
||
.map((row) => ({
|
||
id: String(row.id || '').trim(),
|
||
name: String(row.name || '').trim(),
|
||
}))
|
||
.filter((row) => row.id);
|
||
|
||
const sortKey = parseFreeCostListSort(options?.sort);
|
||
const sortDir = parseFreeCostListSortDir(options?.sortDir);
|
||
const listParams = [...params];
|
||
let orderSql =
|
||
'ORDER BY CASE WHEN COALESCE(cd.status, 20) = 10 THEN 0 ELSE 1 END, cd.created_at DESC';
|
||
if (sortKey === 'amount') {
|
||
orderSql = `ORDER BY cd.amount ${sortDir} NULLS LAST, cd.created_at DESC`;
|
||
} else if (sortKey === 'subtype') {
|
||
listParams.push(types.map((item) => item.code));
|
||
const catalogIdx = listParams.length;
|
||
orderSql = `ORDER BY COALESCE(array_position($${catalogIdx}::text[], cd.cost_subtype), 2147483647) ${sortDir}, cd.cost_subtype ${sortDir} NULLS LAST, cd.created_at DESC`;
|
||
}
|
||
listParams.push(pageSize, offset);
|
||
const result = await pool.query(
|
||
`SELECT cd.*,
|
||
COALESCE(NULLIF(TRIM(p.full_name), ''), NULLIF(TRIM(p.username), '')) AS inputter_name,
|
||
COALESCE(NULLIF(TRIM(ap.full_name), ''), NULLIF(TRIM(ap.username), '')) AS auditor_name
|
||
FROM cost_details cd
|
||
LEFT JOIN public.profiles p ON p.id = cd.inputter_id
|
||
LEFT JOIN public.profiles ap ON ap.id = cd.auditor_id
|
||
WHERE cd.cost_type = $1 ${branchSql}${dateSql}${listScopeSql}${statusSql}
|
||
${orderSql}
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||
listParams
|
||
);
|
||
|
||
return {
|
||
rows: result.rows.map((row) => decorateFreeCostRow(row, types)),
|
||
total,
|
||
amountTotal,
|
||
page,
|
||
pageSize,
|
||
statusCounts,
|
||
statusAmounts,
|
||
paymentAmounts,
|
||
applicants,
|
||
};
|
||
}
|
||
|
||
export async function getFreeCostSummary(
|
||
ctx?: TenantContext | null,
|
||
cycleCode?: string,
|
||
dateFieldRaw?: string | null
|
||
) {
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const params: unknown[] = [FREE_COST_TYPE];
|
||
const branchSql = branchFilter(ctx, 'cd', params);
|
||
// 其他成本为期间费用:始终按入账日
|
||
const dateSql = entryDateFilter(cycleCode, 'cd', params);
|
||
|
||
const freeResult = await pool.query(
|
||
`SELECT COALESCE(SUM(cd.amount), 0) AS free_total
|
||
FROM cost_details cd
|
||
WHERE cd.cost_type = $1 AND ${FREE_COST_POSTED_CD_SQL} ${branchSql}${dateSql}`,
|
||
params
|
||
);
|
||
|
||
// 占比对照:营收按订单 date_field(默认配送日)
|
||
const revenueParams: unknown[] = [];
|
||
const orderBranchSql = branchFilter(ctx, 'o', revenueParams);
|
||
let orderJoinSql = '';
|
||
let orderCycleSql = '';
|
||
const original = cycleCode ? String(cycleCode).trim() : '';
|
||
const rangeMatch = /^(\d{8})_(\d{8})$/.exec(original.replace(/-/g, ''));
|
||
if (rangeMatch) {
|
||
const from = `${rangeMatch[1].slice(0, 4)}-${rangeMatch[1].slice(4, 6)}-${rangeMatch[1].slice(6, 8)}`;
|
||
const to = `${rangeMatch[2].slice(0, 4)}-${rangeMatch[2].slice(4, 6)}-${rangeMatch[2].slice(6, 8)}`;
|
||
revenueParams.push(from, to);
|
||
const fromIdx = revenueParams.length - 1;
|
||
const toIdx = revenueParams.length;
|
||
orderJoinSql = orderFinanceJoinSql(dateField, true);
|
||
orderCycleSql = ` AND ${orderFinanceRangeCondSql(dateField, fromIdx, toIdx)}`;
|
||
} else {
|
||
const monthKey = original.replace(/-/g, '').slice(0, 6);
|
||
if (/^\d{6}$/.test(monthKey)) {
|
||
revenueParams.push(monthKey);
|
||
orderCycleSql = ` AND o.cycle_code = $${revenueParams.length}`;
|
||
}
|
||
}
|
||
|
||
const revenueResult = await pool.query(
|
||
`SELECT COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) AS revenue_total
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderJoinSql}
|
||
WHERE ${salesLinePredicateSql('o', 'oi')} ${orderBranchSql}${orderCycleSql}`,
|
||
revenueParams
|
||
);
|
||
|
||
const freeTotal = Number(freeResult.rows[0]?.free_total) || 0;
|
||
const revenueTotal = Number(revenueResult.rows[0]?.revenue_total) || 0;
|
||
const ratio = revenueTotal > 0 ? freeTotal / revenueTotal : 0;
|
||
const warnExceeded = ratio > WARN_RATIO;
|
||
|
||
return {
|
||
freeTotal,
|
||
revenueTotal,
|
||
ratio,
|
||
ratioPct: Math.round(ratio * 10000) / 100,
|
||
warnThresholdPct: WARN_RATIO * 100,
|
||
warnExceeded,
|
||
message: warnExceeded
|
||
? `其他成本占营收 ${(ratio * 100).toFixed(2)}%,已超过 ${WARN_RATIO * 100}% 预警线`
|
||
: undefined,
|
||
};
|
||
}
|
||
|
||
/** 删除一条其他成本入账 */
|
||
export async function deleteFreeCostEntry(
|
||
id: string,
|
||
ctx?: TenantContext | null,
|
||
operatorId?: string | null
|
||
) {
|
||
const entryId = String(id || '').trim();
|
||
if (!entryId) throw new Error('缺少记录 id');
|
||
const params: unknown[] = [FREE_COST_TYPE, entryId];
|
||
const branchSql = branchFilter(ctx, 'cost_details', params);
|
||
const existing = await pool.query(
|
||
`SELECT id, amount, cost_subtype, status, reference_id, voucher_url, branch_code
|
||
FROM cost_details
|
||
WHERE cost_type = $1 AND id = $2::uuid ${branchSql}
|
||
LIMIT 1`,
|
||
params
|
||
);
|
||
const beforeRow = existing.rows[0];
|
||
if (!beforeRow) throw Object.assign(new Error('其他成本记录不存在'), { status: 404 });
|
||
const delParams: unknown[] = [FREE_COST_TYPE, entryId];
|
||
const delBranch = branchFilter(ctx, 'cost_details', delParams);
|
||
const result = await pool.query(
|
||
`DELETE FROM cost_details
|
||
WHERE cost_type = $1 AND id = $2::uuid ${delBranch}
|
||
RETURNING id`,
|
||
delParams
|
||
);
|
||
if (!result.rowCount) throw Object.assign(new Error('其他成本记录不存在'), { status: 404 });
|
||
const types = await listFreeCostTypes(ctx?.branchCode || beforeRow.branch_code || null);
|
||
const voucherCount = normalizeFreeCostVoucherPaths(beforeRow.voucher_url).length;
|
||
const snap = buildFreeCostAuditSnapshot({
|
||
id: beforeRow.id,
|
||
amount: beforeRow.amount,
|
||
costSubtype: beforeRow.cost_subtype,
|
||
subtypeLabel: labelForFreeSubtype(String(beforeRow.cost_subtype || ''), types),
|
||
status: beforeRow.status,
|
||
remark: beforeRow.reference_id,
|
||
voucherCount,
|
||
});
|
||
await writeFreeCostAuditLog({
|
||
operatorId,
|
||
operationType: 'free_cost_delete',
|
||
targetId: entryId,
|
||
branchCode: beforeRow.branch_code || ctx?.branchCode || null,
|
||
oldValue: snap,
|
||
newValue: { ...snap, deleted: true },
|
||
});
|
||
return { id: entryId, deleted: true as const };
|
||
}
|
||
|
||
export async function approveFreeCostEntry(
|
||
id: string,
|
||
auditorId: string | null | undefined,
|
||
ctx?: TenantContext | null
|
||
) {
|
||
const entryId = String(id || '').trim();
|
||
if (!entryId) throw Object.assign(new Error('缺少记录 id'), { status: 400 });
|
||
const params: unknown[] = [FREE_COST_TYPE, entryId, FREE_COST_STATUS.pending, auditorId || null];
|
||
const branchSql = branchFilter(ctx, 'cost_details', params);
|
||
const result = await pool.query(
|
||
`UPDATE cost_details
|
||
SET status = 20, auditor_id = $4
|
||
WHERE cost_type = $1 AND id = $2::uuid AND COALESCE(status, 20) = $3 ${branchSql}
|
||
RETURNING *`,
|
||
params
|
||
);
|
||
if (!result.rowCount) {
|
||
throw Object.assign(new Error('待审记录不存在或已处理'), { status: 404 });
|
||
}
|
||
const types = await listFreeCostTypes(ctx?.branchCode || null);
|
||
const decorated = decorateFreeCostRow(result.rows[0], types);
|
||
const row = result.rows[0];
|
||
const voucherCount = normalizeFreeCostVoucherPaths(row.voucher_url).length;
|
||
const after = buildFreeCostAuditSnapshot({
|
||
id: row.id,
|
||
amount: row.amount,
|
||
costSubtype: row.cost_subtype,
|
||
subtypeLabel: decorated?.subtype_label,
|
||
status: 20,
|
||
remark: row.reference_id,
|
||
voucherCount,
|
||
});
|
||
await writeFreeCostAuditLog({
|
||
operatorId: auditorId,
|
||
operationType: 'free_cost_approve',
|
||
targetId: entryId,
|
||
branchCode: row.branch_code || ctx?.branchCode || null,
|
||
oldValue: { ...after, status: FREE_COST_STATUS.pending },
|
||
newValue: after,
|
||
});
|
||
return decorated;
|
||
}
|
||
|
||
export async function rejectFreeCostEntry(
|
||
id: string,
|
||
auditorId: string | null | undefined,
|
||
ctx?: TenantContext | null,
|
||
reason?: string
|
||
) {
|
||
const entryId = String(id || '').trim();
|
||
if (!entryId) throw Object.assign(new Error('缺少记录 id'), { status: 400 });
|
||
const remark = String(reason || '').trim().slice(0, 200);
|
||
const params: unknown[] = [
|
||
FREE_COST_TYPE,
|
||
entryId,
|
||
FREE_COST_STATUS.pending,
|
||
auditorId || null,
|
||
remark || null,
|
||
];
|
||
const branchSql = branchFilter(ctx, 'cost_details', params);
|
||
const result = await pool.query(
|
||
`UPDATE cost_details
|
||
SET status = 30, auditor_id = $4, remark = COALESCE(NULLIF($5, ''), remark)
|
||
WHERE cost_type = $1 AND id = $2::uuid AND COALESCE(status, 20) = $3 ${branchSql}
|
||
RETURNING *`,
|
||
params
|
||
);
|
||
if (!result.rowCount) {
|
||
throw Object.assign(new Error('待审记录不存在或已处理'), { status: 404 });
|
||
}
|
||
const types = await listFreeCostTypes(ctx?.branchCode || null);
|
||
const decorated = decorateFreeCostRow(result.rows[0], types);
|
||
const row = result.rows[0];
|
||
const voucherCount = normalizeFreeCostVoucherPaths(row.voucher_url).length;
|
||
const after = buildFreeCostAuditSnapshot({
|
||
id: row.id,
|
||
amount: row.amount,
|
||
costSubtype: row.cost_subtype,
|
||
subtypeLabel: decorated?.subtype_label,
|
||
status: 30,
|
||
remark: remark || row.reference_id,
|
||
voucherCount,
|
||
});
|
||
await writeFreeCostAuditLog({
|
||
operatorId: auditorId,
|
||
operationType: 'free_cost_reject',
|
||
targetId: entryId,
|
||
branchCode: row.branch_code || ctx?.branchCode || null,
|
||
oldValue: { ...after, status: FREE_COST_STATUS.pending, remark: String(row.reference_id || '').trim().slice(0, 200) || null },
|
||
newValue: after,
|
||
});
|
||
return decorated;
|
||
}
|
||
|
||
/** 负毛利订单告警(与毛利明细同口径:qty×unit_cost) */
|
||
export async function listNegativeMarginAlerts(
|
||
ctx?: TenantContext | null,
|
||
limit = 20,
|
||
cycleCode?: string,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
) {
|
||
return listNegativeMarginFromLedger(ctx, cycleCode, limit, dateFieldRaw, customerCode);
|
||
}
|