-- ============================================================================
-- V38 마스터 + 데모 폐루프 데이터 전면 시드 (킨텍스 리뉴얼 Phase 2)
-- 담당: kintex-testdata-dev · 작성: 2026-07-12
-- ----------------------------------------------------------------------------
-- 원칙(불변):
--   • V1~V37 파일 불변. 본 파일은 순증(additive)만 수행하며 전부 순수 INSERT ... ON CONFLICT DO NOTHING.
--     (기존 시드/실데이터 UPDATE·DELETE 절대 금지 — 재실행·재배포 안전.)
--   • 테넌트 표준 = 'KINTEX'(대문자, V31 정규화). tenant_id 보유 테이블만 명시 세팅.
--   • 폐루프 축 = 기존 행사 e-2026-smf(2026 스마트팩토리 코리아, 개장 2026-08-11).
--   • PII(이름/전화/이메일)는 전부 가짜 더미(@kintex.test · 010-0000-xxxx 계열). 실존 인물 금지.
--   • 마감/할 일 활성화 날짜는 now()/CURRENT_DATE 상대값(배포 시점 기준으로 항상 유효).
-- 홈 할 일(HomeMapper) 활성화 대상:
--   결재 대기(approval_line.CURRENT), 서류 D-3(required_document due=CURRENT_DATE+3),
--   옥션 낙찰 선정(마감 경과+낙찰 미확정 AUC-2026-0511), 응찰 마감 임박(AUC-2026-0102 D-2),
--   미수 청구(invoice pending/overdue), 오늘 체크인(visitor_registration.checkin_at::date=today).
-- ============================================================================


-- ============================================================================
-- 1. 마스터 데이터
-- ============================================================================

-- 1-1) 공통코드 — 실사용 그룹(부스 타입·서류 상태·옥션 카테고리·업종) --------------
INSERT INTO common_code_group (grp_code, grp_name, description, sort_order) VALUES
  ('BOOTH_TYPE',       '부스 타입',     'booth.booth_type — assembled|independent|corner|island', 30),
  ('DOC_STATUS',       '서류 상태',     'required_document.status', 31),
  ('AUCTION_CATEGORY', '옥션 카테고리', 'auction.category — 공사/장치 발주 분류', 32),
  ('INDUSTRY',         '업종',          '참가업체/리드 업종 분류', 33),
  ('INVOICE_STATUS',   '청구 상태',     'invoice.status', 34),
  ('BOOTH_SALE_STATUS','부스 판매상태', 'booth_sale.status', 35)
ON CONFLICT (grp_code) DO NOTHING;

INSERT INTO common_code (grp_code, code, code_name, sort_order) VALUES
  ('BOOTH_TYPE','assembled','조립부스',1),
  ('BOOTH_TYPE','independent','독립부스',2),
  ('BOOTH_TYPE','corner','코너부스',3),
  ('BOOTH_TYPE','island','아일랜드부스',4),
  ('DOC_STATUS','pending','대기',1),
  ('DOC_STATUS','draft','작성중',2),
  ('DOC_STATUS','submitted','제출',3),
  ('DOC_STATUS','approved','승인',4),
  ('DOC_STATUS','rejected','반려',5),
  ('AUCTION_CATEGORY','전시디자인설치','전시디자인설치',1),
  ('AUCTION_CATEGORY','구조물 임대','구조물 임대',2),
  ('AUCTION_CATEGORY','전기/조명','전기/조명',3),
  ('AUCTION_CATEGORY','영상/음향','영상/음향',4),
  ('AUCTION_CATEGORY','네트워크','네트워크',5),
  ('INDUSTRY','MFG','제조/자동화',1),
  ('INDUSTRY','ROBOT','로봇',2),
  ('INDUSTRY','ELEC','전기/전자',3),
  ('INDUSTRY','LOGI','물류/유통',4),
  ('INDUSTRY','ICT','ICT/소프트웨어',5),
  ('INDUSTRY','BIO','바이오/헬스',6),
  ('INDUSTRY','ETC','기타',7),
  ('INVOICE_STATUS','pending','미발행',1),
  ('INVOICE_STATUS','invoiced','발행',2),
  ('INVOICE_STATUS','paid','완납',3),
  ('INVOICE_STATUS','overdue','연체',4),
  ('INVOICE_STATUS','cancelled','취소',5),
  ('BOOTH_SALE_STATUS','available','판매가능',1),
  ('BOOTH_SALE_STATUS','held','선점',2),
  ('BOOTH_SALE_STATUS','sold','판매완료',3),
  ('BOOTH_SALE_STATUS','blocked','판매불가',4)
ON CONFLICT (grp_code, code) DO NOTHING;

