forked from kjung0109/paytrace-mvp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2021 lines (1776 loc) · 69.1 KB
/
script.js
File metadata and controls
2021 lines (1776 loc) · 69.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* PayScore MVP prototype (vanilla JS)
- P0-only UI behaviors
- Local "server" simulation for matching + scoring
*/
const RULES = {
rentWarningRange: { min: 50_000, max: 5_000_000 }, // FE 경고(제출 허용)
matchRuleRange: { min: 50_000, max: 5_000_000 }, // 서버 판정용(고정 룰셋)
ruleVersionMatch: "ref-rule-set-v1",
ruleVersionScore: "payscore-rule-v1",
};
const PRODUCT_DATA = {
SPROUT: [ // 새싹 납부러 (0~40점)
{
type: "카드",
name: "KB국민 체크-신용 하이브리드",
desc: "체크카드에 신용 기능을 더하다",
url: "https://m.kbcard.com/SVC/DVIEW/MSCMCXHIASVC0010"
},
{
type: "대출",
name: "서민금융진흥원 햇살론유스",
desc: "청년층의 자금애로 해소",
url: "https://www.kinfa.or.kr/financialProduct/hessalLoanYoos.do"
},
{
type: "대출",
name: "우리은행 WON Easy 생활비 대출",
desc: "소액 생활자금 필요시 간편하게",
url: "https://spot.wooribank.com/pot/Dream?withyou=POLON0052&cc=c010528:c010531;c012425:c012399&PRD_CD=P020006604"
},
{
type: "카드",
name: "신한카드 처음(First)",
desc: "첫 출발을 위한 맞춤 혜택",
url: "https://www.shinhancard.com/pconts/html/card/apply/credit/1227020_2207.html"
}
],
SINCERE: [ // 성실 납부러 (41~70점)
{
type: "대출",
name: "카카오뱅크 비상금대출",
desc: "휴대폰 본인인증만으로 간편한 대출",
url: "https://www.kakaobank.com/products/emergencyLoan"
},
{
type: "카드",
name: "현대카드 ZERO Edition3 (할인형)",
desc: "조건 없는 무제한 할인 혜택",
url: "https://www.hyundaicard.com/cpc/cr/CPCCR0201_01.hc?cardWcd=ZROE3"
},
{
type: "카드",
name: "삼성카드 taptap O",
desc: "내 라이프스타일에 맞춘 맞춤형 카드",
url: "https://www.samsungcard.com/home/card/cardinfo/PGHPPCCCardCardinfoDetails001?code=AAP1483"
},
{
type: "카드",
name: "신한카드 Deep Dream",
desc: "전월 실적 조건 없는 기본 적립",
url: "https://www.shinhancard.com/pconts/html/card/apply/credit/1188220_2207.html"
}
],
MASTER: [ // 마스터 납부러 (71~100점)
{
type: "대출",
name: "햇살론뱅크",
desc: "성실 상환자를 위한 징검다리 대출",
url: "https://www.kinfa.or.kr/financialProduct/hessalLoanBank.do"
},
{
type: "카드",
name: "신한카드 Mr.Life",
desc: "공과금 및 생활비 밀착형 할인",
url: "https://www.shinhancard.com/pconts/html/card/apply/credit/1187937_2207.html"
},
{
type: "카드",
name: "KB국민 청춘대로 톡톡",
desc: "온라인 쇼핑부터 음식점까지 할인",
url: "https://card.kbcard.com/CRD/DVIEW/HCAMCXPRICAC0076?cooperationcode=09174&mainCC=a"
},
{
type: "대출",
name: "토스뱅크 마이너스통장",
desc: "필요할 때 쓰고 이자만 내세요",
url: "https://www.tossbank.com/product-service/loans/minus-account"
}
]
};
const REASON_TEXT = {
RENT_OUT_OF_RANGE: "월세 금액이 기준 범위를 벗어나 추가 확인이 필요합니다.",
MGMT_OUT_OF_RANGE: "관리비 금액이 기준 범위를 벗어나 추가 확인이 필요합니다.",
INSUFFICIENT_MONTHS: "납부 개월 수가 부족해 산출할 수 없습니다.",
NO_RENT_ITEM: "월세 항목이 없어 산출할 수 없습니다.",
INVALID_AMOUNT: "금액 정보가 유효하지 않아 산출할 수 없습니다.",
};
const FIXED_TYPES = [
{ key: "OTT", label: "OTT" },
{ key: "MUSIC", label: "음악 스트리밍" },
{ key: "EBOOK", label: "전자책 구독" },
];
const state = {
sessionId: cryptoRandomId("sess"),
utm: parseUtmParams(),
lastContractPayload: null,
selectionId: null,
match: null,
selection: null,
score: { status: "IDLE", result: null, reason_code: null },
report: { inProgress: false, completed: false, reportId: null, email: null, loggedComplete: false },
ui: { lastScoreClickAt: 0 },
events: [],
};
document.addEventListener("DOMContentLoaded", () => {
bindLanding();
bindForm();
bindMatch();
bindErrorScreens();
bindScore();
bindReportFail();
bindReportSendFail();
bindReportComplete();
bindReportPreview();
bindPdfPreview();
bindModals();
bindToast();
setView("landing");
logEvent("landing_view", {
timestamp: new Date().toISOString(),
session_id: state.sessionId,
utm: state.utm,
});
});
function $(id) {
return document.getElementById(id);
}
function setView(name) {
const views = [
"landing",
"form",
"match",
"error-server",
"error-timeout",
"score-loading",
"score",
"report-processing",
"report-fail",
"report-send-fail",
"report-complete",
"report-preview",
"pdf-preview",
];
for (const v of views) {
const el = $(`view-${v}`);
if (!el) continue;
el.classList.toggle("hidden", v !== name);
}
window.scrollTo({ top: 0, behavior: "auto" });
// Log view change as a generic event
logEvent("view_change", {
view_name: name,
session_id: state.sessionId,
timestamp: new Date().toISOString()
});
// Track standard GA4 view_item for major funnel steps
if (name === "score") {
logEvent("view_item", {
item_id: "report_summary",
item_name: "PayScore Summary",
item_category: "report"
});
} else if (name === "report-preview") {
logEvent("view_item", {
item_id: "report_full",
item_name: "PayScore Full Report",
item_category: "report"
});
// ✨ 금융상품 추천 페이지 진입 시에만 상품 목록 조회 이벤트 발생
const res = state.score.result;
if (res?.scorable) {
let category = "SPROUT";
if (res.payscore >= 71) category = "MASTER";
else if (res.payscore >= 41) category = "SINCERE";
const products = PRODUCT_DATA[category];
logEvent("view_item_list", {
item_list_id: "financial_recommendations",
item_list_name: `Recommendations for ${category}`,
items: products.map(p => ({
item_name: p.name,
item_category: p.type
}))
});
}
}
}
function logEvent(name, payload) {
const evt = { name, ...payload };
state.events.push(evt);
// Debug log
console.log("[event]", evt);
// Send to GA4
if (typeof gtag === 'function') {
// 1. Map to Standard Recommended Events where applicable
let gaName = name;
let gaPayload = { ...payload };
switch (name) {
case "contact_submit":
gaName = "generate_lead";
// lead name/email are excluded for privacy
break;
case "pdf_share_success":
gaName = "share";
gaPayload.method = payload.type || "unknown"; // "file" or "url"
gaPayload.content_type = "pdf_report";
gaPayload.item_id = state.report.reportId;
break;
case "pdf_download_click":
gaName = "file_download";
gaPayload.file_extension = "pdf";
gaPayload.file_name = "Paytrace_Report.pdf";
break;
case "recommendation_click":
gaName = "select_item";
gaPayload.item_list_id = "financial_recommendations";
gaPayload.items = [{
item_name: payload.product_name,
item_category: payload.product_type
}];
break;
case "landing_to_start_click":
gaName = "select_content";
gaPayload.content_type = "button";
gaPayload.content_id = "btn-start";
break;
}
// 2. Send the event (either original or mapped)
gtag('event', gaName, gaPayload);
}
}
function bindLanding() {
$("btn-start").addEventListener("click", () => {
logEvent("landing_to_start_click", { session_id: state.sessionId, timestamp: new Date().toISOString() });
setView("form");
updateContractSubmitButton();
});
}
function bindForm() {
const form = $("contract-form");
$("startDate").addEventListener("change", onContractDatesChanged);
$("endDate").addEventListener("change", onContractDatesChanged);
$("rentAmount").addEventListener("input", (e) => {
e.target.value = digitsOnly(e.target.value);
renderRentWarning();
});
for (const radio of document.querySelectorAll('input[name="mgmtIncluded"]')) {
radio.addEventListener("change", onMgmtIncludedChanged);
}
$("mgmtAmount").addEventListener("input", (e) => {
e.target.value = digitsOnly(e.target.value);
});
for (const cb of document.querySelectorAll('input[name="fixedType"]')) {
cb.addEventListener("change", () => {
const wrap = $(`fixed-${cb.value}`);
wrap.classList.toggle("hidden", !cb.checked);
const label = cb.closest("label");
if (label) label.classList.toggle("is-checked", cb.checked);
if (cb.checked) ensureFixedHasRow(cb.value);
// 선택 해제 시 입력값 유지(요구사항 없음) — 단, 재제출 시 미선택이면 서버에 포함되지 않음.
});
}
bindFixedRowsInteraction();
form.addEventListener("input", updateContractSubmitButton);
form.addEventListener("change", updateContractSubmitButton);
updateContractSubmitButton();
const formBack = $("btn-form-back");
if (formBack) formBack.addEventListener("click", () => setView("landing"));
form.addEventListener("submit", async (e) => {
e.preventDefault();
clearAllFieldErrors();
const payload = buildContractPayload();
state.lastContractPayload = payload;
const { errors, firstErrorId, firstErrorEl } = validateContractPayload(payload);
if (Object.keys(errors).length > 0) {
showFieldErrors(errors);
if (firstErrorEl) {
scrollToFirstErrorEl(firstErrorEl);
} else {
scrollToFirstError(firstErrorId);
}
return;
}
if (firstErrorEl) {
// 고정비 행 에러 등(필드 맵 외)
scrollToFirstErrorEl(firstErrorEl);
return;
}
setSubmitLoading(true);
try {
const res = await withTimeout(simulateContractSubmit(payload), 6000);
state.match = { status: res.status, reasonCodes: res.reasonCodes, rule_version: res.rule_version };
state.selection = res.selection;
state.selectionId = res.selection_id;
renderMatchResult();
setView("match");
} catch (err) {
const now = new Date().toISOString();
if (err && err.code === "TIMEOUT") {
$("err-timeout-time").textContent = now;
setView("error-timeout");
} else {
$("err-server-time").textContent = now;
setView("error-server");
}
} finally {
setSubmitLoading(false);
}
});
}
function bindFixedRowsInteraction() {
const view = $("view-form");
if (!view) return;
// add/delete row
view.addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (!btn) return;
const action = btn.dataset.action;
const type = btn.dataset.fixedType;
if (!action || !type) return;
if (action === "add-row") {
addFixedRow(type);
}
if (action === "del-row") {
const row = btn.closest(".fixed-row");
if (!row) return;
removeFixedRow(type, row);
}
});
// digits-only for dynamic inputs
view.addEventListener("input", (e) => {
const input = e.target;
if (!(input instanceof HTMLInputElement)) return;
if (!input.matches('input[data-fixed-field="amount"], input[data-fixed-field="months"]')) return;
input.value = digitsOnly(input.value);
});
}
function getFixedRowsContainer(type) {
return document.querySelector(`.fixed-rows[data-fixed-type="${type}"]`);
}
function ensureFixedHasRow(type) {
const container = getFixedRowsContainer(type);
if (!container) return;
if (container.querySelectorAll(".fixed-row").length === 0) {
addFixedRow(type);
} else {
updateFixedRowDeleteButtons(type);
}
}
function addFixedRow(type) {
const container = getFixedRowsContainer(type);
if (!container) return;
const row = document.createElement("div");
row.className = "fixed-row";
row.dataset.fixedType = type;
row.innerHTML = `
<div class="input-suffix">
<input type="text" inputmode="numeric" autocomplete="off" placeholder="0" data-fixed-type="${escapeHtml(
type,
)}" data-fixed-field="amount" />
<span class="suffix" aria-hidden="true">원</span>
</div>
<div class="input-suffix">
<input type="text" inputmode="numeric" autocomplete="off" placeholder="0" data-fixed-type="${escapeHtml(
type,
)}" data-fixed-field="months" />
<span class="suffix" aria-hidden="true">개월</span>
</div>
<button type="button" class="btn-del-row" data-action="del-row" data-fixed-type="${escapeHtml(
type,
)}" aria-label="행 삭제">×</button>
<p class="row-error error" role="alert" aria-live="polite"></p>
`;
container.appendChild(row);
updateFixedRowDeleteButtons(type);
}
function removeFixedRow(type, rowEl) {
const container = getFixedRowsContainer(type);
if (!container) return;
const rows = Array.from(container.querySelectorAll(".fixed-row"));
if (rows.length <= 1) return; // 최소 1행 유지(선택 상태에서 빈 값 방지)
rowEl.remove();
updateFixedRowDeleteButtons(type);
}
function updateFixedRowDeleteButtons(type) {
const container = getFixedRowsContainer(type);
if (!container) return;
const rows = Array.from(container.querySelectorAll(".fixed-row"));
const disable = rows.length <= 1;
for (const row of rows) {
const btn = row.querySelector(".btn-del-row");
if (btn) btn.disabled = disable;
}
}
function scrollToFirstErrorEl(el) {
if (!el) return;
const top = el.getBoundingClientRect().top + window.scrollY - 90;
window.scrollTo({ top, behavior: "smooth" });
try {
el.focus?.({ preventScroll: true });
} catch {
// ignore
}
}
function bindMatch() {
const matchBack = $("btn-match-back");
if (matchBack) matchBack.addEventListener("click", () => {
setView("form");
updateContractSubmitButton();
});
$("btn-to-score").addEventListener("click", () => {
renderSelectionTable();
renderScoreState("IDLE");
setReportButtonEnabled(false);
setView("score");
});
const editBtn = $("btn-edit-input");
if (editBtn) {
editBtn.addEventListener("click", () => {
setView("form");
updateContractSubmitButton();
// 기존 입력값은 DOM에 유지됨 (요구사항: 입력값 유지)
});
}
}
function bindErrorScreens() {
$("btn-back-to-form-1").addEventListener("click", () => {
setView("form");
updateContractSubmitButton();
});
$("btn-back-to-form-2").addEventListener("click", () => {
setView("form");
updateContractSubmitButton();
});
$("btn-retry-server").addEventListener("click", async () => retryContractSubmit());
$("btn-retry-timeout").addEventListener("click", async () => retryContractSubmit());
const top1 = $("btn-error-topbar-1");
if (top1) top1.addEventListener("click", () => {
setView("form");
updateContractSubmitButton();
});
const top2 = $("btn-error-topbar-2");
if (top2) top2.addEventListener("click", () => {
setView("form");
updateContractSubmitButton();
});
}
async function retryContractSubmit() {
if (!state.lastContractPayload) {
setView("form");
updateContractSubmitButton();
return;
}
setSubmitLoading(true);
try {
const res = await withTimeout(simulateContractSubmit(state.lastContractPayload), 6000);
state.match = { status: res.status, reasonCodes: res.reasonCodes, rule_version: res.rule_version };
state.selection = res.selection;
state.selectionId = res.selection_id;
renderMatchResult();
setView("match");
} catch (err) {
const now = new Date().toISOString();
if (err && err.code === "TIMEOUT") {
$("err-timeout-time").textContent = now;
setView("error-timeout");
} else {
$("err-server-time").textContent = now;
setView("error-server");
}
} finally {
setSubmitLoading(false);
}
}
function bindScore() {
$("btn-score").addEventListener("click", async () => {
const now = Date.now();
if (now - state.ui.lastScoreClickAt < 3000) {
// 3초 이내 연속 클릭 차단
return;
}
state.ui.lastScoreClickAt = now;
$("btn-score").disabled = true;
// 로딩 화면으로 전환(우정인_PayScore 계산 중)
renderSelectionTable();
renderScoreState("LOADING");
setReportButtonEnabled(false);
setView("score-loading");
logEvent("score_cta_click", {
session_id: state.sessionId,
selection_id: state.selectionId,
rule_version: RULES.ruleVersionScore,
timestamp: new Date().toISOString(),
});
try {
const res = await withTimeout(
simulateScoreRangeApi({ session_id: state.sessionId, selection_id: state.selectionId }),
7000,
);
// 리포트 ID 생성 (한 번만)
const reportId = cryptoRandomId("PT").toUpperCase().replace(/_/g, "-");
const reportDate = new Date().toLocaleDateString("ko-KR", {
year: "numeric",
month: "long",
day: "numeric"
});
state.score = {
status: "SUCCESS",
result: res,
reason_code: res.reason_code ?? null,
reportId: reportId,
reportDate: reportDate
};
setView("score");
renderScoreState("SUCCESS");
setReportButtonEnabled(res.scorable === true);
logEvent("score_result_success", {
session_id: state.sessionId,
selection_id: state.selectionId,
rule_version: res.rule_version,
timestamp: new Date().toISOString(),
reason_code: res.reason_code ?? null,
});
} catch (err) {
const reason = err?.reason_code ?? null;
state.score = { status: "FAIL", result: null, reason_code: reason };
setView("score");
renderScoreState("FAIL");
setReportButtonEnabled(false);
logEvent("score_result_fail", {
session_id: state.sessionId,
selection_id: state.selectionId,
rule_version: RULES.ruleVersionScore,
timestamp: new Date().toISOString(),
reason_code: reason,
});
} finally {
$("btn-score").disabled = false;
}
});
$("btn-report").addEventListener("click", () => {
if (state.score.status !== "SUCCESS" || state.score.result?.scorable !== true) return;
if (state.report.inProgress || state.report.completed) return;
logEvent("report_cta_click", {
session_id: state.sessionId,
selection_id: state.selectionId,
rule_version: state.score.result?.rule_version ?? RULES.ruleVersionScore,
timestamp: new Date().toISOString(),
reason_code: state.score.result?.reason_code ?? null,
});
openContactModal();
});
const scoreBack = $("btn-score-back");
if (scoreBack) scoreBack.addEventListener("click", () => setView("match"));
}
function bindModals() {
$("btn-close-contact").addEventListener("click", closeAllModals);
$("btn-open-terms").addEventListener("click", () => openTermsModal());
$("btn-close-terms").addEventListener("click", closeTermsAndReturnToContact);
$("btn-terms-ok").addEventListener("click", closeTermsAndReturnToContact);
$("btn-open-criteria").addEventListener("click", () => openCriteriaModal());
$("btn-close-criteria").addEventListener("click", closeAllModals);
$("btn-criteria-ok").addEventListener("click", closeAllModals);
$("contactName").addEventListener("input", validateContactForm);
$("contactEmail").addEventListener("input", validateContactForm);
$("consentRequired").addEventListener("change", validateContactForm);
$("btn-contact-submit").addEventListener("click", async () => {
clearContactErrors();
const name = $("contactName").value.trim();
const email = $("contactEmail").value.trim();
const consent = $("consentRequired").checked;
const errors = {};
if (!name) errors.contactName = "이름을 입력해 주세요";
if (!email || !isValidEmail(email)) errors.contactEmail = "이메일 형식을 확인해 주세요";
if (!consent) {
// 제출 버튼 자체가 비활성이라 일반적으로 도달하지 않음
}
if (Object.keys(errors).length > 0) {
showContactErrors(errors);
return;
}
// "저장"은 로컬 모사: reportId 생성, 이벤트 로깅(개인정보는 이벤트에 포함하지 않음)
state.report.reportId = cryptoRandomId("rpt");
state.report.email = email;
closeAllModals();
logEvent("contact_submit", {
session_id: state.sessionId,
selection_id: state.selectionId,
report_id: state.report.reportId,
timestamp: new Date().toISOString(),
});
await startReportProcessing();
});
}
function bindReportFail() {
const back = $("btn-report-fail-back");
if (back) back.addEventListener("click", () => setView("score"));
const retry = $("btn-report-retry");
if (retry) retry.addEventListener("click", () => startReportProcessing());
const cancel = $("btn-report-cancel");
if (cancel) cancel.addEventListener("click", () => setView("score"));
}
function bindReportSendFail() {
const toStart = $("btn-report-send-fail-to-start");
if (toStart) toStart.addEventListener("click", () => setView("landing"));
}
function bindReportComplete() {
const guide = $("btn-report-guide");
if (guide) guide.addEventListener("click", () => {
renderReportPreview();
setView("report-preview");
});
const toStart = $("btn-report-to-start");
if (toStart) toStart.addEventListener("click", () => setView("landing"));
}
function bindReportPreview() {
const back = $("btn-report-preview-back");
if (back) back.addEventListener("click", () => setView("report-complete"));
const share = $("btn-report-share");
if (share) {
share.addEventListener("click", async () => {
const score = state.score.result?.payscore || 0;
const text = `[Paytrace] 내 PayScore는 ${score}점입니다. 리포트를 확인해보세요!`;
const url = window.location.href;
if (navigator.share) {
try {
await navigator.share({
title: "PayScore 리포트",
text: text,
url: url,
});
} catch (err) {
// share cancel or fail
console.log("Share skipped", err);
}
} else {
try {
await navigator.clipboard.writeText(url);
alert("링크가 복사되었습니다.");
} catch (e) {
alert("브라우저가 공유 기능을 지원하지 않습니다.");
}
}
});
}
const download = $("btn-report-download");
if (download) download.addEventListener("click", () => {
renderPdfPreview();
setView("pdf-preview");
});
}
async function handlePdfShare() {
const payload = state.lastContractPayload;
const res = state.score?.result;
if (!payload || !res || !res.scorable) {
showToast("데이터가 부족하여 PDF를 공유할 수 없습니다.");
return;
}
const btn = $("btn-report-share");
if (btn) btn.disabled = true;
showToast("공유용 PDF를 생성하고 있습니다...");
logEvent("pdf_share_click", {
session_id: state.sessionId,
payscore: res.payscore,
timestamp: new Date().toISOString()
});
try {
const file = await createPdfFile();
if (!file) throw new Error("PDF 생성 실패");
const score = state.score.result?.payscore || 0;
const text = `[Paytrace] 내 PayScore는 ${score}점입니다. 리포트를 확인해보세요!`;
if (navigator.canShare && navigator.canShare({ files: [file] })) {
await navigator.share({
files: [file],
title: "PayScore 리포트",
text: text,
});
logEvent("pdf_share_success", { type: "file", session_id: state.sessionId });
} else {
await navigator.share({
title: "PayScore 리포트",
text: text,
url: window.location.href,
});
logEvent("pdf_share_success", { type: "url_fallback", session_id: state.sessionId });
}
} catch (err) {
if (err.name !== "AbortError") {
console.error("Share failed", err);
showToast("공유하기를 실행할 수 없습니다.");
logEvent("pdf_share_error", { error: err.message, session_id: state.sessionId });
} else {
logEvent("pdf_share_cancel", { session_id: state.sessionId });
}
} finally {
if (btn) btn.disabled = false;
}
}
async function createPdfFile() {
updatePdfPreviewIframe();
const iframe = $("pdf-preview-iframe");
if (!iframe) return null;
await new Promise((resolve) => {
if (iframe.contentDocument && iframe.contentDocument.readyState === "complete") {
resolve();
} else {
iframe.onload = () => resolve();
}
});
await sleep(1200);
const doc = iframe.contentDocument || iframe.contentWindow.document;
const element = doc.querySelector(".doc");
if (!element) return null;
try {
const opt = {
margin: 0,
filename: "Paytrace_Report.pdf",
image: { type: "jpeg", quality: 0.98 },
html2canvas: {
scale: 2,
useCORS: true,
logging: false,
backgroundColor: "#ffffff",
},
jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
};
const blob = await html2pdf().set(opt).from(element).output("blob");
return new File([blob], "Paytrace_Report.pdf", { type: "application/pdf" });
} catch (e) {
console.error("PDF Blob generation failed", e);
return null;
}
}
function renderReportPreview() {
const res = state.score.result;
const badgeEl = $("report-preview-badge");
const scoreEl = $("report-preview-score");
const niceEl = $("report-preview-nice");
const kcbEl = $("report-preview-kcb");
const basisEl = $("report-preview-product-basis");
const productListEl = $("report-preview-products");
if (!res?.scorable) {
if (badgeEl) badgeEl.textContent = "-";
if (scoreEl) scoreEl.textContent = "-";
if (niceEl) niceEl.textContent = "-";
if (kcbEl) kcbEl.textContent = "-";
if (basisEl) basisEl.textContent = "PayScore -점 기준 추천";
if (productListEl) productListEl.innerHTML = "";
return;
}
const cr = res.credit_score_increase;
const niceText = cr && Number.isInteger(cr.min) && Number.isInteger(cr.max) ? `+${cr.min}~${cr.max}점` : "-";
if (badgeEl) badgeEl.textContent = getScoreBadgeLabel(res.payscore);
if (scoreEl) scoreEl.textContent = String(res.payscore);
if (niceEl) niceEl.textContent = niceText;
if (kcbEl) kcbEl.textContent = niceText;
if (basisEl) basisEl.textContent = `PayScore ${res.payscore}점 기준 추천`;
// 추천 상품 렌더링
if (productListEl) {
let category = "SPROUT";
if (res.payscore >= 71) category = "MASTER";
else if (res.payscore >= 41) category = "SINCERE";
const products = PRODUCT_DATA[category];
productListEl.innerHTML = products.map(p => `
<div class="report-preview-product-card">
<span class="report-preview-product-type">${escapeHtml(p.type)}</span>
<h4 class="report-preview-product-name">${escapeHtml(p.name)}</h4>
<p class="report-preview-product-desc">${escapeHtml(p.desc)}</p>
<a href="${p.url}" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-sm"
onclick="logEvent('recommendation_click', { product_name: '${escapeHtml(p.name)}', product_type: '${escapeHtml(p.type)}' })">상세보기</a>
</div>
`).join("");
}
}
function bindPdfPreview() {
const back = $("btn-pdf-preview-back");
if (back) back.addEventListener("click", () => setView("report-preview"));
const download = $("btn-pdf-download");
if (download) {
download.addEventListener("click", handlePdfDownload);
}
}
function renderPdfPreview() {
const payload = state.lastContractPayload;
const res = state.score?.result;
const tendencyEl = $("pdf-preview-tendency");
const scoreNumEl = $("pdf-preview-score-num");
const badgeEl = $("pdf-preview-badge");
const creditHintEl = $("pdf-preview-credit-hint");
const contractSummaryEl = $("pdf-preview-contract-summary");
const months = payload ? calcContractMonths(payload.startDate, payload.endDate) : null;
const monthText = months != null ? `${months}개월` : "-";
if (tendencyEl) tendencyEl.textContent = `귀하는 ${monthText} 이력을 보유하고 있습니다.`;
if (res?.scorable) {
if (scoreNumEl) scoreNumEl.textContent = String(res.payscore);
if (badgeEl) badgeEl.textContent = getScoreBadgeLabel(res.payscore);
const cr = res.credit_score_increase;
const hintText = cr && Number.isInteger(cr.min) && Number.isInteger(cr.max) ? `예상 상승 +${cr.min}~${cr.max}점 내외` : "예상 상승 -";
if (creditHintEl) creditHintEl.textContent = hintText;
} else {
if (scoreNumEl) scoreNumEl.textContent = "-";
if (badgeEl) badgeEl.textContent = "-";
if (creditHintEl) creditHintEl.textContent = "예상 상승 -";
}
if (contractSummaryEl && payload) {
const periodStr =
payload.startDate && payload.endDate && months != null
? `${payload.startDate} ~ ${payload.endDate} (${months}개월)`
: "-";
const rentStr = formatWon(payload.rentAmount);
const mgmtStr = payload.mgmtIncluded === true ? `포함 (${formatWon(payload.mgmtAmount)})` : "미포함";
contractSummaryEl.innerHTML = `
<div class="pdf-preview-summary-row"><span class="k">계약 기간</span><span class="v">${escapeHtml(periodStr)}</span></div>
<div class="pdf-preview-summary-row"><span class="k">월세 금액</span><span class="v">${escapeHtml(rentStr)}</span></div>
<div class="pdf-preview-summary-row"><span class="k">관리비</span><span class="v">${escapeHtml(mgmtStr)}</span></div>
`;
} else if (contractSummaryEl) {
contractSummaryEl.innerHTML = "";
}
// ✨ PDF iframe 업데이트
updatePdfPreviewIframe();
}
function bindToast() {
$("btn-toast-close").addEventListener("click", hideToast);
}
function openContactModal() {
$("contactName").value = "";
$("contactEmail").value = "";
$("consentRequired").checked = false;
const opt = $("consentOptional");
if (opt) opt.checked = false;
clearContactErrors();
validateContactForm();
showModal("modal-contact");
$("contactName").focus();
}
function openTermsModal() {
showModal("modal-terms");
$("btn-terms-ok").focus();
}
function openCriteriaModal() {
showModal("modal-criteria");
$("btn-criteria-ok").focus();
}
function showModal(id) {
$("modal-backdrop").classList.remove("hidden");
$("modal-backdrop").setAttribute("aria-hidden", "false");
$(id).classList.remove("hidden");
}
function closeAllModals() {
$("modal-backdrop").classList.add("hidden");
$("modal-backdrop").setAttribute("aria-hidden", "true");
$("modal-contact").classList.add("hidden");
$("modal-terms").classList.add("hidden");
$("modal-criteria").classList.add("hidden");
}
/** 개인정보 수집·이용 동의 모달에서 확인/닫기 시 이메일 입력 모달로 복귀 */
function closeTermsAndReturnToContact() {
$("modal-terms").classList.add("hidden");
const contact = $("modal-contact");
if (contact && !contact.classList.contains("hidden")) {
const nameEl = $("contactName");
if (nameEl) nameEl.focus();
}
}
function validateContactForm() {
const nameOk = $("contactName").value.trim().length > 0;
const email = $("contactEmail").value.trim();
const emailOk = email.length > 0 && isValidEmail(email);
const consentOk = $("consentRequired").checked;
$("btn-contact-submit").disabled = !(nameOk && emailOk && consentOk);
}
async function startReportProcessing() {
state.report.inProgress = true;
setView("report-processing");
hideToast();
setProgressPct(0);
const steps = [0, 33, 66]; // 100%는 성공 응답 시점에만