-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud-sync.js
More file actions
2158 lines (2042 loc) · 88.1 KB
/
Copy pathcloud-sync.js
File metadata and controls
2158 lines (2042 loc) · 88.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
// ScopeWeave cloud sync — an OPT-IN overlay on the offline planner.
// Logged out, every export here is a no-op and the app behaves exactly as the
// original localStorage-only planner (so existing e2e tests are unaffected).
// Logged in with a project open, edits sync to the API with optimistic
// concurrency and a project sees other tabs' changes live over SSE.
const TOKEN_KEY = 'scopeweave:token';
const PROJECT_KEY = 'scopeweave:project';
const ROUTE_TOKEN_RE = /^[A-Za-z0-9_-]{16,128}$/;
let host = null; // { hydrateState, renderAll, getState } provided by app.js
let version = 0; // open project's doc version (optimistic concurrency)
let sse = null;
let pushTimer = null;
let currentOrgId = null; // org of the open project, for team management
let shareMode = false; // viewing via a public share token → read-only
const getToken = () => localStorage.getItem(TOKEN_KEY) || '';
const setToken = (t) => (t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY));
const getProjectId = () => localStorage.getItem(PROJECT_KEY) || '';
const setProjectId = (id) => (id ? localStorage.setItem(PROJECT_KEY, String(id)) : localStorage.removeItem(PROJECT_KEY));
const isAuthed = () => Boolean(getToken());
export function routeTokenPathSegment(value) {
const token = String(value || '').trim();
return ROUTE_TOKEN_RE.test(token) ? token : '';
}
function safeApiPath(path) {
if (typeof path !== 'string' || !path.startsWith('/api/')) throw new Error('invalid api path');
const origin = typeof location !== 'undefined' ? location.origin : 'http://localhost';
const url = new URL(path, origin);
if (url.origin !== origin || !(url.pathname === '/api' || url.pathname.startsWith('/api/'))) {
throw new Error('invalid api path');
}
return `${url.pathname}${url.search}`;
}
function toast(message) {
const el = document.getElementById('toast');
if (!el) return;
el.textContent = message;
el.classList.add('visible');
clearTimeout(toast._t);
toast._t = setTimeout(() => el.classList.remove('visible'), 3200);
}
async function api(path, { method = 'GET', body } = {}) {
const res = await fetch(safeApiPath(path), {
method,
headers: {
'content-type': 'application/json',
...(getToken() ? { authorization: `Bearer ${getToken()}` } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
if (res.status === 401) { setToken(''); setProjectId(''); renderAuthUI(); throw new Error('unauthorized'); }
const data = await res.json().catch(() => ({}));
if (!res.ok) throw Object.assign(new Error(data.error || res.statusText), { status: res.status, data });
return data;
}
// ---- realtime (EventSource can't set headers → token via query; ceiling:
// swap for a short-lived stream token before prod so JWTs stay out of URLs)
function subscribe(id) {
if (sse) { sse.close(); sse = null; }
sse = new EventSource(`/api/projects/${id}/stream?token=${encodeURIComponent(getToken())}`);
sse.onmessage = (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch { return; }
if (msg.type === 'update' && typeof msg.version === 'number' && msg.version > version) {
openProject(id, { silent: true }).then(() => toast('실시간 업데이트를 반영했습니다.')).catch(() => {});
}
};
}
async function openProject(id, { silent = false } = {}) {
const p = await api(`/api/projects/${id}`);
setProjectId(id);
currentOrgId = p.orgId || projectsCache.find((x) => String(x.id) === String(id))?.orgId || currentOrgId;
version = p.version;
host?.hydrateState({ projectName: p.name, baseDate: p.baseDate, tasks: p.tasks });
host?.renderAll();
subscribe(id);
// opening = seen: clear the unseen badge for this project
notifCache.delete(String(id));
api(`/api/projects/${id}/seen`, { method: 'POST' }).catch(() => {});
renderAuthUI();
if (!silent) toast(`'${p.name}' 프로젝트를 열었습니다.`);
}
async function doPush(payload) {
clearTimeout(pushTimer);
pushTimer = null;
try {
const r = await api(`/api/projects/${getProjectId()}`, {
method: 'PUT',
body: { name: payload.projectName, baseDate: payload.baseDate, tasks: payload.tasks, version },
});
version = r.version;
} catch (e) {
if (e.status === 409) {
await openProject(getProjectId(), { silent: true }).catch(() => {});
toast('다른 사용자가 먼저 저장하여 최신본을 불러왔습니다.');
} else if (e.message !== 'unauthorized') {
toast('클라우드 저장 실패 — 로컬에는 저장되었습니다.');
}
}
}
// ---------------------------------------------------------------- public API
export const cloud = {
init(hostApi) {
host = hostApi;
ensureAuthUI();
renderAuthUI();
if (isAuthed()) refreshProjects().then(renderAuthUI).catch(() => {});
},
// Returns the saved project state to hydrate, or null (→ local/seed path).
async boot() {
// public read-only share view (?share=TOKEN) — no account needed
const shareToken = routeTokenPathSegment(new URLSearchParams(location.search).get('share'));
if (shareToken) {
try {
const p = await api(`/api/shared/${shareToken}`);
shareMode = true;
renderAuthUI();
toast('읽기 전용 공유 보기입니다 — 변경은 저장되지 않습니다.');
return { projectName: p.name, baseDate: p.baseDate, tasks: p.tasks };
} catch {
toast('공유 링크가 만료되었거나 철회되었습니다.');
}
}
if (!isAuthed() || !getProjectId()) { renderAuthUI(); return null; }
try {
const p = await api(`/api/projects/${getProjectId()}`);
version = p.version;
currentOrgId = p.orgId || currentOrgId; // team/dashboard need the org right after reload
subscribe(p.id);
renderAuthUI();
return { projectName: p.name, baseDate: p.baseDate, tasks: p.tasks };
} catch {
renderAuthUI();
return null;
}
},
// Called from persistState(). No-op unless logged in with a project open.
push(payload) {
if (shareMode) return; // read-only share view never writes
if (!isAuthed() || !getProjectId()) return;
clearTimeout(pushTimer);
pushTimer = setTimeout(() => doPush(payload), 600);
},
};
// ------------------------------------------------------------------- auth UI
function ensureAuthUI() {
if (document.getElementById('cloud-auth')) return;
const titleRow = document.querySelector('.title-row');
if (!titleRow) return;
const bar = document.createElement('div');
bar.id = 'cloud-auth';
bar.className = 'cloud-auth';
titleRow.appendChild(bar);
// modal (reuses .modal/.hidden conventions from the gantt modal)
const modal = document.createElement('div');
modal.id = 'cloud-modal';
modal.className = 'modal hidden';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
modal.setAttribute('aria-labelledby', 'cloud-modal-title');
modal.innerHTML = `
<div class="modal-backdrop" data-cloud-close="true"></div>
<div class="modal-panel cloud-panel">
<div class="modal-header">
<h2 id="cloud-modal-title">클라우드 로그인</h2>
<button type="button" class="icon-button close-button" data-cloud-close="true" aria-label="닫기"><span aria-hidden="true">✕</span></button>
</div>
<form id="cloud-form" class="cloud-form">
<label class="meta-field"><span>이메일</span><input id="cloud-email" type="email" autocomplete="username" required /></label>
<label class="meta-field cloud-name-field hidden"><span>이름</span><input id="cloud-name" type="text" autocomplete="name" /></label>
<label class="meta-field"><span>비밀번호 (8자 이상)</span><input id="cloud-password" type="password" autocomplete="current-password" minlength="8" required /></label>
<p id="cloud-error" class="cloud-error" role="alert"></p>
<div class="cloud-actions">
<button type="submit" class="primary-button" id="cloud-submit">로그인</button>
<button type="button" class="secondary-button" id="cloud-toggle">계정 만들기</button>
</div>
<button type="button" class="secondary-button" id="cloud-sso" style="width:100%;margin-top:8px">SSO로 로그인 (OIDC)</button>
</form>
</div>`;
document.body.appendChild(modal);
let mode = 'login';
const $ = (id) => modal.querySelector(id);
const setMode = (m) => {
mode = m;
$('#cloud-modal-title').textContent = m === 'login' ? '클라우드 로그인' : '계정 만들기';
$('#cloud-submit').textContent = m === 'login' ? '로그인' : '가입';
$('#cloud-toggle').textContent = m === 'login' ? '계정 만들기' : '로그인으로';
modal.querySelector('.cloud-name-field').classList.toggle('hidden', m !== 'signup');
$('#cloud-error').textContent = '';
};
$('#cloud-toggle').addEventListener('click', () => setMode(mode === 'login' ? 'signup' : 'login'));
$('#cloud-sso').addEventListener('click', () => { window.location.href = '/api/auth/oidc/start'; });
modal.addEventListener('click', (e) => { if (e.target.dataset.cloudClose) modal.classList.add('hidden'); });
$('#cloud-form').addEventListener('submit', async (e) => {
e.preventDefault();
const email = $('#cloud-email').value.trim();
const password = $('#cloud-password').value;
const name = $('#cloud-name').value.trim();
try {
const r = await api(`/api/auth/${mode === 'login' ? 'login' : 'signup'}`, { method: 'POST', body: { email, password, name } });
setToken(r.token);
modal.classList.add('hidden');
await refreshProjects();
renderAuthUI();
toast(mode === 'login' ? '로그인되었습니다.' : '가입되어 클라우드 저장이 켜졌습니다.');
} catch (err) {
$('#cloud-error').textContent = err.data?.error || err.message || '요청 실패';
}
});
bar._openModal = () => { setMode('login'); modal.classList.remove('hidden'); $('#cloud-email').focus(); };
}
let projectsCache = [];
let notifCache = new Map(); // projectId -> unseen count
async function refreshProjects() {
try { projectsCache = (await api('/api/projects')).projects || []; } catch { projectsCache = []; }
try {
const n = await api('/api/notifications');
notifCache = new Map((n.notifications || []).map((x) => [String(x.projectId), x.unseen]));
} catch { notifCache = new Map(); }
}
function renderAuthUI() {
const bar = document.getElementById('cloud-auth');
if (!bar) return;
bar.textContent = '';
if (shareMode) {
const tag = document.createElement('span');
tag.className = 'team-role-tag';
tag.textContent = '읽기 전용 공유 보기';
bar.appendChild(tag);
return;
}
if (!isAuthed()) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'secondary-button';
btn.textContent = '☁ 클라우드 로그인';
btn.addEventListener('click', openLoginModal);
bar.appendChild(btn);
return;
}
// logged in: onboarding (no projects yet) → sample; else project switcher.
if (!projectsCache.length) {
const sample = document.createElement('button');
sample.type = 'button';
sample.className = 'primary-button';
sample.textContent = '✨ 샘플로 시작';
sample.addEventListener('click', sampleStart);
bar.appendChild(sample);
}
const select = document.createElement('select');
select.className = 'cloud-select';
select.setAttribute('aria-label', '프로젝트 선택');
const openId = getProjectId();
const ph = document.createElement('option');
ph.value = '';
ph.textContent = projectsCache.length ? '프로젝트 선택…' : '프로젝트 없음';
select.appendChild(ph);
for (const p of projectsCache.filter((x) => !x.archived)) {
const opt = document.createElement('option');
opt.value = String(p.id);
const unseen = notifCache.get(String(p.id));
opt.textContent = unseen ? `${p.name} ●${unseen}` : p.name; // textContent → XSS-safe
if (String(p.id) === String(openId)) opt.selected = true;
select.appendChild(opt);
}
const archivedProjects = projectsCache.filter((x) => x.archived);
if (archivedProjects.length) {
const group = document.createElement('optgroup');
group.label = '보관됨';
for (const p of archivedProjects) {
const opt = document.createElement('option');
opt.value = String(p.id);
opt.textContent = `📦 ${p.name}`;
if (String(p.id) === String(openId)) opt.selected = true;
group.appendChild(opt);
}
select.appendChild(group);
}
select.addEventListener('change', () => { if (select.value) openProject(select.value).catch((e) => toast(e.message)); });
bar.appendChild(select);
const newBtn = document.createElement('button');
newBtn.type = 'button';
newBtn.className = 'secondary-button';
newBtn.textContent = '+ 새 프로젝트';
newBtn.addEventListener('click', createProjectFlow);
bar.appendChild(newBtn);
const dash = document.createElement('button');
dash.type = 'button';
dash.className = 'secondary-button';
dash.textContent = '대시보드';
dash.addEventListener('click', () => openPortfolioModal().catch((e) => toast(e.message || '대시보드를 불러오지 못했습니다.')));
bar.appendChild(dash);
const team = document.createElement('button');
team.type = 'button';
team.className = 'secondary-button';
team.textContent = '팀';
team.addEventListener('click', () => openTeamModal().catch((e) => toast(e.message || '팀 정보를 불러오지 못했습니다.')));
bar.appendChild(team);
if (getProjectId()) {
const bl = document.createElement('button');
bl.type = 'button';
bl.className = 'secondary-button';
bl.textContent = '기준선';
bl.addEventListener('click', () => openBaselineModal().catch((e) => toast(e.message || '기준선을 불러오지 못했습니다.')));
bar.appendChild(bl);
const dup = document.createElement('button');
dup.type = 'button';
dup.className = 'secondary-button';
dup.textContent = '복제';
dup.addEventListener('click', async () => {
const name = prompt('새 프로젝트 이름 (템플릿으로 복제)');
if (name === null) return;
try {
const created = await api(`/api/projects/${getProjectId()}/duplicate`, { method: 'POST', body: { name } });
await refreshProjects();
await openProject(created.id);
toast(`"${created.name}" 프로젝트로 복제했습니다.`);
} catch (err) { toast(err.data?.error || err.message); }
});
bar.appendChild(dup);
const share = document.createElement('button');
share.type = 'button';
share.className = 'secondary-button';
share.textContent = '공유';
share.addEventListener('click', () => openShareModal().catch((e) => toast(e.data?.error || e.message)));
bar.appendChild(share);
const report = document.createElement('button');
report.type = 'button';
report.className = 'secondary-button';
report.textContent = '주간보고';
report.addEventListener('click', () => { try { openReportModal(); } catch (e) { toast(e.message || '보고서 생성 실패'); } });
bar.appendChild(report);
const msp = document.createElement('button');
msp.type = 'button';
msp.className = 'secondary-button';
msp.textContent = 'MSP 가져오기';
msp.addEventListener('click', () => {
let fi = document.getElementById('msp-file-input');
if (!fi) {
fi = document.createElement('input');
fi.id = 'msp-file-input';
fi.type = 'file';
fi.accept = '.xml,text/xml';
fi.hidden = true;
fi.addEventListener('change', () => {
const f = fi.files?.[0];
fi.value = '';
if (f) importMsProjectFile(f).catch((e) => toast(e.message || 'MSP 가져오기에 실패했습니다.'));
});
document.body.appendChild(fi);
}
fi.click();
});
bar.appendChild(msp);
const cur = projectsCache.find((x) => String(x.id) === String(getProjectId()));
const arch = document.createElement('button');
arch.type = 'button';
arch.className = 'secondary-button';
arch.textContent = cur?.archived ? '보관 해제' : '보관';
arch.addEventListener('click', async () => {
try {
const res = await api(`/api/projects/${getProjectId()}/archive`, { method: 'POST', body: { archived: !cur?.archived } });
await refreshProjects();
renderAuthUI();
toast(res.archived ? '프로젝트를 보관했습니다.' : '보관을 해제했습니다.');
} catch (err) { toast(err.data?.error || err.message); }
});
bar.appendChild(arch);
}
const search = document.createElement('button');
search.type = 'button';
search.className = 'secondary-button';
search.textContent = '검색';
search.addEventListener('click', openSearchModal);
bar.appendChild(search);
if (getProjectId()) {
const spr = document.createElement('button');
spr.type = 'button';
spr.className = 'secondary-button';
spr.textContent = '스프린트';
spr.addEventListener('click', () => openSprintModal().catch((e) => toast(e.data?.error || e.message)));
bar.appendChild(spr);
const att = document.createElement('button');
att.type = 'button';
att.className = 'secondary-button';
att.textContent = '산출물';
att.addEventListener('click', () => openAttachmentsModal().catch((e) => toast(e.data?.error || e.message)));
bar.appendChild(att);
const cmt = document.createElement('button');
cmt.type = 'button';
cmt.className = 'secondary-button';
cmt.textContent = '코멘트';
cmt.addEventListener('click', () => openCommentsModal().catch((e) => toast(e.message || '코멘트를 불러오지 못했습니다.')));
bar.appendChild(cmt);
}
const out = document.createElement('button');
out.type = 'button';
out.className = 'secondary-button';
out.textContent = '로그아웃';
out.addEventListener('click', () => {
if (sse) { sse.close(); sse = null; }
setToken(''); setProjectId(''); projectsCache = [];
renderAuthUI();
toast('로그아웃되었습니다. 로컬 저장으로 전환합니다.');
});
bar.appendChild(out);
}
function openLoginModal() {
const modal = document.getElementById('cloud-modal');
const bar = document.getElementById('cloud-auth');
if (bar && bar._openModal) return bar._openModal();
modal?.classList.remove('hidden');
}
// Create a cloud project and seed it with `seedState` (defaults to what's on
// screen). Used by both "새 프로젝트" and the "샘플로 시작" onboarding.
async function makeProject(name, seedState) {
const r = await api('/api/projects', { method: 'POST', body: { name } });
await refreshProjects();
version = r.version;
setProjectId(r.id);
const meta = projectsCache.find((x) => String(x.id) === String(r.id));
if (meta) currentOrgId = meta.orgId;
const base = seedState || host?.getState?.() || { baseDate: '', tasks: [] };
await doPush({ ...base, projectName: name }); // keep the chosen project name
subscribe(r.id);
renderAuthUI();
return r;
}
async function createProjectFlow() {
const name = prompt('새 프로젝트 이름');
if (!name || !name.trim()) return;
try {
await makeProject(name.trim());
toast(`'${name.trim()}' 프로젝트를 만들었습니다.`);
} catch (e) {
toast(e.message || '프로젝트 생성 실패');
}
}
// Onboarding: a first project pre-populated from the app's source-backed seed
// (whatever app.js has loaded on screen — the wbs.json sample for a new user).
async function sampleStart() {
try {
await makeProject('샘플 프로젝트', host?.getState?.());
toast('샘플 프로젝트로 시작했습니다. 자유롭게 편집하세요.');
} catch (e) {
toast(e.message || '샘플 프로젝트 생성 실패');
}
}
// ------------------------------------------------------------- team / RBAC UI
const ROLE_LABELS = { owner: '소유자', admin: '관리자', member: '멤버', viewer: '뷰어' };
async function exportOrg() {
try {
const res = await fetch(`/api/orgs/${currentOrgId}/export`, { headers: { authorization: `Bearer ${getToken()}` } });
if (res.status === 403) return toast('소유자만 데이터를 내보낼 수 있습니다.');
if (!res.ok) return toast('내보내기에 실패했습니다.');
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `scopeweave-org-${currentOrgId}.json`;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
toast('워크스페이스 데이터를 내보냈습니다.');
} catch {
toast('내보내기에 실패했습니다.');
}
}
async function resolveOrgId() {
if (currentOrgId) return currentOrgId;
const me = await api('/api/me');
currentOrgId = me.orgs?.[0]?.id || null;
return currentOrgId;
}
// ---------------------------------------------------------------- share links
async function openShareModal() {
const pid = getProjectId();
if (!pid) return;
let modal = document.getElementById('share-modal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'share-modal';
modal.className = 'modal';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop';
backdrop.addEventListener('click', () => modal.classList.add('hidden'));
const panel = document.createElement('div');
panel.className = 'modal-panel';
panel.id = 'share-panel';
modal.append(backdrop, panel);
document.body.appendChild(modal);
}
modal.classList.remove('hidden');
const panel = modal.querySelector('#share-panel');
panel.textContent = '';
const head = document.createElement('div');
head.className = 'modal-header';
const h2 = document.createElement('h2');
h2.textContent = '읽기 전용 공유';
const close = document.createElement('button');
close.type = 'button';
close.className = 'icon-button close-button';
close.setAttribute('aria-label', '공유 닫기');
close.textContent = '✕';
close.addEventListener('click', () => modal.classList.add('hidden'));
head.append(h2, close);
panel.appendChild(head);
const make = document.createElement('button');
make.type = 'button';
make.className = 'primary-button';
make.textContent = '공유 링크 만들기';
make.addEventListener('click', async () => {
try {
const res = await api(`/api/projects/${pid}/shares`, { method: 'POST' });
const url = `${location.origin}${res.url}`;
try { await navigator.clipboard.writeText(url); toast('공유 링크를 복사했습니다.'); }
catch { prompt('공유 링크 (복사하세요)', url); }
openShareModal();
} catch (e) { toast(e.data?.error || e.message); }
});
panel.appendChild(make);
const list = document.createElement('ul');
list.className = 'team-list';
panel.appendChild(list);
const data = await api(`/api/projects/${pid}/shares`);
if (!data.shares.length) {
const li = document.createElement('li');
li.textContent = '활성 공유 링크가 없습니다.';
list.appendChild(li);
return;
}
for (const sRow of data.shares) {
const li = document.createElement('li');
const who = document.createElement('span');
who.className = 'team-who';
who.textContent = `${location.origin}/?share=${sRow.token.slice(0, 8)}… · ${String(sRow.createdAt).slice(0, 10)}`;
const copyB = document.createElement('button');
copyB.type = 'button';
copyB.className = 'secondary-button';
copyB.textContent = '복사';
copyB.addEventListener('click', async () => {
const url = `${location.origin}/?share=${sRow.token}`;
try { await navigator.clipboard.writeText(url); toast('복사했습니다.'); } catch { prompt('공유 링크', url); }
});
const rev = document.createElement('button');
rev.type = 'button';
rev.className = 'secondary-button team-remove';
rev.textContent = '철회';
rev.addEventListener('click', () =>
api(`/api/projects/${pid}/shares/${sRow.id}`, { method: 'DELETE' })
.then(() => { toast('공유를 철회했습니다.'); openShareModal(); })
.catch((e) => toast(e.data?.error || e.message)));
li.append(who, copyB, rev);
list.appendChild(li);
}
}
// ------------------------------------------------------------ weekly report
// 주간보고 generator — the PM deliverable, straight from live data.
// Pure: takes tasks + a reference date, returns markdown.
export function buildWeeklyReport(tasks, refDate, projectName = '') {
const ref = new Date(refDate);
if (Number.isNaN(ref.getTime())) return '';
const day = (d) => d.toISOString().slice(0, 10);
const monday = new Date(ref);
monday.setDate(ref.getDate() - ((ref.getDay() + 6) % 7)); // this week's Monday
const weekStart = day(monday);
const weekEnd = day(new Date(monday.getTime() + 6 * 86400000));
const nextStart = day(new Date(monday.getTime() + 7 * 86400000));
const nextEnd = day(new Date(monday.getTime() + 13 * 86400000));
const today = day(ref);
const name = (t) => t.name || t.task || t.activity || t.phase || t.id;
const leaf = (tasks || []).filter((t) => !t.isSynthetic);
const done = leaf.filter((t) => t.actualEndDate && t.actualEndDate >= weekStart && t.actualEndDate <= weekEnd);
const doing = leaf.filter((t) => {
const a = Number(t.actualProgress) || 0;
return a > 0 && a < 100 && !t.actualEndDate;
});
const late = leaf.filter((t) => t.plannedEndDate && t.plannedEndDate < today && (Number(t.actualProgress) || 0) < 100);
const upcoming = leaf.filter((t) => t.plannedStartDate && t.plannedStartDate >= nextStart && t.plannedStartDate <= nextEnd);
let wSum = 0, pv = 0, ev = 0;
for (const t of leaf) {
const w = Number(t.weight) || 1;
wSum += w;
pv += w * ((Number(t.plannedProgress) || 0) / 100);
ev += w * ((Number(t.actualProgress) || 0) / 100);
}
const pvPct = wSum ? (pv / wSum) * 100 : 0;
const evPct = wSum ? (ev / wSum) * 100 : 0;
const spi = pvPct > 0 ? evPct / pvPct : null;
const section = (title, items, fmt) =>
`## ${title}\n${items.length ? items.map((t) => `- ${fmt(t)}`).join('\n') : '- (없음)'}`;
return [
`# 주간보고${projectName ? ` — ${projectName}` : ''} (${weekStart} ~ ${weekEnd})`,
'',
`**진척 요약**: 계획 ${pvPct.toFixed(1)}% · 실적 ${evPct.toFixed(1)}%` +
(spi === null ? '' : ` · SPI ${spi.toFixed(2)} (${spi >= 1 ? '일정 준수' : spi >= 0.9 ? '경미한 지연' : '지연 위험'})`),
'',
section('금주 완료', done, (t) => `${name(t)} (${t.actualEndDate})`),
'',
section('진행 중', doing, (t) => `${name(t)} — ${Number(t.actualProgress) || 0}%${t.owner ? ` (${t.owner})` : ''}`),
'',
section('지연', late, (t) => `${name(t)} — 계획종료 ${t.plannedEndDate}, 실적 ${Number(t.actualProgress) || 0}%${t.owner ? ` (${t.owner})` : ''}`),
'',
section('차주 예정', upcoming, (t) => `${name(t)} (${t.plannedStartDate} 시작${t.owner ? `, ${t.owner}` : ''})`),
'',
].join('\n');
}
function openReportModal() {
const state = host?.getState?.();
if (!state) { toast('프로젝트를 먼저 여세요.'); return; }
const md = buildWeeklyReport(state.tasks, new Date().toISOString().slice(0, 10), state.projectName || '');
let modal = document.getElementById('report-modal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'report-modal';
modal.className = 'modal';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop';
backdrop.addEventListener('click', () => modal.classList.add('hidden'));
const panel = document.createElement('div');
panel.className = 'modal-panel';
panel.id = 'report-panel';
modal.append(backdrop, panel);
document.body.appendChild(modal);
}
modal.classList.remove('hidden');
const panel = modal.querySelector('#report-panel');
panel.textContent = '';
const head = document.createElement('div');
head.className = 'modal-header';
const h2 = document.createElement('h2');
h2.textContent = '주간보고';
const close = document.createElement('button');
close.type = 'button';
close.className = 'icon-button close-button';
close.setAttribute('aria-label', '주간보고 닫기');
close.textContent = '✕';
close.addEventListener('click', () => modal.classList.add('hidden'));
head.append(h2, close);
panel.appendChild(head);
const copy = document.createElement('button');
copy.type = 'button';
copy.className = 'primary-button';
copy.textContent = '마크다운 복사';
copy.addEventListener('click', async () => {
try { await navigator.clipboard.writeText(md); toast('주간보고를 복사했습니다.'); }
catch { toast('복사에 실패했습니다 — 아래 내용을 직접 선택하세요.'); }
});
panel.appendChild(copy);
const ai = document.createElement('button');
ai.type = 'button';
ai.className = 'secondary-button';
ai.style.marginLeft = '8px';
ai.textContent = 'AI 요약';
ai.addEventListener('click', async () => {
ai.disabled = true;
ai.textContent = '분석 중…';
try {
const res = await api(`/api/projects/${getProjectId()}/ai/brief`, { method: 'POST' });
let box = document.getElementById('report-ai');
if (!box) {
box = document.createElement('pre');
box.id = 'report-ai';
box.style.whiteSpace = 'pre-wrap';
box.style.borderLeft = '3px solid var(--primary, #2563eb)';
box.style.paddingLeft = '10px';
panel.insertBefore(box, panel.querySelector('#report-body'));
}
box.textContent = `🤖 AI 브리핑\n${res.analysis}`;
} catch (e) { toast(e.data?.error || e.message); }
finally { ai.disabled = false; ai.textContent = 'AI 요약'; }
});
panel.appendChild(ai);
const pre = document.createElement('pre');
pre.id = 'report-body';
pre.style.whiteSpace = 'pre-wrap';
pre.style.userSelect = 'text';
pre.textContent = md;
panel.appendChild(pre);
}
// ------------------------------------------------------- MS Project import
// Parse Microsoft Project XML (Project 2003+ .xml export) into ScopeWeave's
// task schema. ponytail: regex block parsing (MSP XML is machine-generated,
// no DOMParser needed → node-testable); swap for a real XML parser if
// hand-edited files ever matter.
export function parseMsProjectXml(xml) {
const tag = (block, name) => {
const m = block.match(new RegExp(`<${name}>([^<]*)</${name}>`));
return m ? m[1].trim() : '';
};
const unescape = (s) => s
.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
.replace(/'/g, "'").replace(/&/g, '&');
const day = (s) => (/^\d{4}-\d{2}-\d{2}/.test(s) ? s.slice(0, 10) : '');
const tasks = [];
const parents = {}; // depth -> last task id at that depth
const blocks = xml.match(/<Task>[\s\S]*?<\/Task>/g) || [];
for (const block of blocks) {
const uid = tag(block, 'UID');
const name = unescape(tag(block, 'Name'));
if (!uid || uid === '0' || !name) continue; // project-summary row / blanks
const level = Math.max(1, Number(tag(block, 'OutlineLevel')) || 1);
const depth = Math.min(level, 3); // deeper levels flatten to task level
const preds = [...block.matchAll(/<PredecessorLink>[\s\S]*?<PredecessorUID>(\d+)<\/PredecessorUID>[\s\S]*?<\/PredecessorLink>/g)]
.map((m) => `msp-${m[1]}`);
const pct = Number(tag(block, 'PercentComplete')) || 0;
const t = {
id: `msp-${uid}`,
parentId: depth > 1 ? (parents[depth - 1] || '') : '',
depth,
phase: depth === 1 ? name : '',
activity: depth === 2 ? name : '',
task: depth === 3 ? name : '',
name,
plannedStartDate: day(tag(block, 'Start')),
plannedEndDate: day(tag(block, 'Finish')),
actualProgress: pct,
predecessors: preds.join(','),
};
tasks.push(t);
parents[depth] = t.id;
for (let d = depth + 1; d <= 3; d++) delete parents[d]; // reset deeper chain
}
return tasks;
}
async function importMsProjectFile(file) {
const xml = await file.text();
const tasks = parseMsProjectXml(xml);
if (!tasks.length) { toast('가져올 작업이 없습니다 (MSP XML 형식을 확인하세요).'); return; }
if (!confirm(`MS Project에서 ${tasks.length}개 작업을 가져옵니다. 현재 프로젝트 내용을 대체합니다.`)) return;
// preserve name/baseDate — only the task tree is replaced
const prev = host?.getState?.() || {};
host?.hydrateState({ projectName: prev.projectName, baseDate: prev.baseDate, tasks });
host?.renderAll();
const state = host?.getState?.();
if (state) await doPush(state);
toast(`MS Project에서 ${tasks.length}개 작업을 가져왔습니다.`);
}
// ------------------------------------------------------------- portfolio
// Executive rollup: every project's weighted progress, SPI, and overdue count.
async function openPortfolioModal() {
if (!currentOrgId) { toast('워크스페이스를 먼저 선택하세요.'); return; }
let modal = document.getElementById('portfolio-modal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'portfolio-modal';
modal.className = 'modal';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop';
backdrop.addEventListener('click', () => modal.classList.add('hidden'));
const panel = document.createElement('div');
panel.className = 'modal-panel';
panel.id = 'portfolio-panel';
modal.append(backdrop, panel);
document.body.appendChild(modal);
}
modal.classList.remove('hidden');
const panel = modal.querySelector('#portfolio-panel');
panel.textContent = '';
const head = document.createElement('div');
head.className = 'modal-header';
const h2 = document.createElement('h2');
h2.textContent = '포트폴리오 대시보드';
const close = document.createElement('button');
close.type = 'button';
close.className = 'icon-button close-button';
close.setAttribute('aria-label', '대시보드 닫기');
close.textContent = '✕';
close.addEventListener('click', () => modal.classList.add('hidden'));
head.append(h2, close);
panel.appendChild(head);
const data = await api(`/api/orgs/${currentOrgId}/portfolio`);
const active = data.projects.filter((p) => !p.archived);
if (!active.length) {
const p = document.createElement('p');
p.textContent = '프로젝트가 없습니다.';
panel.appendChild(p);
return;
}
const summary = document.createElement('p');
const late = active.filter((p) => p.status === 'delay').length;
const totOverdue = active.reduce((n, p) => n + p.overdue, 0);
summary.textContent = `프로젝트 ${active.length}개 · 주의/지연 ${late}개 · 지연 작업 합계 ${totOverdue}건`;
panel.appendChild(summary);
const wrap = document.createElement('div');
wrap.style.overflowX = 'auto';
const table = document.createElement('table');
table.className = 'wbs-table';
const thead = document.createElement('thead');
const hr = document.createElement('tr');
for (const t of ['프로젝트', '작업', '계획%', '실적%', 'SPI', '상태', '지연', '']) {
const th = document.createElement('th');
th.textContent = t;
hr.appendChild(th);
}
thead.appendChild(hr);
const tbody = document.createElement('tbody');
for (const p of active) {
const tr = document.createElement('tr');
const cells = [p.name, String(p.tasks), `${p.planned}%`, `${p.actual}%`, p.spi === null ? '-' : p.spi.toFixed(2), p.label, p.overdue ? `${p.overdue}건` : '-'];
for (const cText of cells) {
const td = document.createElement('td');
td.textContent = cText;
tr.appendChild(td);
}
if (p.status === 'delay') tr.style.color = 'var(--delay, #ea580c)';
const td = document.createElement('td');
const open = document.createElement('button');
open.type = 'button';
open.className = 'secondary-button';
open.textContent = '열기';
open.addEventListener('click', async () => {
modal.classList.add('hidden');
await openProject(p.id).catch((err) => toast(err.message));
});
td.appendChild(open);
tr.appendChild(td);
tbody.appendChild(tr);
}
table.append(thead, tbody);
wrap.appendChild(table);
panel.appendChild(wrap);
}
// --------------------------------------------------------------- sprints
// Agile/Hybrid 지표 (순수): 스프린트별 커밋/완료 스토리포인트와 팀 벨로시티.
// 작업 배정 = task.sprint(이름 일치), 추정 = task.storyPoints, 완료 = 실적 100%.
export function computeSprintStats(tasks, sprints, today) {
const leaf = (tasks || []).filter((t) => !t.isSynthetic);
const rows = (sprints || []).map((sp) => {
const mine = leaf.filter((t) => String(t.sprint || '').trim() === sp.name);
const pts = (t) => Number(t.storyPoints) || 0;
const committed = mine.reduce((n, t) => n + pts(t), 0);
const completed = mine.filter((t) => (Number(t.actualProgress) || 0) >= 100).reduce((n, t) => n + pts(t), 0);
const closed = Boolean(sp.endDate && today && sp.endDate < today);
return { id: sp.id, name: sp.name, startDate: sp.startDate, endDate: sp.endDate, goal: sp.goal, taskCount: mine.length, committed, completed, remaining: committed - completed, closed };
});
const closedWithWork = rows.filter((r) => r.closed && r.committed > 0);
const velocity = closedWithWork.length
? closedWithWork.reduce((n, r) => n + r.completed, 0) / closedWithWork.length
: null;
const backlog = leaf.filter((t) => !String(t.sprint || '').trim() || !(sprints || []).some((sp) => sp.name === String(t.sprint).trim()));
return { rows, velocity, backlogCount: backlog.length };
}
// 번다운 (순수): 스프린트 기간의 일별 잔여 포인트 — ideal(선형 소진) vs
// actual(완료일 actualEndDate 기준; 완료일 없는 100% 작업은 오늘 완료로 간주).
export function computeBurndown(tasks, sprint, today) {
if (!sprint?.startDate || !sprint?.endDate || sprint.endDate < sprint.startDate) return null;
const leaf = (tasks || []).filter((t) => !t.isSynthetic && String(t.sprint || '').trim() === sprint.name);
const pts = (t) => Number(t.storyPoints) || 0;
const committed = leaf.reduce((n, t) => n + pts(t), 0);
if (committed <= 0) return null;
const days = [];
for (let d = new Date(sprint.startDate); ; d.setDate(d.getDate() + 1)) {
const iso = d.toISOString().slice(0, 10);
days.push(iso);
if (iso >= sprint.endDate) break;
if (days.length > 120) break; // 안전 상한
}
const n = days.length;
const ideal = days.map((_, i) => committed * (1 - (n === 1 ? 1 : i / (n - 1))));
const doneAt = (t) => t.actualEndDate || ((Number(t.actualProgress) || 0) >= 100 ? today : null);
const actual = days.map((day) => {
if (today && day > today) return null; // 미래는 미기록
const burned = leaf.filter((t) => { const d = doneAt(t); return d && d <= day; }).reduce((s2, t) => s2 + pts(t), 0);
return committed - burned;
});
return { days, committed, ideal, actual };
}
function renderBurndownSvg(bd) {
const W = 420, H = 110, PAD = 6;
const n = bd.days.length;
const x = (i) => PAD + (n === 1 ? 0 : (i / (n - 1)) * (W - 2 * PAD));
const y = (v) => H - PAD - (v / bd.committed) * (H - 2 * PAD);
const NS = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(NS, 'svg');
svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
svg.setAttribute('role', 'img');
svg.setAttribute('aria-label', `번다운: 커밋 ${bd.committed}pt`);
svg.style.width = '100%';
svg.style.maxWidth = '460px';
const grid = document.createElementNS(NS, 'line');
grid.setAttribute('x1', PAD); grid.setAttribute('x2', W - PAD);
grid.setAttribute('y1', y(0)); grid.setAttribute('y2', y(0));
grid.setAttribute('stroke', '#e2e8f0');
svg.appendChild(grid);
const idealLine = document.createElementNS(NS, 'polyline');
idealLine.setAttribute('points', bd.ideal.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' '));
idealLine.setAttribute('fill', 'none');
idealLine.setAttribute('stroke', '#94a3b8');
idealLine.setAttribute('stroke-dasharray', '4 3');
svg.appendChild(idealLine);
const actualPts = bd.actual.map((v, i) => (v === null ? null : `${x(i).toFixed(1)},${y(v).toFixed(1)}`)).filter(Boolean);
if (actualPts.length) {
const actualLine = document.createElementNS(NS, 'polyline');
actualLine.setAttribute('points', actualPts.join(' '));
actualLine.setAttribute('fill', 'none');
actualLine.setAttribute('stroke', '#2563eb');
actualLine.setAttribute('stroke-width', '2');
svg.appendChild(actualLine);
}
return svg;
}
const METHODOLOGY_LABELS = { waterfall: 'Waterfall (예측형)', agile: 'Agile (적응형)', hybrid: 'Hybrid (혼합형)' };
async function openSprintModal() {
const pid = getProjectId();
if (!pid) return;
let modal = document.getElementById('sprint-modal');
if (!modal) {
modal = document.createElement('div');
modal.id = 'sprint-modal';
modal.className = 'modal';
modal.setAttribute('role', 'dialog');
modal.setAttribute('aria-modal', 'true');
const backdrop = document.createElement('div');
backdrop.className = 'modal-backdrop';
backdrop.addEventListener('click', () => modal.classList.add('hidden'));
const panel = document.createElement('div');
panel.className = 'modal-panel';
panel.id = 'sprint-panel';
modal.append(backdrop, panel);
document.body.appendChild(modal);
}
modal.classList.remove('hidden');
const panel = modal.querySelector('#sprint-panel');
panel.textContent = '';
const head = document.createElement('div');
head.className = 'modal-header';
const h2 = document.createElement('h2');
h2.textContent = '스프린트 (Agile / Hybrid)';
const close = document.createElement('button');
close.type = 'button';
close.className = 'icon-button close-button';