-- 1-2) 프로그램 등록부(sys_program) — App.tsx 라우트 스캔·화면 등록 -----------------
INSERT INTO sys_program (tenant_id, id, program_name, program_type, program_url, category) VALUES
  ('KINTEX','pg-home','메인 홈','SCREEN','/home','공통'),
  ('KINTEX','pg-login','로그인','SCREEN','/login','인증'),
  ('KINTEX','pg-otp','OTP 설정','SCREEN','/otp-setup','인증'),
  ('KINTEX','pg-dashboard','행사 대시보드','SCREEN','/events/:eventId/dashboard','부스코어'),
  ('KINTEX','pg-booth-home','부스 홈','SCREEN','/events/:eventId/booths/:boothId/home','부스코어'),
  ('KINTEX','pg-layout','홀 배치 에디터','SCREEN','/events/:eventId/halls/:hallId/layout','부스코어'),
  ('KINTEX','pg-comparison','배치안 비교','SCREEN','/events/:eventId/halls/:hallId/comparison','부스코어'),
  ('KINTEX','pg-design','부스 설계','SCREEN','/events/:eventId/booths/:boothId/design','부스코어'),
  ('KINTEX','pg-utility','유틸리티','SCREEN','/events/:eventId/booths/:boothId/utility','부스코어'),
  ('KINTEX','pg-utility-order','유틸리티 신청','SCREEN','/events/:eventId/booths/:boothId/utility/order','부스코어'),
  ('KINTEX','pg-compliance','규정 검토','SCREEN','/events/:eventId/booths/:boothId/compliance','부스코어'),
  ('KINTEX','pg-review','도면 검수','SCREEN','/events/:eventId/halls/:hallId/booths/:booth/review','부스코어'),
  ('KINTEX','pg-gallery','AI 갤러리','SCREEN','/events/:eventId/booths/:boothId/gallery','부스코어'),
  ('KINTEX','pg-booth-sales','부스 판매','SCREEN','/booth-sales','부스코어'),
  ('KINTEX','pg-halls','전시장/홀','SCREEN','/halls','부스코어'),
  ('KINTEX','pg-analytics','경영분석/BI','SCREEN','/analytics','도메인'),
  ('KINTEX','pg-ops','운영 관제','SCREEN','/ops/operations','도메인'),
  ('KINTEX','pg-docs','신고서류','SCREEN','/docs','도메인'),
  ('KINTEX','pg-docs-authoring','서류 작성','SCREEN','/docs/authoring','도메인'),
  ('KINTEX','pg-logistics','물류/반입반출','SCREEN','/logistics','도메인'),
  ('KINTEX','pg-auctions','공사 옥션','SCREEN','/auctions','도메인'),
  ('KINTEX','pg-auction-detail','옥션 상세','SCREEN','/auctions/:auctionId','도메인'),
  ('KINTEX','pg-auction-award','옥션 낙찰선정','SCREEN','/auctions/:auctionId/award','도메인'),
  ('KINTEX','pg-contractor','공사업체 대시보드','SCREEN','/contractor/dashboard','도메인'),
  ('KINTEX','pg-visitors','관람객 등록','SCREEN','/visitors','도메인'),
  ('KINTEX','pg-checkin','현장 체크인','SCREEN','/visitors/checkin','도메인'),
  ('KINTEX','pg-leads','리드 스코어링','SCREEN','/leads','도메인'),
  ('KINTEX','pg-campaigns','EDM 캠페인','SCREEN','/campaigns','도메인'),
  ('KINTEX','pg-sponsorship','스폰서십','SCREEN','/sponsorship','도메인'),
  ('KINTEX','pg-cms','CMS','SCREEN','/cms','도메인'),
  ('KINTEX','pg-cms-microsite','마이크로사이트','SCREEN','/cms/microsite','도메인'),
  ('KINTEX','pg-cms-i18n','다국어 관리','SCREEN','/cms/i18n','도메인'),
  ('KINTEX','pg-settlement','정산/청구','SCREEN','/settlement','도메인'),
  ('KINTEX','pg-work-approval','전자결재','SCREEN','/work/approval','공통업무'),
  ('KINTEX','pg-work-worklog','업무일지','SCREEN','/work/worklog','공통업무'),
  ('KINTEX','pg-work-schedule','일정','SCREEN','/work/schedule','공통업무'),
  ('KINTEX','pg-work-message','쪽지','SCREEN','/work/message','공통업무'),
  ('KINTEX','pg-work-notice','공지','SCREEN','/work/notice','공통업무'),
  ('KINTEX','pg-work-opinion','의견','SCREEN','/work/opinion','공통업무'),
  ('KINTEX','pg-work-meeting','회의','SCREEN','/work/meeting','공통업무'),
  ('KINTEX','pg-work-report','보고서','SCREEN','/work/report','공통업무'),
  ('KINTEX','pg-work-search','통합검색','SCREEN','/work/search','공통업무'),
  ('KINTEX','pg-notifications','알림','SCREEN','/notifications','공통업무'),
  ('KINTEX','pg-me','내 정보','SCREEN','/me','공통업무'),
  ('KINTEX','pg-admin','관리 대시보드','SCREEN','/admin','시스템관리'),
  ('KINTEX','pg-admin-users','사용자 관리','SCREEN','/admin/users','시스템관리'),
  ('KINTEX','pg-admin-roles','역할/권한','SCREEN','/admin/roles','시스템관리'),
  ('KINTEX','pg-admin-codes','공통코드','SCREEN','/admin/codes','시스템관리'),
  ('KINTEX','pg-admin-menus','메뉴 관리','SCREEN','/admin/menus','시스템관리'),
  ('KINTEX','pg-admin-depts','조직 관리','SCREEN','/admin/depts','시스템관리'),
  ('KINTEX','pg-admin-companies','회사 관리','SCREEN','/admin/companies','시스템관리'),
  ('KINTEX','pg-admin-programs','프로그램 관리','SCREEN','/admin/programs','시스템관리'),
  ('KINTEX','pg-admin-role-menus','역할-메뉴','SCREEN','/admin/role-menus','시스템관리'),
  ('KINTEX','pg-admin-auth-policy','인증 정책','SCREEN','/admin/auth-policy','시스템관리'),
  ('KINTEX','pg-admin-login-history','로그인 이력','SCREEN','/admin/login-history','시스템관리'),
  ('KINTEX','pg-admin-error-log','오류 로그','SCREEN','/admin/error-log','시스템관리'),
  ('KINTEX','pg-admin-system-health','시스템 상태','SCREEN','/admin/system-health','시스템관리'),
  ('KINTEX','pg-admin-settings','시스템 설정','SCREEN','/admin/settings','시스템관리'),
  ('KINTEX','pg-admin-audit','감사로그','SCREEN','/admin/audit','시스템관리'),
  ('KINTEX','pg-admin-rulesets','규정/요율 룰셋','SCREEN','/admin/masterdata/rulesets','시스템관리'),
  ('KINTEX','pg-admin-tenants','테넌트 관리','SCREEN','/admin/tenants','시스템관리'),
  ('KINTEX','pg-admin-login-slides','로그인 슬라이드','SCREEN','/admin/login-slides','시스템관리'),
  ('KINTEX','pg-admin-mail-config','메일 설정','SCREEN','/admin/mail-config','시스템관리'),
  ('KINTEX','pg-admin-notify-config','알림 설정','SCREEN','/admin/notify-config','시스템관리'),
  ('KINTEX','pg-app-qr','앱 QR 배포','SCREEN','/app-qr','시스템관리'),
  ('KINTEX','pg-public','공개 홈','SCREEN','/public','공개사이트'),
  ('KINTEX','pg-public-event','공개 행사','SCREEN','/public/events/:eventId','공개사이트'),
  ('KINTEX','pg-public-floorplan','공개 평면도','SCREEN','/public/events/:eventId/floorplan','공개사이트'),
  ('KINTEX','pg-public-register','관람객 사전등록','SCREEN','/public/events/:eventId/register','공개사이트'),
  ('KINTEX','pg-public-exhibitor','공개 참가업체','SCREEN','/public/exhibitors/:exhibitorId','공개사이트'),
  ('KINTEX','pg-public-inquiry','참가문의','SCREEN','/public/exhibit-inquiry','공개사이트'),
  ('KINTEX','pg-ticket-purchase','입장권 구매','SCREEN','/tickets/:eventId/purchase','공개사이트'),
  ('KINTEX','pg-ticket-lookup','입장권 조회','SCREEN','/tickets/lookup','공개사이트'),
  ('KINTEX','pg-m-checklist','현장 체크리스트(모바일)','SCREEN','/m/booths/:boothId/checklist','모바일'),
  ('KINTEX','pg-m-inspection','현장 점검(모바일)','SCREEN','/m/booths/:boothId/inspection','모바일')
ON CONFLICT (tenant_id, id) DO NOTHING;

-- 1-3) 부서 트리(dept) — 3레벨 --------------------------------------------------
INSERT INTO dept (tenant_id, id, dept_name, parent_id, sort_order) VALUES
  ('KINTEX','d-exhib',    '전시사업본부',   NULL,       1),
  ('KINTEX','d-hall',     '홀운영팀',       'd-exhib',  1),
  ('KINTEX','d-hall-c1',  '제1전시장파트',  'd-hall',   1),
  ('KINTEX','d-hall-c2',  '제2전시장파트',  'd-hall',   2),
  ('KINTEX','d-sales',    '전시영업팀',     'd-exhib',  2),
  ('KINTEX','d-sales-dom','국내영업파트',   'd-sales',  1),
  ('KINTEX','d-sales-glo','해외영업파트',   'd-sales',  2),
  ('KINTEX','d-mkt',      '마케팅팀',       'd-exhib',  3),
  ('KINTEX','d-mgmt',     '경영지원본부',   NULL,       2),
  ('KINTEX','d-fin',      '재무회계팀',     'd-mgmt',   1),
  ('KINTEX','d-fin-set',  '정산파트',       'd-fin',    1),
  ('KINTEX','d-hr',       '인사총무팀',     'd-mgmt',   2),
  ('KINTEX','d-it',       '정보시스템본부', NULL,       3),
  ('KINTEX','d-it-ops',   '시스템운영팀',   'd-it',     1),
  ('KINTEX','d-it-dev',   '서비스개발팀',   'd-it',     2)
