-- 구매 수량 확정 관련 테이블 생성

-- 1. 구매 확정 마스터 테이블
CREATE TABLE IF NOT EXISTS purchase_confirmations (
    id SERIAL PRIMARY KEY,
    job_no VARCHAR(50) NOT NULL,
    file_id INTEGER REFERENCES files(id),
    bom_name VARCHAR(255) NOT NULL,
    revision VARCHAR(50) NOT NULL DEFAULT 'Rev.0',
    confirmed_at TIMESTAMP NOT NULL,
    confirmed_by VARCHAR(100) NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 2. 확정된 구매 품목 테이블
CREATE TABLE IF NOT EXISTS confirmed_purchase_items (
    id SERIAL PRIMARY KEY,
    confirmation_id INTEGER REFERENCES purchase_confirmations(id) ON DELETE CASCADE,
    item_code VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,
    specification TEXT,
    size VARCHAR(100),
    material VARCHAR(100),
    bom_quantity DECIMAL(15,3) NOT NULL DEFAULT 0,
    calculated_qty DECIMAL(15,3) NOT NULL DEFAULT 0,
    unit VARCHAR(20) NOT NULL DEFAULT 'EA',
    safety_factor DECIMAL(5,3) NOT NULL DEFAULT 1.0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 3. files 테이블에 확정 관련 컬럼 추가 (이미 있으면 무시)
ALTER TABLE files 
ADD COLUMN IF NOT EXISTS purchase_confirmed BOOLEAN DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS confirmed_at TIMESTAMP,
ADD COLUMN IF NOT EXISTS confirmed_by VARCHAR(100);

-- 인덱스 생성
CREATE INDEX IF NOT EXISTS idx_purchase_confirmations_job_revision 
ON purchase_confirmations(job_no, revision, is_active);

CREATE INDEX IF NOT EXISTS idx_confirmed_purchase_items_confirmation 
ON confirmed_purchase_items(confirmation_id);

CREATE INDEX IF NOT EXISTS idx_confirmed_purchase_items_category 
ON confirmed_purchase_items(category);

CREATE INDEX IF NOT EXISTS idx_files_purchase_confirmed 
ON files(purchase_confirmed);

-- 코멘트 추가
COMMENT ON TABLE purchase_confirmations IS '구매 수량 확정 마스터 테이블';
COMMENT ON TABLE confirmed_purchase_items IS '확정된 구매 품목 상세 테이블';
COMMENT ON COLUMN files.purchase_confirmed IS '구매 수량 확정 여부';
COMMENT ON COLUMN files.confirmed_at IS '구매 수량 확정 시간';
COMMENT ON COLUMN files.confirmed_by IS '구매 수량 확정자';




















