-- ====================================================================
-- sales_registration / shipment_log
-- ====================================================================
-- 출처: wace_plm 운영 DB 211.115.91.141:11133/waceplm (PG 16.8)
-- 추출일: 2026-05-07
-- 판매관리(sales) + 매출관리(revenue)의 메인 테이블.
-- sales_registration: 프로젝트별 1건 (UNIQUE project_no) — 헤더성격
-- shipment_log: 분할출하/매출 마감 이력 — 라인성격 + 매출 추가 컬럼
-- ====================================================================

CREATE SEQUENCE IF NOT EXISTS sales_registration_sale_no_seq;

CREATE TABLE IF NOT EXISTS sales_registration (
    sale_no                 INTEGER       PRIMARY KEY DEFAULT nextval('sales_registration_sale_no_seq'),
    project_no              VARCHAR(50)   NOT NULL UNIQUE,
    shipping_order_status   VARCHAR(50),                              -- 출하지시 상태
    serial_no               TEXT,                                     -- S/N (쉼표 구분)
    sales_quantity          INTEGER,
    sales_unit_price        NUMERIC,
    sales_supply_price      NUMERIC,
    sales_vat               NUMERIC,
    sales_total_amount      NUMERIC,
    sales_currency          VARCHAR(10),
    sales_exchange_rate     NUMERIC,
    shipping_date           DATE,
    shipping_method         VARCHAR(50),
    manager_user_id         VARCHAR(50),
    incoterms               VARCHAR(20),
    reg_date                TIMESTAMP    DEFAULT now(),
    reg_user_id             VARCHAR(50),
    upd_date                TIMESTAMP,
    upd_user_id             VARCHAR(50),
    has_split_shipment      BOOLEAN       DEFAULT false               -- true: 분할출하 있음
);

ALTER SEQUENCE sales_registration_sale_no_seq OWNED BY sales_registration.sale_no;

CREATE INDEX IF NOT EXISTS idx_sales_reg_project ON sales_registration(project_no);
CREATE INDEX IF NOT EXISTS idx_sales_reg_manager ON sales_registration(manager_user_id);
CREATE INDEX IF NOT EXISTS idx_sales_reg_date    ON sales_registration(reg_date DESC);

COMMENT ON TABLE  sales_registration IS '판매 등록 정보 - 프로젝트별 판매/출하 데이터 관리';
COMMENT ON COLUMN sales_registration.sale_no              IS '판매 일련번호 (PK)';
COMMENT ON COLUMN sales_registration.project_no           IS '프로젝트 번호 (UNIQUE)';
COMMENT ON COLUMN sales_registration.shipping_order_status IS '출하지시 상태';
COMMENT ON COLUMN sales_registration.serial_no            IS 'S/N (쉼표 구분)';
COMMENT ON COLUMN sales_registration.has_split_shipment   IS '분할출하 여부 (true: 분할출하 있음)';

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

CREATE SEQUENCE IF NOT EXISTS shipment_log_log_id_seq;

CREATE TABLE IF NOT EXISTS shipment_log (
    log_id              INTEGER        PRIMARY KEY DEFAULT nextval('shipment_log_log_id_seq'),
    target_objid        VARCHAR(50)    NOT NULL,                     -- 대상 계약 OBJID (→ contract_mgmt)
    log_type            VARCHAR(50)    NOT NULL,                     -- SPLIT_SHIPMENT 등
    log_message         TEXT,
    split_quantity      INTEGER,                                     -- 분할 수량
    original_quantity   INTEGER,                                     -- 원본 수량
    remaining_quantity  INTEGER,                                     -- 잔여 수량
    reg_date            TIMESTAMP      DEFAULT now(),
    reg_user_id         VARCHAR(50),
    -- 출하 정보
    shipping_status     VARCHAR(20)    DEFAULT 'PENDING',            -- PENDING/COMPLETED/CANCELLED
    shipping_date       DATE,
    shipping_method     VARCHAR(50),                                 -- DIRECT/PARCEL
    -- 판매 금액
    sales_unit_price    NUMERIC(15,2),
    sales_supply_price  NUMERIC(15,2),
    sales_vat           NUMERIC(15,2),
    sales_total_amount  NUMERIC(15,2),
    sales_currency      VARCHAR(10),
    sales_exchange_rate NUMERIC(15,4),
    manager_user_id     VARCHAR(50),
    incoterms           VARCHAR(20),
    remark              TEXT,
    -- 분할 추적
    is_split_record     BOOLEAN        DEFAULT true,                 -- 분할출하 레코드 여부
    serial_no           TEXT,
    parent_sale_no      INTEGER,                                     -- → sales_registration(sale_no)
    -- ★ 매출관리 전용 컬럼들 (revenueMode=Y에서 입력) ★
    sales_deadline_date VARCHAR(10),                                 -- 매출 마감일
    tax_type            VARCHAR(20),                                 -- 과세구분
    tax_invoice_date    VARCHAR(10),                                 -- 세금계산서 발행일
    export_decl_no      VARCHAR(100),                                -- 수출신고필증 번호
    loading_date        VARCHAR(10),                                 -- 선적일자
    sales_slip_date     VARCHAR(10),                                 -- 매출전표일
    sales_slip_menu_sq  INTEGER,                                     -- 매출전표 menu_sq
    split_serial_no     TEXT                                         -- 분할 S/N (콤마 구분)
);

ALTER SEQUENCE shipment_log_log_id_seq OWNED BY shipment_log.log_id;

CREATE INDEX IF NOT EXISTS idx_shipment_log_objid  ON shipment_log(target_objid);
CREATE INDEX IF NOT EXISTS idx_shipment_log_type   ON shipment_log(log_type);
CREATE INDEX IF NOT EXISTS idx_shipment_log_date   ON shipment_log(reg_date DESC);
CREATE INDEX IF NOT EXISTS idx_shipment_log_parent ON shipment_log(parent_sale_no);

COMMENT ON TABLE  shipment_log IS '분할출하 이력 로그';
COMMENT ON COLUMN shipment_log.log_id              IS '로그 ID';
COMMENT ON COLUMN shipment_log.target_objid        IS '대상 계약 OBJID';
COMMENT ON COLUMN shipment_log.log_type            IS '로그 유형 (SPLIT_SHIPMENT 등)';
COMMENT ON COLUMN shipment_log.shipping_status     IS '출하상태 (PENDING, COMPLETED, CANCELLED)';
COMMENT ON COLUMN shipment_log.parent_sale_no      IS '원본 판매번호 (sales_registration.sale_no)';
COMMENT ON COLUMN shipment_log.split_serial_no     IS '분할S/N - 해당 출하건에서 선택한 S/N 목록 (콤마 구분)';