ON CONFLICT (tenant_id, id) DO NOTHING;

-- 1-4) 회사(company) — 공사업체 2건 순증(V6 co-0001~4 포함 총 6) + 참가업체 10건 -----
--      company 는 tenant_id 컬럼 없음(V2 스키마). UNIQUE(registration_no) 멱등 키.
INSERT INTO company (id, registration_no, name, category, region, registered, phone) VALUES
  -- 공사(장치)업체 순증 2 (registered=true)
  ('co-0005', '555-55-55555', '(주)미디어라이트',   '영상/음향',    '서울', true, '02-0000-5501'),
  ('co-0006', '666-66-66666', '넷워크시스템즈',      '네트워크',     '경기', true, '031-000-6601'),
  -- 참가업체 10 (전시 참가사 — 등록업체 DB 등재)
  ('co-ex-01', '301-81-10001', '(주)스마트오토메이션', '제조/자동화', '경기', true, '031-000-1001'),
  ('co-ex-02', '302-81-10002', '델타로보틱스',         '로봇',        '서울', true, '02-0000-1002'),
  ('co-ex-03', '303-81-10003', '한국센서테크',         '전기/전자',   '인천', true, '032-000-1003'),
  ('co-ex-04', '304-81-10004', '비전인더스트리',       '제조/자동화', '경기', true, '031-000-1004'),
  ('co-ex-05', '305-81-10005', '(주)테크솔루션',       'ICT/소프트웨어','서울',true, '02-0000-1005'),
  ('co-ex-06', '306-81-10006', '넥스트이노베이션',     'ICT/소프트웨어','경기',true, '031-000-1006'),
  ('co-ex-07', '307-81-10007', '글로벌테크',           '물류/유통',   '부산', true, '051-000-1007'),
  ('co-ex-08', '308-81-10008', '미래제조연구소',       '제조/자동화', '대전', true, '042-000-1008'),
  ('co-ex-09', '309-81-10009', '두산로보틱스데모',     '로봇',        '경기', true, '031-000-1009'),
  ('co-ex-10', '310-81-10010', '바이오헬스랩',         '바이오/헬스', '서울', true, '02-0000-1010')
ON CONFLICT (registration_no) DO NOTHING;

-- 공사업체 평판(company_reputation) — 순증 2건(V16 co-0001~4 포함 총 6) ------------
INSERT INTO company_reputation (company_id, rating, jobs_done, claim_rate) VALUES
  ('co-0005', 4.5, 9,  1.0),
  ('co-0006', 4.3, 7,  1.8)
ON CONFLICT (company_id) DO NOTHING;

-- 1-5) 요율 부족분 순증(master_data RATE — ON CONFLICT DO NOTHING) -----------------
INSERT INTO master_data (category, code, name, value_json, ruleset_version) VALUES
  ('RATE', 'independentBoothPerM2', '독립부스 임대 요율(원/㎡)', '2420'::jsonb, 'rates-v1.0'),
  ('RATE', 'cornerPremiumPercent',  '코너 가산율(%)',            '10'::jsonb,   'rates-v1.0'),
  ('RATE', 'lateApplicationPercent','마감 후 신청 가산율(%)',    '20'::jsonb,   'rates-v1.0'),
  ('UTILITY_FEE', 'network.wifiAp', '전용 WiFi AP(원)',          '250000'::jsonb,'rates-v1.0'),
  ('UTILITY_FEE', 'power.night24h', '24시간 전원 상시공급(원/kW)','82500'::jsonb,'rates-v1.0')
ON CONFLICT (category, code) DO NOTHING;


-- ============================================================================
-- 2. 데모 계정 4 (app_user) + 행사 멤버십(event_member)
--    비밀번호 규칙: Kintex!Demo<Role>1  · BCrypt($2a$10) · otp_enabled=false(데모 편의)
-- ============================================================================
INSERT INTO app_user (tenant_id, id, email, display_name, password_hash, hall_manager,
                      role_code, status, verify_method, otp_enabled, dept_id, company_name) VALUES
  ('KINTEX','demo-organizer','demo-organizer@kintex.test','데모 주최자(홍길동)',
     '$2a$10$15dUJ7rlPO7kwgC/fgCUFuOK7Q0yS5lC4LTedszf1vn/R7CsShZ2y', false,
     'USER','ACTIVE','EMAIL', false, 'd-hall', 'KINTEX 전시사업본부'),
  ('KINTEX','demo-exhibitor','demo-exhibitor@kintex.test','데모 참가업체(김참가)',
     '$2a$10$aaUiIhPWfAMJ/AIfpZYBSurTRwnCYIY1R9mmmgpZyGVTMxXIyxlsC', false,
     'USER','ACTIVE','EMAIL', false, NULL, '(주)스마트오토메이션'),
  ('KINTEX','demo-contractor','demo-contractor@kintex.test','데모 공사업체(이시공)',
     '$2a$10$hFPyMTvnOYQwfHcktl9Kuu0W2/Mrl//IiSjS83wOmBd22enBDRj5G', false,
     'USER','ACTIVE','EMAIL', false, NULL, '(주)한빛부스디자인'),
  ('KINTEX','demo-visitor','demo-visitor@kintex.test','데모 관람객(박관람)',
     '$2a$10$UhVNjelRRZt3SpDCJfT.V.2pfHH9Lrme9KRteadUUJ1YhFwMvyH4K', false,
     'USER','ACTIVE','EMAIL', false, NULL, NULL)
ON CONFLICT (email) DO NOTHING;

-- 행사 단위 RBAC — e-2026-smf. contractor 는 등록업체(co-0001) 연결 → 옥션 응찰 게이트 통과.
INSERT INTO event_member (id, event_id, user_id, role_code, booth_id, company_id) VALUES
  ('em-demo-org', 'e-2026-smf', 'demo-organizer',  'ORGANIZER',  NULL,            NULL),
  ('em-demo-exh', 'e-2026-smf', 'demo-exhibitor',  'EXHIBITOR',  'booth-smf-a102', NULL),
  ('em-demo-con', 'e-2026-smf', 'demo-contractor', 'CONTRACTOR', NULL,            'co-0001')
ON CONFLICT (event_id, user_id, role_code) DO NOTHING;


-- ============================================================================
-- 3. 부스 폐루프 — 홀 배정 + 데모 배치(layout) + 부스 12(POLYGON) + 판매 오버레이
--    SRID 0 = 홀 로컬 평면(미터). 부스=6m×3m(18㎡) 4×3 그리드.
-- ============================================================================
-- H1 홀 배정(V28 BOQ 레이아웃 정합) + 데모 부스용 배정은 기존 H7(primary) 사용.
INSERT INTO hall_assignment (id, event_id, hall_id, is_primary) VALUES
  ('ha-2026-smf-h1', 'e-2026-smf', 'H1', false)
ON CONFLICT (event_id, hall_id) DO NOTHING;

INSERT INTO layout (id, event_id, hall_id, version, name, status) VALUES
  ('ly-smf-demo', 'e-2026-smf', 'H7', 1, 'SMF 데모 배치(판매)', 'confirmed')
ON CONFLICT (id) DO NOTHING;

