后端只返回 needs_processing_badge(订单行仓内加工/未完工加工需求单);前端徽标与筛选用新字段,needs_processing 仍只驱动原加工/入库流程。
360 lines
14 KiB
TypeScript
360 lines
14 KiB
TypeScript
import { pool } from '../db';
|
||
import { getEffectiveBranchCode, type TenantContext } from './tenantScope';
|
||
import { resolvePresetRange } from './orderManagementQueryService';
|
||
import { clampManagementPage } from './purchaseOrderQueryService';
|
||
import { orderCodeActiveExistsSql } from './orderTrashScope';
|
||
import { inspectionVisibleInListSql } from './independentInboundService';
|
||
import { isOrderCodeSearch } from '../utils/orderCodeQuery';
|
||
import { LAST_INBOUND_ZONE_JOIN, LAST_INBOUND_ZONE_SELECT } from './inspectionTaskQuery';
|
||
|
||
export type InspectionDateField = 'delivery_date' | 'created_at';
|
||
|
||
export interface ListInspectionsForManagementInput {
|
||
page?: number;
|
||
pageSize?: number;
|
||
sortOrder?: 'asc' | 'desc';
|
||
statusGroup?: 'pending' | 'done' | 'all' | string | null;
|
||
dateRangePreset?: 'today' | 'week' | 'month' | 'day' | 'all' | 'custom';
|
||
dateFrom?: string | null;
|
||
dateTo?: string | null;
|
||
/** 配送日(默认)或订单下单日;无关联订单时回退验收建单日 */
|
||
dateField?: InspectionDateField | string | null;
|
||
sourceType?: string | null;
|
||
qualityRating?: string | null;
|
||
supplierCode?: string | null;
|
||
categoryCode?: string | null;
|
||
search?: string | null;
|
||
}
|
||
|
||
export function normalizeInspectionDateField(value: unknown): InspectionDateField {
|
||
return String(value || '').trim() === 'created_at' ? 'created_at' : 'delivery_date';
|
||
}
|
||
|
||
/** 中国日历日:配送日 / 下单日;订单缺失时回退验收建单日 */
|
||
export function inspectionDayExpr(dateField: InspectionDateField): string {
|
||
return dateField === 'created_at'
|
||
? `COALESCE(
|
||
(o.created_at AT TIME ZONE 'Asia/Shanghai')::date,
|
||
(i.created_at AT TIME ZONE 'Asia/Shanghai')::date
|
||
)`
|
||
: `COALESCE(
|
||
o.delivery_date::date,
|
||
(i.created_at AT TIME ZONE 'Asia/Shanghai')::date
|
||
)`;
|
||
}
|
||
|
||
/** 中国日历日闭区间:配送日 / 下单日;订单缺失时回退 i.created_at */
|
||
export function inspectionDateRangeSql(
|
||
dateField: InspectionDateField,
|
||
startParam: number,
|
||
endParam: number
|
||
): string {
|
||
return `${inspectionDayExpr(dateField)} BETWEEN ($${startParam}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date
|
||
AND ($${endParam}::timestamptz AT TIME ZONE 'Asia/Shanghai')::date`;
|
||
}
|
||
|
||
/**
|
||
* 称上待验:上海日历「今天 ±1 天」(配送日;无订单回退验收建单日)。
|
||
* 设计 20260910-weigh-inspection-near-today
|
||
*/
|
||
export function weighInspectionNearTodaySql(inspectionAlias = 'i'): string {
|
||
const a = inspectionAlias;
|
||
return `COALESCE(
|
||
(SELECT o.delivery_date::date FROM orders o WHERE o.order_code = ${a}.order_code LIMIT 1),
|
||
(${a}.created_at AT TIME ZONE 'Asia/Shanghai')::date
|
||
) BETWEEN ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Shanghai')::date - 1)
|
||
AND ((CURRENT_TIMESTAMP AT TIME ZONE 'Asia/Shanghai')::date + 1)`;
|
||
}
|
||
|
||
export const MOBILE_INSPECTION_PENDING_SQL = `
|
||
i.inspection_time IS NULL
|
||
AND COALESCE(i.quality_rating, '') = ''
|
||
AND COALESCE(i.actual_qty, 0) = 0
|
||
AND ${inspectionVisibleInListSql('i')}
|
||
`;
|
||
|
||
/** 智能入库宫格:全部还未入库的待验条数(无日期、无来源、无 LIMIT) */
|
||
export async function countPendingInspectionsAll(): Promise<number> {
|
||
const { pruneAllDuplicateSelfPurchasePendingInspections } = await import(
|
||
'./inspectionRejectFulfillmentService'
|
||
);
|
||
await pruneAllDuplicateSelfPurchasePendingInspections();
|
||
const result = await pool.query(
|
||
`SELECT COUNT(*)::int AS c
|
||
FROM inspections i
|
||
WHERE ${MOBILE_INSPECTION_PENDING_SQL}`
|
||
);
|
||
return Number(result.rows[0]?.c) || 0;
|
||
}
|
||
|
||
export async function listInspectionsForManagement(
|
||
ctx: TenantContext | null,
|
||
operatingBranchCode: string | null | undefined,
|
||
input: ListInspectionsForManagementInput
|
||
): Promise<{
|
||
rows: Record<string, unknown>[];
|
||
total: number;
|
||
stats: {
|
||
pending: number;
|
||
done: number;
|
||
/** 与列表同 where:入库数量合计(对齐前端 inboundQty) */
|
||
inbound_qty: number;
|
||
/** 与列表同 where:入库金额合计(对齐前端 inboundAmount) */
|
||
inbound_amount: number;
|
||
};
|
||
}> {
|
||
if (!ctx) throw Object.assign(new Error('未登录'), { status: 401 });
|
||
const branchCode = getEffectiveBranchCode(ctx, operatingBranchCode);
|
||
if (ctx.isSuperAdmin && !branchCode) {
|
||
throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required' });
|
||
}
|
||
|
||
const { pageSize, offset } = clampManagementPage(input.page, input.pageSize);
|
||
const sortOrder = input.sortOrder === 'asc' ? 'ASC' : 'DESC';
|
||
const statusGroup = String(input.statusGroup || 'all').toLowerCase();
|
||
const dateField = normalizeInspectionDateField(input.dateField);
|
||
const preset = input.dateRangePreset || 'custom';
|
||
const range = resolvePresetRange(preset, null, input.dateFrom, input.dateTo);
|
||
// ① preset=all 或 按订单号搜索 → 不加日期条件;
|
||
// ② 其余无有效区间时回退今天(旧行为)。
|
||
const effectiveRange =
|
||
preset === 'all' || isOrderCodeSearch(input.search)
|
||
? { start: '', end: '' }
|
||
: range.start && range.end
|
||
? range
|
||
: resolvePresetRange('today', null, null, null);
|
||
|
||
try {
|
||
const { healOrphanIndependentInboundsAfterPass } = await import('./selfPurchaseStockInboundService');
|
||
await healOrphanIndependentInboundsAfterPass(branchCode || ctx.branchCode);
|
||
} catch (healErr) {
|
||
console.warn('[inspectionQuery] independent inbound heal skipped:', (healErr as Error)?.message);
|
||
}
|
||
|
||
const params: unknown[] = [];
|
||
const where: string[] = ['1=1', inspectionVisibleInListSql('i')];
|
||
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
where.push(`i.branch_code = $${params.length}`);
|
||
} else if (ctx.branchCode) {
|
||
params.push(ctx.branchCode);
|
||
where.push(`i.branch_code = $${params.length}`);
|
||
}
|
||
|
||
if (effectiveRange.start && effectiveRange.end) {
|
||
params.push(effectiveRange.start, effectiveRange.end);
|
||
where.push(inspectionDateRangeSql(dateField, params.length - 1, params.length));
|
||
}
|
||
|
||
if (input.sourceType) {
|
||
params.push(String(input.sourceType).trim());
|
||
where.push(`COALESCE(i.source_type, '') = $${params.length}`);
|
||
}
|
||
if (input.qualityRating) {
|
||
params.push(String(input.qualityRating).trim());
|
||
where.push(`COALESCE(i.quality_rating, '') = $${params.length}`);
|
||
}
|
||
if (input.supplierCode) {
|
||
params.push(String(input.supplierCode).trim());
|
||
where.push(`i.supplier_code = $${params.length}`);
|
||
}
|
||
if (input.categoryCode) {
|
||
params.push(String(input.categoryCode).trim());
|
||
where.push(`COALESCE(sk.category_code, oi.category_code, '') = $${params.length}`);
|
||
}
|
||
|
||
const search = String(input.search || '').trim();
|
||
if (search) {
|
||
params.push(`%${search.replace(/[%_]/g, '\\$&')}%`);
|
||
const idx = params.length;
|
||
where.push(`(
|
||
COALESCE(i.order_code, '') ILIKE $${idx}
|
||
OR COALESCE(i.sku_code, '') ILIKE $${idx}
|
||
OR COALESCE(sk.sku_name, '') ILIKE $${idx}
|
||
OR COALESCE(oi.item_name, '') ILIKE $${idx}
|
||
OR COALESCE(sup.company_name, '') ILIKE $${idx}
|
||
)`);
|
||
}
|
||
|
||
// 顶部状态统计与列表同筛选(分公司/日期/来源/评级/供应商/分类/搜索),但不套状态 Tab
|
||
const statsParams = [...params];
|
||
const statsWhere = [...where];
|
||
|
||
if (statusGroup === 'pending') {
|
||
where.push(`i.inspection_time IS NULL`);
|
||
} else if (statusGroup === 'done') {
|
||
where.push(`i.inspection_time IS NOT NULL`);
|
||
}
|
||
|
||
const whereSql = where.join(' AND ');
|
||
const fromSql = `
|
||
FROM inspections i
|
||
LEFT JOIN orders o ON o.order_code = i.order_code
|
||
LEFT JOIN skus sk ON sk.sku_code = i.sku_code
|
||
LEFT JOIN suppliers sup ON sup.supplier_code = i.supplier_code
|
||
LEFT JOIN LATERAL (
|
||
SELECT oi2.item_name, oi2.category_code, oi2.unit, oi2.category_name,
|
||
oi2.processing_method AS line_processing_method,
|
||
oi2.processing_owner AS line_processing_owner
|
||
FROM order_items oi2
|
||
WHERE oi2.order_code = i.order_code
|
||
AND (oi2.sku_code = i.sku_code OR i.sku_code IS NULL)
|
||
ORDER BY oi2.created_at DESC NULLS LAST
|
||
LIMIT 1
|
||
) oi ON TRUE
|
||
LEFT JOIN categories cat ON cat.category_code = COALESCE(sk.category_code, oi.category_code)
|
||
LEFT JOIN LATERAL (
|
||
SELECT
|
||
COALESCE(pt.material_qty, 0)::float AS demand_material_qty,
|
||
COALESCE(pt.net_weight, 0)::float AS demand_net_weight,
|
||
COALESCE(pt.loss_qty, 0)::float AS demand_loss_qty
|
||
FROM processing_demand_items di
|
||
JOIN processing_tasks pt ON pt.id = di.task_id
|
||
WHERE di.order_code = i.order_code
|
||
AND di.sku_code = i.sku_code
|
||
AND pt.source_type = 'demand'
|
||
AND pt.process_status < 50
|
||
ORDER BY pt.updated_at DESC NULLS LAST
|
||
LIMIT 1
|
||
) demand_sheet ON TRUE
|
||
`;
|
||
|
||
const statsRes = await pool.query(
|
||
`SELECT
|
||
COUNT(*) FILTER (WHERE i.inspection_time IS NULL)::int AS pending,
|
||
COUNT(*) FILTER (WHERE i.inspection_time IS NOT NULL)::int AS done
|
||
${fromSql}
|
||
WHERE ${statsWhere.join(' AND ')}`,
|
||
statsParams
|
||
);
|
||
|
||
const countResult = await pool.query(
|
||
`SELECT COUNT(*)::int AS cnt ${fromSql} WHERE ${whereSql}`,
|
||
params
|
||
);
|
||
const total = Number(countResult.rows[0]?.cnt) || 0;
|
||
|
||
// 入库单价 = **真实成本价**(2026-09-24 开发者口径):
|
||
// ① **订单行当前成本价**(财务口径「采购成本/所有成本用订单行口径」)—— 订单侧改成本价后,
|
||
// 入库列表单价/金额**立即跟着变**。原实现只取入库时的快照,改价后不动:
|
||
// 2026-09-22 `orderEnteredCostWritebackService` 有意排除「已入库」行,快照永远停在入库当时。
|
||
// ② 入库时的实收成本快照(`inspections.purchase_price`,0 视为真实值);
|
||
// ③ 备货价兜底(原是第①优先;无订单行/无验收成本时才用);
|
||
// ④ 独立入库单价(无订单进仓);
|
||
// ⑤ 0。
|
||
// ⚠️ 本表达式同时决定列表行「单价」与表脚「金额」;该金额只被入库列表页消费,不是财务 KPI。
|
||
// 同单同 SKU 多行时,优先取「供应商与验收行一致」的那行,其次 sort_order,保证确定性。
|
||
const inboundQtySql = `CASE
|
||
WHEN COALESCE(i.actual_qty, 0) > 0 THEN COALESCE(i.actual_qty, 0)::numeric
|
||
ELSE COALESCE(i.prepare_qty, 0)::numeric
|
||
END`;
|
||
const inboundPriceSql = `COALESCE(
|
||
(
|
||
SELECT oi.unit_cost
|
||
FROM order_items oi
|
||
WHERE oi.order_code = i.order_code
|
||
AND oi.sku_code = i.sku_code
|
||
ORDER BY
|
||
CASE WHEN COALESCE(oi.supplier_code, '') = COALESCE(i.supplier_code, '') THEN 0 ELSE 1 END,
|
||
oi.sort_order ASC NULLS LAST,
|
||
oi.id
|
||
LIMIT 1
|
||
),
|
||
NULLIF(i.purchase_price, 0),
|
||
(
|
||
SELECT sp.purchase_price
|
||
FROM supplier_preparations sp
|
||
WHERE sp.order_code = i.order_code
|
||
AND sp.sku_code = i.sku_code
|
||
AND COALESCE(sp.supplier_code, '') = COALESCE(i.supplier_code, '')
|
||
ORDER BY sp.prepare_time DESC NULLS LAST
|
||
LIMIT 1
|
||
),
|
||
(
|
||
SELECT spi.unit_cost
|
||
FROM self_purchase_stock_inbounds spi
|
||
WHERE spi.inspection_id = i.id
|
||
AND spi.voided_at IS NULL
|
||
ORDER BY spi.created_at DESC NULLS LAST
|
||
LIMIT 1
|
||
),
|
||
0
|
||
)::numeric`;
|
||
const filterTotalsRes = await pool.query(
|
||
`SELECT
|
||
COALESCE(SUM(${inboundQtySql}), 0)::numeric AS inbound_qty,
|
||
COALESCE(SUM(${inboundQtySql} * ${inboundPriceSql}), 0)::numeric AS inbound_amount
|
||
${fromSql}
|
||
WHERE ${whereSql}`,
|
||
params
|
||
);
|
||
|
||
const listFromSql = `${fromSql}\n${LAST_INBOUND_ZONE_JOIN}`;
|
||
const listParams = [...params, pageSize, offset];
|
||
const listResult = await pool.query(
|
||
`SELECT i.*,
|
||
sk.sku_name,
|
||
sk.spec AS sku_spec,
|
||
sk.unit AS sku_unit,
|
||
sk.category_code AS sku_category_code,
|
||
cat.category_name,
|
||
cat.requires_photo_inspection,
|
||
sup.company_name AS supplier_name,
|
||
o.delivery_date AS order_delivery_date,
|
||
o.created_at AS order_created_at,
|
||
oi.item_name AS order_item_name,
|
||
oi.unit AS order_item_unit,
|
||
oi.category_code AS order_item_category_code,
|
||
oi.category_name AS order_item_category_name,
|
||
demand_sheet.demand_material_qty,
|
||
demand_sheet.demand_net_weight,
|
||
demand_sheet.demand_loss_qty,
|
||
-- 仅用于入库列表「需加工」徽标,不驱动任何入库/加工流程。
|
||
(CASE
|
||
WHEN LOWER(TRIM(COALESCE(oi.line_processing_owner, ''))) IN
|
||
('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.line_processing_method), ''), '原材料') <> '原材料'
|
||
THEN TRUE
|
||
WHEN demand_sheet.demand_material_qty IS NOT NULL
|
||
OR demand_sheet.demand_net_weight IS NOT NULL
|
||
THEN TRUE
|
||
ELSE FALSE
|
||
END) AS needs_processing_badge,
|
||
${LAST_INBOUND_ZONE_SELECT},
|
||
${inboundPriceSql} AS inbound_unit_price
|
||
${listFromSql}
|
||
WHERE ${whereSql}
|
||
ORDER BY i.created_at ${sortOrder} NULLS LAST, i.id DESC
|
||
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
||
listParams
|
||
);
|
||
|
||
const rows = listResult.rows.map((row) => ({
|
||
...row,
|
||
sku_name: row.sku_name || row.order_item_name || row.sku_code,
|
||
spec: row.sku_spec || null,
|
||
unit: row.unit || row.order_item_unit || row.sku_unit || '斤',
|
||
category_code: row.sku_category_code || row.order_item_category_code || null,
|
||
category_name: row.category_name || row.order_item_category_name || null,
|
||
supplier_name: row.supplier_name || null,
|
||
purchase_price:
|
||
row.inbound_unit_price != null ? Number(row.inbound_unit_price) : Number(row.purchase_price) || null,
|
||
demand_material_qty: row.demand_material_qty == null ? null : Number(row.demand_material_qty),
|
||
demand_net_weight: row.demand_net_weight == null ? null : Number(row.demand_net_weight),
|
||
demand_loss_qty: row.demand_loss_qty == null ? null : Number(row.demand_loss_qty),
|
||
needs_processing_badge: row.needs_processing_badge === true,
|
||
}));
|
||
|
||
return {
|
||
rows,
|
||
total,
|
||
stats: {
|
||
pending: Number(statsRes.rows[0]?.pending) || 0,
|
||
done: Number(statsRes.rows[0]?.done) || 0,
|
||
inbound_qty: Math.round((Number(filterTotalsRes.rows[0]?.inbound_qty) || 0) * 1000) / 1000,
|
||
inbound_amount: Math.round((Number(filterTotalsRes.rows[0]?.inbound_amount) || 0) * 100) / 100,
|
||
},
|
||
};
|
||
}
|