-- ============================================
-- 此文件由 Meoo Cloud 自动生成，请勿修改
-- This file is auto-generated by Meoo Cloud, DO NOT MODIFY
-- ============================================


-- 创建成品出入库记录表
CREATE TABLE finished_product_inventory_records (
 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
 company_id UUID NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
 
 -- 关联信息
 finished_product_id UUID NOT NULL REFERENCES finished_products(id) ON DELETE CASCADE,
 
 -- 记录类型
 record_type TEXT NOT NULL CHECK (record_type IN ('inbound', 'outbound')),
 
 -- 数量信息
 rolls INTEGER NOT NULL DEFAULT 0,
 meters DECIMAL(12, 2) NOT NULL DEFAULT 0,
 
 -- 关联单据
 washing_completion_id UUID REFERENCES washing_plan_completions(id) ON DELETE SET NULL,
 related_order_id UUID,
 related_order_type TEXT,
 
 -- 仓库信息
 warehouse_id UUID REFERENCES warehouses(id) ON DELETE SET NULL,
 warehouse_location TEXT,
 
 -- 备注
 notes TEXT,
 batch_no TEXT,
 
 -- 元数据
 operator_id UUID REFERENCES profiles(id),
 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 创建索引
CREATE INDEX idx_finished_inventory_company ON finished_product_inventory_records(company_id);
CREATE INDEX idx_finished_inventory_product ON finished_product_inventory_records(finished_product_id);
CREATE INDEX idx_finished_inventory_type ON finished_product_inventory_records(record_type);
CREATE INDEX idx_finished_inventory_created ON finished_product_inventory_records(created_at);

-- 启用 RLS
ALTER TABLE finished_product_inventory_records ENABLE ROW LEVEL SECURITY;

-- RLS 策略
CREATE POLICY company_select_finished_inventory ON finished_product_inventory_records
 FOR SELECT USING (company_id = get_user_master_company_id());

CREATE POLICY company_insert_finished_inventory ON finished_product_inventory_records
 FOR INSERT WITH CHECK (company_id = get_user_master_company_id());

CREATE POLICY company_update_finished_inventory ON finished_product_inventory_records
 FOR UPDATE USING (company_id = get_user_master_company_id());

CREATE POLICY company_delete_finished_inventory ON finished_product_inventory_records
 FOR DELETE USING (company_id = get_user_master_company_id());

