list.js
32.2 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
/* 数据处理 - 列表页 + 新增/重新生成弹窗(原生 JS) */
(function () {
var state = { page: 1, size: 10, total: 0 };
var typeConfigs = [];
var modalMode = ''; // '' | 'create' | 'regenerate'
var editingTaskId = null;
var formFiles = {}; // form_type -> { file, fileName, size, oldUrl }
var modalPeriodType = 'month'; // 'month' | 'week'
var modalWeekNum = null; // 1~当月周数(4~6)
// ---------- 通用 ----------
function api(url, opts) {
return fetch(url, opts).then(function (r) {
if (r.status === 401) { location.href = '/login.html'; throw new Error('未登录'); }
return r.json();
});
}
function toast(msg, isErr) {
var t = document.createElement('div');
t.className = 'toast' + (isErr ? ' error' : '') + ' show';
t.textContent = msg;
document.body.appendChild(t);
setTimeout(function () { t.remove(); }, 2400);
}
// ---------- Loading ----------
function showLoading(text) {
var mask = document.getElementById('loadingMask');
document.getElementById('loadingText').textContent = text || '正在处理,请稍候…';
mask.style.display = 'flex';
}
function hideLoading() {
document.getElementById('loadingMask').style.display = 'none';
}
// ---------- 登录态 ----------
function checkLogin() {
return api('/api/me').then(function (res) {
if (res.code !== 0) { location.href = '/login.html'; return null; }
var u = res.data;
var el = document.getElementById('sidebarUser');
if (el) el.textContent = (u.nickname || u.username) || u.username;
return u;
});
}
var logoutBtn = document.getElementById('btnLogoutSidebar');
if (logoutBtn) {
logoutBtn.onclick = function () {
fetch('/api/logout', { method: 'POST' }).then(function () {
location.href = '/login.html';
});
};
}
// ---------- 侧边栏菜单切换 ----------
function switchPage(page) {
document.querySelectorAll('.page-section').forEach(function (sec) {
sec.style.display = 'none';
});
document.querySelectorAll('.menu-item').forEach(function (m) {
m.classList.remove('active');
});
var sec = document.querySelector('[data-page-section="' + page + '"]');
if (sec) sec.style.display = '';
var item = document.querySelector('.menu-item[data-page="' + page + '"]');
if (item) item.classList.add('active');
}
document.querySelectorAll('.menu-item').forEach(function (m) {
m.addEventListener('click', function () {
switchPage(m.getAttribute('data-page'));
});
});
// ---------- 筛选 ----------
var fType = document.getElementById('fType');
var fMonth = document.getElementById('fMonth');
var fStatus = document.getElementById('fStatus');
var fCreator = document.getElementById('fCreator');
var tbody = document.getElementById('tbody');
var emptyTip = document.getElementById('emptyTip');
// 初始化月份选择器 - 处理 placeholder 显示逻辑
function initMonthPicker() {
var fMonth = document.getElementById('fMonth');
var mMonth = document.getElementById('mMonth');
function setupMonthPicker(input) {
if (!input) return;
var wrapper = input.closest('.month-picker-wrapper');
if (!wrapper) return;
var placeholder = wrapper.querySelector('.month-placeholder');
function updatePlaceholder() {
if (input.value) {
wrapper.classList.add('has-value');
if (placeholder) placeholder.style.display = 'none';
} else {
wrapper.classList.remove('has-value');
if (placeholder) placeholder.style.display = 'block';
}
}
input.addEventListener('input', updatePlaceholder);
input.addEventListener('change', updatePlaceholder);
updatePlaceholder();
}
setupMonthPicker(fMonth);
setupMonthPicker(mMonth);
}
function loadTypes() {
return api('/api/meta/task-types').then(function (res) {
if (res.code !== 0) return;
typeConfigs = res.data;
res.data.forEach(function (t) {
var o = document.createElement('option');
o.value = t.code; o.textContent = t.name;
fType.appendChild(o);
});
});
}
// ---------- 列表 ----------
var STATUS_MAP = { PROCESSING: '处理中', COMPLETED: '已完成', FAILED: '失败' };
// 失败原因浮层:用 textContent 写入,禁止 innerHTML,避免错误信息里的尖括号被当成 HTML
var statusTip = document.createElement('div');
statusTip.className = 'status-tip';
document.body.appendChild(statusTip);
function showStatusTip(el) {
var text = el.getAttribute('data-error') || el.getAttribute('title') || '';
if (!text) return;
statusTip.textContent = text;
statusTip.style.display = 'block';
var rect = el.getBoundingClientRect();
var top = rect.bottom + 6;
if (top + statusTip.offsetHeight > window.innerHeight) {
top = Math.max(6, rect.top - statusTip.offsetHeight - 6);
}
var left = Math.min(rect.left, window.innerWidth - statusTip.offsetWidth - 12);
statusTip.style.top = top + 'px';
statusTip.style.left = Math.max(6, left) + 'px';
}
function hideStatusTip() {
statusTip.style.display = 'none';
}
document.addEventListener('mouseover', function (e) {
var el = e.target.closest ? e.target.closest('.status.has-error') : null;
if (el) showStatusTip(el);
});
document.addEventListener('mouseout', function (e) {
var el = e.target.closest ? e.target.closest('.status.has-error') : null;
if (el) hideStatusTip();
});
window.addEventListener('scroll', hideStatusTip, true);
function renderList(list) {
tbody.innerHTML = '';
emptyTip.style.display = list.length ? 'none' : 'block';
var seq = (state.page - 1) * state.size;
list.forEach(function (item) {
var tr = document.createElement('tr');
var canDownload = item.status === 'COMPLETED';
var canRegen = item.status === 'COMPLETED' || item.status === 'FAILED';
// 所属周期:按周时显示 "W3 (2026-08-17~2026-08-23)",否则显示日期区间或整月
var periodText = '-';
if (item.period_type === 'week' && item.week_num && item.period_start && item.period_end) {
periodText = 'W' + item.week_num + ' (' + item.period_start + ' ~ ' + item.period_end + ')';
} else if (item.period_start && item.period_end) {
periodText = item.period_start + ' ~ ' + item.period_end;
}
tr.innerHTML =
'<td>' + (++seq) + '</td>' +
'<td>' + (item.data_table_type_name || item.data_table_type) + '</td>' +
'<td>' + item.month + '</td>' +
'<td>' + periodText + '</td>' +
'<td>' + (item.creator || '-') + '</td>' +
'<td>' + item.created_at + '</td>' +
'<td>' + (item.updater || '-') + '</td>' +
'<td>' + (item.updated_at || '-') + '</td>' +
'<td class="cell-status"><span class="status status-' + item.status + '">' + (STATUS_MAP[item.status] || item.status) + '</span></td>' +
'<td>' +
(canDownload ? '<button class="btn-link" data-act="download" data-id="' + item.id + '">下载 </button>' : '') +
(canRegen ? '<button class="btn-link" data-act="regen" data-id="' + item.id + '"> 重新生成</button>' : '') +
'</td>';
// 失败任务:把失败原因挂到状态标签上,悬停展示
if (item.status === 'FAILED' && item.error_msg) {
var badge = tr.querySelector('.cell-status .status');
if (badge) {
badge.classList.add('has-error');
// title 走原生提示兜底,data-error 供自定义浮层使用
badge.setAttribute('title', item.error_msg);
badge.setAttribute('data-error', item.error_msg);
}
}
tbody.appendChild(tr);
});
document.getElementById('pageInfo').textContent =
'共 ' + state.total + ' 条,第 ' + state.page + ' / ' + Math.max(1, Math.ceil(state.total / state.size)) + ' 页';
document.getElementById('btnPrev').disabled = state.page <= 1;
document.getElementById('btnNext').disabled = state.page >= Math.ceil(state.total / state.size);
}
function loadList() {
var params = new URLSearchParams({ page: state.page, size: state.size });
if (fType.value) params.set('dataTableType', fType.value);
if (fMonth.value) params.set('month', fMonth.value);
if (fCreator.value) params.set('creator', fCreator.value.trim());
if (fStatus.value) params.set('status', fStatus.value);
// 周期粒度筛选(取按钮组当前 active 的 data-type)
var activePeriodBtn = document.querySelector('#fPeriodTypeGroup .seg-btn.active');
if (activePeriodBtn && activePeriodBtn.dataset.type) {
params.set('periodType', activePeriodBtn.dataset.type);
}
api('/api/tasks?' + params.toString()).then(function (res) {
if (res.code !== 0) { toast(res.msg, true); return; }
state.total = res.data.total;
renderList(res.data.list);
});
}
// ---------- 弹窗 ----------
var modal = document.getElementById('modal');
var mType = document.getElementById('mType');
var mMonth = document.getElementById('mMonth');
var mFiles = document.getElementById('mFiles');
function fillModalTypes() {
mType.innerHTML = '';
var empty = document.createElement('option');
empty.value = ''; empty.textContent = '请选择';
mType.appendChild(empty);
typeConfigs.forEach(function (t) {
var o = document.createElement('option');
o.value = t.code; o.textContent = t.name;
mType.appendChild(o);
});
}
function renderFileInputs(forms) {
mFiles.innerHTML = '';
formFiles = {};
forms.forEach(function (formType) {
var row = document.createElement('div');
row.className = 'modal-file';
var label = document.createElement('label');
label.className = 'required';
label.textContent = formType;
var upload = document.createElement('div');
upload.className = 'file-upload';
var input = document.createElement('input');
input.type = 'file';
input.accept = '.xlsx,.xls';
var btn = document.createElement('span');
btn.className = 'file-btn';
btn.textContent = '添加附件';
btn.onclick = function () { input.click(); };
var name = document.createElement('span');
name.className = 'file-name';
name.textContent = '未选择文件';
input.onchange = function () {
var f = input.files[0];
if (!f) return;
if (!/\.(xlsx|xls)$/i.test(f.name)) { toast('仅支持 .xlsx / .xls 格式', true); input.value = ''; return; }
if (f.size > 100 * 1024 * 1024) { toast('文件超过 100M 限制', true); input.value = ''; return; }
formFiles[formType] = { file: f, fileName: f.name, size: f.size };
name.textContent = f.name + '(' + (f.size / 1024 / 1024).toFixed(2) + ' MB)';
// 防御性:选中/重新上传文件后确保「确定」按钮可用
var sb = document.getElementById('btnSubmit');
if (sb) sb.disabled = false;
};
upload.appendChild(btn);
upload.appendChild(input);
upload.appendChild(name);
var tip = document.createElement('span');
tip.className = 'tip';
tip.textContent = '注:请上传' + formType + ',最大不超过100M,仅支持.xlsx .xls格式;';
row.appendChild(label);
row.appendChild(upload);
row.appendChild(tip);
mFiles.appendChild(row);
});
}
function onTypeChange() {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg);
}
// ---------- 所属周期(日期区间)----------
var mPeriodRow = document.getElementById('mPeriodRow');
var mPeriodStart = document.getElementById('mPeriodStart');
var mPeriodEnd = document.getElementById('mPeriodEnd');
var mPeriodHint = document.getElementById('mPeriodHint');
// 计算某月最后一天
function lastDayOfMonth(monthVal) {
if (!monthVal) return null;
var parts = monthVal.split('-');
var y = parseInt(parts[0], 10), m = parseInt(parts[1], 10);
return new Date(y, m, 0).getDate();
}
// 月份值 YYYY-MM → YYYY-MM-DD(day=1)
function monthToDate(monthVal) {
if (!monthVal) return '';
return monthVal + '-01';
}
function setPeriodDefault(monthVal) {
// 已手动改过周期的不覆盖;仅在自动初始化时使用
if (!monthVal) { mPeriodStart.value = ''; mPeriodEnd.value = ''; return; }
var last = lastDayOfMonth(monthVal);
var start = monthToDate(monthVal);
var end = monthVal + '-' + String(last).padStart(2, '0');
mPeriodStart.value = start;
mPeriodEnd.value = end;
}
function togglePeriodRow(cfg) {
var need = cfg && cfg.need_period;
var isWeek = modalPeriodType === 'week';
if (isWeek || need) {
// 按周:无论 need_period 是什么,都显示周期行且 disabled
// 按月 + need_period=True:显示,可编辑(现有行为)
mPeriodRow.style.display = '';
if (isWeek) {
mPeriodStart.disabled = true;
mPeriodEnd.disabled = true;
// 按周时自动填入日期(如果已有 weekNum)
if (modalWeekNum) applyWeekPeriod(modalWeekNum);
} else {
mPeriodStart.disabled = false;
mPeriodEnd.disabled = false;
if (!mPeriodStart.value || !mPeriodEnd.value) setPeriodDefault(mMonth.value);
}
} else {
// need_period=False 且按月:隐藏
mPeriodRow.style.display = 'none';
}
}
// 前端周计算函数(与后端 compute_week_period / _weekly_ranges 规则一致)
// 规则:累计制,每个周区间都从当月 1 号起算;WN = 1 号 ~ 当月第 N 个周日,
// 最后一个周日之后到月末的余段截到月底、单独作最后一周。
// 周数动态:通常 5 周;当月有 5 个周日且月末落在周中时为 6 周(如
// 2026-03 / 08 / 11);2 月恰为 28 天且 1 号为周一时只有 4 周(2027-02)。
// 例:2026-09 → W1 1~6、W2 1~13、W3 1~20、W4 1~27、W5 1~30
function computeWeekOptions(monthVal) {
if (!monthVal) return [];
var parts = monthVal.split('-');
var y = parseInt(parts[0], 10), m = parseInt(parts[1], 10);
// 该月第一天
var firstDay = new Date(y, m - 1, 1); // JS Date: month 0-indexed
// firstDay.getDay(): 周日=0, 周一=1, ..., 周六=6
// 转换为:周一=0, 周日=6(与 Python weekday() 对齐)
var jsDay = firstDay.getDay(); // 0=周日 .. 6=周六
var pyWeekday = (jsDay === 0 ? 6 : jsDay - 1); // 周一=0, 周日=6
// 当月第一个周日:1 号往后推到最近的周日;1 号本身就是周日时取当天
// 例:2026-09-01 周二 pyWeekday=1 → offset=(6-1)%7=5 → 9/1+5天=9/6(与需求示例一致)
var offset = (6 - pyWeekday) % 7;
var firstSunday = new Date(y, m - 1, 1 + offset);
var monthEndStr = monthVal + '-' + String(lastDayOfMonth(monthVal)).padStart(2, '0');
// 每个周日收一周(起点恒为 1 号)
var options = [];
for (var d = new Date(firstSunday); d.getMonth() + 1 === m; d.setDate(d.getDate() + 7)) {
options.push(makeWeekOption(options.length + 1, monthVal, fmtDate(d)));
}
// 末尾不足一周的余段(如 9/28~9/30)截到月底,单独作最后一周
if (options.length && options[options.length - 1].end !== monthEndStr) {
options.push(makeWeekOption(options.length + 1, monthVal, monthEndStr));
}
return options;
}
// 组装一个周选项:start 恒为当月 1 号,end 为传入的结束日期字符串
function makeWeekOption(w, monthVal, endStr) {
var startStr = monthVal + '-01';
var sm = parseInt(startStr.slice(5, 7), 10), sd = parseInt(startStr.slice(8, 10), 10);
var em = parseInt(endStr.slice(5, 7), 10), ed = parseInt(endStr.slice(8, 10), 10);
return {
week: w,
label: 'W' + w + ' (' + sm + '/' + sd + '-' + em + '/' + ed + ')',
start: startStr,
end: endStr
};
}
// Date 对象 → 'YYYY-MM-DD'
function fmtDate(d) {
var y = d.getFullYear();
var mo = String(d.getMonth() + 1).padStart(2, '0');
var da = String(d.getDate()).padStart(2, '0');
return y + '-' + mo + '-' + da;
}
// 渲染周选择下拉框
function renderWeekSelect(monthVal) {
var sel = document.getElementById('mWeekSelect');
sel.innerHTML = '';
var opts = computeWeekOptions(monthVal);
if (!opts.length) { sel.style.display = 'none'; return; }
opts.forEach(function (o) {
var opt = document.createElement('option');
opt.value = o.week;
opt.textContent = o.label;
sel.appendChild(opt);
});
sel.style.display = '';
// 选中已有的 weekNum(重新生成回填时),否则默认 W1
if (modalWeekNum) {
sel.value = String(modalWeekNum);
applyWeekPeriod(modalWeekNum);
} else {
modalWeekNum = opts[0].week;
applyWeekPeriod(opts[0].week);
}
}
// 根据周序号自动填入 period start/end
function applyWeekPeriod(weekNum) {
var opts = computeWeekOptions(mMonth.value);
var found = null;
for (var i = 0; i < opts.length; i++) {
if (opts[i].week === weekNum) { found = opts[i]; break; }
}
if (!found) return;
mPeriodStart.value = found.start;
mPeriodEnd.value = found.end;
modalWeekNum = weekNum;
}
// 周期粒度行:仅 support_week=true 的类型(通用+权益)才显示
// 其他类型(整月、月份+自定义日期)统一隐藏,用户不可切换按月/按周
function togglePeriodTypeRow(cfg) {
var row = document.getElementById('mPeriodTypeRow');
var show = cfg && cfg.support_week;
row.style.display = show ? '' : 'none';
// 防御:若当前 period_type 为 week 但新类型不支持,强制重置为 month
if (!show && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
document.getElementById('mWeekSelect').style.display = 'none';
}
}
// 周期提示:结束日期 ≤ 月份最后一天;开始默认1号
function updatePeriodHint() {
if (!mPeriodRow || mPeriodRow.style.display === 'none') return;
if (!mMonth.value) { if (mPeriodHint) mPeriodHint.textContent = ''; return; }
var last = lastDayOfMonth(mMonth.value);
var maxEnd = mMonth.value + '-' + String(last).padStart(2, '0');
mPeriodStart.max = maxEnd;
mPeriodEnd.max = maxEnd;
if (mPeriodStart.value && !mPeriodStart.value.startsWith(mMonth.value + '-')) {
// 开始日期强制该月1号
mPeriodStart.value = monthToDate(mMonth.value);
}
if (mPeriodHint) {
mPeriodHint.textContent = '默认当月 1 号至月末,可调整结束日期(≤' + maxEnd + ')';
}
}
function openModal(mode, task) {
modalMode = mode;
editingTaskId = task ? task.id : null;
// 初始化周期粒度状态(regenerate 时从任务回填,否则默认 month)
modalPeriodType = (task && task.period_type) ? task.period_type : 'month';
modalWeekNum = (task && task.week_num) ? task.week_num : null;
document.getElementById('modalTitle').textContent = mode === 'regenerate' ? '重新生成' : '新增数据';
fillModalTypes();
mType.value = task ? task.data_table_type : '';
mMonth.value = task ? task.month : '';
// 周期默认值(编辑态回填任务周期,否则按月份初始化)
if (task && task.period_start && task.period_end) {
mPeriodStart.value = task.period_start;
mPeriodEnd.value = task.period_end;
} else {
setPeriodDefault(mMonth.value);
}
mMonth.dispatchEvent(new Event('change')); // 更新 placeholder 显示
var locked = mode === 'regenerate';
mType.disabled = locked;
mMonth.disabled = locked;
// 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑)
var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : ''); });
// 防御:若原 task 的 period_type 为 week 但当前类型不支持,强制重置
if (cfg && !cfg.support_week && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
}
renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled
updatePeriodHint();
// 初始化粒度按钮组 active 状态
var btns = document.querySelectorAll('#mPeriodTypeGroup .seg-btn');
btns.forEach(function (b) {
if (b.dataset.type === modalPeriodType) b.classList.add('active');
else b.classList.remove('active');
});
// 按周时渲染周选择下拉
if (modalPeriodType === 'week') {
renderWeekSelect(mMonth.value);
} else {
document.getElementById('mWeekSelect').style.display = 'none';
}
// 编辑态:用原文件回填文件名
if (locked && task && task.files) {
task.files.forEach(function (f) {
var rows = mFiles.querySelectorAll('.modal-file');
rows.forEach(function (row) {
if (row.querySelector('label').textContent === f.form_type) {
row.querySelector('.file-name').textContent = f.file_name + '(原文件)';
formFiles[f.form_type] = { file: null, fileName: f.file_name, size: f.file_size, oldUrl: f.file_url };
}
});
});
}
modal.style.display = 'flex';
// 关键修复:打开弹窗时强制启用「确定」按钮,清除上一次提交可能因卡住而残留的 disabled 态
var sb = document.getElementById('btnSubmit');
if (sb) sb.disabled = false;
}
function closeModal() {
modal.style.display = 'none';
modalMode = ''; editingTaskId = null; formFiles = {};
modalPeriodType = 'month'; modalWeekNum = null;
// 防御性:清理可能残留的 loading 遮罩与「确定」按钮禁用态
var lm = document.getElementById('loadingMask');
if (lm) lm.style.display = 'none';
var sb = document.getElementById('btnSubmit');
if (sb) sb.disabled = false;
}
// ---------- 直传 OSS ----------
// 后端下发签名(policy/signature),前端直接 POST 文件到 OSS,不走后端中转
// key 使用短格式:data-process/{uuid}.{ext},链接更短
function genUuid() {
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0;
var v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function uploadFileToOss(file, token) {
var ext = (file.name.match(/\.[^.]+$/) || [''])[0];
var key = token.dir + genUuid() + ext;
var fd = new FormData();
fd.append('key', key);
fd.append('policy', token.policy);
fd.append('OSSAccessKeyId', token.accessKeyId);
fd.append('signature', token.signature);
fd.append('success_action_status', '200');
fd.append('file', file);
var req = fetch(token.host, { method: 'POST', body: fd });
// 超时保护:直传挂起时 reject,避免「确定」按钮与 loading 遮罩永久卡死
var timeout = new Promise(function (_, reject) {
setTimeout(function () { reject(new Error('直传 OSS 超时(60s)')); }, 60000);
});
return Promise.race([req, timeout]).then(function (r) {
if (r.status !== 200) { throw new Error('直传 OSS 失败:' + r.status); }
return token.host + '/' + key;
});
}
// ---------- 提交 ----------
function collectAndSubmit() {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (!cfg) { toast('请选择数据表类型', true); return; }
if (!mMonth.value) { toast('请选择所属月份', true); return; }
// 周期校验:
// 按周 → 必须有 week_num(后端会根据 month+week_num 重算日期,这里只是前端兜底检查)
// 按月 + need_period=True → 必须选 period_start/end
// 按月 + need_period=False → 不需要周期(如预算达成数据)
var isWeek = modalPeriodType === 'week';
if (isWeek) {
if (!modalWeekNum) { toast('请选择第几周', true); return; }
} else if (cfg.need_period) {
var ps = mPeriodStart.value || '', pe = mPeriodEnd.value || '';
if (!ps || !pe) { toast('请选择所属周期(开始日期~结束日期)', true); return; }
if (pe < ps) { toast('所属周期结束日期不能早于开始日期', true); return; }
}
// 必填:新增模式所有附件必填;重新生成未上传视为保留原文件(通过 formFiles.oldUrl 标记)
var missing = [];
var toUpload = []; // 需要直传的新文件
cfg.forms.forEach(function (ft) {
var f = formFiles[ft];
if (!f || (!f.file && !f.oldUrl)) { missing.push(ft); return; }
if (f.file) toUpload.push({ form_type: ft, file: f.file, fileName: f.fileName, size: f.size });
});
if (missing.length && modalMode === 'create') {
toast('请上传全部附件:' + missing.join('、'), true); return;
}
if (missing.length && modalMode === 'regenerate') {
if (missing.length === cfg.forms.length) { toast('请至少上传一个附件', true); return; }
}
var btn = document.getElementById('btnSubmit');
btn.disabled = true;
showLoading('正在上传文件,请稍候…');
// 1) 获取直传签名
api('/api/oss/upload-token').then(function (res) {
if (res.code !== 0) { hideLoading(); toast(res.msg, true); btn.disabled = false; return; }
var token = res.data;
// 2) 逐个直传 OSS(并行)
var uploads = toUpload.map(function (u) {
return uploadFileToOss(u.file, token).then(function (url) {
return { form_type: u.form_type, file_name: u.fileName, file_url: url, file_size: u.size };
});
});
return Promise.all(uploads);
}).then(function (uploaded) {
// 3) 组装 JSON 提交后端(含保留的原文件)
var filesPayload = [];
cfg.forms.forEach(function (ft) {
var u = uploaded.find(function (x) { return x.form_type === ft; });
if (u) { filesPayload.push(u); return; }
var old = formFiles[ft];
if (old && old.oldUrl) {
filesPayload.push({ form_type: ft, file_name: old.fileName, file_url: old.oldUrl, file_size: old.size });
}
});
var payload = {
data_table_type: mType.value,
month: mMonth.value,
period_type: modalPeriodType,
week_num: modalWeekNum,
files: filesPayload
};
// 周期日期:按周时也填上(后端会根据 week_num 重算做双重保险)
if (isWeek || cfg.need_period) {
payload.period_start = mPeriodStart.value;
payload.period_end = mPeriodEnd.value;
}
var url = modalMode === 'regenerate'
? '/api/tasks/' + editingTaskId + '/regenerate'
: '/api/tasks';
return api(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
}).then(function (res) {
hideLoading();
if (res.code !== 0) { toast(res.msg, true); btn.disabled = false; return; }
toast(res.msg);
closeModal();
loadList();
}).catch(function (e) {
hideLoading();
toast(e.message || '提交失败', true);
btn.disabled = false;
});
}
// ---------- 事件 ----------
document.getElementById('btnSearch').onclick = function () { state.page = 1; loadList(); };
document.getElementById('btnReset').onclick = function () {
fType.value = ''; fMonth.value = ''; fCreator.value = ''; fStatus.value = '';
fMonth.dispatchEvent(new Event('change')); // 更新 placeholder 显示
state.page = 1; loadList();
};
document.getElementById('btnPrev').onclick = function () { if (state.page > 1) { state.page--; loadList(); } };
document.getElementById('btnNext').onclick = function () { state.page++; loadList(); };
document.getElementById('btnAdd').onclick = function () { openModal('create'); };
tbody.addEventListener('click', function (e) {
var btn = e.target.closest('button[data-act]');
if (!btn) return;
var id = btn.getAttribute('data-id');
var act = btn.getAttribute('data-act');
if (act === 'download') {
api('/api/tasks/' + id + '/download').then(function (res) {
if (res.code !== 0) { toast(res.msg, true); return; }
window.open(res.data.url, '_blank');
});
} else if (act === 'regen') {
api('/api/tasks/' + id).then(function (res) {
if (res.code !== 0) { toast(res.msg, true); return; }
openModal('regenerate', res.data);
});
}
});
mType.addEventListener('change', onTypeChange);
mMonth.addEventListener('change', function () {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (modalPeriodType === 'week') {
// 按周:月份变了重新生成周选项
modalWeekNum = null;
renderWeekSelect(mMonth.value);
} else {
// 按月:原有逻辑
setPeriodDefault(mMonth.value);
}
togglePeriodRow(cfg);
updatePeriodHint();
});
mPeriodStart.addEventListener('change', function () {
if (mMonth.value && mPeriodStart.value && !mPeriodStart.value.startsWith(mMonth.value + '-')) {
// 开始日期只能取该月1号,自动纠正
mPeriodStart.value = monthToDate(mMonth.value);
}
if (mPeriodEnd.value && mPeriodStart.value && mPeriodEnd.value < mPeriodStart.value) {
toast('结束日期不能早于开始日期', true);
}
updatePeriodHint();
});
mPeriodEnd.addEventListener('change', function () {
if (mPeriodEnd.value && mPeriodStart.value && mPeriodEnd.value < mPeriodStart.value) {
toast('结束日期不能早于开始日期', true);
mPeriodEnd.value = mPeriodStart.value;
}
updatePeriodHint();
});
// ---------- 弹窗:周期粒度切换 ----------
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) {
btn.addEventListener('click', function () {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
// 防御:当前类型不支持按周时忽略点击(理论上行已隐藏,用户不可达)
if (!cfg || !cfg.support_week) return;
modalPeriodType = btn.dataset.type;
// 更新按钮组 active 状态
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) {
if (b === btn) b.classList.add('active');
else b.classList.remove('active');
});
// 切换粒度时重置 weekNum
modalWeekNum = null;
if (modalPeriodType === 'week') {
// 按周:渲染周下拉 + 自动计算日期
document.getElementById('mWeekSelect').style.display = '';
if (mMonth.value) renderWeekSelect(mMonth.value);
} else {
// 按月:隐藏周下拉 + 恢复默认
document.getElementById('mWeekSelect').style.display = 'none';
setPeriodDefault(mMonth.value);
}
togglePeriodRow(cfg);
updatePeriodHint();
});
});
// 弹窗:周选择下拉 change
var mWeekSelect = document.getElementById('mWeekSelect');
if (mWeekSelect) {
mWeekSelect.addEventListener('change', function () {
var w = parseInt(mWeekSelect.value, 10);
if (w >= 1) applyWeekPeriod(w);
});
}
// ---------- 列表筛选:粒度切换 ----------
var fPeriodTypeBtns = document.querySelectorAll('#fPeriodTypeGroup .seg-btn');
fPeriodTypeBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
fPeriodTypeBtns.forEach(function (b) {
if (b === btn) b.classList.add('active');
else b.classList.remove('active');
});
state.page = 1;
loadList();
});
});
document.getElementById('btnCancel').onclick = closeModal;
document.getElementById('modalClose').onclick = closeModal;
// 不移除:点击弹窗外区域不关闭弹窗,只能通过取消按钮或关闭按钮关闭
// modal.addEventListener('click', function (e) { if (e.target === modal) closeModal(); });
document.getElementById('btnSubmit').onclick = collectAndSubmit;
// ---------- 初始化:先校验登录,再加载页面数据 ----------
initMonthPicker();
checkLogin().then(function (u) {
if (!u) return;
loadTypes().then(loadList);
});
})();