INSERT INTO booth (id, layout_id, booth_no, booth_type, geom, size_w_m, size_d_m, height_m,
                   floor_load_t_per_m2, assigned_company_name, premium) VALUES
  ('booth-smf-b101','ly-smf-demo','B-101','independent',ST_GeomFromText('POLYGON((0 0,6 0,6 3,0 3,0 0))',0),      6,3,3.5,1.0,'(주)스마트오토메이션',true),
  ('booth-smf-b102','ly-smf-demo','B-102','assembled',  ST_GeomFromText('POLYGON((7 0,13 0,13 3,7 3,7 0))',0),    6,3,3.0,1.0,'델타로보틱스',false),
  ('booth-smf-b103','ly-smf-demo','B-103','assembled',  ST_GeomFromText('POLYGON((14 0,20 0,20 3,14 3,14 0))',0), 6,3,3.0,1.0,NULL,false),
  ('booth-smf-b104','ly-smf-demo','B-104','corner',     ST_GeomFromText('POLYGON((21 0,27 0,27 3,21 3,21 0))',0), 6,3,3.5,1.0,'한국센서테크',false),
  ('booth-smf-b105','ly-smf-demo','B-105','assembled',  ST_GeomFromText('POLYGON((0 4,6 4,6 7,0 7,0 4))',0),      6,3,3.0,1.0,NULL,false),
  ('booth-smf-b106','ly-smf-demo','B-106','island',     ST_GeomFromText('POLYGON((7 4,13 4,13 7,7 7,7 4))',0),    6,3,4.0,1.0,'비전인더스트리',true),
  ('booth-smf-b107','ly-smf-demo','B-107','assembled',  ST_GeomFromText('POLYGON((14 4,20 4,20 7,14 7,14 4))',0), 6,3,3.0,1.0,'(주)테크솔루션',false),
  ('booth-smf-b108','ly-smf-demo','B-108','assembled',  ST_GeomFromText('POLYGON((21 4,27 4,27 7,21 7,21 4))',0), 6,3,3.0,1.0,NULL,false),
  ('booth-smf-b109','ly-smf-demo','B-109','independent',ST_GeomFromText('POLYGON((0 8,6 8,6 11,0 11,0 8))',0),    6,3,3.5,1.0,'넥스트이노베이션',false),
  ('booth-smf-b110','ly-smf-demo','B-110','assembled',  ST_GeomFromText('POLYGON((7 8,13 8,13 11,7 11,7 8))',0),  6,3,3.0,1.0,NULL,false),
  ('booth-smf-b111','ly-smf-demo','B-111','corner',     ST_GeomFromText('POLYGON((14 8,20 8,20 11,14 11,14 8))',0),6,3,3.5,1.0,'미래제조연구소',false),
  ('booth-smf-b112','ly-smf-demo','B-112','assembled',  ST_GeomFromText('POLYGON((21 8,27 8,27 11,21 11,21 8))',0),6,3,3.0,1.0,'바이오헬스랩',false)
ON CONFLICT (id) DO NOTHING;

-- 판매 오버레이(booth_sale) — 상태 분포: sold 5 · available 4 · held 1 · blocked 2 -------
INSERT INTO booth_sale (tenant_id, id, event_id, hall_id, booth_id, booth_no, status, unit_price,
                        area_m2, held_by, held_until, sold_to_company, sold_by, sold_at,
                        blocked_reason, created_by) VALUES
  ('KINTEX','bs-smf-101','e-2026-smf','H7','booth-smf-b101','B-101','sold',      5445000,18,NULL,NULL,'(주)스마트오토메이션','demo-organizer',now()-interval '20 day',NULL,'system-seed'),
  ('KINTEX','bs-smf-102','e-2026-smf','H7','booth-smf-b102','B-102','sold',      4356000,18,NULL,NULL,'델타로보틱스','demo-organizer',now()-interval '15 day',NULL,'system-seed'),
  ('KINTEX','bs-smf-103','e-2026-smf','H7','booth-smf-b103','B-103','available', NULL,   18,NULL,NULL,NULL,NULL,NULL,NULL,'system-seed'),
  ('KINTEX','bs-smf-104','e-2026-smf','H7','booth-smf-b104','B-104','sold',      4791600,18,NULL,NULL,'한국센서테크','demo-organizer',now()-interval '12 day',NULL,'system-seed'),
  ('KINTEX','bs-smf-105','e-2026-smf','H7','booth-smf-b105','B-105','available', NULL,   18,NULL,NULL,NULL,NULL,NULL,NULL,'system-seed'),
  ('KINTEX','bs-smf-106','e-2026-smf','H7','booth-smf-b106','B-106','sold',      6534000,18,NULL,NULL,'비전인더스트리','demo-organizer',now()-interval '8 day',NULL,'system-seed'),
  ('KINTEX','bs-smf-107','e-2026-smf','H7','booth-smf-b107','B-107','sold',      4356000,18,NULL,NULL,'(주)테크솔루션','demo-organizer',now()-interval '5 day',NULL,'system-seed'),
  ('KINTEX','bs-smf-108','e-2026-smf','H7','booth-smf-b108','B-108','held',      NULL,   18,'demo-exhibitor',now()+interval '30 minute',NULL,NULL,NULL,NULL,'system-seed'),
  ('KINTEX','bs-smf-109','e-2026-smf','H7','booth-smf-b109','B-109','available', NULL,   18,NULL,NULL,NULL,NULL,NULL,NULL,'system-seed'),
  ('KINTEX','bs-smf-110','e-2026-smf','H7','booth-smf-b110','B-110','blocked',   NULL,   18,NULL,NULL,NULL,NULL,NULL,'소방 통로 확보 구역','system-seed'),
  ('KINTEX','bs-smf-111','e-2026-smf','H7','booth-smf-b111','B-111','available', NULL,   18,NULL,NULL,NULL,NULL,NULL,NULL,'system-seed'),
  ('KINTEX','bs-smf-112','e-2026-smf','H7','booth-smf-b112','B-112','blocked',   NULL,   18,NULL,NULL,NULL,NULL,NULL,'전기 분전반 점유','system-seed')
ON CONFLICT (id) DO NOTHING;


-- ============================================================================
-- 4. 서류 폐루프 — 마감 임박(D-3) 필수 서류 순증 (홈 '서류 D-3' 할 일 활성화)
--    V14 기존 서류 due=2026-08-04(고정)는 배포 시점 무관하게 임박하지 않으므로
--    상대일(CURRENT_DATE+3) 신규 doc_type 1건 추가.
-- ============================================================================
INSERT INTO required_document (id, event_id, doc_type, name, status, due_date, sort_order) VALUES
  ('doc-smf-reinspect','e-2026-smf','safety_reinspection','전기안전 재점검 확인서','draft', CURRENT_DATE + 3, 8)
ON CONFLICT (event_id, doc_type) DO NOTHING;


-- ============================================================================
-- 5. 옥션 폐루프 — 응찰 보강(3~5씩) + 낙찰 선정 대기 옥션 신설(AUC-2026-0511)
--    기존 V16: AUC-0102(3응찰·진행), AUC-0405(2응찰·진행), AUC-0210(2응찰·낙찰완료).
-- ============================================================================
-- 5-1) 기존 옥션 초대·응찰 보강 -----------------------------------------------
INSERT INTO auction_invite (id, auction_id, company_id) VALUES
  ('ai-0405-3', 'AUC-2026-0405', 'co-0001'),
  ('ai-0405-4', 'AUC-2026-0405', 'co-0005'),
  ('ai-0210-2', 'AUC-2026-0210', 'co-0002')
ON CONFLICT (auction_id, company_id) DO NOTHING;

