-- ============================================================
-- 판매관리 자동 검증 SQL (BEGIN/ROLLBACK 시나리오)
-- 메인 테이블: project_mgmt + sales_registration + contract_mgmt
-- ============================================================

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

-- ─────────────────────────────────────────────────────────
-- [0] 사전 카운트
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[0] 사전 카운트 ============================'
SELECT 'project_mgmt'        AS tbl, COUNT(*) FROM project_mgmt
UNION ALL SELECT 'sales_registration',   COUNT(*) FROM sales_registration
UNION ALL SELECT 'project_mgmt matched by SR.project_no LIKE',
                COUNT(DISTINCT T.project_no)
       FROM project_mgmt T JOIN sales_registration SR ON SR.project_no LIKE T.project_no || '%';

-- ─────────────────────────────────────────────────────────
-- [1] 그리드 V1 신규 8개 컬럼 정합성 검증
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[1] 그리드 V1 신규 컬럼 (제품구분/국내해외/접수일/고객사요청사항/주문서첨부/출하방법/담당자/인도조건) =========================='
SELECT
  T.project_no,
  CC_PRD.code_name  AS product_type_name,
  CC_AREA.code_name AS nation_name,
  CM.receipt_date,
  COALESCE(NULLIF(CM.customer_request, ''), '-') AS customer_request,
  COALESCE(AF.cu01_cnt, 0) AS cu01_cnt,
  SR.shipping_method,
  U_MGR.user_name   AS manager_name,
  SR.incoterms
FROM project_mgmt T
LEFT JOIN contract_mgmt CM      ON CM.objid = T.contract_objid
LEFT JOIN sales_registration SR ON SR.project_no = T.project_no
LEFT JOIN user_info U_MGR       ON U_MGR.user_id = SR.manager_user_id
LEFT JOIN comm_code CC_AREA     ON CC_AREA.code_id = T.area_cd AND CC_AREA.status='active'
LEFT JOIN comm_code CC_PRD      ON CC_PRD.code_id  = T.product AND CC_PRD.status='active'
LEFT JOIN (
  SELECT target_objid,
         COUNT(*) FILTER (WHERE doc_type IN ('FTC_ORDER','ORDER')) AS cu01_cnt
  FROM attach_file_info WHERE UPPER(status)='ACTIVE'
  GROUP BY target_objid
) AF ON AF.target_objid = T.contract_objid
ORDER BY T.regdate DESC NULLS LAST, T.project_no DESC
LIMIT 10;

-- ─────────────────────────────────────────────────────────
-- [2] 판매상태 wace 로직 검증 (미판매/완판/분할판매)
-- ─────────────────────────────────────────────────────────
\echo ''
\echo '[2] 판매상태 wace 로직 (미판매/완판/분할판매) =========================='
SELECT
  T.project_no,
  T.quantity AS order_qty,
  COALESCE(SR_AGG.sales_qty_sum, 0) AS sales_qty_sum,
  CASE
    WHEN COALESCE(SR_AGG.sales_qty_sum, 0) = 0 THEN '미판매'
    WHEN COALESCE(SR_AGG.sales_qty_sum, 0) >= COALESCE(CAST(NULLIF(REPLACE(T.quantity, ',', ''), '') AS NUMERIC), 0) THEN '완판'
    WHEN COALESCE(SR_AGG.sales_qty_sum, 0) > 0 THEN '분할판매'
    ELSE ''
  END AS sales_status
FROM project_mgmt T
LEFT JOIN (
  SELECT SR2.project_no, SUM(SR2.sales_quantity) AS sales_qty_sum
  FROM sales_registration SR2
  GROUP BY SR2.project_no
) SR_AGG ON SR_AGG.project_no LIKE T.project_no || '%'
ORDER BY T.regdate DESC NULLS LAST
LIMIT 10;


\echo ''
\echo '================== Sale 검증 끝 =================='
