-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecommand-test.html
More file actions
1119 lines (949 loc) · 41.4 KB
/
recommand-test.html
File metadata and controls
1119 lines (949 loc) · 41.4 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
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>가구 추천 알림 시스템 테스트</title>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
max-width: 900px;
width: 100%;
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 28px;
margin-bottom: 10px;
}
.header p {
opacity: 0.9;
font-size: 14px;
}
.content {
padding: 30px;
}
.section {
margin-bottom: 30px;
}
.section h2 {
color: #333;
margin-bottom: 15px;
font-size: 20px;
border-bottom: 2px solid #667eea;
padding-bottom: 10px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: 500;
}
input, select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus, select:focus {
outline: none;
border-color: #667eea;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px 30px;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
margin-right: 10px;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
}
button:disabled {
background: #ccc;
cursor: not-allowed;
transform: none;
}
.status {
padding: 15px;
border-radius: 8px;
margin-bottom: 15px;
font-weight: 500;
}
.status.disconnected {
background: #ffebee;
color: #c62828;
border-left: 4px solid #c62828;
}
.status.connected {
background: #e8f5e9;
color: #2e7d32;
border-left: 4px solid #2e7d32;
}
.notifications {
max-height: 400px;
overflow-y: auto;
border: 2px solid #e0e0e0;
border-radius: 8px;
padding: 15px;
background: #f9f9f9;
}
.notification-item {
background: white;
padding: 15px;
border-radius: 8px;
margin-bottom: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
animation: slideIn 0.3s ease-out;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.notification-item.success {
border-left: 4px solid #4caf50;
}
.notification-item.failed {
border-left: 4px solid #f44336;
}
.notification-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.notification-type {
font-weight: 600;
color: #333;
}
.notification-time {
font-size: 12px;
color: #999;
}
.notification-body {
color: #555;
font-size: 14px;
line-height: 1.6;
}
.notification-body strong {
color: #333;
}
.logs {
background: #263238;
color: #aed581;
padding: 15px;
border-radius: 8px;
max-height: 300px;
overflow-y: auto;
font-family: 'Courier New', monospace;
font-size: 12px;
line-height: 1.5;
}
.log-entry {
margin-bottom: 5px;
}
.log-entry .timestamp {
color: #80deea;
}
.log-entry .level-info {
color: #4fc3f7;
}
.log-entry .level-success {
color: #66bb6a;
}
.log-entry .level-error {
color: #ef5350;
}
.log-entry .level-warn {
color: #ffca28;
}
.button-group {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.user-info {
background: #f5f5f5;
padding: 15px;
border-radius: 8px;
margin-bottom: 15px;
}
.user-info p {
margin-bottom: 5px;
color: #555;
}
.user-info strong {
color: #333;
}
/* 추천 결과 카드 스타일 */
.recommendation-container {
background: #f9f9f9;
padding: 20px;
border-radius: 12px;
margin-top: 20px;
}
.room-analysis {
background: white;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.room-analysis h3 {
color: #667eea;
margin-bottom: 10px;
font-size: 16px;
}
.analysis-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 15px;
margin-bottom: 15px;
}
.analysis-item {
background: #f5f5f5;
padding: 12px;
border-radius: 8px;
border-left: 4px solid #667eea;
}
.analysis-item-label {
font-size: 12px;
color: #999;
font-weight: 600;
text-transform: uppercase;
margin-bottom: 5px;
}
.analysis-item-value {
font-size: 16px;
color: #333;
font-weight: 600;
}
.detected-furniture {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.furniture-tag {
background: #667eea;
color: white;
padding: 6px 12px;
border-radius: 20px;
font-size: 12px;
font-weight: 600;
}
.recommendation-info {
background: white;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.recommendation-info h3 {
color: #667eea;
margin-bottom: 10px;
font-size: 16px;
}
.recommendation-info p {
color: #555;
font-size: 14px;
line-height: 1.6;
margin-bottom: 10px;
}
.search-query {
background: #f5f5f5;
padding: 10px;
border-radius: 6px;
color: #666;
font-size: 13px;
margin-bottom: 10px;
border-left: 3px solid #667eea;
}
.reasoning {
background: #e8f4f8;
padding: 12px;
border-radius: 6px;
color: #1565c0;
font-size: 13px;
line-height: 1.6;
border-left: 3px solid #1565c0;
margin-bottom: 10px;
}
/* 추천 가구 카드 그리드 */
.furniture-cards-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
margin-top: 15px;
}
.furniture-card {
background: white;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s, box-shadow 0.3s;
}
.furniture-card:hover {
transform: translateY(-5px);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}
.furniture-card-image {
width: 100%;
height: 150px;
object-fit: cover;
background: #f5f5f5;
}
.furniture-card-body {
padding: 12px;
}
.furniture-rank {
display: inline-block;
background: #667eea;
color: white;
padding: 4px 10px;
border-radius: 20px;
font-size: 11px;
font-weight: 600;
margin-bottom: 8px;
}
.furniture-score {
display: block;
color: #999;
font-size: 11px;
margin-bottom: 6px;
}
.furniture-name {
font-size: 13px;
color: #333;
font-weight: 600;
word-break: break-word;
}
.no-recommendations {
text-align: center;
padding: 40px;
color: #999;
}
.no-recommendations svg {
width: 80px;
height: 80px;
margin-bottom: 15px;
opacity: 0.5;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
@media (max-width: 600px) {
.form-row {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🛋️ 가구 추천 AI 시스템</h1>
<p>WebSocket을 통한 실시간 추천 알림 테스트</p>
</div>
<div class="content">
<!-- 로그인 섹션 -->
<div class="section" id="loginSection">
<h2>🔐 로그인</h2>
<div class="form-group">
<label for="email">이메일</label>
<input type="email" id="email" placeholder="test@example.com" value="test@example.com">
</div>
<div class="form-group">
<label for="password">비밀번호</label>
<input type="password" id="password" placeholder="비밀번호 입력" value="password123">
</div>
<button onclick="login()">로그인</button>
</div>
<!-- 사용자 정보 섹션 -->
<div class="section" id="userInfoSection" style="display: none;">
<h2>👤 사용자 정보</h2>
<div class="user-info">
<p><strong>회원 ID:</strong> <span id="userId">-</span></p>
<p><strong>이메일:</strong> <span id="userEmail">-</span></p>
<p><strong>토큰:</strong> <span id="userToken" style="word-break: break-all; font-size: 11px;">-</span></p>
</div>
<button onclick="logout()">로그아웃</button>
</div>
<!-- WebSocket 연결 섹션 -->
<div class="section" id="websocketSection" style="display: none;">
<h2>🔌 WebSocket 연결</h2>
<div id="connectionStatus" class="status disconnected">
⚫ 연결 끊김
</div>
<div class="button-group">
<button onclick="connectWebSocket()" id="connectBtn">WebSocket 연결</button>
<button onclick="disconnectWebSocket()" id="disconnectBtn" disabled>연결 끊기</button>
<button onclick="sendPing()" id="pingBtn" disabled>Ping 전송</button>
</div>
</div>
<!-- 추천 요청 섹션 -->
<div class="section" id="recommendSection" style="display: none;">
<h2>🎨 가구 추천 요청</h2>
<div class="form-group">
<label for="imageFile">이미지 파일 선택</label>
<input type="file" id="imageFile" accept="image/*" style="padding: 8px;">
</div>
<div class="form-row">
<div class="form-group">
<label for="category">가구 카테고리</label>
<select id="category">
<option value="chair">의자 (Chair)</option>
<option value="table">테이블 (Table)</option>
<option value="lamp">조명 (Lamp)</option>
<option value="sofa">소파 (Sofa)</option>
<option value="desk">책상 (Desk)</option>
<option value="shelf">선반 (Shelf)</option>
<option value="bed">침대 (Bed)</option>
<option value="cabinet">캐비닛 (Cabinet)</option>
<option value="refrigerator">냉장고 (Refrigerator)</option>
<option value="furniture">가구 (General)</option>
</select>
</div>
<div class="form-group">
<label for="topK">추천 결과 개수</label>
<select id="topK">
<option value="3">3개</option>
<option value="5" selected>5개</option>
<option value="10">10개</option>
<option value="15">15개</option>
</select>
</div>
</div>
<div id="uploadStatus" style="margin: 15px 0;"></div>
<button onclick="requestRecommendation()" id="recommendBtn">이미지 분석 및 추천 요청</button>
</div>
<!-- 추천 결과 섹션 -->
<div class="section" id="resultSection" style="display: none;">
<h2>✨ 추천 결과</h2>
<div id="resultContent"></div>
</div>
<!-- 알림 수신 섹션 -->
<div class="section" id="notificationSection" style="display: none;">
<h2>🔔 수신된 알림 (<span id="notificationCount">0</span>)</h2>
<button onclick="clearNotifications()" style="margin-bottom: 15px;">알림 지우기</button>
<div class="notifications" id="notifications">
<p style="color: #999; text-align: center;">수신된 알림이 없습니다.</p>
</div>
</div>
<!-- 로그 섹션 -->
<div class="section">
<h2>📋 로그</h2>
<button onclick="clearLogs()" style="margin-bottom: 15px;">로그 지우기</button>
<div class="logs" id="logs"></div>
</div>
</div>
</div>
<script>
// 전역 변수
let stompClient = null;
let token = null;
let userId = null;
let notificationCount = 0;
const SERVER_URL = 'http://localhost:8080';
// 로그 함수
function log(message, level = 'info') {
const timestamp = new Date().toLocaleTimeString('ko-KR');
const logEntry = document.createElement('div');
logEntry.className = 'log-entry';
logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> <span class="level-${level}">[${level.toUpperCase()}]</span> ${message}`;
const logsDiv = document.getElementById('logs');
logsDiv.appendChild(logEntry);
logsDiv.scrollTop = logsDiv.scrollHeight;
}
// JWT 토큰에서 Payload 디코딩
function parseJwt(token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
} catch (e) {
log('❌ JWT 파싱 실패: ' + e.message, 'error');
return null;
}
}
// 로그인
async function login() {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
if (!email || !password) {
alert('이메일과 비밀번호를 입력하세요.');
return;
}
log(`로그인 시도: ${email}`, 'info');
try {
const response = await fetch(`${SERVER_URL}/api/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password })
});
if (response.ok) {
const data = await response.json();
log('📦 로그인 응답 데이터: ' + JSON.stringify(data), 'info');
token = data.token || data.accessToken || data.jwtToken;
if (!token) {
log('❌ 토큰을 찾을 수 없습니다.', 'error');
alert('로그인 실패: 토큰을 받지 못했습니다.');
return;
}
// JWT에서 사용자 정보 추출
const jwtPayload = parseJwt(token);
log('🔓 JWT Payload: ' + JSON.stringify(jwtPayload), 'info');
let userEmail = email;
if (jwtPayload) {
userId = jwtPayload.id || jwtPayload.userId || jwtPayload.memberId || jwtPayload.sub;
userEmail = jwtPayload.sub || jwtPayload.email || email;
}
if (!userId) {
userId = data.userId || data.id || data.memberId || data.member_id;
}
log('🔑 추출된 토큰: ' + (token ? '있음' : '없음'), 'info');
log('👤 추출된 userId: ' + userId, 'info');
log('📧 추출된 email: ' + userEmail, 'info');
if (!userId) {
log('⚠️ userId를 찾을 수 없습니다. JWT Payload를 확인하세요.', 'error');
alert('로그인은 성공했으나 사용자 ID를 가져올 수 없습니다. 콘솔을 확인하세요.');
return;
}
log('✅ 로그인 성공', 'success');
log(`회원 ID: ${userId}`, 'info');
// UI 업데이트
document.getElementById('loginSection').style.display = 'none';
document.getElementById('userInfoSection').style.display = 'block';
document.getElementById('websocketSection').style.display = 'block';
document.getElementById('recommendSection').style.display = 'block';
document.getElementById('notificationSection').style.display = 'block';
document.getElementById('userId').textContent = userId;
document.getElementById('userEmail').textContent = userEmail;
document.getElementById('userToken').textContent = token;
} else {
const error = await response.text();
log(`❌ 로그인 실패: ${error}`, 'error');
alert('로그인 실패: ' + error);
}
} catch (error) {
log(`❌ 로그인 오류: ${error.message}`, 'error');
alert('로그인 중 오류 발생: ' + error.message);
}
}
// 로그아웃
function logout() {
if (stompClient && stompClient.connected) {
disconnectWebSocket();
}
token = null;
userId = null;
document.getElementById('loginSection').style.display = 'block';
document.getElementById('userInfoSection').style.display = 'none';
document.getElementById('websocketSection').style.display = 'none';
document.getElementById('recommendSection').style.display = 'none';
document.getElementById('notificationSection').style.display = 'none';
document.getElementById('resultSection').style.display = 'none';
log('로그아웃 완료', 'info');
}
// 추천 요청
async function requestRecommendation() {
const fileInput = document.getElementById('imageFile');
const file = fileInput.files[0];
if (!file) {
alert('이미지 파일을 선택하세요.');
return;
}
if (!token) {
alert('먼저 로그인하세요.');
return;
}
if (!file.type.startsWith('image/')) {
alert('이미지 파일만 업로드 가능합니다.');
return;
}
const category = document.getElementById('category').value;
const topK = parseInt(document.getElementById('topK').value);
log(`📤 추천 요청 시작: ${file.name} (${(file.size / 1024).toFixed(2)} KB), category=${category}, topK=${topK}`, 'info');
const recommendBtn = document.getElementById('recommendBtn');
const uploadStatus = document.getElementById('uploadStatus');
recommendBtn.disabled = true;
uploadStatus.innerHTML = '<p style="color: #1565c0;">⏳ 분석 중...</p>';
try {
// FormData 생성
const formData = new FormData();
formData.append('image', file);
// 쿼리 파라미터로 category와 topK 추가
const url = new URL(`${SERVER_URL}/api/recommand/request`);
url.searchParams.append('category', category);
url.searchParams.append('topK', topK);
// API 호출
const response = await fetch(url.toString(), {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
},
body: formData
});
if (response.ok) {
const responseMessage = await response.text();
log('✅ 추천 요청 성공', 'success');
log(`서버 응답: ${responseMessage}`, 'info');
uploadStatus.innerHTML = `
<div style="background: #e8f5e9; padding: 15px; border-radius: 8px; border-left: 4px solid #4caf50;">
<p style="color: #2e7d32; font-weight: 600; margin-bottom: 5px;">✅ 추천 요청 전송 성공!</p>
<p style="color: #555; font-size: 14px;">🔄 가구 추천 분석이 시작되었습니다. 아래에서 결과를 확인하세요.</p>
</div>
`;
// 파일 입력 초기화
fileInput.value = '';
// 결과 섹션 준비
const resultSection = document.getElementById('resultSection');
const resultContent = document.getElementById('resultContent');
resultContent.innerHTML = `
<div style="text-align: center; padding: 40px;">
<div style="display: inline-block;">
<div style="font-size: 48px; margin-bottom: 20px;">⏳</div>
<p style="color: #666; font-size: 16px; font-weight: 600;">분석 진행 중...</p>
<p style="color: #999; font-size: 14px; margin-top: 10px;">AI가 방을 분석하고 가구를 추천하고 있습니다.</p>
</div>
</div>
`;
resultSection.style.display = 'block';
if (!stompClient || !stompClient.connected) {
uploadStatus.innerHTML += `
<div style="background: #fff3e0; padding: 15px; border-radius: 8px; border-left: 4px solid #ff9800; margin-top: 10px;">
<p style="color: #e65100; font-weight: 600;">⚠️ WebSocket이 연결되지 않았습니다!</p>
<p style="color: #555; font-size: 14px;">결과를 받으려면 WebSocket을 연결하세요.</p>
</div>
`;
log('⚠️ WebSocket 미연결 - 결과를 받을 수 없습니다', 'warn');
} else {
log('🔔 추천 결과 대기 중...', 'info');
}
} else {
const error = await response.text();
log(`❌ 요청 실패: ${error}`, 'error');
uploadStatus.innerHTML = `
<div style="background: #ffebee; padding: 15px; border-radius: 8px; border-left: 4px solid #f44336;">
<p style="color: #c62828; font-weight: 600;">❌ 요청 실패</p>
<p style="color: #555; font-size: 14px;">${error}</p>
</div>
`;
}
} catch (error) {
log(`❌ 요청 오류: ${error.message}`, 'error');
uploadStatus.innerHTML = `
<div style="background: #ffebee; padding: 15px; border-radius: 8px; border-left: 4px solid #f44336;">
<p style="color: #c62828; font-weight: 600;">❌ 요청 오류</p>
<p style="color: #555; font-size: 14px;">${error.message}</p>
</div>
`;
} finally {
recommendBtn.disabled = false;
}
}
// WebSocket 연결
function connectWebSocket() {
if (!token) {
alert('먼저 로그인하세요.');
return;
}
log('WebSocket 연결 시도...', 'info');
const socket = new SockJS(`${SERVER_URL}/ws?token=${encodeURIComponent(token)}`);
stompClient = Stomp.over(socket);
stompClient.connect({},
function(frame) {
log('✅ WebSocket 연결 성공', 'success');
updateConnectionStatus(true);
// 추천 결과 알림 구독 (특정 회원 ID로)
stompClient.subscribe(`/topic/recommand/${userId}`, function(message) {
log('📨 추천 결과 알림 수신', 'info');
log('📦 수신한 메시지: ' + message.body.substring(0, 100) + '...', 'info');
const parsedMessage = JSON.parse(message.body);
handleRecommendationResult(parsedMessage);
});
// Pong 응답 구독
stompClient.subscribe('/topic/pong', function(message) {
log(`🏓 Pong 수신: ${message.body}`, 'success');
});
log(`구독 완료: /topic/recommand/${userId}`, 'success');
},
function(error) {
log(`❌ WebSocket 연결 실패: ${error}`, 'error');
updateConnectionStatus(false);
}
);
}
// WebSocket 연결 끊기
function disconnectWebSocket() {
if (stompClient) {
stompClient.disconnect();
log('WebSocket 연결 종료', 'info');
updateConnectionStatus(false);
}
}
// 연결 상태 업데이트
function updateConnectionStatus(connected) {
const statusDiv = document.getElementById('connectionStatus');
const connectBtn = document.getElementById('connectBtn');
const disconnectBtn = document.getElementById('disconnectBtn');
const pingBtn = document.getElementById('pingBtn');
if (connected) {
statusDiv.className = 'status connected';
statusDiv.innerHTML = '🟢 연결됨';
connectBtn.disabled = true;
disconnectBtn.disabled = false;
pingBtn.disabled = false;
} else {
statusDiv.className = 'status disconnected';
statusDiv.innerHTML = '⚫ 연결 끊김';
connectBtn.disabled = false;
disconnectBtn.disabled = true;
pingBtn.disabled = true;
}
}
// 추천 결과 처리
function handleRecommendationResult(result) {
log('📨 추천 결과 처리 시작: ' + JSON.stringify(result).substring(0, 200) + '...', 'info');
notificationCount++;
document.getElementById('notificationCount').textContent = notificationCount;
const notificationsDiv = document.getElementById('notifications');
if (notificationCount === 1) {
notificationsDiv.innerHTML = '';
}
const notificationItem = document.createElement('div');
const status = result.status || 'success';
notificationItem.className = `notification-item ${status.toLowerCase()}`;
const time = new Date(result.timestamp || Date.now()).toLocaleString('ko-KR');
let bodyHTML = `<p><strong>상태:</strong> ${status}</p>`;
if (result.roomAnalysis) {
bodyHTML += `<p><strong>방 스타일:</strong> ${result.roomAnalysis.style || 'N/A'}</p>`;
if (result.roomAnalysis.detectedFurniture && result.roomAnalysis.detectedFurniture.length > 0) {
bodyHTML += `<p><strong>감지된 가구:</strong> ${result.roomAnalysis.detectedFurniture.join(', ')}</p>`;
}
}
if (result.recommendation) {
bodyHTML += `<p><strong>추천 카테고리:</strong> ${result.recommendation.targetCategory || 'N/A'}</p>`;
bodyHTML += `<p><strong>추천 개수:</strong> ${result.recommendation.resultCount || result.recommendation.results?.length || 0}개</p>`;
}
notificationItem.innerHTML = `
<div class="notification-header">
<span class="notification-type">추천 결과 - ${status}</span>
<span class="notification-time">${time}</span>
</div>
<div class="notification-body">
${bodyHTML}
</div>
`;
notificationsDiv.insertBefore(notificationItem, notificationsDiv.firstChild);
// 결과 화면 업데이트
const resultSection = document.getElementById('resultSection');
const resultContent = document.getElementById('resultContent');
if (result.roomAnalysis && result.recommendation && result.recommendation.results) {
log('✅ displayRecommendationResult 호출', 'success');
displayRecommendationResult(result);
} else {
log('⚠️ 필수 데이터 부족: roomAnalysis=' + !!result.roomAnalysis + ', recommendation=' + !!result.recommendation, 'warn');
resultContent.innerHTML = `
<div style="background: #fff3e0; padding: 30px; border-radius: 8px; text-align: center; border-left: 4px solid #ff9800;">
<p style="color: #e65100; font-weight: 600; font-size: 18px;">⚠️ 분석 진행 중</p>
<p style="color: #666; margin-top: 10px;">데이터를 처리하는 중입니다. 잠시 후 결과가 표시됩니다.</p>
${result.roomAnalysis ? `<p style="color: #666; font-size: 14px; margin-top: 15px;"><strong>방 분석:</strong> ${result.roomAnalysis.style || 'N/A'} 스타일</p>` : ''}
</div>
`;
}
resultSection.style.display = 'block';
// 브라우저 알림
if (Notification.permission === 'granted') {
const title = status === 'success' ? '🎉 가구 추천 완료!' : '⚠️ 추천 처리 중';
const body = result.recommendation?.targetCategory
? `${result.recommendation.targetCategory} 추천이 준비되었습니다.`
: '추천 분석을 처리하고 있습니다.';
new Notification(title, { body });
}
}
// 추천 결과 화면에 표시
function displayRecommendationResult(result) {
log('🎨 추천 결과 UI 렌더링 시작', 'info');
const resultContent = document.getElementById('resultContent');
const roomAnalysis = result.roomAnalysis;
const recommendation = result.recommendation;
if (!recommendation || !recommendation.results) {
log('❌ 추천 데이터 누락: recommendation=' + !!recommendation + ', results=' + !!(recommendation?.results), 'error');
resultContent.innerHTML = `
<div style="background: #ffebee; padding: 30px; border-radius: 8px; text-align: center; border-left: 4px solid #f44336;">
<p style="color: #c62828; font-weight: 600; font-size: 18px;">❌ 데이터 오류</p>
<p style="color: #666; margin-top: 10px;">추천 결과를 표시할 수 없습니다.</p>
</div>
`;
return;
}
let html = `<div class="recommendation-container">`;
// 방 분석 결과 (있으면 표시)
if (roomAnalysis) {
html += `
<div class="room-analysis">
<h3>🏠 방 분석 결과</h3>
<div class="analysis-grid">
<div class="analysis-item">
<div class="analysis-item-label">스타일</div>
<div class="analysis-item-value">${roomAnalysis.style || 'N/A'}</div>
</div>
<div class="analysis-item">
<div class="analysis-item-label">색상</div>
<div class="analysis-item-value">${roomAnalysis.color || 'N/A'}</div>
</div>
<div class="analysis-item">
<div class="analysis-item-label">재질</div>
<div class="analysis-item-value">${roomAnalysis.material || 'N/A'}</div>
</div>
<div class="analysis-item">
<div class="analysis-item-label">감지된 가구</div>