INSERT INTO bid (id, auction_id, company_id, round, subtotal, vat, total, lead_days) VALUES
  ('bid-0405-3', 'AUC-2026-0405', 'co-0001', 1, 4400000, 440000, 4400000, 7),
  ('bid-0405-4', 'AUC-2026-0405', 'co-0005', 1, 4780000, 478000, 4780000, 10),
  ('bid-0210-3', 'AUC-2026-0210', 'co-0002', 1, 12500000, 1250000, 12500000, 16)
ON CONFLICT (auction_id, company_id) DO NOTHING;

-- 5-2) 낙찰 선정 대기 옥션(마감 경과 + 낙찰 미확정) — 홈 '옥션 낙찰 선정' 할 일 활성화 -----
INSERT INTO auction (id, event_id, title, category, auction_type, award_criteria,
                     weight_price, weight_reputation, weight_delivery, round, deadline,
                     material_package_id, materials, accent, created_by) VALUES
  ('AUC-2026-0511', 'e-2026-smf', 'D-1 옥외 사이니지 설치', '영상/음향', 'reverse', 'comprehensive',
     55, 25, 20, 1, now() - interval '1 day', NULL, 'layout,boq', 'primary', 'demo-organizer')
ON CONFLICT (id) DO NOTHING;

INSERT INTO auction_invite (id, auction_id, company_id) VALUES
  ('ai-0511-1', 'AUC-2026-0511', 'co-0001'),
  ('ai-0511-2', 'AUC-2026-0511', 'co-0002'),
  ('ai-0511-3', 'AUC-2026-0511', 'co-0005'),
  ('ai-0511-4', 'AUC-2026-0511', 'co-0006')
ON CONFLICT (auction_id, company_id) DO NOTHING;

INSERT INTO bid (id, auction_id, company_id, round, subtotal, vat, total, lead_days) VALUES
  ('bid-0511-1', 'AUC-2026-0511', 'co-0001', 1, 6800000, 680000, 6800000, 9),
  ('bid-0511-2', 'AUC-2026-0511', 'co-0002', 1, 7100000, 710000, 7100000, 8),
  ('bid-0511-3', 'AUC-2026-0511', 'co-0005', 1, 6500000, 650000, 6500000, 11),
  ('bid-0511-4', 'AUC-2026-0511', 'co-0006', 1, 6950000, 695000, 6950000, 10)
ON CONFLICT (auction_id, company_id) DO NOTHING;


-- ============================================================================
-- 6. 관람객·리드 폐루프
-- ============================================================================
-- 6-1) 관람객 사전등록 순증 — 오늘 체크인 분포(홈 KPI todayCheckins 활성화) ----------
--      checkin_at 은 CURRENT_DATE 기준 상대(now()) — 재배포 시점의 '오늘'로 집계.
INSERT INTO visitor_registration
    (id, event_id, name, phone, email, company, visitor_type, agree_privacy, agree_marketing,
     badge_code, badge_issued, checkin_state, qr_token, checkin_at, registered_at) VALUES
  ('vr-smf-101','e-2026-smf','조민준','010-0000-1101','visitor101@kintex.test','(주)스마트오토메이션','buyer', true,true, 'KTX-V-0101',true,'done',   'QR-DEMO0000000000000101', now()-interval '3 hour', now()-interval '2 day'),
  ('vr-smf-102','e-2026-smf','윤서아','010-0000-1102','visitor102@kintex.test','델타로보틱스',        'visitor',true,true, 'KTX-V-0102',true,'done',   'QR-DEMO0000000000000102', now()-interval '2 hour', now()-interval '2 day'),
  ('vr-smf-103','e-2026-smf','임도현','010-0000-1103','visitor103@kintex.test','한국센서테크',        'vip',    true,false,'KTX-V-0103',true,'done',   'QR-DEMO0000000000000103', now()-interval '1 hour', now()-interval '1 day'),
  ('vr-smf-104','e-2026-smf','장하윤','010-0000-1104','visitor104@kintex.test',NULL,                  'visitor',true,true, 'KTX-V-0104',true,'done',   'QR-DEMO0000000000000104', now()-interval '30 minute', now()-interval '1 day'),
  ('vr-smf-105','e-2026-smf','서지호','010-0000-1105','visitor105@kintex.test','넥스트이노베이션',    'buyer',  true,true, 'KTX-V-0105',true,'waiting', 'QR-DEMO0000000000000105', NULL, now()-interval '1 day'),
  ('vr-smf-106','e-2026-smf','오예린','010-0000-1106','visitor106@kintex.test','글로벌테크',          'visitor',true,false,'KTX-V-0106',false,'waiting','QR-DEMO0000000000000106', NULL, now()-interval '6 hour'),
  ('vr-smf-demo','e-2026-smf','데모 관람객(박관람)','010-0000-0000','demo-visitor@kintex.test',NULL,'visitor',true,true,'KTX-V-DEMO',true,'done','QR-DEMO000000000000DEMO', now()-interval '90 minute', now()-interval '3 day')
ON CONFLICT (id) DO NOTHING;

