-- 助手聊天记录(按账号 × 分公司)。设计:docs/design/20260921-assistant-chat-persist.md -- 不进 ALLOWED_TABLES;确认闸仍走 Redis pendingWrite。 DO $$ DECLARE sch text; BEGIN FOR sch IN SELECT nspname FROM pg_namespace WHERE nspname IN ('public', 'legacy_public', 'tenant_template') OR nspname LIKE 'tenant_%' LOOP IF to_regclass(format('%I.orders', sch)) IS NULL THEN CONTINUE; END IF; EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.assistant_conversations ( id UUID PRIMARY KEY, user_id VARCHAR(64) NOT NULL, branch_code VARCHAR(50) NOT NULL, surface VARCHAR(32) NOT NULL, title VARCHAR(120) NOT NULL DEFAULT '''', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT assistant_conversations_surface_chk CHECK (surface IN (''web'', ''miniprogram'')) )', sch ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_assistant_conversations_owner ON %I.assistant_conversations (user_id, branch_code, surface, updated_at DESC)', sch ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.assistant_messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), conversation_id UUID NOT NULL REFERENCES %I.assistant_conversations(id) ON DELETE CASCADE, role VARCHAR(16) NOT NULL, content TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT assistant_messages_role_chk CHECK (role IN (''user'', ''assistant'')) )', sch, sch ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_assistant_messages_conversation ON %I.assistant_messages (conversation_id, created_at, id)', sch ); IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'canteen_app_rls') THEN BEGIN EXECUTE format( 'GRANT SELECT, INSERT, UPDATE ON TABLE %I.assistant_conversations TO canteen_app_rls', sch ); EXECUTE format( 'GRANT SELECT, INSERT ON TABLE %I.assistant_messages TO canteen_app_rls', sch ); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'skip grant on %.assistant_chat: %', sch, SQLERRM; END; END IF; END LOOP; END $$; CREATE OR REPLACE FUNCTION public.tenant_business_tables() RETURNS TEXT[] LANGUAGE sql IMMUTABLE AS $$ SELECT ARRAY[ 'after_sale_returns', 'after_sales', 'ai_prompt_overrides', 'ai_prompt_revisions', 'ai_prompt_templates', 'alias_recognition_logs', 'allocation_tasks', 'assistant_conversations', 'assistant_messages', '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_quote_versions', 'customer_quote_sheets', 'customer_quote_sheet_items', 'customer_quote_sheet_customers', 'customer_sku_aliases', 'customer_processing_aliases', 'customer_sku_remarks', 'customer_skus', 'customer_statements', 'statement_lines', 'statement_disputes', 'statement_payments', 'customers', 'delivery_person_users', 'delivery_persons', 'delivery_person_locations', 'delivery_location_history', 'delivery_tasks', 'exception_tickets', 'fixed_costs', 'free_cost_invoice_links', 'free_cost_invoices', 'inspections', 'inspection_loss_confirmations', 'inspection_returns', 'inspection_review_logs', 'inventory', 'inventory_logs', 'inventory_reservations', 'invoices', 'import_mapping_memories', 'notifications', 'operation_logs', 'order_item_fulfillments', 'order_item_returns', 'order_items', 'orders', 'parse_sessions', 'parse_session_items', 'picking_assign_rules', 'picking_items', 'picking_tasks', 'picking_containers', 'picking_scan_logs', 'price_invert_events', 'processing_logs', 'processing_tasks', 'processing_demand_items', 'processing_demand_picks', 'product_catalog', 'purchase_orders', 'self_purchase_stock_inbounds', 'purchaser_users', 'quality_reports', 'quality_report_prep_links', 'sign_records', 'sku_suppliers', 'skus', 'sku_direct_delivery_customers', 'smart_classification_rules', 'supplier_categories', 'supplier_preparations', 'supplier_prep_amend_requests', 'supplier_statements', 'supplier_rating_snapshots', 'product_substitutions', 'delivery_signatures', 'customer_recipients', 'customer_portal_users', 'market_prices', 'market_compare_exclusions', 'market_price_history', 'market_price_indices', 'market_external_catalog', 'market_sku_external_bindings', 'seasonal_recommendations', 'order_allocation_batches', 'delivery_schedules', 'supplier_users', 'suppliers', 'supplier_price_agreements', 'system_configs', 'unit_conversions', 'user_preferences', 'voice_recognition_logs', 'warehouses', 'warehouse_locations', 'weigh_devices', 'print_jobs' ]::text[]; $$; SELECT public.ensure_tenant_schemas_match_template(); SELECT public.assert_tenant_template_matches_business_tables();