-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathongoingworks.html
More file actions
764 lines (717 loc) · 36.9 KB
/
ongoingworks.html
File metadata and controls
764 lines (717 loc) · 36.9 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
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Deadliner – Ongoing Works</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700,italic" rel="stylesheet"/>
<style>
:root{ --ink:#171F39; --muted:#9B9A9A; --bg:#E5E7E9; --side:#1E2A38; --panel:#fff; --pill:#F7F5F4; --rule:#ECE9E7; --accent:#0A88B4; --danger:#e05a5a; --yellow:#FCFCE5; --shadow:0 8px 24px rgba(0,0,0,.08); }
*{ box-sizing:border-box } html,body{ height:100% }
body{ margin:0; font-family:'Open Sans',Arial,sans-serif; background:var(--bg); color:var(--ink) }
.app{ display:grid; grid-template-columns:201px 1fr; grid-template-rows:80px 1fr; grid-template-areas:"side head" "side main"; min-height:100vh }
/* Sidebar (dashboard-clone) */
.side{ grid-area:side; background:var(--side); color:#fff }
.brand{ display:flex; gap:10px; align-items:center; margin:24px 0 28px 24px }
.brand .logo{ width:30px; height:30px; border-radius:6px; }
.brand .name{ font-weight:700; font-style:italic; font-size:24px }
.nav{ display:flex; flex-direction:column; gap:22px; margin:10px 0 0 48px }
.nav a{ text-decoration:none; color:#fff; font-size:16px; opacity:.9 }
.nav a.active{ opacity:1; font-weight:700 }
.side .login-area{ margin:32px 0 0 48px }
.btn{ border:2px solid #3a465e; border-radius:10px; padding:10px 14px; font-weight:700; background:rgba(30,42,56,0.98); color:var(--accent); cursor:pointer; box-shadow:0 2px 8px rgba(0,0,0,0.18); transition:box-shadow 0.18s; }
/* Header */
.head{ grid-area:head; display:flex; align-items:center; padding:0 28px }
.title{ font-size:40px; font-weight:800; font-style:italic; margin-left:24px }
.sp{ flex:1 }
/* Main */
.main{ grid-area:main; display:block; padding:24px 28px 40px 28px }
.project-area{ max-width:860px }
.page-title{ font-size:28px; font-style:italic; font-weight:800; margin:12px 0 20px 0 }
.proj-card{ background:#fff; border-radius:16px; width:100%; height:140px; position:relative; margin:16px 0; cursor:pointer; box-shadow:var(--shadow); transition:background 0.2s }
.proj-card.selected{ background:var(--yellow); }
.proj-card .ttl{ position:absolute; left:20px; top:15px; font-size:20px; font-weight:700 }
.proj-card .meta{ position:absolute; left:20px; top:56px; font-size:14px; color:var(--muted) }
.proj-card .bar{ position:absolute; left:20px; top:92px; right:20px; height:10px; background:var(--rule); border-radius:999px; overflow:hidden }
.proj-card .bar>i{ height:100%; background:var(--accent); display:block; width:40% }
.proj-card .days{ position:absolute; right:20px; top:18px; font-size:12px; color:#5a6377 }
.add-proj{ width:100%; height:36px; background:var(--pill); border-radius:8px; display:flex; align-items:center; justify-content:center; color:var(--muted); font-size:20px; font-style:italic; font-weight:700; margin-top:18px; cursor:pointer }
.muted{ color:#8b8f9c } .empty{ color:#8b8f9c; font-size:14px; margin:8px 0 }
/* Drawer */
.boards-backdrop{ position:fixed; inset:0; background:rgba(23,31,57,.45); opacity:0; pointer-events:none; transition:.2s }
.boards-drawer{ position:fixed; top:0; right:-820px; width:800px; height:100vh; background:#f2f3f6; padding:28px; overflow:auto; transition:.25s; box-shadow:-8px 0 24px rgba(0,0,0,.08) }
.boards-drawer .close{ position:sticky; top:0; display:flex; justify-content:flex-end; margin-bottom:6px }
.boards-drawer .xbtn{ border:0; background:#fff; width:36px; height:36px; border-radius:10px; cursor:pointer; font-size:18px }
.board-card{ border-radius:24px; padding:28px 34px; min-height:150px; background:#fff; width:100%; margin:0 0 24px 0; box-shadow:var(--shadow) }
.board-title{ font-size:26px; font-style:italic; font-weight:800; color:#232B44; margin:0 0 18px 0 }
.item-row{ display:flex; align-items:center; gap:12px; font-size:18px; font-style:italic; font-weight:700; color:#232B44; margin:12px 0 }
.item-row input[type="checkbox"]{ width:28px; height:22px; border-radius:14px; border:2px solid #CACBD1; background:#fff; appearance:none; position:relative; cursor:pointer }
.item-row input[type="checkbox"]:checked{ background:#232B44; border-color:#232B44 }
.item-row input[type="checkbox"]:checked::after{ content:''; position:absolute; left:8px; top:4px; width:12px; height:12px; border-radius:50%; background:#fff }
.row-actions{ margin-left:auto; display:flex; gap:6px }
.icon-btn{ border:0; background:#fff; width:28px; height:28px; border-radius:8px; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; box-shadow:0 1px 3px rgba(0,0,0,.12); }
.icon-btn.danger{ background:#ffecec; color:#b42222 }
.ck-group{margin:10px 0 18px 0; padding:12px 14px; border:1px solid #ECE9E7; border-radius:14px; background:#fff;}
.ck-hd{display:flex; align-items:center; gap:10px; margin-bottom:8px;}
.ck-title{font-weight:800; font-style:italic; color:#232B44;}
.ck-count{color:#8b8f9c; font-size:13px; margin-left:6px;}
.ck-items{margin-left:6px;}
.mini-btn{border:0; border-radius:8px; padding:6px 10px; background:#eaf6fb; color:#0A88B4; font-weight:800; cursor:pointer;}
.mini-btn.ghost{background:#fff; border:1px solid #d8e6f1;}
.drawer-toolbar{display:flex; justify-content:flex-end; gap:8px; margin:6px 0 16px;}
/* Login Modal (dashboard clone) */
#loginModal{display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.18);align-items:center;justify-content:center;}
#loginModal .panel{background:#fff;padding:32px 32px 24px 32px;border-radius:16px;max-width:380px;width:96vw;box-shadow:0 4px 24px rgba(0,0,0,0.12);position:relative;display:flex;flex-direction:column;gap:18px;}
#loginModalClose{position:absolute;top:16px;right:16px;background:none;border:none;font-size:20px;cursor:pointer;}
#loginModal form{display:flex;flex-direction:column;gap:12px;}
#loginModal input{width:100%;padding:12px;border-radius:8px;border:1px solid #eee;font-size:16px;}
#loginModal .submit{width:100%;background:#232B44;color:#fff;border-radius:8px;border:none;padding:12px 0;font-size:16px;font-weight:700;cursor:pointer;}
/* Toast & show states */
.toast{ position:fixed; right:20px; bottom:20px; background:#111; color:#fff; padding:10px 14px; border-radius:10px; opacity:0; transform:translateY(6px); transition:.25s }
.toast.show{ opacity:1; transform:none }
.show-backdrop{ opacity:1; pointer-events:auto }
.show-drawer{ right:0 }
</style>
</head>
<body>
<div class="app">
<!-- Login Modal -->
<div id="loginModal">
<div class="panel">
<button id="loginModalClose">×</button>
<div style="font-size:22px;font-weight:700;text-align:center;margin-bottom:8px;">Log in</div>
<hr style="margin:0 0 8px 0;border:0;border-top:2px solid #eee;">
<form id="loginForm">
<input type="email" id="loginEmail" placeholder="Email">
<input type="password" id="loginPassword" placeholder="Password">
<button type="submit" class="submit">Log in</button>
</form>
<hr style="margin:12px 0 8px 0;border:0;border-top:1px solid #eee;">
<div style="text-align:center;font-size:14px;color:#888;margin-bottom:8px;">OR</div>
<button id="loginKakao" class="submit" style="background:#fee500;color:#3c1e1e;margin-bottom:8px;">Continue with Kakao</button>
<button id="loginGoogle" class="submit" style="background:#4285F4;">Continue with Google</button>
</div>
</div>
<!-- Sidebar -->
<aside class="side">
<div class="brand">
<img src="/public/icons/deadlinear-icon.svg" class="logo" alt="Deadliner"/>
<div class="name">Deadliner</div>
</div>
<nav class="nav">
<a href="/deadLiner-dashBoard.html"><img src="/public/icons/home-icon.svg" alt="Home" style="width:20px;height:20px;vertical-align:middle;margin-right:8px;"/>Home</a>
<a href="/calender.html"><img src="/public/icons/calendar-icon.svg" alt="Calender" style="width:20px;height:20px;vertical-align:middle;margin-right:8px;"/>Calendar</a>
<a class="active" href="/ongoingworks.html"><img src="/public/icons/ongoingworks-icon.svg" alt="Ongoing Works" style="width:20px;height:20px;vertical-align:middle;margin-right:8px;"/>Ongoing Works</a>
<a href="/idea-board.html"><img src="/public/icons/idea-icon.svg" alt="Idea" style="width:20px;height:20px;vertical-align:middle;margin-right:8px;"/>Idea</a>
<a href="/main.html"><img src="/public/icons/proofticket-icon.svg" alt="Proof ticket" style="width:20px;height:20px;vertical-align:middle;margin-right:8px;"/>Proof ticket</a>
</nav>
<div class="login-area">
<button id="loginBtn" class="btn" style="width:120px;display:flex;align-items:center;gap:8px;">
<img src="/public/icons/login-icon.svg" alt="Login" style="width:20px;height:20px;vertical-align:middle;"/>
<span id="loginBtnText">Log in</span>
</button>
</div>
</aside>
<!-- Header -->
<header class="head">
<div class="title">Ongoing Works</div>
<div class="sp"></div>
</header>
<!-- Main -->
<main class="main">
<section class="project-area">
<div class="page-title">Projects</div>
<div id="projectList"></div>
<div class="add-proj" id="btnOpenNewDeadline">+</div>
</section>
</main>
<!-- Drawer -->
<div id="boardsBackdrop" class="boards-backdrop"></div>
<aside id="boardsDrawer" class="boards-drawer" aria-hidden="true">
<div class="close"><button class="xbtn" id="closeDrawer">×</button></div>
<!-- Toolbar: add checklist & delete deadline -->
<div class="drawer-toolbar">
<button id="btnDeleteDeadline" class="mini-btn" style="background:#ffecec;color:#b42222;border:1px solid #f2c6c6;">데드라인 삭제</button>
</div>
<div class="board-card">
<div class="board-title">Today</div>
<div id="listToday"></div>
</div>
<div class="board-card">
<div class="board-title">Tomorrow</div>
<div id="listTomorrow"></div>
</div>
<div class="board-card">
<div class="board-title">This week</div>
<div id="listWeek"></div>
</div>
</aside>
</div>
<!-- Deadline Modal -->
<div id="deadlineModal" style="display:none;position:fixed;inset:0;z-index:9998;background:rgba(0,0,0,.18);align-items:center;justify-content:center;">
<div class="box" style="background:#fff;padding:28px 32px;border-radius:16px;max-width:430px;width:96vw;box-shadow:0 4px 24px rgba(0,0,0,0.12)">
<h3 style="margin-top:0">이벤트 선택</h3>
<div id="eventListWrap" style="max-height:240px;overflow-y:auto;margin-bottom:16px;"></div>
<div style="margin-bottom:10px">
<label>메모(선택)</label><br/>
<input id="deadlineNote" style="width:100%;border:1px solid #E5E7EB;border-radius:10px;padding:10px" placeholder="메모 입력"/>
</div>
<div style="display:flex;gap:10px;justify-content:flex-end;">
<button class="btn" id="deadlineCancel">취소</button>
<button class="btn" id="deadlineCreateBtn">생성</button>
</div>
</div>
</div>
<div id="toast" class="toast"></div>
<script>
/* ===== API ===== */
const API_BASE = 'https://api.rightmarks.site';
const ENDPOINTS = {
deadlinesList: '/api/deadlines',
deadlineCreate: '/api/deadlines',
deadlineDelete: (deadlineId)=>`/api/deadlines/${deadlineId}`,
dlChecklistsList: (deadlineId)=>`/api/deadlines/${deadlineId}/checklists`,
dlChecklistAdd: (deadlineId)=>`/api/deadlines/${deadlineId}/checklists`,
dlChecklistDelete:(deadlineId, checklistId)=>`/api/deadlines/${deadlineId}/checklists/${checklistId}`,
itemsList: (checklistId)=>`/api/checklists/${checklistId}/items`,
itemAdd: (checklistId)=>`/api/checklists/${checklistId}/items`,
itemComplete: (itemId)=>`/api/items/${itemId}/complete`,
itemDelete: (itemId)=>`/api/items/${itemId}`,
};
const token = () => {
const tk = localStorage.getItem('accessToken')||''; return tk ? (tk.startsWith('Bearer ')?tk:`Bearer ${tk}`) : '';
};
async function jfetch(path, {method='GET', headers={}, params, body}={}) {
const url = new URL(API_BASE + path);
if(params) Object.entries(params).forEach(([k,v])=> v!=null && url.searchParams.append(k,v));
const res = await fetch(url, {
method,
headers:{
'accept':'application/json;charset=UTF-8',
...(body ? {'Content-Type':'application/json;charset=UTF-8'}:{}),
...(token() ? {'Authorization': token()} : {}),
...headers
},
body: body ? JSON.stringify(body) : undefined
});
const text = await res.text();
let data; try{ data = text ? JSON.parse(text) : {}; } catch { data = text; }
if(!res.ok || (data && typeof data==='object' && data.isSuccess === false)){
const msg = data?.message || `HTTP ${res.status}`; throw new Error(msg);
}
return data?.result ?? data;
}
/* ===== Utils ===== */
function toast(msg){ const t=document.getElementById('toast'); t.textContent=msg; t.classList.add('show'); setTimeout(()=>t.classList.remove('show'),1600); }
function daysRemaining(dueAt){ const now=new Date(), due=new Date(dueAt); const diff=Math.ceil((due-now)/(1000*60*60*24)); return diff>0?`${diff} days remaining`:'Due'; }
const mapDeadline = (dl) => ({
deadlineId: dl.deadline_id ?? dl.deadlineId ?? dl.id,
progress: dl.progress ?? 0,
note: dl.note ?? '',
createdAt: dl.created_at ?? dl.createdAt ?? '',
checklistCount: dl.checklist_count ?? dl.checklistCount ?? 0,
event: {
eventId: dl.event?.event_id ?? dl.event?.eventId ?? dl.event_id ?? dl.eventId,
title: dl.event?.title ?? '',
memo: dl.event?.memo ?? '',
dueAt: dl.event?.due_at ?? dl.event?.dueAt ?? '',
startAt: dl.event?.start_at ?? dl.event?.startAt ?? ''
}
});
const loginBtn = document.getElementById('loginBtn');
const loginBtnText = document.getElementById('loginBtnText');
const loginModal = document.getElementById('loginModal');
document.getElementById('loginModalClose').onclick = () => loginModal.style.display = 'none';
// Toggle login/logout modal
loginBtn.onclick = () => {
if (loginBtnText.textContent.endsWith('님')) {
showLogoutConfirm();
} else {
loginModal.style.display = 'flex';
}
};
function showLogoutConfirm() {
let modal = document.getElementById('logoutModal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'logoutModal';
modal.style.position = 'fixed';
modal.style.inset = '0';
modal.style.zIndex = '9999';
modal.style.background = 'rgba(0,0,0,0.18)';
modal.style.display = 'flex';
modal.style.alignItems = 'center';
modal.style.justifyContent = 'center';
modal.innerHTML = `
<div style="background:#fff;padding:32px 32px 24px 32px;border-radius:16px;max-width:320px;width:96vw;box-shadow:0 4px 24px rgba(0,0,0,0.12);position:relative;display:flex;flex-direction:column;gap:18px;">
<button id="logoutModalClose" style="position:absolute;top:16px;right:16px;background:none;border:none;font-size:20px;cursor:pointer;">×</button>
<div style="font-size:18px;font-weight:700;text-align:center;margin-bottom:8px;">로그아웃 하시겠습니까?</div>
<div style="display:flex;gap:12px;justify-content:center;margin-top:12px;">
<button id="logoutCancel" style="background:#eee;color:#223044;border-radius:8px;padding:8px 18px;font-weight:700;border:none;cursor:pointer;">취소</button>
<button id="logoutConfirm" style="background:#232B44;color:#fff;border-radius:8px;padding:8px 18px;font-weight:700;border:none;cursor:pointer;">로그아웃</button>
</div>
</div>
`;
document.body.appendChild(modal);
document.getElementById('logoutModalClose').onclick = () => { modal.style.display = 'none'; };
document.getElementById('logoutCancel').onclick = () => { modal.style.display = 'none'; };
document.getElementById('logoutConfirm').onclick = async () => {
const btn = document.getElementById('logoutConfirm');
const cancelBtn = document.getElementById('logoutCancel');
btn.disabled = true; cancelBtn.disabled = true;
try {
try {
const res = await fetch(API_BASE + '/api/users/logout', {
method: 'POST',
headers: {
'accept':'application/json;charset=UTF-8',
...(token() ? {'Authorization': token()} : {})
}
});
const txt = await res.text(); let data = {};
try { data = txt ? JSON.parse(txt) : {}; } catch { data = {}; }
} catch (e) {}
} finally {
localStorage.removeItem('access_token');
localStorage.removeItem('accessToken');
loginBtnText.textContent = 'Log in';
modal.style.display = 'none';
toast('로그아웃 완료');
btn.disabled = false; cancelBtn.disabled = false;
// Immediately refresh UI after logout
location.reload();
}
};
} else {
modal.style.display = 'flex';
}
}
document.getElementById('loginForm').onsubmit = async (e) => {
e.preventDefault();
const email = document.getElementById('loginEmail').value.trim();
const password = document.getElementById('loginPassword').value.trim();
if(!email || !password) return toast('이메일과 비밀번호를 입력하세요.');
try {
const res = await fetch(API_BASE + '/api/users/login', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({email,password})});
const data = await res.json();
const raw = data?.result?.access_token || data?.result?.accessToken || data?.access_token || data?.accessToken;
if(!raw){ loginBtnText.textContent='로그인 실패'; return; }
localStorage.setItem('accessToken', raw.startsWith('Bearer ')?raw.slice(7):raw);
let username = data?.result?.me?.name || email.split('@')[0];
loginBtnText.textContent = username + '님';
loginModal.style.display = 'none';
toast('로그인 완료'); loadAll();
} catch(e) { toast('로그인 실패'); }
};
// Social login API handlers
const loginKakaoBtn = document.getElementById('loginKakao');
const loginGoogleBtn = document.getElementById('loginGoogle');
const OAUTH_BASE = 'https://api.rightmarks.site';
const redirect = encodeURIComponent(window.location.origin + '/auth/callback_deadliner.html');
if (loginKakaoBtn) {
loginKakaoBtn.onclick = () => {
window.location.href = `${OAUTH_BASE}/oauth2/authorization/kakao?redirect_uri=${redirect}`;
};
}
if (loginGoogleBtn) {
loginGoogleBtn.onclick = () => {
window.location.href = `${OAUTH_BASE}/oauth2/authorization/google?redirect_uri=${redirect}`;
};
}
async function showUsernameIfLoggedIn() {
const tokenVal = localStorage.getItem('accessToken');
if (tokenVal) {
try {
const res = await fetch(API_BASE + '/api/users/me', {
method: 'GET',
headers: {
'Authorization': token(),
'accept': 'application/json;charset=UTF-8'
}
});
const data = await res.json();
let username = data?.result?.name || data?.name || '';
if (username) {
loginBtnText.textContent = username + '님';
}
} catch (e) {
loginBtnText.textContent = 'Log in';
}
} else {
loginBtnText.textContent = 'Log in';
}
}
showUsernameIfLoggedIn();
/* ===== Projects list ===== */
async function fetchDeadlines(){ const res = await jfetch(ENDPOINTS.deadlinesList); const arr = res?.deadlines ?? []; return arr.map(mapDeadline); }
function renderProjects(deadlines){
// Hide passed deadlines (due date < today) and sort by due date ascending
const today0 = new Date(); today0.setHours(0,0,0,0);
deadlines = (deadlines||[])
.filter(d => {
const dueAt = d?.event?.dueAt;
if(!dueAt) return false; // hide items without due date
const due = new Date(dueAt);
return !isNaN(due) && due >= today0;
})
.sort((a, b) => {
const aDue = new Date(a?.event?.dueAt);
const bDue = new Date(b?.event?.dueAt);
return aDue - bDue;
});
const wrap = document.getElementById('projectList'); wrap.innerHTML = '';
if(!deadlines.length){ wrap.innerHTML = '<div class="muted">No projects yet.</div>'; return; }
const groups = new Map();
deadlines.forEach(d => {
const uniqueKey = `${d.event.title}_${d.deadlineId}`;
groups.set(uniqueKey, [d]);
});
function getProgressPercent(startDate, dueDate) {
const start = new Date(startDate);
const end = new Date(dueDate);
const now = new Date();
if (isNaN(start) || isNaN(end)) return 0;
if (now < start) return 0;
if (now > end) return 100;
const total = end - start;
const passed = now - start;
return Math.round((passed / total) * 100);
}
let selectedCard = null;
function getBarColor(dueAt) {
if (!dueAt) return '#1aa3d9'; // default blue
const today = new Date(); today.setHours(0,0,0,0);
const due = new Date(dueAt); due.setHours(0,0,0,0);
const diff = Math.ceil((due - today) / (1000*60*60*24));
if (diff === 0) return '#e05a5a'; // today: red
if (diff > 0 && diff <= 3) return '#f7b731'; // <=3 days: yellow
if (diff >= 4 && diff <= 7) return '#f5cd79'; // 4-7 days: light yellow
if (diff >= 14) return '#2ecc71'; // >=14 days: green
return '#1aa3d9'; // default blue
}
for(const [title, list] of groups.entries()){
const d0 = list[0];
const dueAt = d0?.event?.dueAt;
let startAt = d0?.event?.startAt;
if (!startAt && dueAt) {
const d = new Date(dueAt); d.setDate(d.getDate() - 14); startAt = d.toISOString().slice(0,10);
}
const percent = (dueAt && startAt) ? getProgressPercent(startAt, dueAt) : 0;
const barColor = getBarColor(dueAt);
const el = document.createElement('div');
el.className = 'proj-card';
el.innerHTML = `
<div class="ttl">${d0.event.title || '(Untitled)'}</div>
<div class="meta">${d0.note ? d0.note : ''}</div>
<div class="bar"><i style="width:${percent}%;background:${barColor};"></i></div>
<div class="days">${d0?.event?.dueAt ? daysRemaining(d0.event.dueAt) : ''}</div>
`;
el.onclick = () => {
if(selectedCard) selectedCard.classList.remove('selected');
el.classList.add('selected');
selectedCard = el;
openBoardsDrawer(d0);
};
wrap.appendChild(el);
}
}
/* ===== Drawer & Boards ===== */
const drawer = document.getElementById('boardsDrawer');
const backdrop = document.getElementById('boardsBackdrop');
const btnDeleteDeadline = document.getElementById('btnDeleteDeadline');
document.getElementById('closeDrawer').onclick = closeBoardsDrawer;
backdrop.onclick = closeBoardsDrawer;
let currentDeadline = null;
function openBoardsDrawer(deadline){
currentDeadline = deadline;
backdrop.classList.add('show-backdrop');
drawer.classList.add('show-drawer');
drawer.setAttribute('aria-hidden','false');
loadBoardsForDeadline(deadline);
}
function closeBoardsDrawer(){
backdrop.classList.remove('show-backdrop');
drawer.classList.remove('show-drawer');
drawer.setAttribute('aria-hidden','true');
['listToday','listTomorrow','listWeek'].forEach(id=>document.getElementById(id).innerHTML='');
}
btnDeleteDeadline.onclick = async () => {
if(!currentDeadline) return;
const ok = confirm('이 데드라인을 삭제할까요?\n(하위 체크리스트 및 아이템은 정책에 따라 함께 제거될 수 있습니다)');
if(!ok) return;
try{
await jfetch(ENDPOINTS.deadlineDelete(currentDeadline.deadlineId), { method:'DELETE' });
toast('데드라인 삭제 성공');
closeBoardsDrawer();
loadAll();
}catch(e){ toast(e.message); }
};
function renderItem({itemId, content, done}, onRemoved){
const row = document.createElement('div'); row.className='item-row';
const cb = document.createElement('input'); cb.type='checkbox'; cb.checked=!!done;
const label = document.createElement('span'); label.textContent = content;
const actions = document.createElement('div'); actions.className='row-actions';
const delBtn = document.createElement('button'); delBtn.className='icon-btn danger'; delBtn.title='아이템 삭제'; delBtn.innerHTML='🗑';
cb.onchange = async (e)=>{
const want = e.target.checked;
try{ await jfetch(ENDPOINTS.itemComplete(itemId), { method:'PATCH', body:{ done: want } }); }
catch(err){ e.target.checked = !want; toast(err.message); }
};
delBtn.onclick = async ()=>{
const ok = confirm('이 아이템을 삭제할까요?');
if(!ok) return;
try{
await jfetch(ENDPOINTS.itemDelete(itemId), { method:'DELETE' });
toast('체크리스트 아이템 삭제 성공');
row.remove();
onRemoved?.();
}catch(e){ toast(e.message); }
};
row.appendChild(cb); row.appendChild(label); actions.appendChild(delBtn); row.appendChild(actions);
return row;
}
function renderChecklistGroup(deadlineTitle, ck, items){
const ckId = ck.checklist_id ?? ck.checklistId ?? ck.id;
const group = document.createElement('div'); group.className='ck-group';
const hd = document.createElement('div'); hd.className='ck-hd';
const title = document.createElement('div'); title.className='ck-title';
let rawTitle = ck.title ?? '';
rawTitle = rawTitle.replace(/^\[(오늘|내일|이번주)\]\s*/, '');
title.textContent = `${deadlineTitle} · ${rawTitle}`;
const count = document.createElement('span'); count.className='ck-count';
count.textContent = `(아이템 ${items.length})`;
// Improved UI: Modal for item creation
const addItemBtn = document.createElement('button');
addItemBtn.className = 'mini-btn ghost';
addItemBtn.innerHTML = '<span style="font-size:1.2em;">+</span> 아이템 추가';
addItemBtn.title = '아이템 추가';
const delCkBtn = document.createElement('button');
delCkBtn.className = 'mini-btn';
delCkBtn.style.background = '#ffecec';
delCkBtn.style.color = '#b42222';
delCkBtn.style.border = '1px solid #f2c6c6';
delCkBtn.innerHTML = '<span style="font-size:1em;">🗑</span> 삭제';
delCkBtn.title = '체크리스트 삭제';
const itemsBox = document.createElement('div'); itemsBox.className = 'ck-items';
function refreshCount() { const n = itemsBox.querySelectorAll('.item-row').length; count.textContent = `(아이템 ${n})`; }
if (items.length) {
items.forEach(it => {
itemsBox.appendChild(renderItem({
itemId: it.item_id ?? it.itemId ?? it.id,
content: it.content ?? it.text ?? '',
done: !!(it.done ?? it.completed ?? false),
}, refreshCount));
});
} else {
const empty = document.createElement('div'); empty.className = 'empty';
empty.textContent = '아이템이 없습니다. 아래 버튼으로 추가하세요.';
itemsBox.appendChild(empty);
}
// Modal for item creation
let itemModal = null;
addItemBtn.onclick = () => {
if (itemModal) itemModal.remove();
itemModal = document.createElement('div');
itemModal.style.position = 'fixed';
itemModal.style.inset = '0';
itemModal.style.zIndex = '9999';
itemModal.style.background = 'rgba(0,0,0,0.18)';
itemModal.style.display = 'flex';
itemModal.style.alignItems = 'center';
itemModal.style.justifyContent = 'center';
itemModal.innerHTML = `
<div style="background:#fff;padding:28px 32px;border-radius:16px;max-width:340px;width:96vw;box-shadow:0 4px 24px rgba(0,0,0,0.12);display:flex;flex-direction:column;gap:16px;">
<h3 style="margin:0;font-size:20px;text-align:center;">아이템 추가</h3>
<input id="newItemContent" style="width:100%;border:1px solid #E5E7EB;border-radius:10px;padding:10px;font-size:16px;" placeholder="아이템 내용을 입력하세요" />
<div style="display:flex;gap:10px;justify-content:flex-end;">
<button class="mini-btn ghost" id="cancelAddItem">취소</button>
<button class="mini-btn" id="confirmAddItem" style="background:#232B44;color:#fff;">추가</button>
</div>
</div>
`;
document.body.appendChild(itemModal);
document.getElementById('cancelAddItem').onclick = () => { itemModal.remove(); };
document.getElementById('confirmAddItem').onclick = async () => {
const txt = document.getElementById('newItemContent').value.trim();
if (!txt) return toast('내용을 입력하세요.');
try {
const created = await jfetch(ENDPOINTS.itemAdd(ckId), { method: 'POST', body: { content: txt } });
toast('아이템이 추가되었습니다.');
const newly = created.result ?? created;
const emptyEl = itemsBox.querySelector('.empty'); if (emptyEl) emptyEl.remove();
itemsBox.appendChild(renderItem({
itemId: newly.item_id ?? newly.itemId ?? newly.id,
content: newly.content ?? txt,
done: !!(newly.done),
}, refreshCount));
refreshCount();
itemModal.remove();
} catch (e) { toast(e.message); }
};
};
delCkBtn.onclick = async () => {
const ok = confirm('이 체크리스트를 삭제할까요?');
if (!ok) return;
try {
await jfetch(ENDPOINTS.dlChecklistDelete(currentDeadline.deadlineId, ckId), { method: 'DELETE' });
toast('체크리스트 삭제 성공');
group.remove();
} catch (e) { toast(e.message); }
};
hd.appendChild(title); hd.appendChild(count); hd.appendChild(addItemBtn); hd.appendChild(delCkBtn);
group.appendChild(hd); group.appendChild(itemsBox);
return group;
}
async function loadBoardsForDeadline(deadline){
const dom = {
today: document.getElementById('listToday'),
tomorrow: document.getElementById('listTomorrow'),
week: document.getElementById('listWeek')
};
Object.values(dom).forEach(el=>el.innerHTML='');
const due = new Date(deadline.event.dueAt||'');
const today = new Date();
const t0 = new Date(today.getFullYear(),today.getMonth(),today.getDate());
const t1 = new Date(t0); t1.setDate(t0.getDate()+1);
const t7 = new Date(t0); t7.setDate(t0.getDate()+6);
let bucket = 'week';
if(due.toDateString()===t0.toDateString()) bucket='today';
else if(due.toDateString()===t1.toDateString()) bucket='tomorrow';
else if(!(due>=t0 && due<=t7)) bucket='week';
['today','tomorrow','week'].forEach(key => {
const btnId = `addChecklistBtn_${key}`;
let btn = document.getElementById(btnId);
if (!btn) {
btn = document.createElement('button');
btn.id = btnId; btn.className = 'mini-btn'; btn.innerHTML = '<span style="font-size:1.2em;">+</span> 체크리스트 추가'; btn.title = `${key} 체크리스트 추가`;
btn.style.margin = '8px 0';
dom[key].parentElement.insertBefore(btn, dom[key]);
btn.onclick = () => {
// Modal for checklist creation
let checklistModal = document.getElementById('checklistCreateModal');
if (checklistModal) checklistModal.remove();
checklistModal = document.createElement('div');
checklistModal.id = 'checklistCreateModal';
checklistModal.style.position = 'fixed';
checklistModal.style.inset = '0';
checklistModal.style.zIndex = '9999';
checklistModal.style.background = 'rgba(0,0,0,0.18)';
checklistModal.style.display = 'flex';
checklistModal.style.alignItems = 'center';
checklistModal.style.justifyContent = 'center';
checklistModal.innerHTML = `
<div style="background:#fff;padding:28px 32px;border-radius:16px;max-width:340px;width:96vw;box-shadow:0 4px 24px rgba(0,0,0,0.12);display:flex;flex-direction:column;gap:16px;">
<h3 style="margin:0;font-size:20px;text-align:center;">체크리스트 추가</h3>
<input id="newChecklistTitle" style="width:100%;border:1px solid #E5E7EB;border-radius:10px;padding:10px;font-size:16px;" placeholder="체크리스트 제목을 입력하세요" />
<div style="display:flex;gap:10px;justify-content:flex-end;">
<button class="mini-btn ghost" id="cancelAddChecklist">취소</button>
<button class="mini-btn" id="confirmAddChecklist" style="background:#232B44;color:#fff;">추가</button>
</div>
</div>
`;
document.body.appendChild(checklistModal);
document.getElementById('cancelAddChecklist').onclick = () => { checklistModal.remove(); };
document.getElementById('confirmAddChecklist').onclick = async () => {
if(!currentDeadline) return;
const title = document.getElementById('newChecklistTitle').value.trim();
if(!title) return toast('제목을 입력하세요.');
let prefix = '';
if(key==='today') prefix = '[오늘] ';
else if(key==='tomorrow') prefix = '[내일] ';
else if(key==='week') prefix = '[이번주] ';
try{
await jfetch(ENDPOINTS.dlChecklistAdd(currentDeadline.deadlineId), { method:'POST', body:{ title: prefix + title } });
toast('체크리스트가 생성되었습니다.');
checklistModal.remove();
loadBoardsForDeadline(currentDeadline);
}catch(e){ toast(e.message); }
};
};
}
});
try{
const ckRes = await jfetch(ENDPOINTS.dlChecklistsList(deadline.deadlineId));
const cks = ckRes.checklists ?? [];
const buckets = { today: [], tomorrow: [], week: [] };
for(const ck of cks){
const title = ck.title ?? '';
if(title.startsWith('[오늘]')) buckets.today.push(ck);
else if(title.startsWith('[내일]')) buckets.tomorrow.push(ck);
else if(title.startsWith('[이번주]')) buckets.week.push(ck);
else buckets.week.push(ck);
}
['today','tomorrow','week'].forEach(key => {
const list = buckets[key];
const el = dom[key];
el.innerHTML = '';
if(!list.length){
el.innerHTML = `<div class="empty">체크리스트가 없습니다.</div>`;
return;
}
list.forEach(async ck => {
const ckId = ck.checklist_id ?? ck.checklistId ?? ck.id;
let items = [];
try{
const itemsRes = await jfetch(ENDPOINTS.itemsList(ckId));
items = itemsRes.items ?? itemsRes ?? [];
}catch{}
el.appendChild(
renderChecklistGroup(deadline.event.title, ck, items)
);
});
});
}catch(e){
dom.today.innerHTML = dom.tomorrow.innerHTML = dom.week.innerHTML = `<div class="empty">로드 실패: ${e.message}</div>`;
}
}
/* ===== Deadline 생성 ===== */
document.getElementById('btnOpenNewDeadline').onclick = openDeadlineModal;
function openDeadlineModal(){
// Check if user is logged in before allowing deadline creation
const tokenVal = localStorage.getItem('accessToken');
if (!tokenVal) {
loginModal.style.display = 'flex';
toast('로그인이 필요합니다.');
return;
}
const modal = document.getElementById('deadlineModal');
const listWrap = document.getElementById('eventListWrap');
const noteIpt = document.getElementById('deadlineNote');
let selectedEventId = null;
listWrap.innerHTML = '<div class="muted">불러오는 중...</div>';
modal.style.display = 'flex';
(async ()=>{
try{
const now = new Date(); const pad=n=>String(n).padStart(2,'0');
const toISO=(d,end)=>`${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${end?'23:59:59':'00:00:00'}+09:00`;
const from = toISO(new Date(now.getFullYear(),now.getMonth(),now.getDate()), false);
const to = toISO(new Date(now.getFullYear(),now.getMonth(),now.getDate()+30), true);
const res = await jfetch('/api/calendar/events', { params:{ from,to,page:0,size:50 }});
const events = res.items ?? res ?? [];
const cand = events.filter(ev => ev.has_deadline === false || ev.hasDeadline === false);
if(!cand.length){ listWrap.innerHTML = '<div class="muted">데드라인 없는 이벤트가 없습니다.</div>'; return; }
listWrap.innerHTML = cand.map((ev,i)=>`
<div class="evt-row" data-id="${ev.eventId ?? ev.event_id}" style="padding:8px 0;cursor:pointer;border-bottom:1px solid #eee;${i===0?'border-top:1px solid #eee;':''}">
<b>${ev.title ?? ''}</b><br><span style="font-size:13px;color:#888">${ev.dueAt ?? ev.due_at ?? ''}</span>
</div>`).join('');
Array.from(listWrap.querySelectorAll('.evt-row')).forEach(row=>{
row.onclick = function(){ Array.from(listWrap.querySelectorAll('.evt-row')).forEach(r=>r.style.background=''); this.style.background='#eaf6fb'; selectedEventId=this.dataset.id; };
});
listWrap.querySelector('.evt-row')?.click();
}catch(e){ listWrap.innerHTML = `<div class="muted">오류: ${e.message}</div>`; }
})();
document.getElementById('deadlineCancel').onclick = ()=>{ modal.style.display='none'; listWrap.innerHTML=''; noteIpt.value=''; selectedEventId=null; };
document.getElementById('deadlineCreateBtn').onclick = async ()=>{
if(!selectedEventId) return toast('이벤트를 선택하세요.');
try{
await jfetch(ENDPOINTS.deadlineCreate, { method:'POST', body:{ eventId:Number(selectedEventId), note:noteIpt.value.trim() }});
toast('데드라인 생성 완료'); modal.style.display='none'; listWrap.innerHTML=''; noteIpt.value=''; selectedEventId=null; loadAll();
}catch(e){ toast(e.message); }
};
}
/* ===== boot ===== */
async function loadAll(){ const all = await fetchDeadlines(); renderProjects(all); }
loadAll();
</script>
</body>
</html>