-- 6-2) 리드 순증 — 총 15건(기존 5 + 신규 10), 핫(score>=80) 총 4건(기존 87·82 + 신규 88·91) ---
INSERT INTO lead
    (id, event_id, booth_id, exhibitor_id, name, phone, email, role, company, product,
     interest, score, ai_reasons, activity, followup_draft, ai_generated, collected_at) VALUES
  ('ld-smf-006','e-2026-smf','booth-smf-b101','demo-exhibitor','문재훈','010-0000-2006','moon@techsol.test','생산기술 팀장','(주)테크솔루션','협동로봇 HR-A1',5,91,
     '["부스 체류 18분(평균 대비 300%)","사양서 다운로드 3회","구매 결정권자 직급"]'::jsonb,
     '[{"text":"HR-A1 시연 참관","at":"오늘 13:40"},{"text":"견적 요청 폼 제출","at":"오늘 13:55"}]'::jsonb,
     '안녕하세요, 문 팀장님. 협동로봇 HR-A1 커스텀 제안서를 준비했습니다. 다음 주 미팅 가능하실까요?', true, now()-interval '5 hour'),
  ('ld-smf-007','e-2026-smf','booth-smf-b106','demo-exhibitor','배수진','010-0000-2007','bae@visionind.test','구매 담당','비전인더스트리','AI 비전 검사 모듈',5,88,
     '["AI 비전 데모 2회 재방문","경쟁사 대비 견적 문의","도입 시기 명확(Q4)"]'::jsonb,
     '[{"text":"AI 비전 모듈 상담","at":"오늘 11:20"}]'::jsonb,
     '안녕하세요, 배 님. 요청하신 AI 비전 검사 모듈 견적서와 파일럿 프로그램 안내드립니다.', true, now()-interval '7 hour'),
  ('ld-smf-008','e-2026-smf','booth-smf-b101','demo-exhibitor','신유리','010-0000-2008','shin@deltarobo.test','기술 기획','델타로보틱스','스마트 물류',3,63,
     '["물류 자동화 세션 참석","브로슈어 다운로드"]'::jsonb,
     '[{"text":"데모 영상 시청","at":"오늘 10:10"}]'::jsonb,
     '안녕하세요, 신 님. 스마트 물류 도입 사례집을 보내드립니다.', true, now()-interval '9 hour'),
  ('ld-smf-009','e-2026-smf','booth-smf-b107',NULL,'홍길동','010-0000-2009','hong@sctsys.test','인프라 엔지니어','SCT시스템','클라우드 모니터링',2,41,
     '["짧은 부스 체류","자료 열람 없음"]'::jsonb,
     '[{"text":"부스 QR 스캔","at":"오늘 09:50"}]'::jsonb,
     '안녕하세요, 홍 님. 클라우드 모니터링 소개서를 보내드립니다.', true, now()-interval '10 hour'),
  ('ld-smf-010','e-2026-smf','booth-smf-b109',NULL,'김철수','010-0000-2010','kim@globaltech.test','설비 담당','글로벌테크','자율주행 AMR',2,38,
     '["AMR 부스 단순 방문"]'::jsonb,
     '[{"text":"부스 QR 스캔","at":"오늘 09:30"}]'::jsonb,
     '안녕하세요, 김 님. 자율주행 AMR 소개 자료를 보내드립니다.', true, now()-interval '11 hour'),
  ('ld-smf-011','e-2026-smf','booth-smf-b111',NULL,'이영희','010-0000-2011','lee@fmlab.test','연구원','미래제조연구소','스마트 팩토리 컨설팅',4,72,
     '["연구 목적 방문","기술 세션 2회 참석"]'::jsonb,
     '[{"text":"기술 상담","at":"오늘 14:30"}]'::jsonb,
     '안녕하세요, 이 연구원님. 스마트 팩토리 컨설팅 자료를 보내드립니다.', true, now()-interval '3 hour'),
  ('ld-smf-012','e-2026-smf','booth-smf-b104',NULL,'박영수','010-0000-2012','park@sensortech.test','품질 담당','한국센서테크','센서 모듈',3,58,
     '["센서 데모 관람","카탈로그 수령"]'::jsonb,
     '[{"text":"카탈로그 QR 스캔","at":"오늘 12:05"}]'::jsonb,
     '안녕하세요, 박 님. 센서 모듈 카탈로그를 보내드립니다.', true, now()-interval '6 hour'),
  ('ld-smf-013','e-2026-smf','booth-smf-b102',NULL,'정미경','010-0000-2013','jung@nextinno.test','마케팅','넥스트이노베이션','AI 솔루션',3,55,
     '["부스 방문","명함 교환"]'::jsonb,
     '[{"text":"명함 교환","at":"오늘 15:10"}]'::jsonb,
     '안녕하세요, 정 님. AI 솔루션 소개서를 보내드립니다.', true, now()-interval '2 hour'),
  ('ld-smf-014','e-2026-smf','booth-smf-b106',NULL,'최동욱','010-0000-2014','choi@biohealth.test','R&D','바이오헬스랩','자동화 장비',4,74,
     '["자동화 장비 상담","도입 검토 중"]'::jsonb,
     '[{"text":"장비 상담","at":"오늘 13:00"}]'::jsonb,
     '안녕하세요, 최 님. 자동화 장비 제안서를 보내드립니다.', true, now()-interval '4 hour'),
  ('ld-smf-015','e-2026-smf','booth-smf-b109',NULL,'강민석','010-0000-2015','kang@doosandemo.test','생산관리','두산로보틱스데모','협동로봇',3,49,
     '["로봇 부스 방문"]'::jsonb,
     '[{"text":"부스 QR 스캔","at":"오늘 11:45"}]'::jsonb,
     '안녕하세요, 강 님. 협동로봇 소개 자료를 보내드립니다.', true, now()-interval '8 hour')
ON CONFLICT (id) DO NOTHING;


-- ============================================================================
-- 7. 마케팅 — EDM 캠페인 순증 2 (기존 V18 4건 + 2)
-- ============================================================================
INSERT INTO edm_campaign (id, event_id, name, status, audience, meta, open_rate, click_rate) VALUES
  ('cp-smf-005','e-2026-smf','참가업체 부스 배정 확정 안내','scheduled', 512, '발송 예정: D-2 10:00', '-', '-'),
  ('cp-smf-006','e-2026-smf','현장 방문객 만족도 조사','draft', 0, '최종 수정: 방금 전', '-', '-')
ON CONFLICT (id) DO NOTHING;


-- ============================================================================
-- 8. 정산 폐루프 — 청구서 순증 4(총 8, 옥션 수수료 1 포함) + 수납/세금계산서/환불
--    기존 V24 4건(paid·invoiced·overdue·pending). 순증 4 = paid·partial·cancelled·auction_fee.
-- ============================================================================
INSERT INTO invoice (id, event_id, exhibitor_id, exhibitor_name, invoice_no, category, source_ref,
                     subtotal, vat, total, paid_amount, status, due_date, issued_at, paid_at,
                     cancelled_at, cancel_reason, line_items, note, created_by) VALUES
  -- 완납
  ('inv-smf-0005','e-2026-smf',NULL,'(주)테크솔루션','SMF-2026-0005','rental',NULL,
     7920000, 792000, 8712000, 8712000, 'paid', DATE '2026-07-20', now()-interval '22 day', now()-interval '6 day',
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (72㎡ · B-107)","quantity":72,"unitPrice":110000,"amount":7920000}]'::jsonb,
     '완납 처리.', 'system-seed'),
  -- 부분수납
  ('inv-smf-0006','e-2026-smf',NULL,'넥스트이노베이션','SMF-2026-0006','rental',NULL,
     10800000, 1080000, 11880000, 4752000, 'invoiced', DATE '2026-07-28', now()-interval '10 day', NULL,
     NULL, NULL,
     '[{"category":"RENTAL","description":"부스 임대료 (108㎡ · B-109)","quantity":108,"unitPrice":100000,"amount":10800000}]'::jsonb,
     '계약금 40% 수납.', 'system-seed'),
  -- 취소(환불 대상) — 계약금 납입 후 취소
  ('inv-smf-0007','e-2026-smf',NULL,'미래제조연구소','SMF-2026-0007','rental',NULL,
     6000000, 600000, 6600000, 2640000, 'cancelled', DATE '2026-07-30', now()-interval '14 day', NULL,
     now()-interval '3 day', '참가 철회(내부 사정) — 환불 규정 적용',
     '[{"category":"RENTAL","description":"부스 임대료 (54㎡ · B-111)","quantity":54,"unitPrice":111111,"amount":6000000}]'::jsonb,
     '취소 확정 — 환불 산정 대상.', 'system-seed'),
  -- 옥션 낙찰 수수료(F084) — AUC-2026-0210 낙찰(aw-0210, co-0003) 5% 수수료
  ('inv-smf-0008','e-2026-smf',NULL,'세계전기시설','SMF-2026-0008','auction_fee','aw-0210',
     600000, 60000, 660000, 0, 'pending', DATE '2026-08-05', NULL, NULL,
     NULL, NULL,
     '[{"category":"AUCTION_FEE","description":"옥션 낙찰 수수료 5% (AUC-2026-0210 · 낙찰 12,000,000원)","quantity":1,"unitPrice":600000,"amount":600000}]'::jsonb,
     '옥션 낙찰 수수료 청구(발행 대기).', 'system-seed')
ON CONFLICT (id) DO NOTHING;

-- 수납 기록(inv-0005 완납 · inv-0006 부분 · inv-0007 취소 전 계약금) --------------------
INSERT INTO invoice_payment (id, invoice_id, amount, method, memo, recorded_by, recorded_at) VALUES
  ('pay-smf-0005-1','inv-smf-0005', 8712000, 'transfer', '일시 완납',  'system-seed', now()-interval '6 day'),
  ('pay-smf-0006-1','inv-smf-0006', 4752000, 'transfer', '계약금 40%', 'system-seed', now()-interval '7 day'),
  ('pay-smf-0007-1','inv-smf-0007', 2640000, 'transfer', '계약금 40%(취소 전 납입)', 'system-seed', now()-interval '12 day')
