来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
580 lines
20 KiB
TypeScript
580 lines
20 KiB
TypeScript
import { pool } from '../db';
|
|
import { writeAuditLog } from './auditService';
|
|
import { notifyRoleUsers, notifyUser } from './notificationService';
|
|
import { updatePreparationPurchasePrice } from './supplierPreparationStatusService';
|
|
import { upsertCustomerStatementForOrder, ensureSupplierStatementsForOrder } from './financeReconciliationService';
|
|
import { assertSupplyQtyInFloatRange } from './prepMinSupplyRatioConfigService';
|
|
import { getSupplierPrepPriceAmendConfig } from './preparationPriceAmendConfigService';
|
|
import { assertSupplyCostPrice } from './supplyCostPrice';
|
|
import { isZeroSupplyCostAllowed } from './zeroSupplyCostConfigService';
|
|
|
|
export const PREP_AMEND_STATUS = {
|
|
pending: 10,
|
|
approved: 20,
|
|
rejected: 30,
|
|
} as const;
|
|
|
|
export type PrepAmendRequestRow = {
|
|
id: string;
|
|
preparation_id: string;
|
|
order_code: string | null;
|
|
sku_code: string | null;
|
|
supplier_code: string | null;
|
|
branch_code: string | null;
|
|
item_name: string | null;
|
|
before_price: number | null;
|
|
before_qty: number | null;
|
|
before_unit: string | null;
|
|
proposed_price: number;
|
|
proposed_qty: number | null;
|
|
proposed_unit: string | null;
|
|
final_price: number | null;
|
|
final_qty: number | null;
|
|
final_unit: string | null;
|
|
status: number;
|
|
requested_by: string | null;
|
|
requested_at: string;
|
|
reviewed_by: string | null;
|
|
reviewed_at: string | null;
|
|
review_remark: string | null;
|
|
supplier_name?: string | null;
|
|
};
|
|
|
|
function bizError(message: string, status = 400, code = 'invalid_request') {
|
|
return Object.assign(new Error(message), { status, code });
|
|
}
|
|
|
|
function mapRow(row: Record<string, unknown>): PrepAmendRequestRow {
|
|
return {
|
|
id: String(row.id),
|
|
preparation_id: String(row.preparation_id),
|
|
order_code: row.order_code != null ? String(row.order_code) : null,
|
|
sku_code: row.sku_code != null ? String(row.sku_code) : null,
|
|
supplier_code: row.supplier_code != null ? String(row.supplier_code) : null,
|
|
branch_code: row.branch_code != null ? String(row.branch_code) : null,
|
|
item_name: row.item_name != null ? String(row.item_name) : null,
|
|
before_price: row.before_price == null ? null : Number(row.before_price),
|
|
before_qty: row.before_qty == null ? null : Number(row.before_qty),
|
|
before_unit: row.before_unit != null ? String(row.before_unit) : null,
|
|
proposed_price: Number(row.proposed_price),
|
|
proposed_qty: row.proposed_qty == null ? null : Number(row.proposed_qty),
|
|
proposed_unit: row.proposed_unit != null ? String(row.proposed_unit) : null,
|
|
final_price: row.final_price == null ? null : Number(row.final_price),
|
|
final_qty: row.final_qty == null ? null : Number(row.final_qty),
|
|
final_unit: row.final_unit != null ? String(row.final_unit) : null,
|
|
status: Number(row.status) || PREP_AMEND_STATUS.pending,
|
|
requested_by: row.requested_by != null ? String(row.requested_by) : null,
|
|
requested_at: String(row.requested_at || ''),
|
|
reviewed_by: row.reviewed_by != null ? String(row.reviewed_by) : null,
|
|
reviewed_at: row.reviewed_at != null ? String(row.reviewed_at) : null,
|
|
review_remark: row.review_remark != null ? String(row.review_remark) : null,
|
|
supplier_name: row.supplier_name != null ? String(row.supplier_name) : null,
|
|
};
|
|
}
|
|
|
|
async function loadPrepForAmend(preparationId: string, supplierCode: string) {
|
|
const result = await pool.query(
|
|
`SELECT sp.id, sp.order_code, sp.sku_code, sp.supplier_code, sp.branch_code,
|
|
sp.prepare_status, sp.purchase_price, sp.prepare_qty, sp.unit,
|
|
sp.item_name, sp.is_stockout, sp.transferred_to_purchase,
|
|
sp.prepare_time, sp.created_at,
|
|
COALESCE(NULLIF(TRIM(sp.item_name), ''), s.sku_name, sp.sku_code) AS display_name,
|
|
COALESCE(sup.company_name, sp.supplier_code) AS supplier_name
|
|
FROM supplier_preparations sp
|
|
LEFT JOIN skus s ON s.sku_code = sp.sku_code
|
|
LEFT JOIN suppliers sup ON sup.supplier_code = sp.supplier_code
|
|
WHERE sp.id = $1 AND sp.supplier_code = $2
|
|
LIMIT 1`,
|
|
[preparationId, supplierCode]
|
|
);
|
|
return result.rows[0] || null;
|
|
}
|
|
|
|
/** 供应商提交/覆盖待审申请;不改正式备货与成本 */
|
|
export async function submitPrepAmendRequest(input: {
|
|
preparationId: string;
|
|
supplierCode: string;
|
|
purchasePrice: number;
|
|
prepareQty?: number | null;
|
|
unit?: string | null;
|
|
requestedBy: string;
|
|
branchCode?: string | null;
|
|
}): Promise<{ request_id: string; status: 'pending'; overwritten: boolean }> {
|
|
const prep = await loadPrepForAmend(input.preparationId, input.supplierCode);
|
|
if (!prep) throw bizError('备货单不存在', 404, 'not_found');
|
|
if (Number(prep.prepare_status) !== 30) {
|
|
throw bizError('仅已完成供货单可追加改价', 409, 'conflict');
|
|
}
|
|
if (prep.is_stockout || prep.transferred_to_purchase) {
|
|
throw bizError('缺货或已流转自采的备货不可追加改价', 409, 'conflict');
|
|
}
|
|
|
|
const branchForWindow = String(input.branchCode || prep.branch_code || '').trim() || null;
|
|
const amendCfg = await getSupplierPrepPriceAmendConfig(branchForWindow);
|
|
if (!(amendCfg.window_hours > 0)) {
|
|
throw bizError('该分公司未开放供应商追加改价', 403, 'forbidden');
|
|
}
|
|
const completedAt = new Date(prep.prepare_time || prep.created_at || 0).getTime();
|
|
if (!Number.isFinite(completedAt) || completedAt <= 0) {
|
|
throw bizError('缺少完成供货时间,无法追加改价', 409, 'conflict');
|
|
}
|
|
const deadlineMs = completedAt + amendCfg.window_hours * 3600 * 1000;
|
|
if (Date.now() > deadlineMs) {
|
|
throw bizError(
|
|
`追加改价已超过时限(完成供货后 ${amendCfg.window_hours} 小时内可改)`,
|
|
409,
|
|
'conflict'
|
|
);
|
|
}
|
|
|
|
const proposedPrice = Number(input.purchasePrice);
|
|
// 「允许成本价为 0」开关:开启后 0 合法(负数/NaN 仍拒)
|
|
const allowZeroProposed = await isZeroSupplyCostAllowed(
|
|
String(input.branchCode || prep.branch_code || '').trim() || null
|
|
);
|
|
if (allowZeroProposed) assertSupplyCostPrice(proposedPrice, '采购价', { allowZero: true });
|
|
else if (!Number.isFinite(proposedPrice) || proposedPrice <= 0) {
|
|
throw bizError('采购价必须大于 0');
|
|
}
|
|
const proposedQty =
|
|
input.prepareQty === undefined || input.prepareQty === null
|
|
? Number(prep.prepare_qty) || null
|
|
: Number(input.prepareQty);
|
|
if (proposedQty !== null && (!Number.isFinite(proposedQty) || proposedQty <= 0)) {
|
|
throw bizError('供货数量无效');
|
|
}
|
|
if (proposedQty !== null) {
|
|
await assertSupplyQtyInFloatRange({
|
|
preparationId: input.preparationId,
|
|
supplyQty: proposedQty,
|
|
fallbackDemandQty: Number(prep.prepare_qty) || 0,
|
|
branchCode: String(input.branchCode || prep.branch_code || '').trim() || null,
|
|
});
|
|
}
|
|
const proposedUnit =
|
|
input.unit != null && String(input.unit).trim()
|
|
? String(input.unit).trim()
|
|
: String(prep.unit || '').trim() || '个';
|
|
|
|
const beforePrice = Number(prep.purchase_price) || 0;
|
|
const beforeQty = Number(prep.prepare_qty) || null;
|
|
const beforeUnit = String(prep.unit || '').trim() || '个';
|
|
const branchCode = String(input.branchCode || prep.branch_code || '').trim() || null;
|
|
|
|
const existing = await pool.query(
|
|
`SELECT id FROM supplier_prep_amend_requests
|
|
WHERE preparation_id = $1 AND status = $2
|
|
LIMIT 1`,
|
|
[input.preparationId, PREP_AMEND_STATUS.pending]
|
|
);
|
|
|
|
let requestId: string;
|
|
let overwritten = false;
|
|
if (existing.rowCount) {
|
|
overwritten = true;
|
|
requestId = String(existing.rows[0].id);
|
|
await pool.query(
|
|
`UPDATE supplier_prep_amend_requests SET
|
|
proposed_price = $2,
|
|
proposed_qty = $3,
|
|
proposed_unit = $4,
|
|
before_price = $5,
|
|
before_qty = $6,
|
|
before_unit = $7,
|
|
requested_by = $8,
|
|
requested_at = NOW(),
|
|
updated_at = NOW(),
|
|
item_name = $9,
|
|
order_code = $10,
|
|
sku_code = $11,
|
|
branch_code = $12
|
|
WHERE id = $1`,
|
|
[
|
|
requestId,
|
|
proposedPrice,
|
|
proposedQty,
|
|
proposedUnit,
|
|
beforePrice,
|
|
beforeQty,
|
|
beforeUnit,
|
|
input.requestedBy,
|
|
prep.display_name || null,
|
|
prep.order_code || null,
|
|
prep.sku_code || null,
|
|
branchCode,
|
|
]
|
|
);
|
|
} else {
|
|
const inserted = await pool.query(
|
|
`INSERT INTO supplier_prep_amend_requests (
|
|
preparation_id, order_code, sku_code, supplier_code, branch_code, item_name,
|
|
before_price, before_qty, before_unit,
|
|
proposed_price, proposed_qty, proposed_unit,
|
|
status, requested_by
|
|
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
|
|
RETURNING id`,
|
|
[
|
|
input.preparationId,
|
|
prep.order_code || null,
|
|
prep.sku_code || null,
|
|
input.supplierCode,
|
|
branchCode,
|
|
prep.display_name || null,
|
|
beforePrice,
|
|
beforeQty,
|
|
beforeUnit,
|
|
proposedPrice,
|
|
proposedQty,
|
|
proposedUnit,
|
|
PREP_AMEND_STATUS.pending,
|
|
input.requestedBy,
|
|
]
|
|
);
|
|
requestId = String(inserted.rows[0].id);
|
|
}
|
|
|
|
const title = '供应商追加修改待确认';
|
|
const content = [
|
|
`${prep.supplier_name || input.supplierCode}`,
|
|
`${prep.display_name || prep.sku_code || ''}`,
|
|
`价 ${beforePrice}→${proposedPrice}`,
|
|
`量 ${beforeQty ?? '-'}→${proposedQty ?? '-'}`,
|
|
`单位 ${beforeUnit}→${proposedUnit}`,
|
|
prep.order_code ? `订单 ${prep.order_code}` : '',
|
|
]
|
|
.filter(Boolean)
|
|
.join(' · ');
|
|
|
|
await notifyRoleUsers({
|
|
roles: ['operator', 'admin', 'super_admin', 'purchaser'],
|
|
notifyType: 'supplier_prep_amend_pending',
|
|
title,
|
|
content,
|
|
relatedOrderCode: requestId,
|
|
branchCode,
|
|
skipIfRecent: false,
|
|
});
|
|
|
|
return { request_id: requestId, status: 'pending', overwritten };
|
|
}
|
|
|
|
export async function listPendingPrepAmends(branchCode?: string | null): Promise<PrepAmendRequestRow[]> {
|
|
const params: unknown[] = [PREP_AMEND_STATUS.pending];
|
|
let branchSql = '';
|
|
if (branchCode) {
|
|
params.push(branchCode);
|
|
branchSql = ` AND COALESCE(r.branch_code, '') = $${params.length}`;
|
|
}
|
|
const result = await pool.query(
|
|
`SELECT r.*, COALESCE(sup.company_name, r.supplier_code) AS supplier_name
|
|
FROM supplier_prep_amend_requests r
|
|
LEFT JOIN suppliers sup ON sup.supplier_code = r.supplier_code
|
|
WHERE r.status = $1 ${branchSql}
|
|
ORDER BY r.requested_at DESC
|
|
LIMIT 200`,
|
|
params
|
|
);
|
|
return result.rows.map(mapRow);
|
|
}
|
|
|
|
/** 当天已确认 + 已驳回(reviewed_at 上海日历日);不含 reviewed_at 为空 */
|
|
export async function listReviewedPrepAmendsToday(branchCode?: string | null): Promise<PrepAmendRequestRow[]> {
|
|
const params: unknown[] = [PREP_AMEND_STATUS.approved, PREP_AMEND_STATUS.rejected];
|
|
let branchSql = '';
|
|
if (branchCode) {
|
|
params.push(branchCode);
|
|
branchSql = ` AND COALESCE(r.branch_code, '') = $${params.length}`;
|
|
}
|
|
const result = await pool.query(
|
|
`SELECT r.*, COALESCE(sup.company_name, r.supplier_code) AS supplier_name
|
|
FROM supplier_prep_amend_requests r
|
|
LEFT JOIN suppliers sup ON sup.supplier_code = r.supplier_code
|
|
WHERE r.status IN ($1, $2)
|
|
AND r.reviewed_at IS NOT NULL
|
|
AND (r.reviewed_at AT TIME ZONE 'Asia/Shanghai')::date
|
|
= (NOW() AT TIME ZONE 'Asia/Shanghai')::date
|
|
${branchSql}
|
|
ORDER BY r.reviewed_at DESC
|
|
LIMIT 200`,
|
|
params
|
|
);
|
|
return result.rows.map(mapRow);
|
|
}
|
|
|
|
export async function getPrepAmendRequest(id: string): Promise<PrepAmendRequestRow | null> {
|
|
const result = await pool.query(
|
|
`SELECT r.*, COALESCE(sup.company_name, r.supplier_code) AS supplier_name
|
|
FROM supplier_prep_amend_requests r
|
|
LEFT JOIN suppliers sup ON sup.supplier_code = r.supplier_code
|
|
WHERE r.id = $1
|
|
LIMIT 1`,
|
|
[id]
|
|
);
|
|
if (!result.rowCount) return null;
|
|
return mapRow(result.rows[0]);
|
|
}
|
|
|
|
/** 按备货 id 批量取最近一条申请(优先 pending) */
|
|
export async function mapLatestAmendByPrepIds(
|
|
prepIds: string[]
|
|
): Promise<Record<string, PrepAmendRequestRow>> {
|
|
const ids = [...new Set(prepIds.map((id) => String(id || '').trim()).filter(Boolean))];
|
|
if (!ids.length) return {};
|
|
const result = await pool.query(
|
|
`SELECT DISTINCT ON (preparation_id) *
|
|
FROM supplier_prep_amend_requests
|
|
WHERE preparation_id = ANY($1::uuid[])
|
|
ORDER BY preparation_id,
|
|
CASE WHEN status = $2 THEN 0 ELSE 1 END,
|
|
requested_at DESC`,
|
|
[ids, PREP_AMEND_STATUS.pending]
|
|
);
|
|
const out: Record<string, PrepAmendRequestRow> = {};
|
|
for (const row of result.rows) {
|
|
const mapped = mapRow(row);
|
|
out[mapped.preparation_id] = mapped;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export async function confirmPrepAmend(input: {
|
|
requestId: string;
|
|
reviewerId: string;
|
|
purchasePrice?: number | null;
|
|
prepareQty?: number | null;
|
|
unit?: string | null;
|
|
remark?: string | null;
|
|
branchCode?: string | null;
|
|
operatorRole?: string | null;
|
|
}) {
|
|
const req = await getPrepAmendRequest(input.requestId);
|
|
if (!req) throw bizError('申请不存在', 404, 'not_found');
|
|
if (req.status !== PREP_AMEND_STATUS.pending) {
|
|
throw bizError('该申请已处理', 409, 'conflict');
|
|
}
|
|
|
|
const finalPrice =
|
|
input.purchasePrice !== undefined && input.purchasePrice !== null
|
|
? Number(input.purchasePrice)
|
|
: Number(req.proposed_price);
|
|
const finalQty =
|
|
input.prepareQty !== undefined && input.prepareQty !== null
|
|
? Number(input.prepareQty)
|
|
: req.proposed_qty != null
|
|
? Number(req.proposed_qty)
|
|
: null;
|
|
const finalUnit =
|
|
input.unit != null && String(input.unit).trim()
|
|
? String(input.unit).trim()
|
|
: String(req.proposed_unit || req.before_unit || '个').trim();
|
|
|
|
// 审批落地同口径(申请时已按开关校验,这里再校一次防止旧申请在开关后落地)
|
|
const allowZeroFinal = await isZeroSupplyCostAllowed(
|
|
String(input.branchCode || req.branch_code || '').trim() || null
|
|
);
|
|
if (allowZeroFinal) assertSupplyCostPrice(finalPrice, '采购价', { allowZero: true });
|
|
else if (!Number.isFinite(finalPrice) || finalPrice <= 0) throw bizError('采购价必须大于 0');
|
|
if (finalQty !== null && (!Number.isFinite(finalQty) || finalQty <= 0)) {
|
|
throw bizError('供货数量无效');
|
|
}
|
|
|
|
const closed = await updatePreparationPurchasePrice(
|
|
{
|
|
ids: [req.preparation_id],
|
|
purchasePrice: finalPrice,
|
|
unit: finalUnit,
|
|
prepareQty: finalQty,
|
|
},
|
|
{
|
|
branchCode: input.branchCode || req.branch_code,
|
|
alignOrderPlanQty: true,
|
|
operatorId: input.reviewerId,
|
|
operatorRole: input.operatorRole || null,
|
|
}
|
|
);
|
|
|
|
const statementOrderCodes = [...new Set((closed.orderCodes || []).filter(Boolean))];
|
|
for (const orderCode of statementOrderCodes) {
|
|
await upsertCustomerStatementForOrder(orderCode);
|
|
await ensureSupplierStatementsForOrder(orderCode);
|
|
}
|
|
|
|
await pool.query(
|
|
`UPDATE supplier_prep_amend_requests SET
|
|
status = $2,
|
|
final_price = $3,
|
|
final_qty = $4,
|
|
final_unit = $5,
|
|
reviewed_by = $6,
|
|
reviewed_at = NOW(),
|
|
review_remark = $7,
|
|
updated_at = NOW()
|
|
WHERE id = $1 AND status = $8`,
|
|
[
|
|
input.requestId,
|
|
PREP_AMEND_STATUS.approved,
|
|
finalPrice,
|
|
finalQty,
|
|
finalUnit,
|
|
input.reviewerId,
|
|
input.remark ? String(input.remark).trim() : null,
|
|
PREP_AMEND_STATUS.pending,
|
|
]
|
|
);
|
|
|
|
const updated = await getPrepAmendRequest(input.requestId);
|
|
try {
|
|
await writeAuditLog({
|
|
operatorId: input.reviewerId,
|
|
operatorRole: input.operatorRole || null,
|
|
operationType: 'prep_amend_confirm',
|
|
actionCategory: 'prep_amend',
|
|
targetTable: 'supplier_prep_amend_requests',
|
|
targetId: req.id,
|
|
branchCode: input.branchCode || req.branch_code,
|
|
oldValue: {
|
|
order_code: req.order_code,
|
|
sku_code: req.sku_code,
|
|
item_name: req.item_name,
|
|
supplier_code: req.supplier_code,
|
|
before_price: req.before_price,
|
|
before_qty: req.before_qty,
|
|
before_unit: req.before_unit,
|
|
proposed_price: req.proposed_price,
|
|
proposed_qty: req.proposed_qty,
|
|
proposed_unit: req.proposed_unit,
|
|
},
|
|
newValue: {
|
|
final_price: finalPrice,
|
|
final_qty: finalQty,
|
|
final_unit: finalUnit,
|
|
review_remark: input.remark ? String(input.remark).trim() : null,
|
|
closed_loop: closed,
|
|
// 改量后对「实收」来源字段的逐行对齐(2026-10-08 方案甲):
|
|
// 含 applied=false 的跳过项(已出库/已称重/已验收/采购已完成),便于事后核对"为什么没跟着变"
|
|
received_qty_alignments: closed.receivedQtyAlignments || [],
|
|
},
|
|
});
|
|
} catch (auditError) {
|
|
console.error('[prepAmend] writeAuditLog confirm failed:', auditError);
|
|
}
|
|
|
|
return {
|
|
request: updated,
|
|
closed_loop: closed,
|
|
received_qty_alignments: closed.receivedQtyAlignments || [],
|
|
};
|
|
}
|
|
|
|
export async function rejectPrepAmend(input: {
|
|
requestId: string;
|
|
reviewerId: string;
|
|
remark?: string | null;
|
|
operatorRole?: string | null;
|
|
}) {
|
|
const req = await getPrepAmendRequest(input.requestId);
|
|
if (!req) throw bizError('申请不存在', 404, 'not_found');
|
|
if (req.status !== PREP_AMEND_STATUS.pending) {
|
|
throw bizError('该申请已处理', 409, 'conflict');
|
|
}
|
|
|
|
await pool.query(
|
|
`UPDATE supplier_prep_amend_requests SET
|
|
status = $2,
|
|
reviewed_by = $3,
|
|
reviewed_at = NOW(),
|
|
review_remark = $4,
|
|
updated_at = NOW()
|
|
WHERE id = $1 AND status = $5`,
|
|
[
|
|
input.requestId,
|
|
PREP_AMEND_STATUS.rejected,
|
|
input.reviewerId,
|
|
input.remark ? String(input.remark).trim() : null,
|
|
PREP_AMEND_STATUS.pending,
|
|
]
|
|
);
|
|
|
|
if (req.requested_by) {
|
|
await notifyUser({
|
|
userId: req.requested_by,
|
|
notifyType: 'supplier_prep_amend_rejected',
|
|
title: '追加修改已驳回',
|
|
content: [
|
|
req.item_name || req.sku_code || '',
|
|
input.remark ? `原因:${String(input.remark).trim()}` : '请修改后重新提交',
|
|
req.order_code ? `订单 ${req.order_code}` : '',
|
|
]
|
|
.filter(Boolean)
|
|
.join(' · '),
|
|
relatedOrderCode: req.order_code || req.id,
|
|
branchCode: req.branch_code,
|
|
});
|
|
} else if (req.supplier_code) {
|
|
const users = await pool.query(
|
|
`SELECT user_id FROM supplier_users WHERE supplier_code = $1 LIMIT 5`,
|
|
[req.supplier_code]
|
|
);
|
|
for (const row of users.rows) {
|
|
await notifyUser({
|
|
userId: String(row.user_id),
|
|
notifyType: 'supplier_prep_amend_rejected',
|
|
title: '追加修改已驳回',
|
|
content: [
|
|
req.item_name || req.sku_code || '',
|
|
input.remark ? `原因:${String(input.remark).trim()}` : '请修改后重新提交',
|
|
]
|
|
.filter(Boolean)
|
|
.join(' · '),
|
|
relatedOrderCode: req.order_code || req.id,
|
|
branchCode: req.branch_code,
|
|
});
|
|
}
|
|
}
|
|
|
|
try {
|
|
await writeAuditLog({
|
|
operatorId: input.reviewerId,
|
|
operatorRole: input.operatorRole || null,
|
|
operationType: 'prep_amend_reject',
|
|
actionCategory: 'prep_amend',
|
|
targetTable: 'supplier_prep_amend_requests',
|
|
targetId: req.id,
|
|
branchCode: req.branch_code,
|
|
oldValue: {
|
|
order_code: req.order_code,
|
|
sku_code: req.sku_code,
|
|
item_name: req.item_name,
|
|
supplier_code: req.supplier_code,
|
|
before_price: req.before_price,
|
|
before_qty: req.before_qty,
|
|
before_unit: req.before_unit,
|
|
proposed_price: req.proposed_price,
|
|
proposed_qty: req.proposed_qty,
|
|
proposed_unit: req.proposed_unit,
|
|
},
|
|
newValue: {
|
|
review_remark: input.remark ? String(input.remark).trim() : null,
|
|
},
|
|
});
|
|
} catch (auditError) {
|
|
console.error('[prepAmend] writeAuditLog reject failed:', auditError);
|
|
}
|
|
|
|
return { request: await getPrepAmendRequest(input.requestId) };
|
|
}
|
|
|
|
export async function countPendingPrepAmends(branchCode?: string | null): Promise<number> {
|
|
const params: unknown[] = [PREP_AMEND_STATUS.pending];
|
|
let branchSql = '';
|
|
if (branchCode) {
|
|
params.push(branchCode);
|
|
branchSql = ` AND COALESCE(branch_code, '') = $${params.length}`;
|
|
}
|
|
const result = await pool.query(
|
|
`SELECT COUNT(*)::int AS c FROM supplier_prep_amend_requests WHERE status = $1 ${branchSql}`,
|
|
params
|
|
);
|
|
return Number(result.rows[0]?.c) || 0;
|
|
}
|