-- ============================================================
-- 매출관리 자동 검증 SQL
-- 메인 테이블: project_mgmt + sales_registration (shipping_date IS NOT NULL)
-- ============================================================

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

\echo ''
\echo '[0] 사전 카운트 ============================'
SELECT 'project_mgmt'        AS tbl, COUNT(*) FROM project_mgmt
UNION ALL SELECT 'sales_registration shipping_date NOT NULL',
                COUNT(*) FROM sales_registration WHERE shipping_date IS NOT NULL;

\echo ''
\echo '[1] 매출 본 필터 (출하등록된 project) — 운영 0건 예상 =========================='
SELECT COUNT(*) AS revenue_visible_cnt
  FROM project_mgmt T
 WHERE EXISTS (SELECT 1 FROM sales_registration SR WHERE SR.project_no=T.project_no AND SR.shipping_date IS NOT NULL)
   AND T.project_no IS NOT NULL AND T.project_no <> '';

\echo ''
\echo '[2] V1 신규 9개 컬럼 정합성 (필터 해제 샘플) =========================='
SELECT
  T.project_no, CM.receipt_date,
  CASE WHEN CM.paid_type='paid' THEN '유상' WHEN CM.paid_type='free' THEN '무상' END AS payment_type_name,
  COALESCE(NULLIF(CI.due_date, ''), NULLIF(T.due_date, ''), NULLIF(CM.due_date, '')) AS request_date,
  CC_RES.code_name AS order_status_name,
  U_MGR.user_name AS manager_name,
  SR.shipping_method,
  SR.incoterms,
  COALESCE(AF.cu01_cnt, 0) AS cu01_cnt
FROM project_mgmt T
LEFT JOIN contract_mgmt CM ON CM.objid = T.contract_objid
LEFT JOIN contract_item CI ON CI.objid = T.contract_item_objid AND CI.status='ACTIVE'
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_RES ON CC_RES.code_id = T.contract_result AND CC_RES.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
WHERE T.project_no IS NOT NULL AND T.project_no <> ''
ORDER BY T.regdate DESC NULLS LAST LIMIT 5;

\echo ''
\echo '================== Revenue 검증 끝 =================='