ON CONFLICT (id) DO NOTHING;

-- 세금계산서(F083) 1건 — 완납 청구 inv-smf-0001 기반 -----------------------------------
INSERT INTO tax_invoice (tenant_id, id, invoice_id, event_id, tax_invoice_no,
                         supplier_name, supplier_biz_no, supplier_ceo, supplier_addr,
                         buyer_name, supply_amount, vat, total, item_summary, status, issued_by) VALUES
  ('KINTEX','tax-smf-0001','inv-smf-0001','e-2026-smf','TAX-2026-0001',
     '킨텍스(KINTEX)','128-81-00000','대표이사','경기도 고양시 일산서구 킨텍스로 217',
     '(주)스마트오토메이션', 18000000, 1800000, 19800000, '부스 임대료 외 (108㎡ · A-101)', 'issued', 'system-seed')
ON CONFLICT (id) DO NOTHING;

-- 환불(F085) 1건 — 취소 청구 inv-smf-0007 기준. base=실납입(2,640,000), 개막 D-일 구간 환불율 적용 ----
INSERT INTO invoice_refund (tenant_id, id, invoice_id, event_id, base_amount, refund_rate_percent,
                            refund_amount, forfeit_amount, days_before_event, bracket_label,
                            reason, ruleset_version, status, created_by) VALUES
  ('KINTEX','ref-smf-0007','inv-smf-0007','e-2026-smf', 2640000, 50.00,
     1320000, 1320000, (DATE '2026-08-11' - (CURRENT_DATE - 3)), '개막 30~15일 전(50%)',
     '참가 철회 — 환불 규정(refund-v1.0) 구간 적용', 'refund-v1.0', 'recorded', 'system-seed')
ON CONFLICT (id) DO NOTHING;


-- ============================================================================
-- 9. 전자결재 폐루프 — 문서 5 (demo-organizer 가 현재 단계 결재자 → 홈 '결재 대기' 활성화)
--    상태: SUBMITTED×2 · IN_PROGRESS×1 · APPROVED×1 · DRAFT×1
--    ★ approver 는 demo-organizer(결정론적). env 관리자(ADMIN)는 broad KPI(서류·미수·낙찰)로 별도 활성.
-- ============================================================================
INSERT INTO approval (tenant_id, id, event_id, doc_type, title, content, ref_type, ref_id,
                      drafter_id, drafter_name, status, cur_step, version, submitted_at, completed_at) VALUES
  ('KINTEX','ap-smf-01','e-2026-smf','GENERAL','부스 B-101 설계안 승인 요청','A-102 독립부스 최종 설계안(3.5m 높이) 승인 요청.','DOCUMENT','booth-smf-b101',
     'demo-exhibitor','데모 참가업체(김참가)','SUBMITTED',1,1, now()-interval '2 day', NULL),
  ('KINTEX','ap-smf-02','e-2026-smf','GENERAL','유틸리티 신청 승인 요청','전기·네트워크 유틸리티 신청 검토 승인 요청.','DOCUMENT','uo-smf-a102',
     'demo-exhibitor','데모 참가업체(김참가)','SUBMITTED',1,1, now()-interval '1 day', NULL),
  ('KINTEX','ap-smf-03','e-2026-smf','GENERAL','옥션 낙찰 결과 승인(AUC-0210)','C-10 통로 조명 공사 낙찰(세계전기시설) 결과 승인.','GENERAL',NULL,
     'demo-contractor','데모 공사업체(이시공)','IN_PROGRESS',2,1, now()-interval '3 day', NULL),
  ('KINTEX','ap-smf-04','e-2026-smf','GENERAL','재해대처계획서 검수 승인','재해대처계획서 최종본 검수 승인(완료).','DOCUMENT','disaster_plan',
     'demo-exhibitor','데모 참가업체(김참가)','APPROVED',1,1, now()-interval '5 day', now()-interval '4 day'),
  ('KINTEX','ap-smf-05','e-2026-smf','GENERAL','스폰서십 계약 품의(임시저장)','다이아몬드 스폰서 계약 품의 초안.','GENERAL',NULL,
     'demo-organizer','데모 주최자(홍길동)','DRAFT',0,1, NULL, NULL)
ON CONFLICT (id) DO NOTHING;

INSERT INTO approval_line (tenant_id, id, approval_id, step_no, approver_id, approver_name, line_status, acted_at, comment) VALUES
  -- ap-01: 1단계 CURRENT = demo-organizer
  ('KINTEX','al-smf-01-1','ap-smf-01',1,'demo-organizer','데모 주최자(홍길동)','CURRENT',NULL,NULL),
  -- ap-02: 1단계 CURRENT = demo-organizer
  ('KINTEX','al-smf-02-1','ap-smf-02',1,'demo-organizer','데모 주최자(홍길동)','CURRENT',NULL,NULL),
  -- ap-03: 1단계 APPROVED(demo-exhibitor) → 2단계 CURRENT = demo-organizer
  ('KINTEX','al-smf-03-1','ap-smf-03',1,'demo-exhibitor','데모 참가업체(김참가)','APPROVED', now()-interval '2 day','1차 확인 완료'),
  ('KINTEX','al-smf-03-2','ap-smf-03',2,'demo-organizer','데모 주최자(홍길동)','CURRENT',NULL,NULL),
  -- ap-04: 1단계 APPROVED(demo-organizer) → 종결
  ('KINTEX','al-smf-04-1','ap-smf-04',1,'demo-organizer','데모 주최자(홍길동)','APPROVED', now()-interval '4 day','검수 승인'),
  -- ap-05: DRAFT — 결재선 1단계 WAIT
  ('KINTEX','al-smf-05-1','ap-smf-05',1,'demo-organizer','데모 주최자(홍길동)','WAIT',NULL,NULL)
ON CONFLICT (tenant_id, id) DO NOTHING;

INSERT INTO approval_history (tenant_id, id, approval_id, step_no, actor_id, actor_name, action, comment, acted_at) VALUES
  ('KINTEX','ah-smf-01-1','ap-smf-01',1,'demo-exhibitor','데모 참가업체(김참가)','SUBMIT','설계안 상신', now()-interval '2 day'),
  ('KINTEX','ah-smf-02-1','ap-smf-02',1,'demo-exhibitor','데모 참가업체(김참가)','SUBMIT','유틸리티 신청 상신', now()-interval '1 day'),
  ('KINTEX','ah-smf-03-1','ap-smf-03',1,'demo-contractor','데모 공사업체(이시공)','SUBMIT','낙찰 승인 상신', now()-interval '3 day'),
  ('KINTEX','ah-smf-03-2','ap-smf-03',1,'demo-exhibitor','데모 참가업체(김참가)','APPROVE','1차 확인 완료', now()-interval '2 day'),
  ('KINTEX','ah-smf-04-1','ap-smf-04',1,'demo-exhibitor','데모 참가업체(김참가)','SUBMIT','계획서 검수 상신', now()-interval '5 day'),
  ('KINTEX','ah-smf-04-2','ap-smf-04',1,'demo-organizer','데모 주최자(홍길동)','APPROVE','검수 승인', now()-interval '4 day')
ON CONFLICT (tenant_id, id) DO NOTHING;


