-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogress.js
More file actions
1393 lines (1308 loc) · 58.5 KB
/
Copy pathprogress.js
File metadata and controls
1393 lines (1308 loc) · 58.5 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
const STORE_KEY = "mgpic2026.registration.v1";
const CHECK_KEY = "mgpic2026.repoCheck.v1";
const FEISHU_KEY = "mgpic2026.feishuStatus.v1";
const FEISHU_ROWS_KEY = "mgpic2026.feishuRows.v1";
const GITHUB_PROFILE_KEY = "mgpic2026.githubProfile.v1";
const AI_REVIEWS_KEY = "mgpic2026.aiReviews.v1";
const NOTIFICATIONS_KEY = "mgpic2026.notifications.v1";
const START_DATE_ISO = "2026-04-28T16:00:00Z";
const MAX_UPLOAD_SIZE = 10 * 1024 * 1024;
const PROPOSAL_FORM_URL = "https://www.gitlink.org.cn/competitions/track1_2026MoonBit";
const DEFAULT_RENDER_API_BASE = "https://mgpic2026.onrender.com";
const API_BASE = resolveApiBase();
const PUBLIC_SELF_SERVICE_ENABLED = true;
let progressActionsBound = false;
let backendSyncStarted = false;
let githubSessionSyncStarted = false;
const $ = (selector, root = document) => root.querySelector(selector);
const escapeHtml = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ({
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'",
}[char]));
function normalizeApiBase(value) {
const text = String(value || "").trim().replace(/\/+$/, "");
if (!text) return "";
try {
const url = new URL(text);
if (!["http:", "https:"].includes(url.protocol)) return "";
return url.href.replace(/\/+$/, "");
} catch {
return "";
}
}
function resolveApiBase() {
const explicit = normalizeApiBase(window.MGPIC_API_BASE);
if (explicit) return explicit;
if (/github\.io$/i.test(window.location.hostname)) return DEFAULT_RENDER_API_BASE;
return "";
}
function hostedPage(path) {
const cleanPath = String(path || "").replace(/^\//, "");
if (API_BASE && /github\.io$/i.test(window.location.hostname)) return `${API_BASE}/${cleanPath}`;
return cleanPath;
}
const fieldAliases = {
name: ["姓名", "参赛者", "项目负责人", "负责人", "name"],
email: ["邮箱", "联系邮箱", "联系方式", "email", "Email"],
githubLogin: ["GitHub 账号", "Github 账号", "GitHub用户名", "GitHub 用户名", "github", "githubLogin"],
githubRepo: ["GitHub 仓库", "Github 仓库", "项目 GitHub 链接", "GitHub仓库链接", "仓库链接", "githubRepo", "repo"],
projectName: ["项目名称", "项目名", "参赛项目", "projectName", "project"],
proposal: ["申报审核状态", "项目申报状态", "立项状态", "申报状态", "proposal", "proposalStatus"],
acceptance: ["验收状态", "项目验收状态", "验收审核状态", "acceptance", "acceptanceStatus"],
reward: ["奖励状态", "激励状态", "奖金状态", "reward", "rewardStatus"],
showcase: ["作品墙状态", "展示状态", "上墙状态", "showcase", "showcaseStatus"],
};
function loadJson(key, fallback = null) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch {
return fallback;
}
}
function saveJson(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
async function apiRequest(path, options = {}) {
const response = await fetch(`${API_BASE}${path}`, {
...options,
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
...(options.headers || {}),
},
});
if (!response.ok) {
const error = new Error(`接口 ${response.status}`);
error.status = response.status;
try {
error.payload = await response.json();
if (error.payload?.error) error.message = error.payload.error;
} catch {
// Ignore non-JSON error pages, for example GitHub Pages 404.
}
throw error;
}
if (response.status === 204) return null;
return response.json();
}
async function backendHealth() {
try {
return await apiRequest("/api/health", { method: "GET" });
} catch {
return null;
}
}
function currentReturnTo() {
const page = window.location.pathname.split("/").pop() || "progress.html";
return page === "register.html" ? "/register.html" : "/progress.html";
}
function githubOAuthStartUrl() {
return `${API_BASE}/api/auth/github/start?return_to=${encodeURIComponent(currentReturnTo())}`;
}
function saveGitHubSessionUser(user) {
if (!user?.login) return;
const profile = {
login: user.login,
name: user.name || "",
email: user.email || "",
avatarUrl: user.avatarUrl || "",
htmlUrl: user.htmlUrl || "",
oauth: true,
connectedAt: new Date().toISOString(),
};
saveJson(GITHUB_PROFILE_KEY, profile);
const previous = getRegistration();
saveJson(STORE_KEY, publicRegistrationValue({
...previous,
githubLogin: previous.githubLogin || profile.login,
email: previous.email || profile.email || "",
updatedAt: new Date().toISOString(),
}));
}
function applyGitHubSessionToForms(user) {
if (!user?.login) return;
const progressForm = $("#progress-connect-form");
if (progressForm) {
if (!progressForm.elements.githubLogin.value) progressForm.elements.githubLogin.value = user.login;
if (user.email && !progressForm.elements.email.value) progressForm.elements.email.value = user.email;
}
const registerForm = $("#registration-form");
if (registerForm) {
if (!registerForm.elements.githubLogin.value) registerForm.elements.githubLogin.value = user.login;
if (user.email && !registerForm.elements.email.value) registerForm.elements.email.value = user.email;
}
renderRegisterGitHubStatus(user);
}
async function syncGitHubOAuthSession(force = false) {
if (githubSessionSyncStarted && !force) return null;
githubSessionSyncStarted = true;
try {
const session = await apiRequest("/api/auth/github/session", { method: "GET" });
if (session?.authenticated && session.user) {
const hadOAuth = Boolean(getGitHubProfile()?.oauth);
saveGitHubSessionUser(session.user);
applyGitHubSessionToForms(session.user);
applyFeishuMatch(getFeishuRows());
renderProgressDashboard();
const loginCard = $("#progress-login");
if (loginCard?.dataset.enhanced === "true" && !hadOAuth) {
loginCard.dataset.enhanced = "false";
initProgressPage();
}
return session;
}
return session;
} catch {
return null;
}
}
async function startGitHubOAuth(message) {
if (message) {
message.hidden = false;
message.className = "progress-alert";
message.textContent = "正在连接 GitHub 授权服务...";
}
try {
const session = await apiRequest("/api/auth/github/session", { method: "GET" });
if (session?.authenticated && session.user) {
saveGitHubSessionUser(session.user);
applyGitHubSessionToForms(session.user);
if (message) {
message.className = "progress-alert progress-alert--ok";
message.textContent = `已通过 GitHub 登录:@${session.user.login}`;
}
renderRegisterGitHubStatus(session.user);
renderProgressDashboard();
const loginCard = $("#progress-login");
if (loginCard) {
loginCard.dataset.enhanced = "false";
initProgressPage();
}
return;
}
if (session?.configured === false) {
throw new Error("后端未配置 GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET,暂时不能发起 GitHub 授权。");
}
window.location.href = githubOAuthStartUrl();
} catch (error) {
if (message) {
message.className = "progress-alert progress-alert--error";
message.textContent = error.status === 404
? "Render OAuth 接口还不可用。请确认 Render 服务已创建并正在运行,然后配置 GitHub OAuth App。"
: error.message;
}
}
}
async function logoutGitHubOAuth(message) {
try {
await apiRequest("/api/auth/github/logout", { method: "POST" });
} catch {
// Static previews do not have a backend session to clear.
}
localStorage.removeItem(GITHUB_PROFILE_KEY);
if (message) {
message.hidden = false;
message.className = "progress-alert progress-alert--ok";
message.textContent = "已退出 GitHub 登录。";
}
renderProgressDashboard();
}
function githubAuthMessage() {
const authStatus = new URLSearchParams(window.location.search).get("github_auth");
return {
ok: "GitHub 登录成功,已同步账号信息。",
not_configured: "Render 后端已连接,但还没有配置 GitHub OAuth App 的 Client ID / Secret。",
denied: "你取消了 GitHub 授权。",
state_error: "GitHub 授权状态已失效,请重新登录。",
failed: "GitHub 授权失败,请稍后重试。",
}[authStatus || ""];
}
function githubUserForDisplay(user = getGitHubProfile()) {
return user?.login ? user : null;
}
function renderRegisterGitHubStatus(user = getGitHubProfile()) {
const target = $("#register-github-status");
if (!target) return;
const profile = githubUserForDisplay(user);
const authMessage = githubAuthMessage();
target.innerHTML = `
<div class="register-github-identity">
${profile?.avatarUrl ? `<img src="${escapeHtml(profile.avatarUrl)}" alt="@${escapeHtml(profile.login)}">` : ""}
<div>
<strong>${profile ? `已登录 GitHub:@${escapeHtml(profile.login)}` : "建议先使用 GitHub 一键登录"}</strong>
<p>${profile ? "报名表会自动带入 GitHub 用户名和邮箱;后续比赛进度也会按该账号匹配。" : "只申请读取公开资料和邮箱,不会申请私有仓库权限。登录后可减少手填并方便后续查看比赛进度。"}</p>
</div>
</div>
<div class="register-github-actions">
<button class="button primary" type="button" data-action="github-oauth">${profile ? "刷新 GitHub 信息" : "使用 GitHub 一键登录"}</button>
${profile ? `<button class="button secondary" type="button" data-action="github-logout">退出 GitHub 登录</button>` : ""}
</div>
<div class="progress-alert ${authMessage?.includes("成功") ? "progress-alert--ok" : authMessage ? "progress-alert--error" : ""}" id="register-github-message" ${authMessage ? "" : "hidden"}>${escapeHtml(authMessage || "")}</div>
`;
target.querySelectorAll("[data-action='github-oauth']").forEach((button) => {
button.addEventListener("click", () => startGitHubOAuth($("#register-github-message") || $("#registration-message")));
});
target.querySelector("[data-action='github-logout']")?.addEventListener("click", () => {
logoutGitHubOAuth($("#register-github-message") || $("#registration-message"));
target.dataset.refreshed = "false";
renderRegisterGitHubStatus(null);
});
}
function safeHttpUrl(value) {
try {
const url = new URL(String(value || ""));
return ["http:", "https:"].includes(url.protocol) ? url.href : "";
} catch {
return "";
}
}
function parseRepo(input) {
const value = (input || "").trim().replace(/\/$/, "");
if (!value) return null;
const match = value.match(/github\.com\/([^/\s]+)\/([^/\s#?]+?)(?:\.git)?$/i)
|| value.match(/^([^/\s]+)\/([^/\s#?]+)$/);
if (!match) return null;
return {
owner: match[1],
repo: match[2].replace(/\.git$/i, ""),
url: `https://github.com/${match[1]}/${match[2].replace(/\.git$/i, "")}`,
};
}
function normalizeText(value) {
return String(value || "").trim().toLowerCase();
}
function normalizeRepo(value) {
const parsed = parseRepo(value);
return parsed ? parsed.url.toLowerCase() : normalizeText(value).replace(/\.git$/, "");
}
function normalizedKeys(row) {
return Object.fromEntries(Object.keys(row || {}).map((key) => [key.replace(/\s+/g, "").toLowerCase(), key]));
}
function fieldToString(value) {
if (Array.isArray(value)) return value.map(fieldToString).filter(Boolean).join(",");
if (value && typeof value === "object") {
return String(value.text || value.name || value.value || value.url || value.link || "").trim();
}
return String(value ?? "").trim();
}
function getField(row, key) {
const source = row?.fields && typeof row.fields === "object" ? { ...row, ...row.fields } : row;
const aliases = fieldAliases[key] || [key];
const compact = normalizedKeys(source);
for (const alias of aliases) {
if (source?.[alias] !== undefined && fieldToString(source[alias])) return fieldToString(source[alias]);
const compactKey = compact[String(alias).replace(/\s+/g, "").toLowerCase()];
if (compactKey && fieldToString(source[compactKey])) return fieldToString(source[compactKey]);
}
return "";
}
async function githubJson(path) {
const response = await fetch(`https://api.github.com${path}`, {
headers: { Accept: "application/vnd.github+json" },
});
if (!response.ok) {
const error = new Error(`GitHub API ${response.status}`);
error.status = response.status;
throw error;
}
return response.json();
}
async function exists(path) {
try {
await githubJson(path);
return true;
} catch {
return false;
}
}
function hasPath(tree, matcher) {
return Array.isArray(tree?.tree) && tree.tree.some((item) => matcher(item.path || ""));
}
function buildCheckResult(parsed, repoInfo, commits, tree, readmeExists, workflowExists, licenseExists, packageExists) {
const commitCount = Array.isArray(commits) ? commits.length : 0;
const hasTests = hasPath(tree, (path) => /(^|\/)(test|tests|__tests__)(\/|$)/i.test(path) || /_test\.mbt$/i.test(path));
const hasMoonBitCode = hasPath(tree, (path) => /\.mbt$/i.test(path));
const checks = [
{ key: "publicRepo", label: "公开仓库", passed: repoInfo.private === false, detail: repoInfo.private ? "仓库不是公开状态" : "GitHub 仓库公开可访问" },
{ key: "commits", label: "有效 commits", passed: commitCount >= 10, detail: `4 月 29 日后检测到 ${commitCount >= 100 ? "100+" : commitCount} 个公开 commits` },
{ key: "readme", label: "README", passed: readmeExists, detail: readmeExists ? "已检测到 README" : "未检测到 README" },
{ key: "ci", label: "CI", passed: workflowExists, detail: workflowExists ? "已检测到 .github/workflows" : "未检测到 CI workflow" },
{ key: "tests", label: "测试", passed: hasTests, detail: hasTests ? "已检测到测试目录或 _test.mbt" : "未检测到测试目录或 _test.mbt" },
{ key: "license", label: "许可证", passed: Boolean(repoInfo.license || licenseExists), detail: repoInfo.license?.spdx_id || (licenseExists ? "已检测到 LICENSE" : "未检测到 LICENSE") },
{ key: "moonbit", label: "MoonBit 代码", passed: hasMoonBitCode, detail: hasMoonBitCode ? "已检测到 .mbt 源码" : "未检测到 .mbt 源码" },
{ key: "package", label: "包配置", passed: packageExists, detail: packageExists ? "已检测到 moon.mod.json 或 moon.pkg.json" : "未检测到 MoonBit 包配置" },
];
return {
owner: parsed.owner,
repo: parsed.repo,
repoUrl: parsed.url,
defaultBranch: repoInfo.default_branch,
checkedAt: new Date().toISOString(),
commitCount,
checks,
};
}
async function checkRepository(repoInput) {
const parsed = parseRepo(repoInput);
if (!parsed) throw new Error("请输入 GitHub 仓库地址,例如 https://github.com/owner/project");
const repoInfo = await githubJson(`/repos/${parsed.owner}/${parsed.repo}`);
const commits = await githubJson(`/repos/${parsed.owner}/${parsed.repo}/commits?since=${encodeURIComponent(START_DATE_ISO)}&per_page=100`);
const tree = await githubJson(`/repos/${parsed.owner}/${parsed.repo}/git/trees/${repoInfo.default_branch}?recursive=1`);
const readmeExists = await exists(`/repos/${parsed.owner}/${parsed.repo}/readme`);
const workflowExists = await exists(`/repos/${parsed.owner}/${parsed.repo}/contents/.github/workflows?ref=${repoInfo.default_branch}`);
const licenseExists = await exists(`/repos/${parsed.owner}/${parsed.repo}/contents/LICENSE?ref=${repoInfo.default_branch}`)
|| await exists(`/repos/${parsed.owner}/${parsed.repo}/contents/LICENSE.md?ref=${repoInfo.default_branch}`);
const packageExists = await exists(`/repos/${parsed.owner}/${parsed.repo}/contents/moon.mod.json?ref=${repoInfo.default_branch}`)
|| await exists(`/repos/${parsed.owner}/${parsed.repo}/contents/moon.pkg.json?ref=${repoInfo.default_branch}`)
|| await exists(`/repos/${parsed.owner}/${parsed.repo}/contents/moon.pkg?ref=${repoInfo.default_branch}`);
return buildCheckResult(parsed, repoInfo, commits, tree, readmeExists, workflowExists, licenseExists, packageExists);
}
async function connectGitHubProfile(input) {
const login = String(input || "").trim().replace(/^@/, "");
if (!login) return null;
const profile = await githubJson(`/users/${encodeURIComponent(login)}`);
const value = {
login: profile.login,
name: profile.name || "",
avatarUrl: profile.avatar_url || "",
htmlUrl: profile.html_url || "",
type: profile.type || "",
connectedAt: new Date().toISOString(),
};
saveJson(GITHUB_PROFILE_KEY, value);
return value;
}
function parseCsv(text) {
const rows = [];
let row = [];
let cell = "";
let quoted = false;
const input = String(text || "").replace(/^\uFEFF/, "");
for (let index = 0; index < input.length; index += 1) {
const char = input[index];
const next = input[index + 1];
if (char === "\"" && quoted && next === "\"") {
cell += "\"";
index += 1;
} else if (char === "\"") {
quoted = !quoted;
} else if (char === "," && !quoted) {
row.push(cell);
cell = "";
} else if ((char === "\n" || char === "\r") && !quoted) {
if (char === "\r" && next === "\n") index += 1;
row.push(cell);
if (row.some((item) => String(item).trim())) rows.push(row);
row = [];
cell = "";
} else {
cell += char;
}
}
row.push(cell);
if (row.some((item) => String(item).trim())) rows.push(row);
if (rows.length < 2) return [];
const headers = rows[0].map((item) => String(item).trim());
return rows.slice(1).map((items) => Object.fromEntries(headers.map((header, index) => [header, String(items[index] || "").trim()])));
}
function parseDataset(text) {
const value = String(text || "").trim();
if (!value) return [];
if (value.startsWith("[") || value.startsWith("{")) {
const parsed = JSON.parse(value);
if (Array.isArray(parsed)) return parsed;
if (Array.isArray(parsed.records)) return parsed.records;
if (Array.isArray(parsed.items)) return parsed.items;
if (Array.isArray(parsed.data)) return parsed.data;
if (Array.isArray(parsed.data?.records)) return parsed.data.records;
if (Array.isArray(parsed.data?.items)) return parsed.data.items;
return [];
}
return parseCsv(value);
}
function compactRecord(row) {
return {
name: getField(row, "name"),
email: getField(row, "email"),
githubLogin: getField(row, "githubLogin"),
githubRepo: getField(row, "githubRepo"),
projectName: getField(row, "projectName"),
proposal: getField(row, "proposal"),
acceptance: getField(row, "acceptance"),
reward: getField(row, "reward"),
showcase: getField(row, "showcase"),
};
}
function getRegistration() {
return loadJson(STORE_KEY, {});
}
function getCheck() {
return loadJson(CHECK_KEY, null);
}
function getGitHubProfile() {
return loadJson(GITHUB_PROFILE_KEY, null);
}
function getFeishuRows() {
return loadJson(FEISHU_ROWS_KEY, []);
}
function getNotifications() {
return loadJson(NOTIFICATIONS_KEY, []);
}
function getFeishuState() {
return loadJson(FEISHU_KEY, {
proposal: "待同步",
acceptance: "未提交",
reward: "未开始",
showcase: "待上墙",
source: "none",
});
}
function maskSensitive(value, keepStart = 3, keepEnd = 4) {
const text = String(value || "").trim();
if (!text) return "";
if (text.length <= keepStart + keepEnd) return "*".repeat(text.length);
return `${text.slice(0, keepStart)}${"*".repeat(text.length - keepStart - keepEnd)}${text.slice(-keepEnd)}`;
}
function publicRegistrationValue(value) {
const {
proposalFile,
studentFile,
idFrontFile,
idBackFile,
idNumber,
bankAccount,
bankBranch,
...safeValue
} = value || {};
return {
...safeValue,
idNumberMasked: safeValue.idNumberMasked || maskSensitive(idNumber),
bankAccountMasked: safeValue.bankAccountMasked || maskSensitive(bankAccount),
sensitiveSubmitted: Boolean(
safeValue.sensitiveSubmitted ||
idNumber ||
bankAccount ||
bankBranch ||
safeValue.idFrontFileName ||
safeValue.idBackFileName
),
};
}
function saveRegistrationFromForm(form) {
const formData = new FormData(form);
const previous = getRegistration();
const value = {
...previous,
name: String(formData.get("name") || "").trim(),
email: String(formData.get("email") || "").trim(),
school: String(formData.get("school") || "").trim(),
idNumber: String(formData.get("idNumber") || "").trim(),
githubLogin: String(formData.get("githubLogin") || "").trim(),
githubRepo: String(formData.get("githubRepo") || "").trim(),
projectName: String(formData.get("projectName") || "").trim(),
projectType: String(formData.get("projectType") || "").trim(),
summary: String(formData.get("summary") || "").trim(),
bankAccount: String(formData.get("bankAccount") || "").trim(),
bankBranch: String(formData.get("bankBranch") || "").trim(),
proposalFileName: form.elements.proposalFile?.files?.[0]?.name || previous.proposalFileName || "",
studentFileName: form.elements.studentFile?.files?.[0]?.name || previous.studentFileName || "",
idFrontFileName: form.elements.idFrontFile?.files?.[0]?.name || previous.idFrontFileName || "",
idBackFileName: form.elements.idBackFile?.files?.[0]?.name || previous.idBackFileName || "",
updatedAt: new Date().toISOString(),
};
saveJson(STORE_KEY, publicRegistrationValue({
...value,
id: "",
serverId: "",
backendMode: "pending",
backendError: "",
backendSavedAt: "",
}));
applyFeishuMatch(getFeishuRows());
return value;
}
function backendPayload(value) {
return {
name: value.name || "",
email: value.email || "",
school: value.school || "",
idNumber: value.idNumber || "",
githubLogin: value.githubLogin || "",
githubRepo: value.githubRepo || "",
projectName: value.projectName || "",
projectType: value.projectType || "",
summary: value.summary || "",
bankAccount: value.bankAccount || "",
bankBranch: value.bankBranch || "",
proposalFileName: value.proposalFileName || "",
studentFileName: value.studentFileName || "",
idFrontFileName: value.idFrontFileName || "",
idBackFileName: value.idBackFileName || "",
proposalFile: value.proposalFile || null,
studentFile: value.studentFile || null,
idFrontFile: value.idFrontFile || null,
idBackFile: value.idBackFile || null,
};
}
async function saveRegistrationToBackend(value) {
const previous = getRegistration();
const serverId = value.serverId || previous.serverId;
const payload = backendPayload(value);
try {
let result = null;
if (serverId) {
try {
result = await apiRequest(`/api/registrations/${encodeURIComponent(serverId)}`, {
method: "PUT",
body: JSON.stringify(payload),
});
} catch (error) {
if (![401, 403, 404].includes(error.status)) throw error;
result = await apiRequest("/api/registrations", {
method: "POST",
body: JSON.stringify(payload),
});
}
} else {
result = await apiRequest("/api/registrations", {
method: "POST",
body: JSON.stringify(payload),
});
}
if (!result?.registration?.id) {
throw new Error("服务器没有返回报名记录,请重新提交。");
}
const saved = publicRegistrationValue({
...value,
...result.registration,
id: result.registration.id,
serverId: result.registration.id,
backendMode: "sqlite",
backendError: "",
backendSavedAt: result.registration.updatedAt || result.registration.createdAt || new Date().toISOString(),
});
saveJson(STORE_KEY, saved);
return { mode: "backend", registration: saved };
} catch (error) {
const saved = publicRegistrationValue({
...value,
id: "",
serverId: "",
backendMode: "local",
backendError: error.message,
});
saveJson(STORE_KEY, saved);
return { mode: "local", registration: saved, error };
}
}
async function syncRegistrationFromBackend() {
const current = getRegistration();
if (!current.serverId || backendSyncStarted) return;
if (!getGitHubProfile()?.oauth) return;
backendSyncStarted = true;
try {
const result = await apiRequest(`/api/registrations/${encodeURIComponent(current.serverId)}`);
saveBackendBundle(result, current);
renderProgressDashboard();
renderPlanPanels(true);
} catch {
// The public GitHub Pages preview has no backend; keep the local copy usable.
}
}
function saveBackendBundle(result, previous = getRegistration()) {
if (!result?.registration) return;
saveJson(STORE_KEY, {
...previous,
...result.registration,
serverId: result.registration.id,
backendMode: "sqlite",
backendSavedAt: result.registration.updatedAt,
files: result.files || previous.files || [],
});
if (result.status) saveJson(FEISHU_KEY, { ...getFeishuState(), ...result.status, source: "backend" });
if (result.repoCheck) saveJson(CHECK_KEY, result.repoCheck);
if (result.aiReviews) saveJson(AI_REVIEWS_KEY, result.aiReviews);
if (result.notifications) saveJson(NOTIFICATIONS_KEY, result.notifications);
}
async function saveRepoCheckToBackend(result) {
const registration = getRegistration();
if (!registration.serverId) return;
try {
await apiRequest(`/api/registrations/${encodeURIComponent(registration.serverId)}/repo-check`, {
method: "POST",
body: JSON.stringify(result),
});
} catch {
// Keep GitHub Pages preview functional without a backend.
}
}
async function saveStatusToBackend(state) {
const registration = getRegistration();
if (!registration.serverId) return null;
try {
return await apiRequest(`/api/registrations/${encodeURIComponent(registration.serverId)}/status`, {
method: "PATCH",
body: JSON.stringify(state),
});
} catch {
return null;
}
}
function matchFeishuRecord(rows) {
const registration = getRegistration();
const check = getCheck();
const profile = getGitHubProfile();
const email = normalizeText(registration.email);
const repo = normalizeRepo(registration.githubRepo || check?.repoUrl);
const login = normalizeText(registration.githubLogin || profile?.login || check?.owner);
const project = normalizeText(registration.projectName || check?.repo);
const records = rows.map((row) => ({ raw: row, compact: compactRecord(row) }));
const matchers = [
{ field: "邮箱", test: (item) => email && normalizeText(item.compact.email) === email },
{ field: "GitHub 仓库", test: (item) => repo && normalizeRepo(item.compact.githubRepo) === repo },
{ field: "GitHub 账号", test: (item) => login && normalizeText(item.compact.githubLogin).replace(/^@/, "") === login },
{ field: "项目名称", test: (item) => project && normalizeText(item.compact.projectName) === project },
];
for (const matcher of matchers) {
const found = records.find(matcher.test);
if (found) return { record: found.compact, matchField: matcher.field };
}
return { record: null, matchField: "" };
}
function applyFeishuMatch(rows) {
const dataRows = Array.isArray(rows) ? rows : [];
const { record, matchField } = matchFeishuRecord(dataRows);
if (!dataRows.length) {
saveJson(FEISHU_KEY, {
proposal: "待同步",
acceptance: "未提交",
reward: "未开始",
showcase: "待上墙",
source: "none",
});
return null;
}
if (!record) {
saveJson(FEISHU_KEY, {
proposal: "已导入,未匹配",
acceptance: "未匹配",
reward: "未匹配",
showcase: "未匹配",
source: "feishu-import",
rowCount: dataRows.length,
matchedAt: new Date().toISOString(),
});
return null;
}
const state = {
proposal: record.proposal || "申报状态未填写",
acceptance: record.acceptance || "验收未提交",
reward: record.reward || "奖励未开始",
showcase: record.showcase || "待上墙",
source: "feishu-import",
rowCount: dataRows.length,
matchField,
record,
matchedAt: new Date().toISOString(),
};
saveJson(FEISHU_KEY, state);
return state;
}
function statusDone(value) {
return /通过|完成|已发放|已上墙|展示中|done|pass/i.test(String(value || ""));
}
function inferStage(registration, check, feishu) {
const passed = check?.checks?.filter((item) => item.passed).length || 0;
const total = check?.checks?.length || 8;
const hasRegistration = Boolean(registration.projectName || registration.githubRepo);
if (statusDone(feishu.acceptance)) return { stage: "已通过验收", next: "等待评选与作品展示" };
if (statusDone(feishu.proposal) && passed >= Math.max(6, total - 1)) return { stage: "具备验收准备条件", next: "等待官方验收安排" };
if (statusDone(feishu.proposal)) return { stage: "项目开发中", next: "补齐仓库检查项" };
if (/拒绝|不通过|需调整|驳回/i.test(String(feishu.proposal || ""))) return { stage: "申报需调整", next: "修改申报材料后重交" };
if (hasRegistration) return { stage: "申报审核中", next: "等待审核或补齐仓库" };
return { stage: "等待项目信息", next: "填写报名信息" };
}
function statusClass(passed) {
return passed ? "progress-check-card progress-check-card--pass" : "progress-check-card progress-check-card--fail";
}
function humanTime(iso) {
if (!iso) return "尚未检查";
try {
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
}).format(new Date(iso));
} catch {
return "尚未检查";
}
}
function renderAvatar(profile) {
if (!profile) return "";
const avatarUrl = safeHttpUrl(profile?.avatarUrl);
if (avatarUrl) return `<img src="${escapeHtml(avatarUrl)}" alt="${escapeHtml(profile.login || "GitHub")}">`;
return profile?.login ? escapeHtml(profile.login.slice(0, 2).toUpperCase()) : "";
}
function progressSourceCard(label, title, body, tone = "") {
return `
<div class="progress-source-card ${tone ? `progress-source-card--${tone}` : ""}">
<span>${escapeHtml(label)}</span>
<strong>${escapeHtml(title)}</strong>
<p>${escapeHtml(body)}</p>
</div>
`;
}
function renderCheckArea(checks, hasRepo) {
if (!hasRepo) {
return `
<div class="progress-empty-check">
<span>仓库检查</span>
<strong>填写 GitHub 仓库后开始检查</strong>
<p>系统会检查公开仓库、4 月 29 日后的有效 commits、README、CI、测试、许可证、MoonBit 代码和包配置。</p>
</div>
`;
}
if (!checks.length) {
return `
<div class="progress-empty-check">
<span>仓库检查</span>
<strong>仓库已填写,等待首次检查</strong>
<p>点击“检查公开仓库”后,这里会显示每一项是否通过。</p>
</div>
`;
}
return `
<div class="progress-check-grid">
${checks.map((item) => `
<div class="${statusClass(item.passed)}">
<span>${item.passed ? "通过" : "待补"}</span>
<strong>${escapeHtml(item.label)}</strong>
<p>${escapeHtml(item.detail)}</p>
</div>
`).join("")}
</div>
`;
}
function progressFlowItems(registration, check, feishu, profile) {
const passed = check?.checks?.filter((item) => item.passed).length || 0;
const total = check?.checks?.length || 8;
const hasRegistration = Boolean(registration.projectName || registration.githubRepo);
const hasRepoCheck = Boolean(check?.checks?.length);
return [
{
title: "GitHub 登录",
body: profile?.oauth ? `已连接 @${profile.login}` : "建议先登录,后续用账号匹配进度。",
done: Boolean(profile?.oauth),
current: !profile?.oauth,
},
{
title: "官方渠道申报",
body: hasRegistration ? "已通过官方渠道填写项目或仓库信息,等待赛方审核。" : "通过官方渠道提交报名信息、GitHub 仓库和 PDF 申报书。",
done: hasRegistration || statusDone(feishu.proposal),
current: Boolean(profile?.oauth && !hasRegistration),
},
{
title: "仓库检查",
body: hasRepoCheck ? `已通过 ${passed} / ${total} 项。` : "检查 commits、README、CI、测试、许可证和包配置。",
done: hasRepoCheck && passed >= Math.max(6, total - 1),
current: hasRegistration && !hasRepoCheck,
},
{
title: "申报审核",
body: feishu.proposal || "等待赛方审核结果。",
done: statusDone(feishu.proposal),
current: hasRegistration && !statusDone(feishu.proposal),
warn: /拒绝|不通过|需调整|驳回/i.test(String(feishu.proposal || "")),
},
{
title: "项目验收",
body: feishu.acceptance || "完成后按官方通知准备验收材料。",
done: statusDone(feishu.acceptance),
current: statusDone(feishu.proposal) && !statusDone(feishu.acceptance),
},
{
title: "作品展示",
body: feishu.showcase || "优秀项目有机会进入作品墙。",
done: statusDone(feishu.showcase),
current: statusDone(feishu.acceptance) && !statusDone(feishu.showcase),
},
];
}
function renderProgressFlow(registration, check, feishu, profile) {
return `
<div class="progress-flow-strip">
${progressFlowItems(registration, check, feishu, profile).map((item, index) => `
<div class="${item.done ? "is-done" : item.warn ? "is-warn" : item.current ? "is-current" : ""}">
<span>${index + 1}</span>
<strong>${escapeHtml(item.title)}</strong>
<p>${escapeHtml(item.body)}</p>
</div>
`).join("")}
</div>
`;
}
function renderProgressDashboard() {
const dashboard = $(".progress-dashboard--preview");
if (!dashboard) return;
const registration = getRegistration();
const check = getCheck();
const profile = getGitHubProfile();
const feishu = getFeishuState();
const notifications = getNotifications();
const lastNotification = notifications[0];
const parsedRepo = parseRepo(registration.githubRepo || check?.repoUrl);
const repoUrl = parsedRepo?.url || "";
const passed = check?.checks?.filter((item) => item.passed).length || 0;
const total = check?.checks?.length || 8;
const hasRegistration = Boolean(registration.projectName || registration.githubRepo);
const hasFeishuMatch = Boolean(feishu.record);
const { stage, next } = inferStage(registration, check, feishu);
const hasRepo = Boolean(repoUrl);
const hasBackendRecord = registration.backendMode === "sqlite";
const hasImportedFeishu = feishu.source && feishu.source !== "none";
const hasShowcaseState = statusDone(feishu.acceptance) || statusDone(feishu.showcase) || /候选|已上墙|暂不展示/.test(String(feishu.showcase || ""));
const percent = Math.max(12, Math.round(((profile ? 1 : 0) + (hasRegistration ? 1 : 0) + (hasFeishuMatch ? 1 : 0) + passed) / (total + 3) * 100));
const checks = check?.checks || [];
const title = registration.projectName || check?.repo || profile?.login || "比赛进度看板";
const repoLine = repoUrl
? `<a href="${escapeHtml(repoUrl)}" target="_blank" rel="noreferrer">${escapeHtml(repoUrl)}</a>`
: "先填写报名信息或 GitHub 仓库,系统再生成检查结果。";
const sourceCards = [
progressSourceCard(
"GitHub 账号",
profile ? `@${profile.login}` : "可选登录",
profile?.oauth
? "已通过 GitHub OAuth 授权;只读取公开资料和邮箱。"
: "可用 GitHub 一键登录自动带入账号;也可以只填写公开仓库地址。",
profile ? "ok" : ""
),
progressSourceCard(
"报名信息",
hasRegistration ? "已填写" : "待填写",
hasRegistration
? (registration.email || "已保存项目名称或 GitHub 仓库,可继续检查仓库。")
: "先完成官方渠道申报,后续才能匹配审核、奖励和验收状态。",
hasRegistration ? "ok" : "todo"
),
];
if (hasBackendRecord || registration.backendMode === "local" || registration.backendError) {
sourceCards.push(progressSourceCard(
"报名记录",
hasBackendRecord ? "已同步" : "待同步",
hasBackendRecord
? "赛方可基于这条记录审核和更新流程;报名编号不作为查询凭证。"
: "当前仅保留浏览器本地进度,后续请以正式提交结果为准。",
hasBackendRecord ? "ok" : "todo"
));
}
if (hasImportedFeishu) {
sourceCards.push(progressSourceCard(
"赛方报名数据",
hasFeishuMatch ? "已匹配" : feishu.proposal,
hasFeishuMatch ? `通过${feishu.matchField}匹配,状态来自赛方数据。` : "赛方已同步报名数据,但还没有匹配到当前项目。",
hasFeishuMatch ? "ok" : "todo"
));
}
if (hasShowcaseState) {
sourceCards.push(progressSourceCard(
"作品墙状态",
feishu.showcase || "待上墙",
"通过验收或表现突出的项目可进入展示墙。",
statusDone(feishu.showcase) ? "ok" : ""
));
}
if (lastNotification) {
sourceCards.push(progressSourceCard(
"通知状态",
lastNotification.status || "已记录",
lastNotification.subject || lastNotification.error || "赛方已生成通知记录。",
lastNotification.status === "sent" ? "ok" : ""
));
}
const avatarMarkup = renderAvatar(profile);
dashboard.innerHTML = `
<div class="progress-user-row ${avatarMarkup ? "" : "progress-user-row--no-avatar"}">
${avatarMarkup ? `<div class="progress-avatar">${avatarMarkup}</div>` : ""}
<div>
<strong>${escapeHtml(title)}</strong>
<p>${repoLine}</p>
</div>