-- ====================================================================
-- contract_mgmt / contract_item / contract_item_serial / contract_mgmt_option
-- ====================================================================
-- 출처: wace_plm 운영 DB 211.115.91.141:11133/waceplm (PG 16.8) 2026-05-07 추출
-- 영업관리 4개 메뉴(견적/주문/판매/매출) 모두의 헤더 테이블.
-- contract_mgmt 가 영업번호(contract_no) 단위 헤더, contract_item이 라인.
-- ⚠️ part_objid 는 vexplor_rps item_info.id (varchar 500) 와 직접 매칭 가능.
-- ====================================================================

CREATE TABLE IF NOT EXISTS contract_mgmt (
    objid                     VARCHAR(50)  PRIMARY KEY,
    contract_no               VARCHAR,                       -- 영업번호 (CONTRACT_NO 채번)
    -- 분류/마스터 참조
    category_cd               VARCHAR,                       -- 주문유형 (공통코드)
    customer_objid            VARCHAR,                       -- 거래처 ('C_'+id 또는 id::text)
    product                   VARCHAR,                       -- 제품구분
    customer_project_name     VARCHAR,
    project_no                VARCHAR,                       -- 프로젝트 번호
    project_name              VARCHAR,
    target_project_no         VARCHAR,
    target_project_no_direct  VARCHAR,
    customer_production_no    VARCHAR,
    -- 상태
    status_cd                 VARCHAR,
    result_cd                 VARCHAR,
    contract_result           VARCHAR,
    spec_result_cd            VARCHAR,
    est_result_cd             VARCHAR,
    sales_closure_status      VARCHAR,
    production_status         VARCHAR(50),
    -- 일자 (모두 varchar)
    due_date                  VARCHAR,
    plan_date                 VARCHAR,
    complete_date             VARCHAR,
    spec_plan_date            VARCHAR,
    spec_comp_date            VARCHAR,
    est_plan_date             VARCHAR,
    est_comp_date             VARCHAR,
    contract_date             VARCHAR,                       -- 발주일
    contract_del_date         VARCHAR,
    req_del_date              VARCHAR,                       -- 요청납기
    receipt_date              VARCHAR,                       -- 접수일
    order_date                VARCHAR,
    -- 사람
    chg_user_id               VARCHAR,
    spec_user_id              VARCHAR,
    est_user_id               VARCHAR,
    pm_user_id                VARCHAR,
    writer                    VARCHAR,
    regdate                   TIMESTAMP,
    -- 위치/시설/장비
    location                  VARCHAR,
    setup                     VARCHAR,
    facility                  VARCHAR,
    facility_qty              VARCHAR,
    facility_type             VARCHAR,
    facility_depth             VARCHAR,
    production_no             VARCHAR,
    bus_cal_cd                VARCHAR,
    category1_cd              VARCHAR,
    customer_equip_name       VARCHAR,
    contract_company          VARCHAR,
    manufacture_plant         VARCHAR,
    mechanical_type           VARCHAR,
    overhaul_order            VARCHAR,
    area_cd                   VARCHAR,                       -- 지역/국내해외
    paid_type                 VARCHAR,                       -- paid/free
    -- 가격
    contract_price            VARCHAR,
    contract_price_currency   VARCHAR,
    contract_currency         VARCHAR,
    exchange_rate             VARCHAR,
    est_price                 VARCHAR,
    est_supply_price          VARCHAR,
    order_unit_price          VARCHAR,
    order_supply_price        VARCHAR,
    order_vat                 VARCHAR,
    order_total_amount        VARCHAR,
    -- 발주
    po_no                     VARCHAR,                       -- 발주번호
    -- 라인 헤더 카피
    part_no                   VARCHAR,
    part_name                 VARCHAR,
    serial_no                 VARCHAR,
    quantity                  VARCHAR,
    customer_request          VARCHAR,
    -- 출하/배송
    shipping_method           VARCHAR,
    incoterms                 VARCHAR,
    -- 분기/플래그
    is_direct_order           VARCHAR,
    approval_required         VARCHAR(1)   DEFAULT 'N',
    split_from_objid          VARCHAR(50)
);

CREATE INDEX IF NOT EXISTS idx_contract_split_from ON contract_mgmt(split_from_objid);

COMMENT ON TABLE contract_mgmt IS '영업/계약 헤더 (견적/주문/판매/매출 공통)';

-- --------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS contract_item (
    objid                VARCHAR(50)  PRIMARY KEY,
    contract_objid       VARCHAR(50)  NOT NULL REFERENCES contract_mgmt(objid) ON DELETE CASCADE,
    seq                  INTEGER      NOT NULL,
    part_objid           VARCHAR(50)  NOT NULL,             -- → item_info(id)
    part_no              VARCHAR(100) NOT NULL,
    part_name            VARCHAR(200) NOT NULL,
    quantity             INTEGER      NOT NULL DEFAULT 1,
    due_date             VARCHAR(10),
    customer_request     TEXT,
    -- 수주 컬럼 (database/add_order_columns_to_contract_item.sql)
    order_quantity       VARCHAR(50),
    order_unit_price     VARCHAR(50),
    order_supply_price   VARCHAR(50),
    order_vat            VARCHAR(50),
    order_total_amount   VARCHAR(50),
    cancel_qty           VARCHAR(50),
    return_reason        VARCHAR,
    product              VARCHAR(20),
    -- 공통
    regdate              TIMESTAMP    NOT NULL DEFAULT NOW(),
    writer               VARCHAR(50),
    chgdate              TIMESTAMP,
    chg_user_id          VARCHAR(50),
    status               VARCHAR(20)  DEFAULT 'ACTIVE'
);

CREATE INDEX IF NOT EXISTS idx_contract_item_contract ON contract_item(contract_objid);
CREATE INDEX IF NOT EXISTS idx_contract_item_seq      ON contract_item(contract_objid, seq);

COMMENT ON TABLE contract_item IS '영업/계약 라인 (견적/주문 공통)';

-- --------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS contract_item_serial (
    objid       VARCHAR(50)  PRIMARY KEY,
    item_objid  VARCHAR(50)  NOT NULL REFERENCES contract_item(objid) ON DELETE CASCADE,
    seq         INTEGER      NOT NULL,
    serial_no   VARCHAR(200) NOT NULL,
    regdate     TIMESTAMP    NOT NULL DEFAULT NOW(),
    writer      VARCHAR(50),
    status      VARCHAR(20)  DEFAULT 'ACTIVE',
    UNIQUE (item_objid, serial_no)
);

CREATE INDEX IF NOT EXISTS idx_contract_item_serial_item ON contract_item_serial(item_objid);
CREATE INDEX IF NOT EXISTS idx_contract_item_serial_seq  ON contract_item_serial(item_objid, seq);

COMMENT ON TABLE contract_item_serial IS '계약 라인별 시리얼번호';

-- --------------------------------------------------------------------

CREATE TABLE IF NOT EXISTS contract_mgmt_option (
    objid           INTEGER  NOT NULL,
    contract_objid  INTEGER  NOT NULL,
    option_objid    INTEGER,
    option_qty      INTEGER,
    price           INTEGER,
    note            VARCHAR
);

COMMENT ON TABLE contract_mgmt_option IS '계약 옵션';