-- ============================================================================
-- 10. 공지(notice) 6 + 알림(notification) + 업무일지/일정(§5B)
-- ============================================================================
INSERT INTO notice (id, event_id, category, title, content, pinned, author_id, author_name, view_count, published_at) VALUES
  ('nt-smf-01','e-2026-smf','SYSTEM','[중요] 2026 스마트팩토리 코리아 반입 일정 안내','반입은 개막 D-2 09:00부터 가능합니다. 차량 등록 필수.', true, 'demo-organizer','데모 주최자(홍길동)', 342, now()-interval '5 day'),
  ('nt-smf-02','e-2026-smf','EVENT','참가업체 필수 서류 제출 마감 안내','재해대처계획서·리깅 구조계산서 마감이 임박했습니다. 기한 내 제출 바랍니다.', true, 'demo-organizer','데모 주최자(홍길동)', 288, now()-interval '3 day'),
  ('nt-smf-03','e-2026-smf','GENERAL','부스 장치공사 안전관리 지침','장치물 최고 높이 5m, 리깅 허용 6.5~8.5m 준수 바랍니다.', false, 'demo-organizer','데모 주최자(홍길동)', 156, now()-interval '2 day'),
  ('nt-smf-04','e-2026-smf','GENERAL','전기·네트워크 유틸리티 신청 마감 안내','유틸리티 신청은 개막 D-7까지 접수합니다.', false, 'demo-organizer','데모 주최자(홍길동)', 121, now()-interval '2 day'),
  ('nt-smf-05','e-2026-smf','EVENT','VIP 바이어 네트워킹 데이 안내','개막 2일차 오후 네트워킹 라운지 운영.', false, 'demo-organizer','데모 주최자(홍길동)', 98, now()-interval '1 day'),
  ('nt-smf-06',NULL,'SYSTEM','[시스템] 정기 점검 안내','매주 일요일 02:00~04:00 정기 점검이 진행됩니다.', false, 'demo-organizer','데모 주최자(홍길동)', 64, now()-interval '6 hour')
ON CONFLICT (id) DO NOTHING;

INSERT INTO notification (id, recipient_id, event_id, noti_type, title, message, link, read_at) VALUES
  ('no-smf-01','demo-organizer','e-2026-smf','APPROVAL','결재 대기 문서','부스 B-101 설계안 승인 요청이 도착했습니다.', '/work/approval', NULL),
  ('no-smf-02','demo-organizer','e-2026-smf','DEADLINE','서류 마감 임박','전기안전 재점검 확인서 마감 D-3.', '/docs', NULL),
  ('no-smf-03','demo-organizer','e-2026-smf','SYSTEM','옥션 낙찰 선정 대기','D-1 옥외 사이니지 설치 옥션 마감 — 낙찰 선정이 필요합니다.', '/auctions/AUC-2026-0511/award', NULL),
  ('no-smf-04','demo-contractor','e-2026-smf','DEADLINE','응찰 마감 임박','A-102 독립부스 시공 응찰 마감 D-2.', '/auctions/AUC-2026-0102', NULL),
  ('no-smf-05','demo-exhibitor','e-2026-smf','MESSAGE','부스 배정 확정','B-101 부스가 배정되었습니다.', '/booth-sales', now()-interval '1 day')
ON CONFLICT (id) DO NOTHING;

INSERT INTO worklog (id, event_id, writer_id, writer_name, dept_id, work_date, title, work_type, progress, status, content, hours) VALUES
  ('wl-smf-01','e-2026-smf','demo-organizer','데모 주최자(홍길동)','d-hall', CURRENT_DATE,     '홀 배치 확정 및 판매 오픈','OPERATION','P100','DONE','H7 데모 배치 12부스 판매 상태 설정 완료.', 4.0),
  ('wl-smf-02','e-2026-smf','demo-organizer','데모 주최자(홍길동)','d-hall', CURRENT_DATE-1,   '서류 검수 및 결재 상신','OPERATION','P75','DOING','필수 서류 검수 진행, 재해대처계획서 반려 후 재요청.', 3.5),
  ('wl-smf-03','e-2026-smf','demo-organizer','데모 주최자(홍길동)','d-hall', CURRENT_DATE-2,   '옥션 3건 응찰 현황 점검','OPERATION','P50','DOING','AUC-0102/0405/0210 응찰 모니터링.', 2.5)
ON CONFLICT (id) DO NOTHING;

INSERT INTO schedule (id, event_id, owner_id, owner_name, dept_id, title, schedule_type, importance, start_at, end_at, all_day, location, content) VALUES
  ('sc-smf-01','e-2026-smf','demo-organizer','데모 주최자(홍길동)','d-hall','주최자 운영 회의','TEAM','HIGH', now()+interval '1 day', now()+interval '1 day 1 hour', false, '킨텍스 제1전시장 회의실', '개막 준비 점검 회의'),
  ('sc-smf-02','e-2026-smf','demo-organizer','데모 주최자(홍길동)','d-hall','옥션 낙찰 선정','EVENT','URGENT', now()+interval '2 hour', now()+interval '3 hour', false, '온라인', 'AUC-2026-0511 낙찰 선정'),
  ('sc-smf-03','e-2026-smf','demo-organizer','데모 주최자(홍길동)','d-hall','반입 리허설','EVENT','NORMAL', now()+interval '5 day', now()+interval '5 day 4 hour', false, '킨텍스 제2전시장 H7', '반입 동선 리허설')
ON CONFLICT (id) DO NOTHING;

-- ============================================================================
-- 검증 쿼리(수동 실행용 — 마이그레이션에는 포함되지 않는 주석):
--   -- 데모 계정: SELECT id,email,role_code,otp_enabled FROM app_user WHERE email LIKE '%@kintex.test';
--   -- demo-organizer 결재대기: SELECT count(*) FROM approval_line al JOIN approval a ON a.id=al.approval_id
--   --   WHERE al.approver_id='demo-organizer' AND al.line_status='CURRENT' AND a.status IN('SUBMITTED','IN_PROGRESS'); -- 기대 3
--   -- 서류 D-7 이내 미승인: SELECT count(*) FROM required_document WHERE event_id='e-2026-smf'
--   --   AND status<>'approved' AND due_date IS NOT NULL AND due_date<=CURRENT_DATE+7; -- >=1 (doc-smf-reinspect)
--   -- 낙찰 미확정 마감경과 옥션: SELECT count(*) FROM auction a WHERE a.deadline<now()
--   --   AND NOT EXISTS(SELECT 1 FROM award w WHERE w.auction_id=a.id); -- >=1 (AUC-2026-0511)
--   -- 오늘 체크인: SELECT count(*) FROM visitor_registration WHERE checkin_at::date=CURRENT_DATE; -- 5
--   -- 미수 청구: SELECT count(*) FROM invoice i JOIN event e ON e.id=i.event_id
--   --   WHERE e.tenant_id='KINTEX' AND i.status IN('pending','overdue'); -- >=3
--   -- 부스 판매분포: SELECT status,count(*) FROM booth_sale WHERE event_id='e-2026-smf' GROUP BY status;
--   -- 리드 15/핫4: SELECT count(*), count(*) FILTER(WHERE score>=80) FROM lead WHERE event_id='e-2026-smf';
-- ============================================================================

-- 신규 company 행 company_name 정합(V37 이 name→company_name 백필하나 본 파일 신규행은 V37 이후 삽입되므로 재백필).
UPDATE company SET company_name = name    WHERE company_name IS NULL AND name IS NOT NULL;
UPDATE company SET biz_no       = registration_no WHERE biz_no IS NULL AND registration_no IS NOT NULL;
UPDATE company SET contact_tel  = phone   WHERE contact_tel IS NULL AND phone IS NOT NULL;
