-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2579 lines (2421 loc) · 108 KB
/
Copy pathapp.js
File metadata and controls
2579 lines (2421 loc) · 108 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 DATA = window.STUDY_DATA;
const STORAGE = {
todos: "study-manager-v2-todos",
homeworks: "study-manager-v2-homeworks",
studyMetrics: "study-manager-v2-study-metrics",
plans: "study-manager-v2-plans",
jobs: "study-manager-v2-jobs",
events: "study-manager-v2-events",
menus: "study-manager-v2-menus",
timetable: "study-manager-v2-timetable",
settings: "study-manager-v2-settings",
studyLogs: "study-manager-v2-study-logs",
subjectProgress: "study-manager-v2-subject-progress",
understandingScores: "study-manager-v2-understanding-scores",
};
const SUPABASE_CONFIG = window.STUDY_MANAGER_SUPABASE || {};
const SUPABASE_BUCKET = SUPABASE_CONFIG.storageBucket || "study-files";
let supabaseClient = null;
let syncSaveTimer = null;
let isApplyingRemote = false;
let syncChannel = null;
let syncState = {
configured: false,
status: "offline",
user: null,
message: "Supabase未設定",
lastJob: null,
lastWorkerAt: null,
lastUploadResult: null,
lastAiJobResult: null,
lastError: null,
lastStorageCheck: null,
};
const routes = [
{ id: "home", label: "ホーム", icon: "home" },
{ id: "calendar", label: "カレンダー", icon: "calendar" },
{ id: "todo", label: "Todo", icon: "check" },
{ id: "homework", label: "宿題", icon: "homework" },
{ id: "questions", label: "問題", icon: "book" },
{ id: "import", label: "AI取り込み", icon: "upload" },
{ id: "settings", label: "設定", icon: "settings" },
];
DATA.today = getTodayKey();
let state = {
route: "home",
calendarTab: "day24",
selectedDate: DATA.today,
homeDate: DATA.today,
selectedYear: Number(DATA.today.slice(0, 4)),
selectedMonth: Number(DATA.today.slice(5, 7)),
todos: loadState(STORAGE.todos, DATA.todos),
homeworks: loadState(STORAGE.homeworks, seedHomeworks()),
studyMetrics: loadState(STORAGE.studyMetrics, {}),
plans: loadState(STORAGE.plans, seedPlans()),
jobs: loadState(STORAGE.jobs, []),
events: loadState(STORAGE.events, DATA.events),
menus: { ...DATA.menus, ...loadState(STORAGE.menus, DATA.menus) },
timetable: loadState(STORAGE.timetable, DATA.timetable),
studyLogs: loadState(STORAGE.studyLogs, []),
subjectProgress: loadState(STORAGE.subjectProgress, []),
understandingScores: loadState(STORAGE.understandingScores, []),
activeClass: null,
scheduleDraft: null,
ocrDraft: null,
settings: loadState(STORAGE.settings, {
ollamaModel: "elyza:jp8b",
ocrLanguage: "japan",
defaultQuestionCount: 10,
}),
};
document.addEventListener("DOMContentLoaded", () => {
renderNav();
renderAll();
bindGlobalActions();
initSupabase();
});
function renderAll() {
renderNavState();
renderHome();
renderCalendar();
renderTodoPage();
renderHomeworkPage();
renderQuestions();
renderImportCenter();
renderSettings();
}
async function initSupabase() {
syncState.configured = Boolean(SUPABASE_CONFIG.url && SUPABASE_CONFIG.anonKey && window.supabase);
if (!syncState.configured) {
syncState.status = "offline";
syncState.message = "supabase-config.jsにURLとanon keyを設定してください";
syncState.lastError = {
context: "supabase-config.js未設定",
message: "Supabase URL、anonKey、またはsupabase-jsが読み込めていません",
code: "",
details: "",
hint: "supabase-config.jsとindex.htmlのscript読み込みを確認してください",
at: new Date().toISOString(),
};
renderAll();
return;
}
supabaseClient = window.supabase.createClient(SUPABASE_CONFIG.url, SUPABASE_CONFIG.anonKey);
const { data } = await supabaseClient.auth.getSession();
syncState.user = data.session?.user || null;
syncState.status = syncState.user ? "online" : "signed_out";
syncState.message = syncState.user ? "Supabase同期中" : "ログインしてください";
if (syncState.user) await loadSupabaseData();
supabaseClient.auth.onAuthStateChange(async (_event, session) => {
syncState.user = session?.user || null;
syncState.status = syncState.user ? "online" : "signed_out";
syncState.message = syncState.user ? "Supabase同期中" : "ログインしてください";
if (syncState.user) {
subscribeSupabaseChanges();
await loadSupabaseData();
}
renderAll();
});
subscribeSupabaseChanges();
renderAll();
}
function isSupabaseReady() {
return Boolean(supabaseClient && syncState.user);
}
async function signInWithEmail(email) {
if (!supabaseClient) {
showToast("Supabaseが未設定です");
return;
}
const redirectTo = `${location.origin}${location.pathname}`;
const { error } = await supabaseClient.auth.signInWithOtp({
email,
options: { emailRedirectTo: redirectTo },
});
if (error) {
showToast(`ログインメール送信に失敗: ${error.message}`);
} else {
showToast("ログイン用メールを送信しました。メール内のリンクを開いてください");
}
}
async function signOutSupabase() {
if (!supabaseClient) return;
if (syncChannel) {
supabaseClient.removeChannel(syncChannel);
syncChannel = null;
}
await supabaseClient.auth.signOut();
syncState.user = null;
syncState.status = "signed_out";
syncState.message = "ログアウトしました";
renderAll();
}
async function loadSupabaseData() {
if (!isSupabaseReady()) return;
isApplyingRemote = true;
try {
const userId = syncState.user.id;
const [{ data: appRows }, { data: todoRows }, { data: jobRows }, { data: resultRows }] = await Promise.all([
supabaseClient.from("app_settings").select("*").eq("user_id", userId).eq("key", "app_state").maybeSingle(),
supabaseClient.from("todos").select("*").eq("user_id", userId).order("created_at", { ascending: false }),
supabaseClient.from("ai_jobs").select("*").eq("user_id", userId).order("created_at", { ascending: false }),
supabaseClient.from("ai_results").select("*").eq("user_id", userId).order("created_at", { ascending: false }),
]);
const hasRemoteAppState = Boolean(appRows?.app_state);
const hasRemoteTodos = Boolean(todoRows?.length);
const appState = appRows?.app_state || {};
if (appState.todos) state.todos = appState.todos;
if (appState.homeworks) state.homeworks = appState.homeworks;
if (appState.studyMetrics) state.studyMetrics = appState.studyMetrics;
if (appState.plans) state.plans = appState.plans;
if (appState.events) state.events = appState.events;
if (appState.menus) state.menus = { ...DATA.menus, ...appState.menus };
if (appState.timetable) state.timetable = appState.timetable;
if (appState.studyLogs) state.studyLogs = appState.studyLogs;
if (appState.subjectProgress) state.subjectProgress = appState.subjectProgress;
if (appState.understandingScores) state.understandingScores = appState.understandingScores;
if (appRows?.settings) state.settings = { ...state.settings, ...appRows.settings };
if (todoRows?.length) state.todos = todoRows.map(dbTodoToState);
state.jobs = await hydrateJobSignedUrls(mapAiJobs(jobRows || [], resultRows || []));
syncState.lastJob = state.jobs[0] || null;
syncState.lastWorkerAt = state.jobs.find((job) => job.worker_processed_at)?.worker_processed_at || null;
cacheAllState();
if (!hasRemoteAppState && !hasRemoteTodos) {
await persistSupabaseNow();
}
syncState.status = "online";
syncState.message = "Supabaseから同期しました";
} catch (error) {
syncState.status = "error";
syncState.message = error.message;
recordSupabaseError("Supabase同期エラー", error);
showToast(`Supabase同期エラー: ${error.message}`);
} finally {
isApplyingRemote = false;
renderAll();
}
}
function subscribeSupabaseChanges() {
if (!supabaseClient || !syncState.user) return;
if (syncChannel) {
supabaseClient.removeChannel(syncChannel);
syncChannel = null;
}
syncChannel = supabaseClient
.channel(`study-manager-${syncState.user.id}`)
.on("postgres_changes", { event: "*", schema: "public", table: "todos", filter: `user_id=eq.${syncState.user.id}` }, () => loadSupabaseData())
.on("postgres_changes", { event: "*", schema: "public", table: "app_settings", filter: `user_id=eq.${syncState.user.id}` }, () => loadSupabaseData())
.on("postgres_changes", { event: "*", schema: "public", table: "ai_jobs", filter: `user_id=eq.${syncState.user.id}` }, () => loadSupabaseData())
.on("postgres_changes", { event: "*", schema: "public", table: "ai_results", filter: `user_id=eq.${syncState.user.id}` }, () => loadSupabaseData())
.subscribe();
}
function cacheAllState() {
saveLocalState(STORAGE.todos, state.todos);
saveLocalState(STORAGE.homeworks, state.homeworks);
saveLocalState(STORAGE.studyMetrics, state.studyMetrics);
saveLocalState(STORAGE.plans, state.plans);
saveLocalState(STORAGE.jobs, state.jobs);
saveLocalState(STORAGE.events, state.events);
saveLocalState(STORAGE.menus, state.menus);
saveLocalState(STORAGE.timetable, state.timetable);
saveLocalState(STORAGE.studyLogs, state.studyLogs);
saveLocalState(STORAGE.subjectProgress, state.subjectProgress);
saveLocalState(STORAGE.understandingScores, state.understandingScores);
saveLocalState(STORAGE.settings, state.settings);
}
function buildAppSnapshot() {
return {
todos: state.todos,
homeworks: state.homeworks,
studyMetrics: state.studyMetrics,
plans: state.plans,
jobs: state.jobs,
events: state.events,
menus: state.menus,
timetable: state.timetable,
settings: state.settings,
studyLogs: state.studyLogs,
subjectProgress: state.subjectProgress,
understandingScores: state.understandingScores,
updatedAt: new Date().toISOString(),
};
}
function persistSupabaseSoon() {
if (isApplyingRemote || !isSupabaseReady()) return;
window.clearTimeout(syncSaveTimer);
syncSaveTimer = window.setTimeout(persistSupabaseNow, 700);
}
async function persistSupabaseNow() {
if (!isSupabaseReady()) return;
try {
const userId = syncState.user.id;
await supabaseClient.from("app_settings").upsert({
user_id: userId,
key: "app_state",
settings: state.settings,
app_state: buildAppSnapshot(),
updated_at: new Date().toISOString(),
}, { onConflict: "user_id,key" });
await upsertTodosToSupabase(userId);
syncState.status = "online";
syncState.message = "Supabaseへ保存しました";
} catch (error) {
syncState.status = "error";
syncState.message = error.message;
}
}
async function upsertTodosToSupabase(userId) {
if (!state.todos.length) return;
const rows = state.todos.map((todo) => ({
user_id: userId,
client_id: todo.id,
title: todo.title,
description: todo.description || "",
subject: todo.subject || "",
due_date: todo.dueDate || todo.due_date || null,
kind: todo.kind || "Todo",
importance: todo.importance || "normal",
completed: Boolean(todo.completed),
countdown_enabled: Boolean(todo.countdownEnabled),
repeat_rule: todo.repeat || "none",
remind_3_days_before: Boolean(todo.remind3DaysBefore),
remind_1_day_before: todo.remind1DayBefore !== false,
remind_on_day: todo.remindOnDay !== false,
show_on_calendar: todo.showOnCalendar !== false,
raw: todo,
updated_at: new Date().toISOString(),
}));
await supabaseClient.from("todos").upsert(rows, { onConflict: "user_id,client_id" });
}
function dbTodoToState(row) {
return {
...(row.raw || {}),
id: row.client_id || row.id,
title: row.title,
description: row.description,
subject: row.subject,
dueDate: row.due_date,
kind: row.kind,
importance: row.importance,
completed: row.completed,
countdownEnabled: row.countdown_enabled,
repeat: row.repeat_rule,
remind3DaysBefore: row.remind_3_days_before,
remind1DayBefore: row.remind_1_day_before,
remindOnDay: row.remind_on_day,
showOnCalendar: row.show_on_calendar,
};
}
function mapAiJobs(jobRows, resultRows) {
const resultsByJob = new Map(resultRows.map((result) => [result.job_id, result]));
return jobRows.map((row) => {
const result = row.result_id ? resultRows.find((item) => item.id === row.result_id) : resultsByJob.get(row.id);
const meta = row.metadata || {};
return {
...(meta || {}),
id: row.id,
job_type: row.job_type,
source_type: row.input_type || meta.source_type || "text",
status: row.status,
created_at: row.created_at,
updated_at: row.updated_at,
started_at: row.started_at,
completed_at: row.completed_at,
worker_processed_at: row.worker_processed_at,
error_message: row.error_message,
ocr_result: row.ocr_layout && Object.keys(row.ocr_layout).length ? row.ocr_layout : row.ocr_text ? { text: row.ocr_text, layout_text: row.ocr_text } : meta.ocr_result || null,
layout_blocks: row.ocr_layout?.blocks || meta.layout_blocks || [],
input_text: row.input_text || "",
result_id: row.result_id,
model_name: row.model_name,
file_path: row.file_path,
file_url: row.file_url,
file_name: meta.file_name || meta.uploaded_file?.name,
original_file_name: meta.original_file_name || meta.file_name || meta.uploaded_file?.name,
storage_file_name: meta.storage_file_name,
storage_path: meta.storage_path || row.file_path,
related_subject: row.subject || meta.related_subject,
related_date: meta.related_date,
related_period: meta.related_period,
related_class: meta.related_class,
uploaded_file: meta.uploaded_file,
material_type: meta.material_type,
result_json: result ? {
summary: result.summary,
important_points: result.important_terms || [],
questions: result.questions || [],
answers: result.answers || [],
understanding_data: result.understanding_data || {},
ocr_layout: result.ocr_layout || null,
} : null,
};
});
}
async function hydrateJobSignedUrls(jobs) {
if (!supabaseClient || !jobs.length) return jobs;
return Promise.all(jobs.map(async (job) => {
if (!job.file_path || job.file_preview_url) return job;
try {
const { data, error } = await supabaseClient.storage.from(SUPABASE_BUCKET).createSignedUrl(job.file_path, 60 * 60);
if (error) return job;
return { ...job, file_preview_url: data?.signedUrl || job.file_url };
} catch {
return job;
}
}));
}
function sanitizeFileName(name) {
return String(name || "upload.bin")
.normalize("NFKC")
.replace(/[\\/:*?"<>|\s]+/g, "_")
.replace(/_+/g, "_")
.slice(0, 120);
}
function getSafeExtension(name) {
const match = String(name || "").match(/\.([a-zA-Z0-9]+)$/);
if (!match) return "";
return `.${match[1].toLowerCase()}`;
}
function createSafeStorageFileName(originalName) {
const ext = getSafeExtension(originalName);
const id = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}_${Math.random().toString(36).slice(2)}`;
return `material_${id}${ext}`;
}
function requireSupabaseUser() {
if (!supabaseClient) {
recordSupabaseError("Supabase未設定", new Error("supabase-config.jsにURLとanon keyを設定してください"));
showToast("supabase-config.jsにURLとanon keyを設定してください");
return false;
}
if (!syncState.user) {
recordSupabaseError("Supabase未ログイン", new Error("SupabaseにログインしてからAI依頼を作成してください"));
showToast("SupabaseにログインしてからAI依頼を作成してください");
return false;
}
if (!syncState.user.id) {
recordSupabaseError("user.id未取得", new Error("ログインユーザーのuser.idを取得できません"));
showToast("ログインユーザーのuser.idを取得できません");
return false;
}
return true;
}
function inputTypeForFile(file) {
if (!file) return "text";
return file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf") ? "pdf" : "image";
}
function recordSupabaseError(context, error) {
const message = supabaseErrorMessage(error);
syncState.lastError = {
context,
message,
code: error?.code || error?.statusCode || error?.status || "",
details: error?.details || "",
hint: error?.hint || "",
at: new Date().toISOString(),
};
syncState.status = "error";
syncState.message = `${context}: ${message}`;
}
function supabaseErrorMessage(error) {
if (!error) return "不明なエラー";
const raw = error.message || error.error_description || error.details || String(error);
const lower = raw.toLowerCase();
if (lower.includes("row-level security") || lower.includes("rls") || lower.includes("policy")) {
return `RLS policy violation: ${raw}`;
}
if (lower.includes("bucket") && lower.includes("not")) {
return `Storage bucketがありません: ${raw}`;
}
if (lower.includes("column") || lower.includes("schema cache")) {
return `DBカラム不一致: ${raw}`;
}
return raw;
}
function recordUploadResult(result) {
syncState.lastUploadResult = {
...result,
at: new Date().toISOString(),
};
}
function recordAiJobResult(result) {
syncState.lastAiJobResult = {
...result,
at: new Date().toISOString(),
};
}
function validateUploadPath(filePath, userId) {
if (!filePath || !userId || !filePath.startsWith(`${userId}/`)) {
throw new Error(`file_pathが不正です。Storage pathは {user_id}/{job_id}/{file_name} 形式にしてください: ${filePath || "空"}`);
}
const parts = filePath.split("/");
if (parts.length < 3 || parts[0] !== userId || !parts[1] || !parts[2]) {
throw new Error(`file_pathが不正です。1階層目はuser.id、2階層目はjob_id、3階層目はfile_nameが必要です: ${filePath}`);
}
if (!/^[a-zA-Z0-9_.-]+$/.test(parts[2])) {
throw new Error(`Invalid key: Storage上のファイル名は英数字・ハイフン・アンダースコアのみで保存してください: ${parts[2]}`);
}
}
async function verifyStorageBucketAccess(userId) {
try {
const { data, error } = await supabaseClient.storage.from(SUPABASE_BUCKET).list(userId, { limit: 1 });
if (error) throw error;
syncState.lastStorageCheck = {
ok: true,
bucket: SUPABASE_BUCKET,
checkedPath: userId,
message: "Storage bucketへアクセスできます",
itemCount: data?.length || 0,
at: new Date().toISOString(),
};
return true;
} catch (error) {
syncState.lastStorageCheck = {
ok: false,
bucket: SUPABASE_BUCKET,
checkedPath: userId,
message: supabaseErrorMessage(error),
at: new Date().toISOString(),
};
recordSupabaseError("Storage bucket確認失敗", error);
throw error;
}
}
async function createSupabaseAiJob({ file = null, jobType, subject = "", inputText = "", prompt = "", metadata = {} }) {
if (!requireSupabaseUser()) throw new Error(syncState.lastError?.message || "Supabase未ログイン");
const userId = syncState.user.id;
const jobId = crypto.randomUUID();
const inputType = inputTypeForFile(file);
let filePath = null;
let fileUrl = null;
let storageFileName = null;
const now = new Date().toISOString();
const fileMeta = file ? {
name: file.name,
size: file.size,
type: file.type || (inputType === "pdf" ? "application/pdf" : "application/octet-stream"),
} : null;
if (file) {
if (!(file instanceof File)) {
const error = new Error("file inputからFileオブジェクトを取得できていません");
recordSupabaseError("File取得失敗", error);
throw error;
}
storageFileName = createSafeStorageFileName(file.name);
filePath = `${userId}/${jobId}/${storageFileName}`;
validateUploadPath(filePath, userId);
await verifyStorageBucketAccess(userId);
try {
const { error: uploadError } = await supabaseClient.storage.from(SUPABASE_BUCKET).upload(filePath, file, {
cacheControl: "3600",
contentType: file.type || "application/octet-stream",
upsert: false,
});
if (uploadError) throw uploadError;
const { data: signedData, error: signedError } = await supabaseClient.storage.from(SUPABASE_BUCKET).createSignedUrl(filePath, 60 * 60);
if (signedError) throw signedError;
fileUrl = signedData?.signedUrl || null;
recordUploadResult({
ok: true,
bucket: SUPABASE_BUCKET,
file_path: filePath,
file_url: fileUrl,
original_file_name: file.name,
safe_file_name: storageFileName,
file_size: file.size,
input_type: inputType,
message: "Storage upload succeeded",
});
} catch (error) {
recordUploadResult({
ok: false,
bucket: SUPABASE_BUCKET,
file_path: filePath,
original_file_name: file.name,
safe_file_name: storageFileName,
input_type: inputType,
message: supabaseErrorMessage(error),
});
recordSupabaseError("Storage upload failed", error);
throw error;
}
}
const jobRow = {
id: jobId,
user_id: userId,
job_type: jobType,
subject,
input_type: inputType,
input_text: inputText,
file_path: filePath,
file_url: fileUrl,
prompt,
status: "pending",
model_name: state.settings.ollamaModel,
metadata: {
...metadata,
source_type: inputType,
uploaded_file: fileMeta,
file_name: fileMeta?.name || null,
original_file_name: fileMeta?.name || null,
storage_file_name: storageFileName,
storage_path: filePath,
file_type: fileMeta?.type || null,
file_size: fileMeta?.size || null,
source: metadata.source || "ai_import_center",
created_from: "github_pages",
},
created_at: now,
updated_at: now,
};
if (filePath && fileMeta) {
try {
const { error: fileError } = await supabaseClient.from("uploaded_files").insert({
user_id: userId,
storage_bucket: SUPABASE_BUCKET,
file_path: filePath,
file_url: fileUrl,
file_name: fileMeta.name,
file_type: fileMeta.type,
file_size: fileMeta.size,
related_subject: subject,
related_date: metadata.related_date || metadata.related_class?.date || null,
related_period: metadata.related_period || metadata.related_class?.period || null,
});
if (fileError) throw fileError;
} catch (error) {
recordSupabaseError("uploaded_files insert failed", error);
throw error;
}
}
let inserted = null;
try {
const { data, error: jobError } = await supabaseClient.from("ai_jobs").insert(jobRow).select("*").single();
if (jobError) throw jobError;
inserted = data;
recordAiJobResult({
ok: true,
id: inserted.id,
status: inserted.status,
job_type: inserted.job_type,
file_path: inserted.file_path,
original_file_name: fileMeta?.name || null,
safe_file_name: storageFileName,
message: "ai_jobs pending insert succeeded",
});
} catch (error) {
recordAiJobResult({
ok: false,
id: jobId,
job_type: jobType,
file_path: filePath,
original_file_name: fileMeta?.name || null,
safe_file_name: storageFileName,
message: supabaseErrorMessage(error),
});
recordSupabaseError("ai_jobs insert failed", error);
throw error;
}
const mapped = (await hydrateJobSignedUrls(mapAiJobs([inserted], [])))[0];
syncState.lastJob = mapped;
return mapped;
}
function renderNav() {
const navHtml = routes
.map((route) => `<button class="nav-item" data-route="${route.id}" type="button"><span class="nav-icon">${icon(route.icon)}</span>${route.label}</button>`)
.join("");
const bottomHtml = routes
.map((route) => `<button class="bottom-item" data-route="${route.id}" type="button"><span>${icon(route.icon)}</span>${route.label}</button>`)
.join("");
document.getElementById("side-nav").innerHTML = navHtml;
document.getElementById("bottom-nav").innerHTML = bottomHtml;
document.querySelectorAll("[data-route]").forEach((button) => button.addEventListener("click", () => setRoute(button.dataset.route)));
}
function renderNavState() {
document.querySelectorAll(".view").forEach((view) => view.classList.remove("active-view"));
document.getElementById(`${state.route}-view`).classList.add("active-view");
document.querySelectorAll("[data-route]").forEach((button) => button.classList.toggle("active", button.dataset.route === state.route));
}
function setRoute(route) {
state.route = route;
renderAll();
}
function renderHome() {
const date = state.homeDate;
const ideal = getPlan(date, "ideal");
const todayTodos = todosForDate(date);
const dayEvents = eventsOnDate(date);
const timetable = timetableForDate(date);
const countdowns = getCountdowns(date).slice(0, 3);
const menu = menuForDate(date);
const counts = jobCounts();
const todaysHomeworks = homeworksForDate(date).filter((item) => !item.completed).slice(0, 6);
const overdue = overdueHomeworks(date).slice(0, 4);
const homeworkStats = homeworkStatsForWeek(weekStartDate(date));
const weeklyAgenda = weekDates(date).map((day) => ({ date: day, items: weeklyAgendaItems(day).slice(0, 4) }));
const view = document.getElementById("home-view");
view.innerHTML = `
<div class="page-heading tight">
<div>
<p class="eyebrow">${formatLongDate(date)}${date === nextDate(DATA.today, 1) ? "(明日)" : ""}</p>
<h1>今日やること</h1>
</div>
<div class="heading-actions">
<button class="ghost-button" id="show-today-home" type="button">今日</button>
</div>
</div>
<div class="home-layout">
<section class="panel hero-panel">
<div class="panel-header compact">
<div>
<p class="section-kicker">24時間</p>
<h2>${formatShortDate(date)}の理想スケジュール</h2>
</div>
<button class="ghost-button" data-calendar-jump="day24" type="button">編集・比較</button>
</div>
<div class="home-hero-grid">
<div id="home-pie" class="pie-chart large"></div>
<div>
<div id="home-legend" class="legend compact-legend"></div>
</div>
</div>
</section>
<section class="panel action-panel">
<div class="panel-header compact">
<div>
<p class="section-kicker">Todo / 課題 / 復習 / 問題</p>
<h2>今日はこれだけやればOK</h2>
</div>
</div>
<div class="todo-list compact-list home-todo-list">${todayTodos.map(renderTodoItem).join("") || emptyText("今日のTodoはありません")}</div>
<div class="button-row">
<button class="secondary-action" data-route="questions" type="button">今日の問題を解く</button>
<button class="ghost-button" data-route="todo" type="button">Todo管理</button>
</div>
</section>
<section class="panel homework-home">
<div class="panel-header compact">
<div><p class="section-kicker">宿題 / 回収</p><h2>今日の宿題</h2></div>
<button class="ghost-button compact-button" data-route="homework" type="button">宿題管理</button>
</div>
${overdue.length ? `<div class="recovery-box"><strong>未回収の宿題が${overdue.length}つあります</strong><span>遅れても完了すればOK。今日中に1つ回収しよう。</span></div>` : ""}
<div class="homework-list compact-list">${[...overdue, ...todaysHomeworks].slice(0, 8).map(renderHomeworkItem).join("") || emptyText("今日の宿題はありません")}</div>
</section>
<section class="panel homework-stats-home">
<p class="section-kicker">今週の宿題達成度</p>
<h2>${homeworkStats.rate}%</h2>
<div class="homework-stat-row">
<span>完了 ${homeworkStats.completed}/${homeworkStats.total}</span>
<span>未回収 ${homeworkStats.overdue}</span>
<span>ペナルティ ${homeworkStats.penalty}</span>
</div>
</section>
<section class="panel weekly-home">
<p class="section-kicker">7日分</p>
<h2>一週間の予定</h2>
<div class="weekly-agenda">${weeklyAgenda.map(renderWeeklyAgendaDay).join("")}</div>
</section>
<section class="panel info-panel events-home">
<p class="section-kicker">カレンダー予定のみ</p>
<h2>今日の予定</h2>
<div class="event-list dense">${dayEvents.map(renderEventCard).join("") || emptyText("学校予定はありません")}</div>
</section>
<section class="panel info-panel countdown-home">
<p class="section-kicker">重要イベント</p>
<h2>カウントダウン</h2>
<div class="countdown-list dense">${countdowns.map(renderCountdown).join("")}</div>
</section>
<section class="panel timetable-home">
<p class="section-kicker">S3-2</p>
<h2>今日の時間割</h2>
<div class="mini-timetable">${timetable.map((entry) => renderVerticalClassCard(entry, date)).join("") || emptyText("授業はありません")}</div>
</section>
<section class="panel menu-home">
<p class="section-kicker">八太郎館</p>
<h2>今日の献立</h2>
${renderCompactMenu(menu)}
</section>
<section class="panel ai-home">
<p class="section-kicker">AI処理</p>
<h2>処理状況</h2>
${renderAiStatusCompact(counts)}
</section>
</div>
`;
renderPie("home-pie", ideal.blocks, "理想");
renderLegend("home-legend", ideal.blocks);
bindTodoCheckboxes(view);
bindHomeworkCheckboxes(view);
bindClassCards(view);
view.querySelector("#show-today-home").addEventListener("click", () => {
state.homeDate = DATA.today;
renderHome();
});
bindRouteButtons(view);
bindCalendarJumpButtons(view);
}
function renderCalendar() {
const view = document.getElementById("calendar-view");
view.innerHTML = `
<div class="page-heading">
<div>
<p class="eyebrow">${formatLongDate(state.selectedDate)}</p>
<h1>カレンダー</h1>
</div>
<div class="heading-actions">
<button class="ghost-button" id="calendar-today" type="button">今日</button>
<button class="primary-action" id="calendar-new-plan" type="button">+ 明日の理想円グラフ</button>
</div>
</div>
<div class="segmented" role="tablist" aria-label="カレンダー表示切り替え">
${["day24", "day", "week", "month", "year"].map((tab) => `<button class="segment ${state.calendarTab === tab ? "active" : ""}" data-calendar-tab="${tab}" type="button">${calendarTabLabel(tab)}</button>`).join("")}
</div>
<div id="calendar-content" class="calendar-content"></div>
`;
view.querySelectorAll("[data-calendar-tab]").forEach((button) => {
button.addEventListener("click", () => {
state.calendarTab = button.dataset.calendarTab;
renderCalendar();
});
});
view.querySelector("#calendar-today").addEventListener("click", () => {
state.selectedDate = DATA.today;
state.selectedYear = Number(DATA.today.slice(0, 4));
state.selectedMonth = Number(DATA.today.slice(5, 7));
state.calendarTab = "day";
renderCalendar();
});
view.querySelector("#calendar-new-plan").addEventListener("click", () => openScheduleModal(nextDate(DATA.today, 1), "ideal"));
const content = view.querySelector("#calendar-content");
if (state.calendarTab === "day24") renderDay24(content);
if (state.calendarTab === "day") renderDay(content, state.selectedDate);
if (state.calendarTab === "week") renderWeek(content);
if (state.calendarTab === "month") renderMonth(content, state.selectedYear, state.selectedMonth);
if (state.calendarTab === "year") renderYear(content, state.selectedYear);
}
function renderDay24(content) {
const ideal = getPlan(state.selectedDate, "ideal");
const actual = getPlan(state.selectedDate, "actual");
content.innerHTML = `
<div class="compare-grid">
<section class="panel">
<div class="panel-header compact">
<div><p class="section-kicker">理想</p><h2>${formatShortDate(state.selectedDate)}</h2></div>
<button class="ghost-button" id="edit-ideal" type="button">編集</button>
</div>
<div id="ideal-pie" class="pie-chart"></div>
<div id="ideal-legend" class="legend"></div>
</section>
<section class="panel">
<div class="panel-header compact">
<div><p class="section-kicker">実際</p><h2>達成度 ${achievement(actual.blocks)}%</h2></div>
<button class="ghost-button" id="edit-actual" type="button">編集</button>
</div>
<div id="actual-pie" class="pie-chart"></div>
<div id="actual-legend" class="legend"></div>
</section>
<section class="panel wide-panel">
<div class="panel-header">
<div>
<p class="section-kicker">比較</p>
<h2>理想と実際の差</h2>
</div>
<button id="copy-ideal-actual" class="primary-action" type="button">理想をコピーして実際スケジュールを作る</button>
</div>
<div class="metric-grid">
${["study", "sleep", "free", "school"].map((category) => renderMetric(category, ideal.blocks, actual.blocks)).join("")}
</div>
</section>
</div>
`;
renderPie("ideal-pie", ideal.blocks, "理想");
renderLegend("ideal-legend", ideal.blocks);
renderPie("actual-pie", actual.blocks, "実際");
renderLegend("actual-legend", actual.blocks);
content.querySelector("#edit-ideal").addEventListener("click", () => openScheduleModal(state.selectedDate, "ideal"));
content.querySelector("#edit-actual").addEventListener("click", () => openScheduleModal(state.selectedDate, "actual"));
content.querySelector("#copy-ideal-actual").addEventListener("click", () => copyIdealToActual(state.selectedDate));
}
function renderDay(content, date) {
const dayTodos = todosForDate(date);
const timetable = timetableForDate(date);
content.innerHTML = `
<div class="day-practical-grid">
<section class="panel">
<p class="section-kicker">学校予定</p>
<h2>${formatShortDate(date)}の予定</h2>
<div class="event-list">${eventsOnDate(date).map(renderEventCard).join("") || emptyText("予定はありません")}</div>
</section>
<section class="panel">
<p class="section-kicker">Todo / 課題 / 復習 / AI生成問題</p>
<h2>チェックリスト</h2>
<div class="todo-list">${dayTodos.map(renderTodoItem).join("") || emptyText("Todoはありません")}</div>
</section>
<section class="panel day-timetable-panel">
<p class="section-kicker">時間割</p>
<h2>授業とアップロード</h2>
<div class="vertical-timetable">${timetable.map((entry) => renderVerticalClassCard(entry, date)).join("") || emptyText("授業はありません")}</div>
</section>
<section class="panel">
<p class="section-kicker">献立</p>
<h2>八太郎館</h2>
${renderMenu(menuForDate(date))}
</section>
</div>
`;
bindTodoCheckboxes(content);
bindClassCards(content);
}
function renderWeek(content) {
const week = weekDates(state.selectedDate);
const rows = [1, 2, 3, 4, 5, 6, 7];
content.innerHTML = `
<section class="panel table-panel">
<div class="panel-header">
<div>
<p class="section-kicker">月〜日</p>
<h2>週間時間割</h2>
</div>
</div>
<div class="timetable-table-wrap">
<table class="timetable-table">
<thead>
<tr>
<th>時限</th>
${week.map((date) => `<th><button class="date-head" data-date="${date}" type="button">${weekdayLabel(date)}<span>${formatMonthDay(date)}</span></button></th>`).join("")}
</tr>
</thead>
<tbody>
${rows
.map(
(period) => `
<tr>
<th>${period}限</th>
${week.map((date) => renderTimetableCell(date, period)).join("")}
</tr>
`,
)
.join("")}
<tr>
<th>放課後/予定</th>
${week.map((date) => `<td class="after-cell">${eventsOnDate(date).slice(0, 2).map((event) => `<button class="small-event type-${event.event_type}" data-date="${date}" type="button">${event.title}</button>`).join("") || "<span class=\"muted\">なし</span>"}</td>`).join("")}
</tr>
</tbody>
</table>
</div>
</section>
`;
content.querySelectorAll("[data-date]").forEach((button) => {
button.addEventListener("click", () => goDay(button.dataset.date));
});
bindClassCards(content);
}
function renderMonth(content, year, month) {
const days = monthGrid(year, month);
content.innerHTML = `
<section class="panel">
<div class="panel-header">
<button class="ghost-button" id="prev-month" type="button">‹ 前月</button>
<div class="center-title">
<p class="section-kicker">月表示</p>
<h2>${year}年${month}月</h2>
</div>
<button class="ghost-button" id="next-month" type="button">翌月 ›</button>
</div>
<div class="month-calendar">
${["日", "月", "火", "水", "木", "金", "土"].map((d) => `<div class="calendar-weekday">${d}</div>`).join("")}
${days.map(renderMonthDay).join("")}
</div>
</section>
`;
content.querySelector("#prev-month").addEventListener("click", () => shiftMonth(-1));
content.querySelector("#next-month").addEventListener("click", () => shiftMonth(1));
content.querySelectorAll(".month-day").forEach((cell) => {
cell.addEventListener("click", () => goDay(cell.dataset.date));
});
}
function renderYear(content, year) {
content.innerHTML = `
<section class="panel">
<div class="panel-header">
<div>
<p class="section-kicker">年間</p>
<h2>${year}年 年間カレンダー</h2>
</div>
</div>
<div class="year-calendar">
${Array.from({ length: 12 }, (_, index) => renderMiniMonth(year, index + 1)).join("")}
</div>
</section>
`;
content.querySelectorAll(".mini-month").forEach((card) => {
card.addEventListener("click", () => {
state.selectedMonth = Number(card.dataset.month);