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


-- 创建水洗计划完成记录表
CREATE TABLE washing_plan_completions (
 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
 company_id UUID NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
 
 -- 关联信息
 washing_plan_id UUID NOT NULL REFERENCES washing_plans(id) ON DELETE CASCADE,
 
 -- 完成数据
 actual_washed_meters DECIMAL(12, 2) NOT NULL,
 actual_shrinkage_rate DECIMAL(5, 2) NOT NULL,
 rolls INTEGER NOT NULL DEFAULT 0,
 washing_date DATE NOT NULL,
 
 -- 成本数据
 actual_washing_cost DECIMAL(10, 2),
 unit_cost DECIMAL(10, 2),
 
 -- 仓库信息
 warehouse_id UUID REFERENCES warehouses(id) ON DELETE SET NULL,
 warehouse_location TEXT,
 
 -- 自动导入成品仓库标记
 auto_imported BOOLEAN DEFAULT FALSE,
 finished_product_id UUID REFERENCES finished_products(id) ON DELETE SET NULL,
 
 -- 备注
 notes TEXT,
 
 -- 元数据
 completed_by UUID REFERENCES profiles(id),
 completed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
 created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- 创建索引
CREATE INDEX idx_washing_completions_company ON washing_plan_completions(company_id);
CREATE INDEX idx_washing_completions_plan ON washing_plan_completions(washing_plan_id);
CREATE INDEX idx_washing_completions_finished_product ON washing_plan_completions(finished_product_id);
CREATE INDEX idx_washing_completions_date ON washing_plan_completions(washing_date);

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

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

CREATE POLICY company_insert_washing_completions ON washing_plan_completions
 FOR INSERT WITH CHECK (company_id = get_user_master_company_id());

CREATE POLICY company_update_washing_completions ON washing_plan_completions
 FOR UPDATE USING (company_id = get_user_master_company_id());

CREATE POLICY company_delete_washing_completions ON washing_plan_completions
 FOR DELETE USING (company_id = get_user_master_company_id());

