import { pool } from '../db'; import { assertOrderItemsFulfilled } from './orderItemFulfillmentService'; import type { TenantContext } from './tenantScope'; import { notifyRoleUsers } from './notificationService'; import { writeAuditLog } from './auditService'; import { refreshMarketPriceIndices } from './marketIndexService'; import { listExcludedMarketSkuCodes } from './marketCompareExclusionService'; import { getBranchWholesaleMarketConfig, isMarketQuoteStale, resolveMarketSession, } from './marketBranchMarketConfigService'; import { isMarketRedBlockEnabled } from './marketRedBlockConfigService'; import { getMarketComparePriceBasisConfig } from './marketComparePriceBasisConfigService'; import { fetchAiMarketPrices, MARKET_PRICE_SOURCE_AI, } from './marketAiPriceQuoteService'; import { isLlmServiceError } from './llmService'; import { isLockedCompletedAfterSale, notifyAfterSaleClosed, notifyAfterSaleCreated, rejectLockedCompletedAfterSaleMutation, } from './afterSaleLifecycleService'; import { detachOrKeepTransferredPurchase } from './preparationStockoutService'; import { applyAfterSaleHandleOrderItem } from './orderManageItemsService'; 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 ''; } /** 仅成本高于市场(买贵)才分级报警;成本不高于市场一律 normal */ function deviationLevel(rate: number): string { if (!(rate > 0)) return 'normal'; const pct = rate * 100; if (pct >= 35) return 'red'; if (pct >= 20) return 'orange'; if (pct >= 10) return 'yellow'; return 'normal'; } /** estimated / 过期行情不参与黄橙红;ai 与 external / supplier_avg 同等可报警 */ function resolveAlertableLevel( deviation: number, source: string, quotedAt?: unknown ): string { if (source === 'estimated' || isMarketQuoteStale(quotedAt)) return 'normal'; if (source !== 'external' && source !== 'supplier_avg' && source !== MARKET_PRICE_SOURCE_AI) { return 'normal'; } return deviationLevel(deviation); } export type MarketPriceFetchMode = 'ai' | 'rebase_only'; /** S01 AI 历史预填:近30天高频 SKU */ export async function getCustomerOrderPrefill(customerCode: string, limit = 20) { const result = await pool.query( `SELECT oi.sku_code, COALESCE(MAX(oi.item_name), MAX(s.sku_name), oi.sku_code) AS sku_name, COALESCE(MAX(oi.unit), MAX(s.unit), '斤') AS unit, COALESCE(AVG(oi.quantity), 1) AS avg_qty, COUNT(*)::int AS order_count, MAX(oi.category_code) AS category_code FROM order_items oi JOIN orders o ON o.order_code = oi.order_code LEFT JOIN skus s ON s.sku_code = oi.sku_code WHERE o.customer_code = $1 AND o.created_at >= NOW() - INTERVAL '30 days' AND oi.sku_code IS NOT NULL GROUP BY oi.sku_code ORDER BY order_count DESC, MAX(o.created_at) DESC LIMIT $2`, [customerCode, limit] ); return result.rows; } /** S05 发起换品(委托 substitutionService 四条件校验) */ export async function createProductSubstitution(input: { orderCode: string; prepId?: string; originalSkuCode: string; substituteSkuCode: string; originalPrice: number; substitutePrice: number; reason?: string; branchCode?: string | null; createdBy?: string | null; }) { const { createSubstitutionWithValidation } = await import('./substitutionService'); return createSubstitutionWithValidation(input); } /** S05 客户确认换品 */ export async function confirmProductSubstitution(substitutionCode: string, confirmed: boolean) { const client = await pool.connect(); try { await client.query('BEGIN'); const selected = await client.query( `SELECT * FROM product_substitutions WHERE substitution_code = $1 AND status = 10 FOR UPDATE`, [substitutionCode] ); if (!selected.rowCount) throw new Error('换品单不存在或已处理'); const row = selected.rows[0]; await client.query( `UPDATE product_substitutions SET customer_confirmed = $2, customer_confirmed_at = NOW(), status = $3 WHERE substitution_code = $1`, [substitutionCode, confirmed, confirmed ? 30 : 40] ); if (row.prep_id) { const prepMeta = await client.query( `SELECT purchase_code, transferred_to_purchase, is_stockout FROM supplier_preparations WHERE id = $1::uuid FOR UPDATE`, [row.prep_id] ); const prepRow = prepMeta.rows[0]; const wasTransferred = Boolean(prepRow?.transferred_to_purchase) || Boolean(prepRow?.purchase_code); if (confirmed) { if (wasTransferred) { const outcome = await detachOrKeepTransferredPurchase(client, { prepId: String(row.prep_id), purchaseCode: prepRow?.purchase_code, remark: '换品确认,取消原无货流转自采', }); if (outcome.action === 'keep_purchase') { throw Object.assign( new Error('该商品无货流转自采已完成或已提交待验收,不能改回备货换品'), { status: 409, code: 'conflict' } ); } } await client.query( `UPDATE supplier_preparations SET sku_code = $2, purchase_price = $3, is_stockout = false, transferred_to_purchase = false, stockout_reason = NULL, purchase_code = NULL, prepare_status = CASE WHEN prepare_status = 40 THEN 10 ELSE prepare_status END WHERE id = $1::uuid`, [row.prep_id, row.substitute_sku_code, row.substitute_price] ); await client.query( `UPDATE order_items oi SET sku_code = $2, price = $3, amount = quantity * $3 FROM order_item_fulfillments f WHERE f.order_item_id = oi.id AND f.supplier_preparation_id = $1::uuid`, [row.prep_id, row.substitute_sku_code, row.substitute_price] ); await client.query( `UPDATE allocation_tasks SET sku_code = $2 WHERE order_code = $3 AND sku_code = $1`, [row.original_sku_code, row.substitute_sku_code, row.order_code] ); // 换品改了 sku/单价/金额:同步结算投影(客户=订单行重建,供应商=按当前订单行重建) { const { syncStatementsForOrderSafe } = await import('./financeReconciliationService'); await syncStatementsForOrderSafe(String(row.order_code || ''), client as any); } } else if (!wasTransferred) { // 拒绝换品仍保留原备货;已流转则不解绑自采。 await client.query( `UPDATE supplier_preparations SET is_stockout = false, transferred_to_purchase = false, stockout_reason = NULL, prepare_status = CASE WHEN prepare_status = 40 THEN 10 ELSE prepare_status END WHERE id = $1::uuid`, [row.prep_id] ); } } await assertOrderItemsFulfilled(client, String(row.order_code)); await client.query('COMMIT'); return { ...row, customer_confirmed: confirmed, status: confirmed ? 30 : 40 }; } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } } /** S07 保存电子签 */ export async function saveDeliverySignature(input: { taskCode: string; orderCode?: string; signType: 'delivery' | 'customer'; signatureData: string; photoUrl?: string; signerName?: string; branchCode?: string | null; }) { await pool.query( `DELETE FROM delivery_signatures WHERE task_code = $1 AND sign_type = $2`, [input.taskCode, input.signType] ); const result = await pool.query( `INSERT INTO delivery_signatures (task_code, order_code, sign_type, signature_data, photo_url, signer_name, branch_code) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`, [ input.taskCode, input.orderCode || null, input.signType, input.signatureData, input.photoUrl || null, input.signerName || null, input.branchCode || null, ] ); if (input.signType === 'customer') { await pool.query( `UPDATE delivery_tasks SET sign_time = COALESCE(sign_time, NOW()) WHERE task_code = $1`, [input.taskCode] ); if (input.orderCode) { // finalize 内会置 task_status=30 与订单 90;失败时任务不得先标完成 const { finalizeOrderFulfillment } = await import('./orderWorkflowFulfillmentService'); await finalizeOrderFulfillment(String(input.orderCode)); } else { await pool.query( `UPDATE delivery_tasks SET task_status = 30, sign_time = COALESCE(sign_time, NOW()) WHERE task_code = $1`, [input.taskCode] ); } } else if (input.signType === 'delivery') { await pool.query( `UPDATE delivery_tasks SET task_status = GREATEST(task_status, 20) WHERE task_code = $1 AND task_status < 30`, [input.taskCode] ); } return result.rows[0]; } export async function listDeliverySignatures(taskCode: string) { const result = await pool.query( `SELECT id, task_code, order_code, sign_type, photo_url, signer_name, signed_at FROM delivery_signatures WHERE task_code = $1 ORDER BY signed_at ASC`, [taskCode] ); return result.rows; } /** S08 售后 24h 校验 + 简易 AI 判责 */ export async function createAfterSalesWithValidation(input: { orderCode: string; customerCode: string; issueType: string; description: string; amount: number; branchCode?: string | null; createdBy?: string | null; confirmed?: boolean; skuCode?: string | null; quantity?: number | null; orderItemId?: string | null; }) { if (input.amount > 500 && !input.confirmed) { throw new Error('售后金额超过500元,须人工确认(请传 confirmed: true)'); } const orderCode = String(input.orderCode || '').trim(); const customerCode = String(input.customerCode || '').trim(); if (!orderCode) throw Object.assign(new Error('缺少订单号'), { status: 400 }); if (!customerCode) throw Object.assign(new Error('缺少客户编码'), { status: 400 }); if (!String(input.description || '').trim()) { throw Object.assign(new Error('请填写问题描述'), { status: 400 }); } const orderResult = await pool.query( `SELECT order_code, customer_code, branch_code, deleted_at FROM orders WHERE order_code = $1 LIMIT 1`, [orderCode] ); const order = orderResult.rows[0]; if (!order) throw Object.assign(new Error('订单不存在'), { status: 404 }); if (order.deleted_at) throw Object.assign(new Error('订单已在垃圾桶'), { status: 409 }); if (String(order.customer_code || '') !== customerCode) { throw Object.assign(new Error('客户与订单不匹配'), { status: 400 }); } let skuCode = input.skuCode ? String(input.skuCode).trim() : null; let quantity = input.quantity != null ? Number(input.quantity) : null; let orderItemId = input.orderItemId ? String(input.orderItemId).trim() : null; if (orderItemId) { const item = await pool.query( `SELECT id, sku_code, quantity FROM order_items WHERE id::text = $1 AND order_code = $2 LIMIT 1`, [orderItemId, orderCode] ); if (!item.rowCount) throw Object.assign(new Error('订单明细不存在或不属于该订单'), { status: 400 }); skuCode = skuCode || (item.rows[0].sku_code ? String(item.rows[0].sku_code) : null); if (quantity == null) quantity = Number(item.rows[0].quantity) || 0; } else if (skuCode) { const item = await pool.query( `SELECT id, quantity FROM order_items WHERE order_code = $1 AND sku_code = $2 ORDER BY sort_order ASC NULLS LAST LIMIT 1`, [orderCode, skuCode] ); if (item.rowCount) { orderItemId = String(item.rows[0].id); if (quantity == null) quantity = Number(item.rows[0].quantity) || 0; } } // 处理必须绑定订单明细(处理确认按行删行/红冲):创建时就把明细定死, // 否则会建出「永远无法处理」的售后单(处理侧 400)。除明细明确 / sku 唯一命中外, // 只剩「整单仅一条有效明细」这一种可无损推断的情形;多条时必须人工选择。 if (!orderItemId) { const activeItems = await pool.query( `SELECT id, quantity FROM order_items WHERE order_code = $1 AND COALESCE(is_returned, false) = false ORDER BY sort_order ASC NULLS LAST, id ASC LIMIT 2`, [orderCode] ); if (activeItems.rowCount === 1) { orderItemId = String(activeItems.rows[0].id); if (quantity == null) quantity = Number(activeItems.rows[0].quantity) || 0; } else if ((activeItems.rowCount ?? 0) > 1) { throw Object.assign(new Error('该订单有多条明细,请选择「关联订单明细」后再建售后'), { status: 400, code: 'invalid_request', }); } else { throw Object.assign(new Error('该订单没有可关联的有效明细,无法建售后'), { status: 400, code: 'invalid_request', }); } } const signResult = await pool.query( `SELECT MAX(sr.created_at) AS sign_time FROM sign_records sr WHERE sr.order_code = $1`, [orderCode] ); const signTime = signResult.rows[0]?.sign_time; if (signTime) { const hours = (Date.now() - new Date(signTime).getTime()) / 3600000; if (hours > 24) { throw new Error('签收已超过24小时,不予受理(V9 铁律)'); } } let liabilityParty = 'internal'; let confidence = 65; const desc = input.description.toLowerCase(); if (/供应商|缺货|质量|腐烂|变质/.test(desc)) { liabilityParty = 'supplier'; confidence = 78; } else if (/客户|错发|多要|不要/.test(desc)) { liabilityParty = 'customer'; confidence = 72; } const code = `AS${Date.now()}`; const branchCode = input.branchCode || order.branch_code || null; const result = await pool.query( `INSERT INTO after_sales ( aftersale_code, order_code, customer_code, aftersale_type, reason, amount, status, branch_code, ai_liability_party, ai_confidence, sign_record_time, responsibility, sku_code, quantity, order_item_id, created_by ) VALUES ($1,$2,$3,$4,$5,$6,10,$7,$8,$9,$10,$8,$11,$12,$13,$14) RETURNING *`, [ code, orderCode, customerCode, input.issueType, input.description, input.amount, branchCode, liabilityParty, confidence, signTime || null, skuCode, quantity, orderItemId, input.createdBy || null, ] ); const row = result.rows[0]; await notifyAfterSaleCreated(row); return row; } /** S08 售后处理:须受理(20)或自动受理(10);同意后走订单删行/红冲(不另建 OIR_) */ export async function handleAfterSalesWithValidation(input: { aftersaleId: string; responsibility: string; handleMethod: string; amount: number; remark?: string; confirmed?: boolean; handledBy?: string | null; }) { const client = await pool.connect(); try { await client.query('BEGIN'); const existing = await client.query( `SELECT * FROM after_sales WHERE id::text = $1 OR aftersale_code = $1 LIMIT 1 FOR UPDATE`, [input.aftersaleId] ); const row = existing.rows[0]; if (!row) throw new Error('售后单不存在'); if (isLockedCompletedAfterSale(row)) rejectLockedCompletedAfterSaleMutation(row); const status = Number(row.status) || 0; if (status >= 30) throw new Error('售后单已处理'); if (status === 10) { await client.query( `UPDATE after_sales SET status = 20, handler_id = COALESCE($2, handler_id), handled_at = NOW() WHERE id = $1`, [row.id, input.handledBy || null] ); } else if (status !== 20) { throw new Error('当前状态不可完成处理'); } const amount = input.amount > 0 ? input.amount : Number(row.amount) || 0; if (amount > 500 && !input.confirmed) { throw new Error('处理金额超过500元,须人工确认(请传 confirmed: true)'); } const orderItemId = String(row.order_item_id || '').trim(); const orderCode = String(row.order_code || '').trim(); if (!orderItemId || !orderCode) { throw Object.assign(new Error('处理前须绑定订单明细'), { status: 400, code: 'invalid_request' }); } const itemOutcome = await applyAfterSaleHandleOrderItem(client, { orderCode, branchCode: row.branch_code || null, itemId: orderItemId, }); let fulfillmentRefType: string | null = null; let fulfillmentRefId: string | null = null; if (itemOutcome === 'returned' || itemOutcome === 'already_returned') { const returned = await client.query( `SELECT return_code FROM order_items WHERE id = $1::uuid LIMIT 1`, [orderItemId] ); fulfillmentRefType = 'order_item_return'; fulfillmentRefId = returned.rows[0]?.return_code ? String(returned.rows[0].return_code) : null; } else if (itemOutcome === 'deleted') { fulfillmentRefType = 'order_item_delete'; fulfillmentRefId = String(row.aftersale_code || ''); } const remarkSuffix = input.remark ? `\n处理备注: ${input.remark}` : ''; const result = await client.query( `UPDATE after_sales SET status = 30, responsibility = $1, handle_method = $2, handle_amount = $3, closed_at = NOW(), handler_id = COALESCE($5, handler_id), handled_at = COALESCE(handled_at, NOW()), reason = COALESCE(reason, '') || $4, fulfillment_ref_type = COALESCE($7, fulfillment_ref_type), fulfillment_ref_id = COALESCE($8, fulfillment_ref_id) WHERE id = $6 RETURNING *`, [ input.responsibility, input.handleMethod, amount, remarkSuffix, input.handledBy || null, row.id, fulfillmentRefType, fulfillmentRefId, ] ); const updated = result.rows[0]; await client.query('COMMIT'); await notifyAfterSaleClosed({ aftersale_code: updated.aftersale_code, order_code: updated.order_code, branch_code: updated.branch_code, created_by: updated.created_by, status: 30, }); try { let skuName: string | null = null; if (row.sku_code) { const skuRes = await pool.query( `SELECT sku_name FROM skus WHERE sku_code = $1 LIMIT 1`, [row.sku_code] ); skuName = skuRes.rows[0]?.sku_name ? String(skuRes.rows[0].sku_name) : null; } await writeAuditLog({ operatorId: input.handledBy || null, operationType: 'aftersale_handle', actionCategory: 'aftersale', targetTable: 'after_sales', targetId: String(updated.aftersale_code || updated.id), branchCode: updated.branch_code || null, oldValue: { status: row.status, order_code: row.order_code, aftersale_type: row.aftersale_type, sku_code: row.sku_code, quantity: row.quantity, amount: row.amount, }, newValue: { status: 30, aftersale_code: updated.aftersale_code, order_code: updated.order_code || row.order_code, aftersale_type: row.aftersale_type, sku_code: row.sku_code, sku_name: skuName, quantity: row.quantity, responsibility: input.responsibility, handle_method: input.handleMethod, handle_amount: amount, remark: input.remark || null, item_outcome: itemOutcome, }, }); } catch (auditError) { console.error('[aftersale] writeAuditLog failed:', auditError); } return { ...updated, item_outcome: itemOutcome, }; } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } } /** S10 刷新市场比价(分公司主市场 + 买贵分级) * 「我们的价格」取自执行中报价单成本价或销售价(分公司配置,多报价取均值)。 * priceFetch=ai:按批调 Ark 写 price_source=ai(未命中保留旧行);rebase_only:不调 AI,仅用库内行情重算 our/偏离/灯色。 * 设计:docs/design/20260818-market-price-via-ark.md */ export async function refreshMarketPrices( ctx?: TenantContext | null, options?: { priceFetch?: MarketPriceFetchMode } ) { const priceFetch: MarketPriceFetchMode = options?.priceFetch === 'rebase_only' ? 'rebase_only' : 'ai'; const effectiveBranch = String(ctx?.branchCode || '').trim(); if (!effectiveBranch) { throw Object.assign(new Error('请选择当前操作分公司后再刷新比价'), { status: 400, code: 'branch_required', }); } const marketCfg = await getBranchWholesaleMarketConfig(effectiveBranch); const priceBasisCfg = await getMarketComparePriceBasisConfig(effectiveBranch); const priceBasis = priceBasisCfg.basis; const province = marketCfg.province; const marketName = marketCfg.market_name; const session = resolveMarketSession(); const quotedAt = new Date(); const params: unknown[] = []; params.push(effectiveBranch); const branchSql = `AND qs.branch_code = $1`; const ourPriceExpr = priceBasis === 'sale' ? `AVG(COALESCE(NULLIF(qi.sale_price, 0), NULLIF(qi.price, 0)))::numeric` : `AVG(qi.cost_price)::numeric`; const ourPriceFilter = priceBasis === 'sale' ? `AND COALESCE(NULLIF(qi.sale_price, 0), NULLIF(qi.price, 0)) > 0` : `AND qi.cost_price > 0`; const skus = await pool.query( `SELECT s.sku_code, COALESCE(MAX(s.sku_name), MAX(qi.sku_name)) AS sku_name, MAX(s.category_code) AS category_code, MAX(COALESCE(s.branch_code, qs.branch_code)) AS branch_code, ${ourPriceExpr} AS our_quote_price FROM customer_quote_sheet_items qi JOIN customer_quote_sheets qs ON qs.quote_sheet_code = qi.quote_sheet_code JOIN skus s ON s.sku_code = qi.sku_code WHERE qs.status = 1 AND qs.approval_status = 30 AND (qs.expires_at IS NULL OR qs.expires_at > NOW()) ${ourPriceFilter} AND s.status = 1 ${branchSql} GROUP BY s.sku_code ORDER BY s.sku_code LIMIT 500`, params ); const existingLevels = await pool.query( `SELECT sku_code, price_level, market_price, price_source, quoted_at FROM market_prices WHERE branch_code = $1`, [effectiveBranch] ); const priorLevelMap = new Map( existingLevels.rows.map((row) => [String(row.sku_code), String(row.price_level || 'normal')]) ); const existingPriceMap = new Map< string, { market_price: number; price_source: string; quoted_at: unknown } >( existingLevels.rows.map((row) => [ String(row.sku_code), { market_price: Number(row.market_price) || 0, price_source: String(row.price_source || ''), quoted_at: row.quoted_at, }, ]) ); const skuCodeList = skus.rows.map((s: { sku_code: string }) => String(s.sku_code)); let aiQuotes = new Map(); let aiBatches = 0; let aiErrors: string[] = []; let providerError: string | null = null; let locationUsed = `${province} ${marketName}`.trim(); if (priceFetch === 'ai') { const quoteItems = skus.rows .filter((s: { our_quote_price: unknown }) => Number(s.our_quote_price) > 0) .map((s: { sku_code: string; sku_name: string }) => ({ sku_code: String(s.sku_code), sku_name: String(s.sku_name || s.sku_code), })); try { const aiResult = await fetchAiMarketPrices({ branchCode: effectiveBranch, items: quoteItems, }); aiQuotes = aiResult.quotes; aiBatches = aiResult.batches; aiErrors = aiResult.errors; locationUsed = aiResult.location; if (aiErrors.length) { providerError = aiErrors.join(';'); } } catch (error: unknown) { if (isLlmServiceError(error)) { throw Object.assign(new Error(error.message), { status: error.code === 'ARK_ACCOUNT_OVERDUE' || error.code === 'ARK_NOT_CONFIGURED' ? 503 : 502, code: error.code, }); } throw error; } } let updated = 0; const newRedSkus: string[] = []; const candidateRedCodes: string[] = []; const candidateRedNames: string[] = []; for (const sku of skus.rows) { const ourPrice = Number(sku.our_quote_price) || 0; if (ourPrice <= 0) continue; let marketPrice = 0; let source = ''; let rowQuotedAt: Date | unknown = quotedAt; if (priceFetch === 'ai') { const aiPrice = aiQuotes.get(String(sku.sku_code)); if (!(aiPrice && aiPrice > 0)) continue; marketPrice = aiPrice; source = MARKET_PRICE_SOURCE_AI; } else { const prior = existingPriceMap.get(String(sku.sku_code)); if (!prior || !(prior.market_price > 0) || !prior.price_source) continue; marketPrice = prior.market_price; source = prior.price_source; rowQuotedAt = prior.quoted_at || quotedAt; } const deviation = marketPrice > 0 ? (ourPrice - marketPrice) / marketPrice : 0; const level = resolveAlertableLevel(deviation, source, rowQuotedAt); const priorLevel = priorLevelMap.get(sku.sku_code) || 'normal'; if (level === 'red' && priorLevel !== 'red') { candidateRedCodes.push(String(sku.sku_code)); candidateRedNames.push(String(sku.sku_name || sku.sku_code)); } await pool.query( `INSERT INTO market_prices ( sku_code, sku_name, category_code, market_price, our_price, deviation_rate, price_level, price_source, province, market_name, branch_code, quoted_at, market_session, updated_at ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,NOW()) ON CONFLICT (sku_code, branch_code) DO UPDATE SET sku_name = EXCLUDED.sku_name, category_code = EXCLUDED.category_code, market_price = EXCLUDED.market_price, our_price = EXCLUDED.our_price, deviation_rate = EXCLUDED.deviation_rate, price_level = EXCLUDED.price_level, price_source = EXCLUDED.price_source, market_name = EXCLUDED.market_name, province = EXCLUDED.province, quoted_at = EXCLUDED.quoted_at, market_session = EXCLUDED.market_session, updated_at = NOW()`, [ sku.sku_code, sku.sku_name, sku.category_code, marketPrice, ourPrice, deviation, level, source, province, marketName, effectiveBranch, priceFetch === 'ai' ? quotedAt.toISOString() : rowQuotedAt instanceof Date ? rowQuotedAt.toISOString() : rowQuotedAt, session, ] ); updated += 1; } if (candidateRedCodes.length) { const excluded = await listExcludedMarketSkuCodes(ctx, candidateRedCodes, effectiveBranch); for (let i = 0; i < candidateRedCodes.length; i += 1) { if (!excluded.has(candidateRedCodes[i])) { newRedSkus.push(candidateRedNames[i]); } } } if (skuCodeList.length > 0) { await pool.query( `DELETE FROM market_prices WHERE branch_code = $1 AND NOT (sku_code = ANY($2::text[]))`, [effectiveBranch, skuCodeList] ); } else { await pool.query(`DELETE FROM market_prices WHERE branch_code = $1`, [effectiveBranch]); } const indexResult = await refreshMarketPriceIndices(ctx); if (newRedSkus.length) { const blockOn = await isMarketRedBlockEnabled(effectiveBranch); await notifyRoleUsers({ roles: ['operator', 'admin', 'super_admin'], notifyType: 'market_price_red', title: '市场比价红灯预警', content: blockOn ? `${newRedSkus.length} 个商品偏离率≥35%,已暂停新订单分配:${newRedSkus.slice(0, 5).join('、')}${newRedSkus.length > 5 ? '…' : ''}` : `${newRedSkus.length} 个商品偏离率≥35%(当前未开启红灯阻断):${newRedSkus.slice(0, 5).join('、')}${newRedSkus.length > 5 ? '…' : ''}`, branchCode: effectiveBranch, }); } const quoteableCount = skus.rows.filter( (s: { our_quote_price: unknown }) => Number(s.our_quote_price) > 0 ).length; return { updated, provider: priceFetch === 'ai' ? 'ark_ai' : 'rebase_only', provider_error: providerError, ai_batches: aiBatches, ai_quoted: priceFetch === 'ai' ? aiQuotes.size : 0, ai_skipped: priceFetch === 'ai' ? Math.max(0, quoteableCount - updated) : 0, location: locationUsed, province, market_name: marketName, market_session: session, branch_code: effectiveBranch, compare_price_basis: priceBasis, indices: indexResult.upserted, new_red_count: newRedSkus.length, }; } export async function listMarketPrices(ctx?: TenantContext | null, limit = 100) { const params: unknown[] = [limit]; const branchSql = branchFilter(ctx, 'mp', params); const branchCode = ctx?.branchCode ? String(ctx.branchCode) : null; let exclusionOn = 'e.sku_code = mp.sku_code'; let bindingOn = 'b.sku_code = mp.sku_code'; if (branchCode) { params.push(branchCode); const branchIdx = params.length; exclusionOn += ` AND e.branch_code = $${branchIdx}`; bindingOn += ` AND b.branch_code = $${branchIdx}`; } else { exclusionOn += ' AND (mp.branch_code IS NULL OR e.branch_code = mp.branch_code)'; bindingOn += ' AND (mp.branch_code IS NULL OR b.branch_code = mp.branch_code)'; } const result = await pool.query( `SELECT mp.*, (e.id IS NOT NULL) AS compare_excluded, b.external_code AS external_binding_code, b.external_name AS external_binding_name FROM market_prices mp LEFT JOIN market_compare_exclusions e ON ${exclusionOn} LEFT JOIN market_sku_external_bindings b ON ${bindingOn} WHERE 1=1 ${branchSql} ORDER BY ABS(mp.deviation_rate) DESC LIMIT $1`, params ); return result.rows.map((row) => { const compareExcluded = Boolean(row.compare_excluded); const priceLevel = String(row.price_level || 'normal'); const priceSource = String(row.price_source || ''); const quoteStale = isMarketQuoteStale(row.quoted_at || row.updated_at); let alertLevel = priceLevel; if (compareExcluded) { alertLevel = 'excluded'; } else if (priceSource === 'estimated') { alertLevel = 'normal'; } else if (quoteStale) { alertLevel = 'stale'; } return { ...row, compare_excluded: compareExcluded, quote_stale: quoteStale, price_source: priceSource, /** 展示/报警用:已排除 / 无可靠行情 / 过期 不按红橙黄报警 */ alert_level: alertLevel, external_binding_code: row.external_binding_code ? String(row.external_binding_code) : null, external_binding_name: row.external_binding_name ? String(row.external_binding_name) : null, }; }); } /** S12 异常超时升级 L1-L4 */ export async function escalateStaleExceptions(ctx?: TenantContext | null) { const params: unknown[] = []; const branchSql = branchFilter(ctx, 'et', params); const stale = await pool.query( `SELECT id, ticket_code, ticket_type, priority, escalation_level, created_at, branch_code FROM exception_tickets et WHERE ticket_status < 90 ${branchSql} ORDER BY created_at ASC LIMIT 100`, params ); let escalated = 0; for (const row of stale.rows) { const ageHours = (Date.now() - new Date(row.created_at).getTime()) / 3600000; let nextLevel = Number(row.escalation_level) || 1; if (ageHours >= 24 && nextLevel < 4) nextLevel = 4; else if (ageHours >= 12 && nextLevel < 3) nextLevel = 3; else if (ageHours >= 4 && nextLevel < 2) nextLevel = 2; else continue; await pool.query( `UPDATE exception_tickets SET escalation_level = $2, escalated_at = NOW() WHERE id = $1`, [row.id, nextLevel] ); await notifyRoleUsers({ roles: nextLevel >= 4 ? ['super_admin'] : nextLevel >= 3 ? ['admin'] : ['operator'], notifyType: 'exception_escalation', title: `异常升级 L${nextLevel}`, content: `工单 ${row.ticket_code}(${row.ticket_type || '异常'})需 L${nextLevel} 处理`, relatedOrderCode: row.ticket_code, branchCode: row.branch_code, }); escalated += 1; } return { escalated, scanned: stale.rows.length }; } /** S03 记录拆合单 */ export async function logOrderBatchAction(input: { actionType: 'split' | 'merge'; orderCodes: string[]; reason?: string; branchCode?: string | null; createdBy?: string | null; }) { const code = `OB${Date.now()}`; const result = await pool.query( `INSERT INTO order_allocation_batches (batch_code, action_type, order_codes, reason, branch_code, created_by) VALUES ($1,$2,$3,$4,$5,$6) RETURNING *`, [code, input.actionType, input.orderCodes, input.reason || null, input.branchCode || null, input.createdBy || null] ); await writeAuditLog({ operatorId: input.createdBy, operationType: `order_${input.actionType}`, targetTable: 'order_allocation_batches', targetId: code, branchCode: input.branchCode, actionCategory: 'order', }); return result.rows[0]; } /** 验收超时三级告警 */ export async function scanInspectionTimeoutAlerts(ctx?: TenantContext | null) { const params: unknown[] = []; const branchSql = branchFilter(ctx, 'i', params); const rows = await pool.query( `SELECT i.id, i.order_code, i.sku_code, i.created_at, i.branch_code FROM inspections i WHERE i.inspection_time IS NULL AND i.created_at <= NOW() - INTERVAL '2 hours' ${branchSql} LIMIT 50`, params ); let created = 0; for (const row of rows.rows) { const ageHours = (Date.now() - new Date(row.created_at).getTime()) / 3600000; const level = ageHours >= 8 ? '超管' : ageHours >= 4 ? '运营' : '仓管'; const sent = await notifyRoleUsers({ roles: ageHours >= 8 ? ['super_admin'] : ageHours >= 4 ? ['admin', 'operator'] : ['operator'], notifyType: 'inspection_timeout', title: `验收超时(${level})`, content: `订单 ${row.order_code} SKU ${row.sku_code} 验收超过 ${Math.floor(ageHours)} 小时`, relatedOrderCode: row.order_code, branchCode: row.branch_code, }); if (sent) created += 1; } return { created }; }