-- ============================================================
-- 주문관리 자동 검증 SQL (BEGIN/ROLLBACK 시나리오)
-- 사용법:
--   PGPASSWORD='vexplor0909!!' psql -h 211.115.91.141 -p 11134 -U postgres \
--     -d vexplor_rps -f scripts/verify-order.sql
-- ============================================================

\echo ''
\echo '================== Order 검증 시작 =================='

-- ─────────────────────────────────────────────────────────
-- [0] 사전 카운트
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[0] 사전 카운트 ============================'
SELECT 'contract_mgmt 전체'  AS tbl, COUNT(*) FROM contract_mgmt
UNION ALL SELECT 'contract_result 수주(0000964)', COUNT(*) FROM contract_mgmt WHERE contract_result='0000964'
UNION ALL SELECT 'contract_result 수주FCST(0000968)', COUNT(*) FROM contract_mgmt WHERE contract_result='0000968'
UNION ALL SELECT 'project_mgmt', COUNT(*) FROM project_mgmt;


-- ─────────────────────────────────────────────────────────
-- [1] 그리드 V1 컬럼 (제품구분/국내해외/접수일/수주상태) 검증
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[1] 그리드 V1 컬럼 정합성 검증 =========================='
SELECT
  T.contract_no,
  CC_RES.code_name AS contract_result_name,
  COALESCE(CI_AGG.product_summary, CC_PRD.code_name) AS product_name,
  CC_AREA.code_name AS area_name,
  T.receipt_date,
  T.order_date,
  COALESCE(CI_AGG.order_quantity_sum, 0) AS order_qty,
  COALESCE(CI_AGG.cancel_qty_sum, 0)     AS cancel_qty
FROM contract_mgmt T
LEFT JOIN comm_code CC_PRD  ON CC_PRD.code_id  = T.product   AND CC_PRD.status='active'
LEFT JOIN comm_code CC_AREA ON CC_AREA.code_id = T.area_cd   AND CC_AREA.status='active'
LEFT JOIN comm_code CC_RES  ON CC_RES.code_id  = T.contract_result AND CC_RES.status='active'
LEFT JOIN (
  SELECT CI.contract_objid,
         STRING_AGG(DISTINCT CC_PRDI.code_name, ', ') FILTER (WHERE CC_PRDI.code_name IS NOT NULL) AS product_summary,
         COALESCE(SUM(CAST(REPLACE(NULLIF(CI.order_quantity, ''), ',', '') AS NUMERIC)), 0) AS order_quantity_sum,
         COALESCE(SUM(CASE WHEN CI.cancel_qty IS NOT NULL AND CI.cancel_qty != '' AND CI.cancel_qty != '0'
                          THEN CAST(CI.cancel_qty AS NUMERIC) END), 0) AS cancel_qty_sum
  FROM contract_item CI
  LEFT JOIN comm_code CC_PRDI ON CC_PRDI.code_id = CI.product AND CC_PRDI.status='active'
  WHERE CI.status='ACTIVE'
  GROUP BY CI.contract_objid
) CI_AGG ON CI_AGG.contract_objid = T.objid
WHERE T.contract_no IN ('26C-0801','26C-0797','26C-0796','26C-0795','26C-0788','26C-0791')
ORDER BY T.contract_no DESC;


-- ─────────────────────────────────────────────────────────
-- [2] 수주확정 G1 — updateStatus 트랜잭션
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[2] 수주확정 G1 시나리오 =========================='
BEGIN;

\echo '  → BEFORE project_mgmt:'
SELECT COUNT(*) AS before_cnt FROM project_mgmt;

-- 26C-0795(견적단계, contract_result NULL)를 수주(0000964)로 전환
UPDATE contract_mgmt SET contract_result='0000964', chg_user_id='admin'
 WHERE contract_no='26C-0795';

-- project_mgmt INSERT 시뮬레이션 (createProjectsFromContract 흐름 일부)
WITH meta AS (
  SELECT
    CASE CC_CAT.code_name WHEN '수리' THEN 'R' WHEN '판매' THEN 'S' ELSE 'T' END AS cat_abbr,
    CASE CC_PRDI.code_name WHEN 'C/T' THEN 'CT' WHEN 'A/S' THEN 'AS' WHEN '기타' THEN '기타' ELSE COALESCE(CC_PRDI.code_name,'X') END AS prd_abbr,
    TO_CHAR(CURRENT_DATE, 'YYMMDD') AS ymd,
    CI.objid AS item_objid, CI.part_objid, CI.part_no, CI.part_name, CI.quantity, CI.product
  FROM contract_item CI
  LEFT JOIN comm_code CC_PRDI ON CC_PRDI.code_id = CI.product AND CC_PRDI.status='active'
  CROSS JOIN comm_code CC_CAT
  WHERE CI.contract_objid IN (SELECT objid FROM contract_mgmt WHERE contract_no='26C-0795')
    AND CI.status='ACTIVE'
    AND CC_CAT.code_id IN (SELECT category_cd FROM contract_mgmt WHERE contract_no='26C-0795')
    AND CC_CAT.status='active'
)
SELECT '예상 project_no (line별)' AS info,
       m.cat_abbr || '-' || m.prd_abbr || '-' || m.ymd || '-' ||
       LPAD(COALESCE((SELECT MAX(SUBSTRING(project_no FROM '\d{3}$')::int) + 1
                      FROM project_mgmt
                      WHERE project_no LIKE m.cat_abbr || '-' || m.prd_abbr || '-' || m.ymd || '-%'), 1)::text, 3, '0')
       AS expected_project_no,
       m.part_no, m.quantity
  FROM meta m;

ROLLBACK;
\echo '  → ROLLBACK 완료'


-- ─────────────────────────────────────────────────────────
-- [3] 수주취소 시나리오 (cancel_qty 다중 UPDATE)
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[3] 수주취소 시나리오 =========================='
BEGIN;

\echo '  → BEFORE 26C-0797 contract_result:'
SELECT contract_no, contract_result FROM contract_mgmt WHERE contract_no='26C-0797';

UPDATE contract_item SET cancel_qty='1', chgdate=NOW(), chg_user_id='admin'
 WHERE contract_objid=(SELECT objid FROM contract_mgmt WHERE contract_no='26C-0797')
   AND status='ACTIVE';

\echo '  → AFTER 라인 cancel_qty (1 이상이면 성공):'
SELECT objid, quantity, cancel_qty FROM contract_item
 WHERE contract_objid=(SELECT objid FROM contract_mgmt WHERE contract_no='26C-0797')
   AND status='ACTIVE';

\echo '  → contract_result 미변경 확인:'
SELECT contract_no, contract_result FROM contract_mgmt WHERE contract_no='26C-0797';

ROLLBACK;
\echo '  → ROLLBACK 완료'


-- ─────────────────────────────────────────────────────────
-- [4] 채번 룰 — 다음 contract_no
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[4] 채번 룰 검증 =========================='
SELECT '다음 contract_no' AS info,
       '26C-' || LPAD(
         (COALESCE((SELECT MAX(SUBSTRING(contract_no FROM '\d{4}$')::int)
                    FROM contract_mgmt WHERE contract_no LIKE '26C-%'), 0) + 1)::text, 4, '0') AS next_no;


\echo ''
\echo '================== Order 검증 끝 (모두 ROLLBACK) =================='
