import type { PoolClient } from 'pg'; import { getRawPoolQuery, pool } from '../db'; import { normalizeWeightUnitKey } from './unitConversionService'; type Db = Pick | typeof pool; export type UnitConversionRow = { unit_code: string; unit_name: string; base_unit: string; factor_to_base: number; is_weight: boolean; status: number; sort_order: number; created_at?: string; updated_at?: string; }; /** * 系统预置重量单位:默认走「停用」保护(DELETE 不带 hard 时只置 status=0)。 * 页面显式「删除」(`?hard=1`)允许物理删,见 deleteUnitConversion。 */ export const PROTECTED_WEIGHT_UNIT_CODES = new Set([ '斤', '市斤', 'jin', '公斤', '千克', 'kg', '克', 'g', '两', ]); /** 与 migrations 20260793 + 20260804 预置一致;无租户表时给小程序兜底 */ export const BUILTIN_ACTIVE_UNITS: UnitConversionRow[] = [ { unit_code: '斤', unit_name: '斤', base_unit: '斤', factor_to_base: 1, is_weight: true, status: 1, sort_order: 10 }, { unit_code: '市斤', unit_name: '市斤', base_unit: '斤', factor_to_base: 1, is_weight: true, status: 1, sort_order: 11 }, { unit_code: 'jin', unit_name: '斤', base_unit: '斤', factor_to_base: 1, is_weight: true, status: 1, sort_order: 12 }, { unit_code: '公斤', unit_name: '公斤', base_unit: '斤', factor_to_base: 2, is_weight: true, status: 1, sort_order: 20 }, { unit_code: '千克', unit_name: '千克', base_unit: '斤', factor_to_base: 2, is_weight: true, status: 1, sort_order: 21 }, { unit_code: 'kg', unit_name: '公斤', base_unit: '斤', factor_to_base: 2, is_weight: true, status: 1, sort_order: 22 }, { unit_code: '两', unit_name: '两', base_unit: '斤', factor_to_base: 0.1, is_weight: true, status: 1, sort_order: 30 }, { unit_code: '克', unit_name: '克', base_unit: '斤', factor_to_base: 0.002, is_weight: true, status: 1, sort_order: 40 }, { unit_code: 'g', unit_name: '克', base_unit: '斤', factor_to_base: 0.002, is_weight: true, status: 1, sort_order: 41 }, { unit_code: '个', unit_name: '个', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 200 }, { unit_code: '件', unit_name: '件', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 210 }, { unit_code: '箱', unit_name: '箱', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 220 }, { unit_code: '包', unit_name: '包', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 230 }, { unit_code: '只', unit_name: '只', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 240 }, { unit_code: '袋', unit_name: '袋', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 250 }, { unit_code: '筐', unit_name: '筐', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 260 }, { unit_code: '瓶', unit_name: '瓶', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 270 }, { unit_code: '盒', unit_name: '盒', base_unit: '斤', factor_to_base: 0, is_weight: false, status: 1, sort_order: 280 }, ]; function mapRow(row: Record): UnitConversionRow { return { unit_code: String(row.unit_code || ''), unit_name: String(row.unit_name || ''), base_unit: String(row.base_unit || '斤'), factor_to_base: Number(row.factor_to_base) || 0, is_weight: row.is_weight === true || row.is_weight === 't' || row.is_weight === 1, status: Number(row.status ?? 1), sort_order: Number(row.sort_order ?? 100), created_at: row.created_at ? String(row.created_at) : undefined, updated_at: row.updated_at ? String(row.updated_at) : undefined, }; } export async function listUnitConversions( options: { activeOnly?: boolean } = {}, db: Db = pool ): Promise { const clauses: string[] = []; if (options.activeOnly) clauses.push('status = 1'); const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : ''; const result = await db.query( `SELECT unit_code, unit_name, base_unit, factor_to_base, is_weight, COALESCE(status, 1) AS status, COALESCE(sort_order, 100) AS sort_order, created_at, updated_at FROM unit_conversions ${where} ORDER BY COALESCE(sort_order, 100) ASC, unit_code ASC` ); return result.rows.map(mapRow); } /** * 小程序单位字典:优先当前租户;无表/空结果时读 tenant_template,再退代码预置。 * 避免 public 无 unit_conversions 时接口 500 → 端上只剩短 FALLBACK。 */ export async function listUnitConversionsForMobile(): Promise { try { const rows = await listUnitConversions({ activeOnly: true }); if (rows.length) return rows; } catch { /* public / 无 search_path */ } try { const rawQuery = getRawPoolQuery(); const result = await rawQuery( `SELECT unit_code, unit_name, base_unit, factor_to_base, is_weight, COALESCE(status, 1) AS status, COALESCE(sort_order, 100) AS sort_order, created_at, updated_at FROM tenant_template.unit_conversions WHERE COALESCE(status, 1) = 1 ORDER BY COALESCE(sort_order, 100) ASC, unit_code ASC` ); if (result.rows.length) return result.rows.map(mapRow); } catch { /* template 未就绪 */ } return BUILTIN_ACTIVE_UNITS.slice(); } export async function createUnitConversion( input: { unit_code: string; unit_name: string; is_weight?: boolean; factor_to_base?: number; sort_order?: number; status?: number; }, db: Db = pool ): Promise { const code = String(input.unit_code || '').trim(); const name = String(input.unit_name || '').trim() || code; if (!code) { throw Object.assign(new Error('单位编码不能为空'), { status: 400, code: 'bad_request' }); } if (code.length > 50) { throw Object.assign(new Error('单位编码不能超过 50 个字符'), { status: 400, code: 'bad_request' }); } const isWeight = input.is_weight === true; const factor = isWeight ? Number(input.factor_to_base) : 0; if (isWeight && (!Number.isFinite(factor) || factor <= 0)) { throw Object.assign(new Error('重量单位必须填写大于 0 的折算系数(相对「斤」)'), { status: 400, code: 'bad_request', }); } try { const result = await db.query( `INSERT INTO unit_conversions (unit_code, unit_name, base_unit, factor_to_base, is_weight, status, sort_order, updated_at) VALUES ($1, $2, '斤', $3, $4, $5, $6, NOW()) RETURNING unit_code, unit_name, base_unit, factor_to_base, is_weight, status, sort_order, created_at, updated_at`, [ code, name, factor, isWeight, input.status === 0 ? 0 : 1, Number.isFinite(Number(input.sort_order)) ? Number(input.sort_order) : 100, ] ); return mapRow(result.rows[0]); } catch (error: any) { if (error?.code === '23505') { throw Object.assign(new Error('单位编码已存在'), { status: 409, code: 'conflict' }); } throw error; } } export async function updateUnitConversion( unitCode: string, patch: { unit_name?: string; is_weight?: boolean; factor_to_base?: number; sort_order?: number; status?: number; }, db: Db = pool ): Promise { const code = String(unitCode || '').trim(); if (!code) { throw Object.assign(new Error('缺少单位编码'), { status: 400, code: 'bad_request' }); } const existing = await db.query(`SELECT * FROM unit_conversions WHERE unit_code = $1`, [code]); if (!existing.rows[0]) { throw Object.assign(new Error('单位不存在'), { status: 404, code: 'not_found' }); } const current = mapRow(existing.rows[0]); const nextName = patch.unit_name != null ? String(patch.unit_name).trim() : current.unit_name; const nextIsWeight = patch.is_weight != null ? patch.is_weight === true : current.is_weight; const nextFactor = patch.factor_to_base != null ? Number(patch.factor_to_base) : nextIsWeight ? current.factor_to_base : 0; const nextStatus = patch.status != null ? (Number(patch.status) === 0 ? 0 : 1) : current.status; const nextSort = patch.sort_order != null && Number.isFinite(Number(patch.sort_order)) ? Number(patch.sort_order) : current.sort_order; if (!nextName) { throw Object.assign(new Error('单位名称不能为空'), { status: 400, code: 'bad_request' }); } if (nextIsWeight && (!Number.isFinite(nextFactor) || nextFactor <= 0)) { throw Object.assign(new Error('重量单位必须填写大于 0 的折算系数(相对「斤」)'), { status: 400, code: 'bad_request', }); } const result = await db.query( `UPDATE unit_conversions SET unit_name = $2, factor_to_base = $3, is_weight = $4, status = $5, sort_order = $6, updated_at = NOW() WHERE unit_code = $1 RETURNING unit_code, unit_name, base_unit, factor_to_base, is_weight, status, sort_order, created_at, updated_at`, [code, nextName, nextIsWeight ? nextFactor : 0, nextIsWeight, nextStatus, nextSort] ); return mapRow(result.rows[0]); } export async function deactivateUnitConversion( unitCode: string, db: Db = pool ): Promise { const code = String(unitCode || '').trim(); if (!code) { throw Object.assign(new Error('缺少单位编码'), { status: 400, code: 'bad_request' }); } // 保护键也允许停用别名(如 jin),但不物理删除 return updateUnitConversion(code, { status: 0 }, db); } export function isProtectedWeightUnit(unitCode: string): boolean { return PROTECTED_WEIGHT_UNIT_CODES.has(String(unitCode || '').trim()); } /** * 物理删除单位(不可恢复)。仅路由在显式 hard 模式(页面「删除」按钮)调用; * 预置重量键同样允许删——删除后历史里用该单位键的记录不再参与重量折算。 */ export async function deleteUnitConversion( unitCode: string, db: Db = pool ): Promise { const code = String(unitCode || '').trim(); if (!code) { throw Object.assign(new Error('缺少单位编码'), { status: 400, code: 'bad_request' }); } const result = await db.query( `DELETE FROM unit_conversions WHERE unit_code = $1 RETURNING unit_code, unit_name, base_unit, factor_to_base, is_weight, status, sort_order, created_at, updated_at`, [code] ); if (!result.rows[0]) { throw Object.assign(new Error('单位不存在'), { status: 404, code: 'not_found' }); } return mapRow(result.rows[0]); } /** 供选择器用:启用单位;展示名优先 unit_name */ export function toUnitSelectOptions(rows: UnitConversionRow[]): Array<{ value: string; label: string; hint?: string }> { return rows .filter((r) => r.status === 1) .map((r) => ({ value: r.unit_name || r.unit_code, label: r.unit_name || r.unit_code, hint: r.is_weight ? `= ${r.factor_to_base} 斤` : '计数单位', searchText: `${r.unit_code} ${r.unit_name}`, })); } export { normalizeWeightUnitKey };