283 lines
8.7 KiB
PL/PgSQL
283 lines
8.7 KiB
PL/PgSQL
-- 独立加工单 P0:多行原料 + 多行成品 + 成品回仓(2026-10-23 开发者裁决)
|
||
-- 决策(本轮已确认):原料多行、成品多行(一个原料可产出多个成品)、损耗自动差额可人工覆盖、
|
||
-- 成品入库成本默认「原料成本按产出均分」且允许人工设置、损耗成本只留痕不进账本、
|
||
-- 报告继承为**可选**(库存批次报告 / 检验报告 各自勾选)、老单只读保留、Web 先行。
|
||
-- 纪律:仅 DDL + 名单登记,不做数据修复;幂等可重跑。
|
||
-- 见 docs/design/20261023-独立加工多产出与成品回仓.md
|
||
|
||
-- ① 两张子表建在 tenant_template(其余分公司由 ensure_tenant_schemas_match_template 克隆)
|
||
DO $$
|
||
DECLARE
|
||
sch text := 'tenant_template';
|
||
BEGIN
|
||
IF to_regclass('tenant_template.processing_tasks') IS NULL THEN
|
||
RAISE NOTICE 'tenant_template.processing_tasks 不存在,跳过建表';
|
||
RETURN;
|
||
END IF;
|
||
|
||
EXECUTE format(
|
||
'CREATE TABLE IF NOT EXISTS %I.processing_task_materials (
|
||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||
task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,
|
||
sku_code VARCHAR(50) NOT NULL,
|
||
sku_name VARCHAR(200),
|
||
spec VARCHAR(60),
|
||
unit VARCHAR(20),
|
||
qty NUMERIC(12,3) NOT NULL DEFAULT 0,
|
||
material_cost NUMERIC(14,2) NOT NULL DEFAULT 0,
|
||
-- 本行实际扣减的批次([{batch_no, qty, cost_price}]):报告继承与对账要用,JSON 省掉第三张表
|
||
deducted_batches JSONB NOT NULL DEFAULT ''[]''::jsonb,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||
)',
|
||
sch, sch
|
||
);
|
||
EXECUTE format(
|
||
'CREATE INDEX IF NOT EXISTS idx_processing_task_materials_task
|
||
ON %I.processing_task_materials (task_id)',
|
||
sch
|
||
);
|
||
EXECUTE format(
|
||
'ALTER TABLE %I.processing_task_materials ADD COLUMN IF NOT EXISTS deducted_batches JSONB NOT NULL DEFAULT ''[]''::jsonb',
|
||
sch
|
||
);
|
||
|
||
EXECUTE format(
|
||
'CREATE TABLE IF NOT EXISTS %I.processing_task_outputs (
|
||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||
task_id UUID NOT NULL REFERENCES %I.processing_tasks(id) ON DELETE CASCADE,
|
||
sku_code VARCHAR(50) NOT NULL,
|
||
sku_name VARCHAR(200),
|
||
spec VARCHAR(60),
|
||
unit VARCHAR(20),
|
||
qty NUMERIC(12,3) NOT NULL DEFAULT 0,
|
||
unit_cost NUMERIC(14,4) NOT NULL DEFAULT 0,
|
||
cost_amount NUMERIC(14,2) NOT NULL DEFAULT 0,
|
||
batch_no VARCHAR(80),
|
||
inventory_id UUID,
|
||
inherit_batch_report BOOLEAN NOT NULL DEFAULT FALSE,
|
||
inherit_inspection_report BOOLEAN NOT NULL DEFAULT FALSE,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||
)',
|
||
sch, sch
|
||
);
|
||
EXECUTE format(
|
||
'CREATE INDEX IF NOT EXISTS idx_processing_task_outputs_task
|
||
ON %I.processing_task_outputs (task_id)',
|
||
sch
|
||
);
|
||
|
||
END $$;
|
||
|
||
-- ①a2 抵减批次 JSON 列:逐 schema 补(克隆只补表,不同步新增列)
|
||
DO $$
|
||
DECLARE
|
||
sch text;
|
||
BEGIN
|
||
FOR sch IN
|
||
SELECT nspname FROM pg_namespace
|
||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||
LOOP
|
||
IF to_regclass(format('%I.processing_task_materials', sch)) IS NOT NULL THEN
|
||
EXECUTE format(
|
||
'ALTER TABLE %I.processing_task_materials ADD COLUMN IF NOT EXISTS deducted_batches JSONB NOT NULL DEFAULT ''[]''::jsonb',
|
||
sch
|
||
);
|
||
END IF;
|
||
END LOOP;
|
||
END $$;
|
||
|
||
-- ①a3 报告关联来源:允许 'inherit'(加工产出继承原料批次报告)
|
||
DO $$
|
||
DECLARE
|
||
sch text;
|
||
BEGIN
|
||
FOR sch IN
|
||
SELECT nspname FROM pg_namespace
|
||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||
LOOP
|
||
IF to_regclass(format('%I.inventory_batch_report_matches', sch)) IS NOT NULL THEN
|
||
EXECUTE format(
|
||
'ALTER TABLE %I.inventory_batch_report_matches DROP CONSTRAINT IF EXISTS inventory_batch_report_matches_source_chk',
|
||
sch
|
||
);
|
||
EXECUTE format(
|
||
'ALTER TABLE %I.inventory_batch_report_matches
|
||
ADD CONSTRAINT inventory_batch_report_matches_source_chk
|
||
CHECK (match_source IN (''auto'', ''manual'', ''inherit''))',
|
||
sch
|
||
);
|
||
END IF;
|
||
END LOOP;
|
||
END $$;
|
||
|
||
-- ①b 幂等键(客户端重试/双击只建一张单):**逐 schema** 加列 + 唯一索引
|
||
-- (克隆函数只补表结构,不同步新增列 ⇒ 必须自己遍历)
|
||
DO $$
|
||
DECLARE
|
||
sch text;
|
||
BEGIN
|
||
FOR sch IN
|
||
SELECT nspname FROM pg_namespace
|
||
WHERE nspname = 'tenant_template' OR nspname LIKE 'tenant\_%'
|
||
LOOP
|
||
IF to_regclass(format('%I.processing_tasks', sch)) IS NOT NULL THEN
|
||
EXECUTE format(
|
||
'ALTER TABLE %I.processing_tasks ADD COLUMN IF NOT EXISTS client_request_no VARCHAR(100)',
|
||
sch
|
||
);
|
||
EXECUTE format(
|
||
'CREATE UNIQUE INDEX IF NOT EXISTS idx_processing_tasks_client_request
|
||
ON %I.processing_tasks (branch_code, client_request_no)
|
||
WHERE client_request_no IS NOT NULL',
|
||
sch
|
||
);
|
||
END IF;
|
||
END LOOP;
|
||
END $$;
|
||
|
||
-- ② 名单登记(双向守卫要求 tenant_template 表集合 == tenant_business_tables())
|
||
CREATE OR REPLACE FUNCTION public.tenant_business_tables()
|
||
RETURNS TEXT[]
|
||
LANGUAGE sql
|
||
IMMUTABLE
|
||
AS $$
|
||
SELECT ARRAY[
|
||
'main_system_sku_mappings',
|
||
'after_sale_returns',
|
||
'after_sales',
|
||
'ai_prompt_overrides',
|
||
'ai_prompt_revisions',
|
||
'ai_prompt_templates',
|
||
'alias_recognition_logs',
|
||
'allocation_tasks',
|
||
'assistant_conversations',
|
||
'assistant_messages',
|
||
'assistant_turns',
|
||
'bid_awards',
|
||
'bid_invitations',
|
||
'bid_prices',
|
||
'bid_quotes',
|
||
'bid_round_items',
|
||
'bid_rounds',
|
||
'categories',
|
||
'cost_adjustments',
|
||
'cost_details',
|
||
'customer_alias_stats',
|
||
'customer_delivery_assignments',
|
||
'customer_portal_users',
|
||
'customer_processing_aliases',
|
||
'customer_quote_sheet_customers',
|
||
'customer_quote_sheet_items',
|
||
'customer_quote_sheets',
|
||
'customer_quote_versions',
|
||
'customer_recipients',
|
||
'customer_sku_aliases',
|
||
'customer_sku_remarks',
|
||
'customer_skus',
|
||
'customer_statements',
|
||
'customers',
|
||
'delivery_location_history',
|
||
'delivery_person_locations',
|
||
'delivery_person_users',
|
||
'delivery_persons',
|
||
'delivery_schedules',
|
||
'delivery_signatures',
|
||
'delivery_tasks',
|
||
'exception_tickets',
|
||
'fixed_costs',
|
||
'free_cost_invoice_links',
|
||
'free_cost_invoices',
|
||
'free_cost_payment_vouchers',
|
||
'import_mapping_memories',
|
||
'inspection_loss_confirmations',
|
||
'inspection_photo_archive_entries',
|
||
'inspection_photo_archives',
|
||
'inspection_returns',
|
||
'inspection_review_logs',
|
||
'inspections',
|
||
'inventory',
|
||
'inventory_batch_report_matches',
|
||
'inventory_batch_reports',
|
||
'inventory_logs',
|
||
'inventory_reservations',
|
||
'invoice_statement_links',
|
||
'invoices',
|
||
'market_compare_exclusions',
|
||
'market_external_catalog',
|
||
'market_price_history',
|
||
'market_price_indices',
|
||
'market_prices',
|
||
'market_sku_external_bindings',
|
||
'notifications',
|
||
'operation_logs',
|
||
'order_allocation_batches',
|
||
'order_item_fulfillments',
|
||
'order_item_returns',
|
||
'order_items',
|
||
'orders',
|
||
'parse_session_items',
|
||
'parse_sessions',
|
||
'picking_assign_rules',
|
||
'picking_containers',
|
||
'picking_items',
|
||
'picking_scan_logs',
|
||
'picking_tasks',
|
||
'price_invert_events',
|
||
'print_jobs',
|
||
'processing_demand_items',
|
||
'processing_demand_picks',
|
||
'processing_logs',
|
||
'processing_tasks',
|
||
'product_catalog',
|
||
'product_substitutions',
|
||
'purchase_orders',
|
||
'purchaser_users',
|
||
'quality_report_prep_links',
|
||
'quality_reports',
|
||
'quote_price_proposals',
|
||
'seasonal_recommendations',
|
||
'self_purchase_stock_inbounds',
|
||
'sign_records',
|
||
'sku_direct_delivery_customers',
|
||
'sku_suppliers',
|
||
'skus',
|
||
'smart_classification_rules',
|
||
'statement_disputes',
|
||
'statement_lines',
|
||
'statement_payments',
|
||
'supplier_categories',
|
||
'supplier_prep_amend_requests',
|
||
'supplier_preparations',
|
||
'supplier_rating_snapshots',
|
||
'supplier_statements',
|
||
'supplier_users',
|
||
'suppliers',
|
||
'system_configs',
|
||
'unit_conversions',
|
||
'user_preferences',
|
||
'voice_recognition_logs',
|
||
'warehouse_locations',
|
||
'warehouses',
|
||
'weigh_devices',
|
||
'processing_task_materials',
|
||
'processing_task_outputs'
|
||
];
|
||
$$;
|
||
|
||
-- ③ 克隆到各分公司 schema(新表 + 新列),再跑 RLS 与双向断言
|
||
DO $$
|
||
BEGIN
|
||
PERFORM public.ensure_tenant_schemas_match_template();
|
||
EXCEPTION WHEN undefined_function THEN
|
||
RAISE NOTICE 'ensure_tenant_schemas_match_template 不存在,跳过';
|
||
END $$;
|
||
|
||
DO $$
|
||
BEGIN
|
||
PERFORM public.ensure_all_tenant_core_rls();
|
||
EXCEPTION WHEN undefined_function THEN
|
||
RAISE NOTICE 'ensure_all_tenant_core_rls 不存在,跳过';
|
||
END $$;
|