来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
701 lines
24 KiB
TypeScript
701 lines
24 KiB
TypeScript
import { pool } from '../db';
|
|
import type { TenantContext } from './tenantScope';
|
|
import { getEffectiveBranchCode } from './tenantScope';
|
|
import {
|
|
orderFinanceJoinSql,
|
|
orderFinanceRangeCondSql,
|
|
CD_POSTED_STATUS_SQL,
|
|
type FinanceDateField,
|
|
} from './marginQueryService';
|
|
import { costEffectiveAmountSql } from './purchaseCostBucketSql';
|
|
import { ORDER_ITEM_REVENUE_SQL } from './orderItemRevenueSql';
|
|
|
|
export type BudgetAlertGrain = 'day' | 'week' | 'month';
|
|
|
|
const YMD_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
|
|
export function normalizeBudgetAlertGrain(value: unknown): BudgetAlertGrain {
|
|
const raw = String(value || '').trim().toLowerCase();
|
|
if (raw === 'week' || raw === 'month') return raw;
|
|
return 'day';
|
|
}
|
|
|
|
export function parseYmd(value: string): { y: number; m: number; d: number } | null {
|
|
if (!YMD_RE.test(value)) return null;
|
|
const [y, m, d] = value.split('-').map(Number);
|
|
if (!y || !m || !d) return null;
|
|
return { y, m, d };
|
|
}
|
|
|
|
export function formatYmd(y: number, m: number, d: number): string {
|
|
return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
|
|
}
|
|
|
|
export function daysInCalendarMonth(ymd: string): number {
|
|
const p = parseYmd(ymd);
|
|
if (!p) return 30;
|
|
return new Date(Date.UTC(p.y, p.m, 0)).getUTCDate();
|
|
}
|
|
|
|
export function addDaysYmd(ymd: string, delta: number): string {
|
|
const p = parseYmd(ymd);
|
|
if (!p) return ymd;
|
|
const dt = new Date(Date.UTC(p.y, p.m - 1, p.d + delta));
|
|
return formatYmd(dt.getUTCFullYear(), dt.getUTCMonth() + 1, dt.getUTCDate());
|
|
}
|
|
|
|
/** 周一为一周开始(中国常用) */
|
|
export function mondayOfWeek(ymd: string): string {
|
|
const p = parseYmd(ymd);
|
|
if (!p) return ymd;
|
|
const dt = new Date(Date.UTC(p.y, p.m - 1, p.d));
|
|
const dow = dt.getUTCDay(); // 0 Sun
|
|
const back = dow === 0 ? 6 : dow - 1;
|
|
return addDaysYmd(ymd, -back);
|
|
}
|
|
|
|
export function resolveAlertWindow(input: {
|
|
grain: BudgetAlertGrain;
|
|
dateFrom?: string | null;
|
|
dateTo?: string | null;
|
|
asOf?: string | null;
|
|
}): { from: string; to: string } {
|
|
const fromRaw = String(input.dateFrom || '').trim();
|
|
const toRaw = String(input.dateTo || '').trim();
|
|
if (YMD_RE.test(fromRaw) && YMD_RE.test(toRaw) && fromRaw <= toRaw) {
|
|
return { from: fromRaw, to: toRaw };
|
|
}
|
|
const asOf =
|
|
(YMD_RE.test(String(input.asOf || '')) && String(input.asOf)) ||
|
|
(YMD_RE.test(toRaw) && toRaw) ||
|
|
(YMD_RE.test(fromRaw) && fromRaw) ||
|
|
new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' });
|
|
if (input.grain === 'day') {
|
|
return { from: asOf, to: asOf };
|
|
}
|
|
if (input.grain === 'week') {
|
|
const from = mondayOfWeek(asOf);
|
|
return { from, to: addDaysYmd(from, 6) };
|
|
}
|
|
const p = parseYmd(asOf)!;
|
|
const last = daysInCalendarMonth(asOf);
|
|
return { from: formatYmd(p.y, p.m, 1), to: formatYmd(p.y, p.m, last) };
|
|
}
|
|
|
|
export function dailyQuota(monthlyBudget: number, ymd: string): number {
|
|
const days = daysInCalendarMonth(ymd);
|
|
if (!(monthlyBudget > 0) || days <= 0) return 0;
|
|
return Math.round((monthlyBudget / days) * 100) / 100;
|
|
}
|
|
|
|
/** 窗口额度 = 窗口内每一天的日额度之和 */
|
|
export function windowQuota(monthlyBudget: number, from: string, to: string): number {
|
|
if (!(monthlyBudget > 0) || from > to) return 0;
|
|
let sum = 0;
|
|
let cur = from;
|
|
let guard = 0;
|
|
while (cur <= to && guard < 400) {
|
|
sum += dailyQuota(monthlyBudget, cur);
|
|
cur = addDaysYmd(cur, 1);
|
|
guard += 1;
|
|
}
|
|
return Math.round(sum * 100) / 100;
|
|
}
|
|
|
|
/** 一侧预警:月预算 0 则不监控(额度/超标为 0) */
|
|
export function computeAlertSide(
|
|
monthlyBudget: number,
|
|
actual: number,
|
|
from: string,
|
|
to: string
|
|
): { quota: number; over: number; pct: number; isOver: boolean } {
|
|
const quota = windowQuota(monthlyBudget, from, to);
|
|
if (!(quota > 0)) {
|
|
return { quota: 0, over: 0, pct: 0, isOver: false };
|
|
}
|
|
const over = Math.round(Math.max(0, actual - quota) * 100) / 100;
|
|
const pct = Math.round((actual / quota) * 10000) / 100;
|
|
return { quota, over, pct, isOver: actual > quota };
|
|
}
|
|
|
|
/** 账本有效金额:采购行只认 amount(与成本 KPI 同源)。见 20260911-cost-follow-picking-actual */
|
|
const CD_AMT = costEffectiveAmountSql('cd');
|
|
|
|
/** 预警默认下单日;显式传配送日/入库日才切换 */
|
|
export function normalizeBudgetAlertDateField(value: unknown): FinanceDateField {
|
|
const raw = String(value || '').trim();
|
|
if (raw === 'delivery_date' || raw === 'inbound') return raw;
|
|
return 'created_at';
|
|
}
|
|
|
|
export function shareAmount(total: number, denom: number): number {
|
|
if (!(denom > 0)) return 0;
|
|
return Math.round((Number(total) / denom) * 100) / 100;
|
|
}
|
|
|
|
/** 同一客户同一配送日多名司机时:优先主责,否则字典序稳定。 */
|
|
export function pickDeliveryPerson(prev: string | undefined, next: string, primary: string): string {
|
|
if (!next) return prev || '';
|
|
if (!prev) return next;
|
|
if (primary && (prev === primary || next === primary)) return primary;
|
|
return prev < next ? prev : next;
|
|
}
|
|
|
|
/**
|
|
* 有任务:只摊给当天任务客户。无任务:按主责绑定。
|
|
* 当天该主责司机有任务但本客户未在任务中 → 0。
|
|
*/
|
|
/**
|
|
* 其他成本(配送员杂费)在「客户 × 日」上的分摊(开发者 2026-09-22 定稿口径):
|
|
* 该客户当天配送员当天产生的其他成本 ÷ **该员当天实际配送客户数**。
|
|
* 当天该客户没有配送记录 → 0(相当于当天没下单、也就没有配送)。
|
|
* 不再用"该员的绑定客户数"兜底分摊。
|
|
*/
|
|
export function miscShareForCustomerDay(
|
|
customerCode: string,
|
|
day: string,
|
|
lookup: {
|
|
personByCustDay: Map<string, string>;
|
|
stopsByDayPerson: Map<string, number>;
|
|
miscByDayPerson: Map<string, number>;
|
|
}
|
|
): number {
|
|
const taskPerson = lookup.personByCustDay.get(`${customerCode}|${day}`) || '';
|
|
if (!taskPerson) return 0;
|
|
const denom = lookup.stopsByDayPerson.get(`${day}|${taskPerson}`) || 0;
|
|
if (denom <= 0) return 0;
|
|
return shareAmount(lookup.miscByDayPerson.get(`${day}|${taskPerson}`) || 0, denom);
|
|
}
|
|
|
|
export function eachYmdInclusive(from: string, to: string): string[] {
|
|
const days: string[] = [];
|
|
let cur = from;
|
|
let guard = 0;
|
|
while (cur <= to && guard < 400) {
|
|
days.push(cur);
|
|
cur = addDaysYmd(cur, 1);
|
|
guard += 1;
|
|
}
|
|
return days;
|
|
}
|
|
|
|
function dayKey(value: unknown): string {
|
|
return String(value || '').slice(0, 10);
|
|
}
|
|
|
|
function alertBizDaySql(dateField: FinanceDateField): string {
|
|
if (dateField === 'created_at') return `(o.created_at AT TIME ZONE 'Asia/Shanghai')::date`;
|
|
if (dateField === 'inbound') {
|
|
return `(COALESCE(ib.first_inbound_at, o.updated_at) AT TIME ZONE 'Asia/Shanghai')::date`;
|
|
}
|
|
return `o.delivery_date`;
|
|
}
|
|
|
|
export type BudgetAlertRow = {
|
|
customer_code: string;
|
|
customer_name: string;
|
|
monthly_budget: number;
|
|
sales_budget: number;
|
|
window_quota: number;
|
|
actual_amount: number;
|
|
sku_cost: number;
|
|
fixed_share: number;
|
|
misc_share: number;
|
|
over_amount: number;
|
|
utilization_pct: number;
|
|
is_cost_over: boolean;
|
|
sales_window_quota: number;
|
|
sales_actual: number;
|
|
sales_over_amount: number;
|
|
sales_utilization_pct: number;
|
|
is_sales_over: boolean;
|
|
is_over: boolean;
|
|
};
|
|
|
|
function branchSql(ctx: TenantContext | null | undefined, alias: string, params: unknown[]): string {
|
|
const branch = getEffectiveBranchCode(ctx || null, null);
|
|
if (!branch) return '';
|
|
params.push(branch);
|
|
return ` AND ${alias}.branch_code = $${params.length}`;
|
|
}
|
|
|
|
export async function listCustomerBudgetAlerts(input: {
|
|
grain?: string | null;
|
|
dateFrom?: string | null;
|
|
dateTo?: string | null;
|
|
dateField?: string | null;
|
|
onlyOver?: boolean;
|
|
customerCode?: string | null;
|
|
}, ctx?: TenantContext | null): Promise<{
|
|
grain: BudgetAlertGrain;
|
|
from: string;
|
|
to: string;
|
|
date_field: FinanceDateField;
|
|
with_budget: number;
|
|
with_cost_budget: number;
|
|
with_sales_budget: number;
|
|
over_count: number;
|
|
rows: BudgetAlertRow[];
|
|
}> {
|
|
const grain = normalizeBudgetAlertGrain(input.grain);
|
|
const dateField = normalizeBudgetAlertDateField(input.dateField);
|
|
const { from, to } = resolveAlertWindow({
|
|
grain,
|
|
dateFrom: input.dateFrom,
|
|
dateTo: input.dateTo,
|
|
});
|
|
const days = eachYmdInclusive(from, to);
|
|
const branchCode = getEffectiveBranchCode(ctx || null, null);
|
|
const customerFilter = String(input.customerCode || '').trim();
|
|
const emptyPayload = {
|
|
grain,
|
|
from,
|
|
to,
|
|
date_field: dateField,
|
|
with_budget: 0,
|
|
with_cost_budget: 0,
|
|
with_sales_budget: 0,
|
|
over_count: 0,
|
|
rows: [] as BudgetAlertRow[],
|
|
};
|
|
|
|
const custParams: unknown[] = [];
|
|
let custBranchC = '';
|
|
if (branchCode) {
|
|
custParams.push(branchCode);
|
|
custBranchC = ` AND c.branch_code = $${custParams.length}`;
|
|
}
|
|
if (customerFilter) custParams.push(customerFilter);
|
|
const customerEq = customerFilter ? ` AND c.customer_code = $${custParams.length}` : '';
|
|
|
|
const customersRes = await pool.query(
|
|
`SELECT c.customer_code,
|
|
COALESCE(NULLIF(TRIM(c.company_name), ''), c.customer_code) AS customer_name,
|
|
COALESCE(c.cost_budget, c.budget_amount, 0)::numeric AS monthly_budget,
|
|
COALESCE(c.sales_budget, 0)::numeric AS sales_budget
|
|
FROM customers c
|
|
WHERE (
|
|
COALESCE(c.cost_budget, c.budget_amount, 0) > 0
|
|
OR COALESCE(c.sales_budget, 0) > 0
|
|
)
|
|
AND COALESCE(c.status, 10) IN (1, 10)
|
|
${custBranchC}
|
|
${customerEq}
|
|
ORDER BY c.company_name, c.customer_code`,
|
|
custParams
|
|
);
|
|
if (customersRes.rows.length === 0) return emptyPayload;
|
|
const budgetCustomerCodes = customersRes.rows.map((row) => String(row.customer_code));
|
|
|
|
const enabledParams: unknown[] = [];
|
|
let enabledBranch = '';
|
|
if (branchCode) {
|
|
enabledParams.push(branchCode);
|
|
enabledBranch = ` AND c.branch_code = $${enabledParams.length}`;
|
|
}
|
|
|
|
const joinSql = orderFinanceJoinSql(dateField, true);
|
|
const rangeSql = orderFinanceRangeCondSql(dateField, 1, 2);
|
|
|
|
const poolParams: unknown[] = [from, to];
|
|
let cdBranch = '';
|
|
if (branchCode) {
|
|
poolParams.push(branchCode);
|
|
cdBranch = ` AND cd.branch_code = $${poolParams.length}`;
|
|
}
|
|
const postedDay = `(cd.created_at AT TIME ZONE 'Asia/Shanghai')::date`;
|
|
|
|
const stopParams: unknown[] = [from, to];
|
|
const stopBranch = branchSql(ctx, 'o', stopParams);
|
|
|
|
const assignParams: unknown[] = [];
|
|
const assignBranch = branchSql(ctx, 'c', assignParams);
|
|
|
|
const salesParams: unknown[] = [from, to];
|
|
const salesBranch = branchSql(ctx, 'o', salesParams);
|
|
salesParams.push(budgetCustomerCodes);
|
|
const salesCustomerEq = ` AND o.customer_code = ANY($${salesParams.length}::text[])`;
|
|
|
|
// ① 商品成本总额 = 订单行口径(quantity × unit_cost),与销售侧同结构、同日期字段
|
|
// (开发者 2026-09-22 定稿:不再用 cost_details 账本汇总;
|
|
// 仓内加工的材料成本由领料完工回写订单行 unit_cost,已在此体现)
|
|
const costParams: unknown[] = [from, to];
|
|
const costBranch = branchSql(ctx, 'o', costParams);
|
|
costParams.push(budgetCustomerCodes);
|
|
const costCustomerEq = ` AND o.customer_code = ANY($${costParams.length}::text[])`;
|
|
|
|
// ② 固定成本 = 「固定成本」界面本月的固定总金额 ÷ 本月天数 ÷ 当前启用客户数(逐日累加)
|
|
const fixedMonths = [...new Set(days.map((d) => d.slice(0, 7).replace('-', '')))];
|
|
const fixedParams: unknown[] = [fixedMonths];
|
|
let fixedBranch = '';
|
|
if (branchCode) {
|
|
fixedParams.push(branchCode);
|
|
fixedBranch = ` AND branch_code = $${fixedParams.length}`;
|
|
}
|
|
|
|
const [enabledRes, skuRes, costPoolRes, fixedRes, salesRes] = await Promise.all([
|
|
pool.query(
|
|
`SELECT COUNT(*)::int AS enabled_n
|
|
FROM customers c
|
|
WHERE COALESCE(c.status, 10) IN (1, 10)
|
|
${enabledBranch}`,
|
|
enabledParams
|
|
),
|
|
pool.query(
|
|
`SELECT o.customer_code,
|
|
COALESCE(SUM(COALESCE(oi.quantity, 0)::numeric * COALESCE(oi.unit_cost, 0)::numeric), 0)::numeric AS sku_cost
|
|
FROM orders o
|
|
JOIN order_items oi ON oi.order_code = o.order_code
|
|
${joinSql}
|
|
WHERE o.deleted_at IS NULL
|
|
AND o.order_status >= 20
|
|
AND ${rangeSql}
|
|
AND COALESCE(oi.is_returned, false) = false
|
|
${costBranch}
|
|
${costCustomerEq}
|
|
GROUP BY o.customer_code`,
|
|
costParams
|
|
),
|
|
pool.query(
|
|
`SELECT kind, d, person_code, amt FROM (
|
|
SELECT 'misc'::text AS kind,
|
|
${postedDay}::text AS d,
|
|
dpu.person_code,
|
|
COALESCE(SUM(${CD_AMT}), 0)::numeric AS amt
|
|
FROM cost_details cd
|
|
JOIN LATERAL (
|
|
SELECT dpu.person_code
|
|
FROM delivery_person_users dpu
|
|
WHERE dpu.user_id = cd.inputter_id
|
|
ORDER BY COALESCE(dpu.is_primary, false) DESC, dpu.person_code
|
|
LIMIT 1
|
|
) dpu ON TRUE
|
|
WHERE cd.cost_type = 'free_overhead'
|
|
AND ${CD_POSTED_STATUS_SQL}
|
|
AND ${postedDay} >= $1::date AND ${postedDay} <= $2::date
|
|
${cdBranch}
|
|
GROUP BY 2, 3
|
|
) cost_pool`,
|
|
poolParams
|
|
),
|
|
// ② 固定成本:取「固定成本」界面本月的固定总金额(fixed_costs 按 cycle_code 汇总)
|
|
pool.query(
|
|
`SELECT cycle_code,
|
|
COALESCE(SUM(COALESCE(actual_amount, budget_amount, 0)), 0)::numeric AS amt
|
|
FROM fixed_costs
|
|
WHERE cycle_code = ANY($1::text[])
|
|
AND COALESCE(status, 10) >= 20
|
|
${fixedBranch}
|
|
GROUP BY cycle_code`,
|
|
fixedParams
|
|
),
|
|
pool.query(
|
|
`SELECT o.customer_code,
|
|
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS sales_amount
|
|
FROM orders o
|
|
JOIN order_items oi ON oi.order_code = o.order_code
|
|
${joinSql}
|
|
WHERE o.deleted_at IS NULL
|
|
AND o.order_status >= 20
|
|
AND ${rangeSql}
|
|
AND COALESCE(oi.is_returned, false) = false
|
|
${salesBranch}
|
|
${salesCustomerEq}
|
|
GROUP BY o.customer_code`,
|
|
salesParams
|
|
),
|
|
]);
|
|
|
|
const hasMisc = costPoolRes.rows.some((row) => String(row.kind) === 'misc');
|
|
const [deliveryRes, assignRes] = hasMisc
|
|
? await Promise.all([
|
|
pool.query(
|
|
`SELECT DISTINCT o.customer_code,
|
|
o.delivery_date::text AS d,
|
|
COALESCE(NULLIF(TRIM(dt.person_code), ''), NULLIF(TRIM(cda.person_code), '')) AS person_code
|
|
FROM orders o
|
|
LEFT JOIN delivery_tasks dt ON dt.order_code = o.order_code
|
|
LEFT JOIN LATERAL (
|
|
SELECT x.person_code
|
|
FROM customer_delivery_assignments x
|
|
WHERE x.customer_code = o.customer_code
|
|
AND COALESCE(x.is_primary, true) = true
|
|
LIMIT 1
|
|
) cda ON TRUE
|
|
WHERE o.deleted_at IS NULL
|
|
AND o.order_status >= 20
|
|
AND o.delivery_date IS NOT NULL
|
|
AND o.delivery_date >= $1::date AND o.delivery_date <= $2::date
|
|
${stopBranch}`,
|
|
stopParams
|
|
),
|
|
pool.query(
|
|
`SELECT cda.customer_code, cda.person_code
|
|
FROM customer_delivery_assignments cda
|
|
JOIN customers c ON c.customer_code = cda.customer_code
|
|
WHERE COALESCE(cda.is_primary, true) = true
|
|
AND COALESCE(c.status, 10) IN (1, 10)
|
|
${assignBranch}`,
|
|
assignParams
|
|
),
|
|
])
|
|
: [{ rows: [] as Array<Record<string, unknown>> }, { rows: [] as Array<Record<string, unknown>> }];
|
|
|
|
const enabledCount = Number(enabledRes.rows[0]?.enabled_n) || 0;
|
|
const skuByCustomer = new Map<string, number>();
|
|
for (const row of skuRes.rows) {
|
|
skuByCustomer.set(String(row.customer_code), Number(row.sku_cost) || 0);
|
|
}
|
|
const salesByCustomer = new Map<string, number>();
|
|
for (const row of salesRes.rows) {
|
|
salesByCustomer.set(String(row.customer_code), Number(row.sales_amount) || 0);
|
|
}
|
|
|
|
const miscByDayPerson = new Map<string, number>();
|
|
for (const row of costPoolRes.rows) {
|
|
const d = dayKey(row.d);
|
|
const amt = Number(row.amt) || 0;
|
|
const person = String(row.person_code || '').trim();
|
|
if (person) miscByDayPerson.set(`${d}|${person}`, amt);
|
|
}
|
|
|
|
// ② 固定成本:本月固定总金额(「固定成本」界面口径)→ 逐日「月额 ÷ 本月天数 ÷ 当前启用客户数」
|
|
const fixedByMonth = new Map<string, number>();
|
|
for (const row of fixedRes.rows) {
|
|
fixedByMonth.set(String(row.cycle_code || '').trim(), Number(row.amt) || 0);
|
|
}
|
|
const daysInMonth = (ym: string): number => {
|
|
const y = Number(ym.slice(0, 4));
|
|
const m = Number(ym.slice(4, 6));
|
|
if (!y || !m) return 0;
|
|
return new Date(y, m, 0).getDate();
|
|
};
|
|
|
|
const primaryByCustomer = new Map<string, string>();
|
|
for (const row of assignRes.rows) {
|
|
const code = String(row.customer_code);
|
|
const person = String(row.person_code || '').trim();
|
|
if (!person) continue;
|
|
primaryByCustomer.set(code, person);
|
|
}
|
|
|
|
const personByCustDay = new Map<string, string>();
|
|
const stopSets = new Map<string, Set<string>>();
|
|
for (const row of deliveryRes.rows) {
|
|
const person = String(row.person_code || '').trim();
|
|
if (!person) continue;
|
|
const code = String(row.customer_code);
|
|
const d = dayKey(row.d);
|
|
const pk = `${code}|${d}`;
|
|
personByCustDay.set(pk, pickDeliveryPerson(personByCustDay.get(pk), person, primaryByCustomer.get(code) || ''));
|
|
const sk = `${d}|${person}`;
|
|
let set = stopSets.get(sk);
|
|
if (!set) {
|
|
set = new Set();
|
|
stopSets.set(sk, set);
|
|
}
|
|
set.add(code);
|
|
}
|
|
const stopsByDayPerson = new Map<string, number>();
|
|
for (const [key, set] of stopSets) {
|
|
stopsByDayPerson.set(key, set.size);
|
|
}
|
|
|
|
const miscLookup = {
|
|
personByCustDay,
|
|
stopsByDayPerson,
|
|
miscByDayPerson,
|
|
};
|
|
|
|
const rows: BudgetAlertRow[] = customersRes.rows.map((row) => {
|
|
const code = String(row.customer_code);
|
|
const monthly = Number(row.monthly_budget) || 0;
|
|
const skuCost = Math.round((skuByCustomer.get(code) || 0) * 100) / 100;
|
|
let fixedShare = 0;
|
|
let miscShare = 0;
|
|
for (const d of days) {
|
|
const ym = d.slice(0, 7).replace('-', '');
|
|
const monthDays = daysInMonth(ym);
|
|
const dailyFixed = monthDays > 0 ? (fixedByMonth.get(ym) || 0) / monthDays : 0;
|
|
fixedShare += shareAmount(dailyFixed, enabledCount);
|
|
miscShare += miscShareForCustomerDay(code, d, miscLookup);
|
|
}
|
|
fixedShare = Math.round(fixedShare * 100) / 100;
|
|
miscShare = Math.round(miscShare * 100) / 100;
|
|
const actual = Math.round((skuCost + fixedShare + miscShare) * 100) / 100;
|
|
const costSide = computeAlertSide(monthly, actual, from, to);
|
|
const salesMonthly = Number(row.sales_budget) || 0;
|
|
const salesActual = Math.round((salesByCustomer.get(code) || 0) * 100) / 100;
|
|
const salesSide = computeAlertSide(salesMonthly, salesActual, from, to);
|
|
const isOver = costSide.isOver || salesSide.isOver;
|
|
return {
|
|
customer_code: code,
|
|
customer_name: String(row.customer_name || code),
|
|
monthly_budget: monthly,
|
|
sales_budget: salesMonthly,
|
|
window_quota: costSide.quota,
|
|
actual_amount: actual,
|
|
sku_cost: skuCost,
|
|
fixed_share: fixedShare,
|
|
misc_share: miscShare,
|
|
over_amount: costSide.over,
|
|
utilization_pct: costSide.pct,
|
|
is_cost_over: costSide.isOver,
|
|
sales_window_quota: salesSide.quota,
|
|
sales_actual: salesActual,
|
|
sales_over_amount: salesSide.over,
|
|
sales_utilization_pct: salesSide.pct,
|
|
is_sales_over: salesSide.isOver,
|
|
is_over: isOver,
|
|
};
|
|
});
|
|
rows.sort(
|
|
(a, b) =>
|
|
Number(b.is_over) - Number(a.is_over) ||
|
|
Math.max(b.over_amount, b.sales_over_amount) - Math.max(a.over_amount, a.sales_over_amount)
|
|
);
|
|
const withBudget = rows.length;
|
|
const withCostBudget = rows.filter((r) => r.monthly_budget > 0).length;
|
|
const withSalesBudget = rows.filter((r) => r.sales_budget > 0).length;
|
|
const overCount = rows.filter((r) => r.is_over).length;
|
|
const filtered = input.onlyOver === false ? rows : rows.filter((r) => r.is_over);
|
|
return {
|
|
grain,
|
|
from,
|
|
to,
|
|
date_field: dateField,
|
|
with_budget: withBudget,
|
|
with_cost_budget: withCostBudget,
|
|
with_sales_budget: withSalesBudget,
|
|
over_count: overCount,
|
|
rows: filtered,
|
|
};
|
|
}
|
|
|
|
export async function summarizeCustomerBudgetAlerts(
|
|
input: Parameters<typeof listCustomerBudgetAlerts>[0],
|
|
ctx?: TenantContext | null
|
|
) {
|
|
const listed = await listCustomerBudgetAlerts({ ...input, onlyOver: false }, ctx);
|
|
return {
|
|
grain: listed.grain,
|
|
from: listed.from,
|
|
to: listed.to,
|
|
date_field: listed.date_field,
|
|
with_budget: listed.with_budget,
|
|
with_cost_budget: listed.with_cost_budget,
|
|
with_sales_budget: listed.with_sales_budget,
|
|
over_count: listed.over_count,
|
|
};
|
|
}
|
|
|
|
export async function getCustomerBudgetAlertDetail(
|
|
customerCode: string,
|
|
input: Parameters<typeof listCustomerBudgetAlerts>[0],
|
|
ctx?: TenantContext | null
|
|
) {
|
|
const code = String(customerCode || '').trim();
|
|
const listed = await listCustomerBudgetAlerts({ ...input, onlyOver: false, customerCode: code }, ctx);
|
|
const header = listed.rows[0] || null;
|
|
const grain = listed.grain;
|
|
const { from, to } = listed;
|
|
const dateField = listed.date_field;
|
|
const params: unknown[] = [from, to, code];
|
|
const orderBranch = branchSql(ctx, 'o', params);
|
|
const joinSql = orderFinanceJoinSql(dateField, true);
|
|
const rangeSql = orderFinanceRangeCondSql(dateField, 1, 2);
|
|
const bizDaySql = alertBizDaySql(dateField);
|
|
const orders = await pool.query(
|
|
// 明细的「订单采购成本」同样用订单行口径(与列表①一致,明细之和 = 列表①)
|
|
`SELECT o.order_code,
|
|
to_char(${bizDaySql}, 'YYYY-MM-DD') AS biz_day,
|
|
COALESCE(MAX(cost.amount), 0)::numeric AS amount,
|
|
COALESCE(MAX(sale.sale_amount), 0)::numeric AS sale_amount
|
|
FROM orders o
|
|
${joinSql}
|
|
LEFT JOIN LATERAL (
|
|
SELECT COALESCE(SUM(COALESCE(oi.quantity, 0)::numeric * COALESCE(oi.unit_cost, 0)::numeric), 0)::numeric AS amount
|
|
FROM order_items oi
|
|
WHERE oi.order_code = o.order_code
|
|
AND COALESCE(oi.is_returned, false) = false
|
|
) cost ON TRUE
|
|
LEFT JOIN LATERAL (
|
|
SELECT COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS sale_amount
|
|
FROM order_items oi
|
|
WHERE oi.order_code = o.order_code
|
|
AND COALESCE(oi.is_returned, false) = false
|
|
) sale ON TRUE
|
|
WHERE o.deleted_at IS NULL
|
|
AND o.order_status >= 20
|
|
AND o.customer_code = $3
|
|
AND ${rangeSql}
|
|
${orderBranch}
|
|
GROUP BY o.order_code, ${bizDaySql}
|
|
ORDER BY 2, o.order_code`,
|
|
params
|
|
);
|
|
return {
|
|
grain,
|
|
from,
|
|
to,
|
|
date_field: dateField,
|
|
customer: header,
|
|
orders: orders.rows.map((row) => ({
|
|
order_code: String(row.order_code),
|
|
biz_day: String(row.biz_day || '').slice(0, 10),
|
|
amount: Math.round((Number(row.amount) || 0) * 100) / 100,
|
|
sale_amount: Math.round((Number(row.sale_amount) || 0) * 100) / 100,
|
|
})),
|
|
};
|
|
}
|
|
|
|
function roundBudget(n: number): number {
|
|
return Math.round(Math.max(0, n) * 100) / 100;
|
|
}
|
|
|
|
export async function updateCustomerCostSalesBudgets(input: {
|
|
customerCode: string;
|
|
costBudget: number;
|
|
salesBudget?: number | null;
|
|
ctx?: TenantContext | null;
|
|
}): Promise<{ customer_code: string; cost_budget: number; sales_budget: number }> {
|
|
const code = String(input.customerCode || '').trim();
|
|
if (!code) {
|
|
throw Object.assign(new Error('缺少客户编码'), { status: 400, code: 'invalid_request' });
|
|
}
|
|
const costBudget = roundBudget(Number(input.costBudget) || 0);
|
|
const branchCode = getEffectiveBranchCode(input.ctx || null, null);
|
|
const existing = await pool.query(
|
|
`SELECT customer_code, branch_code, COALESCE(sales_budget, 0)::float AS sales_budget
|
|
FROM customers WHERE customer_code = $1 LIMIT 1`,
|
|
[code]
|
|
);
|
|
if (!existing.rowCount) {
|
|
throw Object.assign(new Error('客户不存在'), { status: 404, code: 'not_found' });
|
|
}
|
|
const row = existing.rows[0];
|
|
if (branchCode && String(row.branch_code || '') !== branchCode) {
|
|
throw Object.assign(new Error('无权修改其它分公司的客户'), { status: 403, code: 'branch_mismatch' });
|
|
}
|
|
const salesBudget =
|
|
input.salesBudget === undefined || input.salesBudget === null
|
|
? roundBudget(Number(row.sales_budget) || 0)
|
|
: roundBudget(Number(input.salesBudget) || 0);
|
|
|
|
const updated = await pool.query(
|
|
`UPDATE customers
|
|
SET cost_budget = $2,
|
|
sales_budget = $3,
|
|
budget_amount = $2
|
|
WHERE customer_code = $1
|
|
RETURNING customer_code, cost_budget::float AS cost_budget, sales_budget::float AS sales_budget`,
|
|
[code, costBudget, salesBudget]
|
|
);
|
|
const out = updated.rows[0];
|
|
return {
|
|
customer_code: String(out.customer_code),
|
|
cost_budget: Number(out.cost_budget) || 0,
|
|
sales_budget: Number(out.sales_budget) || 0,
|
|
};
|
|
}
|