重构共享逻辑并修复值班提醒回执去重
This commit is contained in:
Vendored
+318
-61
@@ -4,6 +4,10 @@
|
||||
(() => {
|
||||
const API = "/api";
|
||||
const TOKEN_KEY = "worklog_token";
|
||||
const MB = 1024 * 1024;
|
||||
const CENTER_PHOTO_BATCH_LIMIT = 50;
|
||||
const CENTER_PHOTO_MAX_MB = 8;
|
||||
const CENTER_ZIP_MAX_MB = 100;
|
||||
|
||||
// ------------------------------------------------------------- 工具
|
||||
const $ = (sel) => document.querySelector(sel);
|
||||
@@ -365,12 +369,47 @@
|
||||
});
|
||||
bindSendCode("#send-code-btn", "#register-form [name=email]", "#register-hint", "#register-error", "register");
|
||||
|
||||
$("#public-loan-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.target;
|
||||
const button = $("#public-loan-submit");
|
||||
$("#public-loan-error").textContent = "";
|
||||
$("#public-loan-status").textContent = "";
|
||||
if (!/^1[3-9]\d{9}$/.test(form.phone.value.trim())) {
|
||||
$("#public-loan-error").textContent = "请填写正确的 11 位手机号";
|
||||
form.phone.focus();
|
||||
return;
|
||||
}
|
||||
button.disabled = true;
|
||||
button.textContent = "正在提交…";
|
||||
try {
|
||||
const data = await api("/center/public-loans", {
|
||||
method: "POST",
|
||||
body: {
|
||||
name: form.name.value.trim(),
|
||||
phone: form.phone.value.trim(),
|
||||
college: form.college.value.trim(),
|
||||
activity_name: form.activity_name.value.trim(),
|
||||
note: form.note.value.trim(),
|
||||
},
|
||||
});
|
||||
form.reset();
|
||||
$("#public-loan-status").textContent = `登记成功,编号 ${data.id.slice(-8).toUpperCase()}。请按现场要求归还物品。`;
|
||||
} catch (error) {
|
||||
$("#public-loan-error").textContent = error.message;
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = "提交借出登记";
|
||||
}
|
||||
});
|
||||
|
||||
$$(".tab").forEach((t) =>
|
||||
t.addEventListener("click", () => {
|
||||
$$(".tab").forEach((x) => x.classList.toggle("active", x === t));
|
||||
$("#login-form").classList.toggle("hidden", t.dataset.auth !== "login");
|
||||
$("#reset-form").classList.add("hidden");
|
||||
$("#register-form").classList.toggle("hidden", t.dataset.auth !== "register");
|
||||
$("#public-loan-form").classList.toggle("hidden", t.dataset.auth !== "loan");
|
||||
})
|
||||
);
|
||||
|
||||
@@ -399,6 +438,49 @@
|
||||
return esc(/[\u4e00-\u9fff]/.test(s) ? s.slice(0, 1) : s.slice(0, 2).toUpperCase());
|
||||
};
|
||||
|
||||
function photoGallery(ids, label = '活动照片') {
|
||||
const unique = [...new Set((ids || []).filter(Boolean))];
|
||||
if (!unique.length) return '';
|
||||
return `<div class="photo-preview" data-photo-ids="${esc(unique.join(','))}" data-photo-label="${esc(label)}">
|
||||
<div class="photo-preview-summary">
|
||||
<button class="btn sm" type="button" data-photo-preview aria-expanded="false">预览图片</button>
|
||||
<span>共 <strong>${unique.length}</strong> 张 · 点击后加载</span>
|
||||
</div>
|
||||
<div class="activity-photos photo-gallery hidden" aria-live="polite"></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function bindPhotoPreviews(container) {
|
||||
if (!container) return;
|
||||
container.querySelectorAll('[data-photo-preview]').forEach(button => {
|
||||
if (button.dataset.bound) return;
|
||||
button.dataset.bound = 'true';
|
||||
button.addEventListener('click', event => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const wrapper = button.closest('.photo-preview');
|
||||
const gallery = wrapper.querySelector('.photo-gallery');
|
||||
const opening = gallery.classList.contains('hidden');
|
||||
if (!opening) {
|
||||
gallery.classList.add('hidden');
|
||||
button.textContent = '预览图片';
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
return;
|
||||
}
|
||||
const ids = (wrapper.dataset.photoIds || '').split(',').filter(Boolean);
|
||||
if (!gallery.dataset.loaded) {
|
||||
const label = wrapper.dataset.photoLabel || '活动照片';
|
||||
gallery.innerHTML = ids.map((id, index) => `<img class="photo-loading" data-photo="${esc(id)}" alt="${esc(label)} ${index + 1}" />`).join('');
|
||||
gallery.dataset.loaded = 'true';
|
||||
}
|
||||
gallery.classList.remove('hidden');
|
||||
button.textContent = '收起图片';
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
loadPhotos(gallery);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function activityCard(a, opts = {}) {
|
||||
const isCenter = a.record_type === 'center';
|
||||
const mine = isCenter ? null : a.my_participation;
|
||||
@@ -447,7 +529,7 @@
|
||||
${a.description ? `<p class="acard-desc">${esc(a.description).slice(0, 160)}${a.description.length > 160 ? "…" : ""}</p>` : ""}
|
||||
${a.record_type === 'center' ? '<span class="tag cat">赋能中心一楼活动记录</span>' : ''}
|
||||
${materialButtons(a)}
|
||||
${(a.photo_ids || []).length ? `<div class="activity-photos">${a.photo_ids.map(id => `<img data-photo="${esc(id)}" alt="活动照片" loading="lazy" />`).join('')}</div>` : ''}
|
||||
${photoGallery(a.photo_ids)}
|
||||
<div class="acard-foot">
|
||||
<div class="faces">
|
||||
${isCenter ? `<span class="faces-label">仅作记录 · 全员可见${a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ''}</span>` : `${faces}${more}<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>`}
|
||||
@@ -458,7 +540,7 @@
|
||||
}
|
||||
|
||||
function bindCardEvents(container) {
|
||||
loadPhotos(container);
|
||||
bindPhotoPreviews(container);
|
||||
container.querySelectorAll(".acard").forEach((card) => {
|
||||
const id = card.dataset.id;
|
||||
const activity = findActivity(id);
|
||||
@@ -522,7 +604,6 @@
|
||||
$("#feed-list").classList.toggle("hidden", !data.items.length);
|
||||
$("#feed-empty").classList.toggle("hidden", !!data.items.length);
|
||||
bindCardEvents($("#feed-list"));
|
||||
loadPhotos($("#feed-list"));
|
||||
try {
|
||||
const ov = await api("/stats/overview");
|
||||
$("#feed-stats").innerHTML = `
|
||||
@@ -553,6 +634,7 @@
|
||||
function renderDutyStatus() {
|
||||
if (!dutySnapshot) return;
|
||||
const now = dutySnapshot.server_now + performance.now() - dutySyncedAt;
|
||||
const scheduleLabel = dutySnapshot.title || "值班安排";
|
||||
const current = dutySnapshot.current;
|
||||
const next = dutySnapshot.next;
|
||||
const active = current && now < current.end_at;
|
||||
@@ -571,11 +653,11 @@
|
||||
$("#duty-banner").classList.toggle("on-duty", !!active);
|
||||
$("#duty-clock").classList.toggle("hidden", !shift || !!expired);
|
||||
if (expired) {
|
||||
$("#duty-label").textContent = "值班安排";
|
||||
$("#duty-label").textContent = `${scheduleLabel} · 更新中`;
|
||||
$("#duty-names").textContent = "正在更新…";
|
||||
$("#duty-time").textContent = "";
|
||||
} else if (shift) {
|
||||
$("#duty-label").textContent = active ? "当前值班" : "下一轮值班";
|
||||
$("#duty-label").textContent = `${scheduleLabel} · ${active ? "当前" : "下一轮"}`;
|
||||
$("#duty-names").textContent = shift.names.join("、");
|
||||
$("#duty-time").textContent = `${active ? shift.slot : dutyDate(shift.start_at, true)} · ${active ? dutyDate(shift.start_at) + "–" + dutyDate(shift.end_at) : "开始"}(北京时间)`;
|
||||
$("#duty-countdown-label").textContent = active ? "本轮剩余" : "距离开始";
|
||||
@@ -584,8 +666,8 @@
|
||||
const clock = [Math.floor(seconds / 3600) % 24, Math.floor(seconds / 60) % 60, seconds % 60].map((n) => String(n).padStart(2, "0")).join(":");
|
||||
$("#duty-countdown").textContent = (days ? `${days}天 ` : "") + clock;
|
||||
} else {
|
||||
$("#duty-label").textContent = "值班安排";
|
||||
$("#duty-names").textContent = dutySnapshot.enabled ? "暂无值班安排" : "值班安排已暂停";
|
||||
$("#duty-label").textContent = scheduleLabel;
|
||||
$("#duty-names").textContent = dutySnapshot.enabled ? "暂无排班" : "已暂停";
|
||||
$("#duty-time").textContent = "";
|
||||
}
|
||||
if ((expired || performance.now() - dutySyncedAt >= 60000) && performance.now() >= dutyRetryAt) loadDutyStatus();
|
||||
@@ -605,7 +687,7 @@
|
||||
dutyRemindersKey = "";
|
||||
$("#duty-reminders").innerHTML = "";
|
||||
$("#duty-banner").classList.remove("on-duty");
|
||||
$("#duty-label").textContent = "值班安排";
|
||||
$("#duty-label").textContent = "招生就业服务队值班";
|
||||
$("#duty-names").textContent = "暂时无法加载";
|
||||
$("#duty-time").textContent = "稍后自动重试";
|
||||
$("#duty-clock").classList.add("hidden");
|
||||
@@ -857,9 +939,9 @@
|
||||
|
||||
function centerUploadFields(prefix) {
|
||||
return `<label>活动照片<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label>
|
||||
<p class="muted">可直接多选相册照片或拍照,每次最多20张(含ZIP内照片),每张不超过8MB。</p><div id="${prefix}-selected-photos" class="activity-photos"></div>
|
||||
<p class="muted">可直接多选相册照片或拍照,支持JPG、PNG、WebP并自动转为统一JPEG;每次最多${CENTER_PHOTO_BATCH_LIMIT}张(含ZIP内照片),每张不超过${CENTER_PHOTO_MAX_MB}MB。</p><div id="${prefix}-selected-photos" class="selected-photo-summary muted"></div>
|
||||
<label>ZIP附件 <span class="hint-inline">(选填)</span><input name="materials" type="file" accept=".zip,application/zip" /></label>
|
||||
<p class="muted">需要附PDF、Word、Excel等文档时再上传ZIP,最大30MB,可不含照片。</p>`;
|
||||
<p class="muted">需要附PDF、Word、Excel等文档时再上传ZIP,最大${CENTER_ZIP_MAX_MB}MB,可不含照片。</p>`;
|
||||
}
|
||||
|
||||
function bindCenterUploads(form, box, label, meter, prefix) {
|
||||
@@ -871,20 +953,44 @@
|
||||
form.photos.addEventListener('change', () => {
|
||||
clearPreview();
|
||||
const preview = $('#' + prefix + '-selected-photos'); preview.replaceChildren();
|
||||
form.photos.setCustomValidity(form.photos.files.length > 20 ? '每次最多上传20张照片,请重新选择' : '');
|
||||
if (form.photos.files.length > 20) { form.photos.reportValidity(); box.classList.add('hidden'); return; }
|
||||
for (const file of form.photos.files) {
|
||||
const img = document.createElement('img'), url = URL.createObjectURL(file);
|
||||
previewUrls.push(url); img.src = url; img.alt = file.name; preview.append(img);
|
||||
}
|
||||
form.photos.setCustomValidity(form.photos.files.length > CENTER_PHOTO_BATCH_LIMIT ? `每次最多上传${CENTER_PHOTO_BATCH_LIMIT}张照片,请重新选择` : '');
|
||||
if (form.photos.files.length > CENTER_PHOTO_BATCH_LIMIT) { form.photos.reportValidity(); box.classList.add('hidden'); return; }
|
||||
const files = [...form.photos.files];
|
||||
if (!files.length) return;
|
||||
preview.innerHTML = `<div class="photo-preview-summary"><button class="btn sm" type="button" data-local-photo-preview aria-expanded="false">预览图片</button><span>已选择 <strong>${files.length}</strong> 张 · 点击后加载</span></div><div class="activity-photos photo-gallery hidden"></div>`;
|
||||
const button = preview.querySelector('[data-local-photo-preview]');
|
||||
const gallery = preview.querySelector('.photo-gallery');
|
||||
button.addEventListener('click', () => {
|
||||
const opening = gallery.classList.contains('hidden');
|
||||
if (!opening) {
|
||||
gallery.classList.add('hidden');
|
||||
button.textContent = '预览图片';
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
return;
|
||||
}
|
||||
if (!gallery.dataset.loaded) {
|
||||
gallery.innerHTML = '';
|
||||
files.forEach((file, index) => {
|
||||
const img = document.createElement('img'), url = URL.createObjectURL(file);
|
||||
previewUrls.push(url);
|
||||
img.src = url;
|
||||
img.alt = `${file.name || '已选照片'} ${index + 1}`;
|
||||
gallery.append(img);
|
||||
});
|
||||
gallery.dataset.loaded = 'true';
|
||||
}
|
||||
gallery.classList.remove('hidden');
|
||||
button.textContent = '收起图片';
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
});
|
||||
box.classList.add('hidden');
|
||||
});
|
||||
form.materials.addEventListener('change', () => { uploadedZip = null; box.classList.add('hidden'); });
|
||||
return async () => {
|
||||
const files = [...form.photos.files], zip = form.materials.files[0];
|
||||
if (files.length > 20) throw new Error('每次最多上传20张照片,请重新选择');
|
||||
if (files.some(file => file.size > 8 * 1024 * 1024 || !(/\.(jpe?g|png|webp)$/i.test(file.name) || /^image\/(jpeg|png|webp)$/.test(file.type)))) throw new Error('照片支持JPG、PNG、WebP,每张最大8MB');
|
||||
if (zip && (zip.size > 30 * 1024 * 1024 || !zip.name.toLowerCase().endsWith('.zip'))) throw new Error('请提交30MB以内的ZIP附件');
|
||||
if (files.length > CENTER_PHOTO_BATCH_LIMIT) throw new Error(`每次最多上传${CENTER_PHOTO_BATCH_LIMIT}张照片,请重新选择`);
|
||||
if (files.some(file => file.size > CENTER_PHOTO_MAX_MB * MB || !(/\.(jpe?g|jpg|jpeg|jpe|jfif|png|webp)$/i.test(file.name) || /^image\/(jpeg|jpg|jpe|jfif|pjpeg|png|webp)$/.test(file.type)))) throw new Error(`照片支持JPG、PNG、WebP,每张最大${CENTER_PHOTO_MAX_MB}MB`);
|
||||
if (zip && (zip.size > CENTER_ZIP_MAX_MB * MB || !zip.name.toLowerCase().endsWith('.zip'))) throw new Error(`请提交${CENTER_ZIP_MAX_MB}MB以内的ZIP附件`);
|
||||
if (files.length || zip) box.classList.remove('hidden');
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
if (!form.isConnected) throw new Error('上传已取消');
|
||||
@@ -903,7 +1009,7 @@
|
||||
const result = await uploadMaterial(zip, (loaded, total) => renderUploadProgress(label, meter, loaded, total, 'ZIP已上传,正在校验附件…'));
|
||||
uploadedZip = { file: zip, id: result.id, photoCount: result.photo_ids.length };
|
||||
}
|
||||
if (files.length + (zip ? uploadedZip.photoCount : 0) > 20) throw new Error('每次最多上传20张照片(含ZIP内照片),请减少照片后重试');
|
||||
if (files.length + (zip ? uploadedZip.photoCount : 0) > CENTER_PHOTO_BATCH_LIMIT) throw new Error(`每次最多上传${CENTER_PHOTO_BATCH_LIMIT}张照片(含ZIP内照片),请减少照片后重试`);
|
||||
meter.value = 100; label.textContent = '上传完成,正在保存记录…';
|
||||
return { photo_ids: files.map(file => uploadedPhotos.get(file)), material_id: zip ? uploadedZip.id : null };
|
||||
};
|
||||
@@ -944,18 +1050,18 @@
|
||||
function openActivityForm(existing = null, defaultType = 'normal') {
|
||||
const isEdit = !!existing;
|
||||
modal(`
|
||||
<h3>${isEdit ? "编辑活动" : "记录一场活动"}</h3>
|
||||
<h3>${isEdit ? "编辑工作" : "记录一项工作"}</h3>
|
||||
<p class="modal-sub muted">提交后立即生效,所有人可见。</p>
|
||||
<form id="act-form">
|
||||
<label>记录类型<select name="record_type"><option value="normal">普通活动记录</option><option value="center">赋能中心一楼活动记录</option></select></label>
|
||||
<label>活动名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label>
|
||||
<label>记录类型<select name="record_type"><option value="normal">普通工作记录</option></select></label>
|
||||
<label>工作名称 *<input name="title" required maxlength="120" value="${esc(existing?.title || "")}" placeholder="例如:周三晚例会" /></label>
|
||||
<div class="form-row">
|
||||
<label>开始时间 *<input name="start_at" type="datetime-local" required value="${existing ? toLocalInput(existing.start_at) : ""}" /></label>
|
||||
<label>地点<input name="location" maxlength="120" value="${esc(existing?.location || "")}" placeholder="如:3 号会议室" /></label>
|
||||
</div>
|
||||
<label>人数上限 <span class="hint-inline">(选填,留空不限人数)</span><input name="capacity" type="number" min="1" max="500" step="1" value="${existing?.capacity ?? ""}" placeholder="不限人数" /></label>
|
||||
<label>备注 <span class="hint-inline">(选填)</span><textarea name="description" rows="3" maxlength="2000" placeholder="做什么、带什么、注意事项…">${esc(existing?.description || "")}</textarea></label>
|
||||
<div id="act-photo-fields" class="hidden">${centerUploadFields('act')}<p class="muted">照片和ZIP至少选择一种。编辑时会保留原照片和附件,所选内容追加保存。</p><div id="act-photo-preview" class="activity-photos">${(existing?.photo_ids || []).map(id => `<img data-photo="${esc(id)}" alt="活动照片" />`).join('')}</div></div>
|
||||
<div id="act-photo-fields" class="hidden">${centerUploadFields('act')}<p class="muted">照片和ZIP至少选择一种。编辑时会保留原照片和附件,所选内容追加保存。</p><div id="act-photo-preview">${photoGallery(existing?.photo_ids, '已有活动照片')}</div></div>
|
||||
<label class="checkline" id="act-visibility"><input type="checkbox" name="visibility" ${!existing || existing.visibility === "public" ? "checked" : ""} /> 公开活动(所有人可见;不勾选则仅参加者可见)</label>
|
||||
<p id="act-center-policy" class="muted hidden">全员可见,仅作活动记录,无需参加,也不计入参加统计。</p>
|
||||
<div id="act-upload-progress" class="upload-progress hidden">
|
||||
@@ -985,7 +1091,7 @@
|
||||
if (isCenter && !activityForm.location.value.trim()) activityForm.location.value = '赋能中心一楼';
|
||||
};
|
||||
activityForm.record_type.addEventListener('change', togglePhotos); togglePhotos();
|
||||
loadPhotos($('#act-photo-preview'));
|
||||
bindPhotoPreviews(activityForm);
|
||||
|
||||
$("#act-cancel").addEventListener("click", closeModal);
|
||||
$("#act-form").addEventListener("submit", async (e) => {
|
||||
@@ -1105,7 +1211,7 @@
|
||||
</div>
|
||||
${a.description ? `<div class="detail-desc">${esc(a.description)}</div>` : ""}
|
||||
${materialButtons(a)}
|
||||
<div class="activity-photos">${(a.photo_ids || []).map(id => `<img data-photo="${esc(id)}" alt="活动照片" />`).join('')}</div>
|
||||
${photoGallery(a.photo_ids)}
|
||||
${noteRow}
|
||||
${isCenter ? '' : `<h4 style="margin:14px 0 2px">一起参加过(${a.participant_count})</h4><ul class="p-list">${rows || '<li class="muted">还没有其他人的参加记录</li>'}</ul>`}
|
||||
<div class="form-actions">
|
||||
@@ -1113,6 +1219,7 @@
|
||||
</div>`);
|
||||
|
||||
$("#d-close").addEventListener("click", closeModal);
|
||||
bindPhotoPreviews($("#modal-root"));
|
||||
|
||||
const reload = async () => {
|
||||
closeModal();
|
||||
@@ -1133,7 +1240,6 @@
|
||||
try { await api(`/activities/${id}`, { method: "DELETE" }); toast("已删除"); closeModal(); refreshCurrent(); } catch (err) { toast(err.message, true); }
|
||||
});
|
||||
|
||||
loadPhotos($("#modal-root"));
|
||||
const noteInput = $("#d-note");
|
||||
if (noteInput) {
|
||||
let timer = null;
|
||||
@@ -1171,21 +1277,35 @@
|
||||
const photoUrls = new Map();
|
||||
async function loadPhotos(container) {
|
||||
if (!container) return;
|
||||
for (const img of container.querySelectorAll('[data-photo]')) {
|
||||
if (img.dataset.loading) continue;
|
||||
img.dataset.loading = 'true';
|
||||
const id = img.dataset.photo;
|
||||
try {
|
||||
if (!photoUrls.has(id)) {
|
||||
photoUrls.set(id, fetch(`/api/center/photos/${encodeURIComponent(id)}`, { headers: { Authorization: `Bearer ${getToken()}` } }).then(async r => {
|
||||
if (!r.ok) throw new Error('照片加载失败');
|
||||
return URL.createObjectURL(await r.blob());
|
||||
}));
|
||||
const images = [...container.querySelectorAll('[data-photo]')].filter(img => !img.dataset.loading);
|
||||
if (!images.length) return;
|
||||
let cursor = 0;
|
||||
const loadOne = async () => {
|
||||
while (cursor < images.length) {
|
||||
const img = images[cursor++];
|
||||
img.dataset.loading = 'true';
|
||||
const id = img.dataset.photo;
|
||||
try {
|
||||
if (!photoUrls.has(id)) {
|
||||
photoUrls.set(id, fetch(`/api/center/photos/${encodeURIComponent(id)}`, { headers: { Authorization: `Bearer ${getToken()}` } }).then(async response => {
|
||||
if (!response.ok) throw new Error('照片加载失败');
|
||||
return URL.createObjectURL(await response.blob());
|
||||
}));
|
||||
}
|
||||
const url = await photoUrls.get(id);
|
||||
img.src = url;
|
||||
img.classList.remove('photo-loading');
|
||||
img.addEventListener('click', () => window.open(url, '_blank', 'noopener'));
|
||||
} catch {
|
||||
photoUrls.delete(id);
|
||||
img.classList.remove('photo-loading');
|
||||
img.classList.add('photo-error');
|
||||
img.alt = '照片暂时无法加载';
|
||||
delete img.dataset.loading;
|
||||
}
|
||||
const url = await photoUrls.get(id); img.src = url;
|
||||
img.addEventListener('click', () => window.open(url, '_blank', 'noopener'));
|
||||
} catch { photoUrls.delete(id); img.alt = '照片暂时无法加载'; }
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(4, images.length) }, loadOne));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 课表收取
|
||||
@@ -1215,7 +1335,7 @@
|
||||
const label = `${weekLabel(week)}:${item.submitted ? item.confirmed ? '已核对' : '已交待核对' : '未交'}`;
|
||||
return item.submitted && person.can_read ? `<button class="btn sm" data-timetable-view="${week}" data-user-id="${person.id}">${label}</button>` : `<span class="tag ${item.submitted ? 'attended' : ''}">${label}</span>`;
|
||||
}).join('')}</div></article>`).join('') || '<div class="empty">没有符合筛选条件的成员。</div>';
|
||||
$('#timetable-export-note').textContent = '输入管理员密钥后可导出全部课表;未核对课表也会包含。只有已核对课表中的空闲时段可列为可值班,待确认不能当作空闲。';
|
||||
$('#timetable-export-note').textContent = '输入管理员密钥后可导出全部课表;未核对和未传完的也会导出并标注,识别失败的成员会标明识别失败。只有已核对课表中的空闲时段可列为可值班。';
|
||||
} catch (error) { if (version === timetableRequest) toast(error.message, true); }
|
||||
}
|
||||
|
||||
@@ -1415,16 +1535,16 @@
|
||||
catch (error) { $('#center-export-status').textContent=error.message; }
|
||||
finally {button.disabled=false;}
|
||||
});
|
||||
let centerItems = [];
|
||||
let centerCanReview = false;
|
||||
let centerRecords = [];
|
||||
function openCenterFromHash() {
|
||||
if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
|
||||
if (!state.me || !['#center', '#center-records', '#center-assets'].includes(location.hash)) return false;
|
||||
centerTab = location.hash === '#center-assets' ? 'assets' : 'records';
|
||||
if (!state.me || !['#center', '#center-records', '#center-duty', '#center-assets', '#center-hall'].includes(location.hash)) return false;
|
||||
centerTab = location.hash === '#center-duty' ? 'duty' : location.hash === '#center-assets' ? 'assets' : location.hash === '#center-hall' ? 'hall' : 'records';
|
||||
$$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab));
|
||||
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
||||
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
|
||||
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
||||
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
|
||||
show('center');
|
||||
return true;
|
||||
}
|
||||
@@ -1441,17 +1561,50 @@
|
||||
if ($('#center-from').value) p.set('date_from', Date.parse($('#center-from').value + 'T00:00:00+08:00'));
|
||||
if ($('#center-to').value) p.set('date_to', Date.parse($('#center-to').value + 'T23:59:59.999+08:00'));
|
||||
const data = await api(`/activities?${p}`); centerRecords = data.items;
|
||||
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录活动时请上传照片。</div>';
|
||||
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录工作时请上传照片。</div>';
|
||||
bindCardEvents($('#center-record-list'));
|
||||
} else if (centerTab === 'duty') {
|
||||
await loadCenterDuty();
|
||||
} else if (centerTab === 'hall') {
|
||||
$('#center-hall-status').textContent = '正在读取金山文档登记表…';
|
||||
const hall = await api('/center/hall-log');
|
||||
$('#center-hall-link').href = hall.link;
|
||||
$('#center-hall-link').classList.toggle('hidden', !hall.link);
|
||||
$('#center-hall-status').textContent = hall.ok ? `共 ${hall.count} 条登记,更新于 ${fmtDate(hall.fetched_at)}(60 秒缓存)` : `读取失败:${hall.error}`;
|
||||
const parseHallDate = text => {
|
||||
const match = /(\d{4})\.(\d{1,2})\.(\d{1,2})/.exec(text || '');
|
||||
return match ? new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]), 23, 59, 59).getTime() : 0;
|
||||
};
|
||||
const seqNumber = r => { const m = /^\d+/.exec((r['序号'] || '').trim()); return m ? Number(m[0]) : Number.MAX_SAFE_INTEGER; };
|
||||
const hallNow = Date.now();
|
||||
const hallRows = hall.records
|
||||
.filter(r => Object.keys(r).some(k => k !== '_row' && k !== '序号' && r[k]))
|
||||
.sort((a, b) => {
|
||||
const pa = parseHallDate(a['日期']), pb = parseHallDate(b['日期']);
|
||||
const pastA = pa && pa < hallNow - 86400000, pastB = pb && pb < hallNow - 86400000;
|
||||
if (pastA !== pastB) return pastA ? 1 : -1;
|
||||
return seqNumber(a) - seqNumber(b);
|
||||
});
|
||||
$('#center-hall-list').innerHTML = hallRows.map(r => {
|
||||
const duty = r['赋能部值班人员及联系方式'] || '';
|
||||
const contact = r['使用单位联系人及联系方式'] || '';
|
||||
const past = parseHallDate(r['日期']) && parseHallDate(r['日期']) < hallNow - 86400000;
|
||||
return `<div class="acard" data-hall-row="${r._row}"><b>${esc(r['使用事项'] || '未填写使用事项')}</b> <span class="tag ${past ? '' : 'joined'}">${esc(r['使用场地'] || '')}${past ? ' · 已结束' : ''}</span><p class="muted">${esc(r['日期'] || '')} ${esc(r['时间'] || '')} · ${esc(r['使用单位'] || '未填写使用单位')}</p><p>参加人数:${esc(r['参加人数'] || '—')}</p><p>联系人:<span class="hall-contact-value">${esc(contact || '—')}</span> <button type="button" class="btn small" data-hall-edit="${r._row}" data-hall-col="7">${contact ? '修改' : '填写'}</button></p><p>值班人:<span class="hall-duty-value">${esc(duty || '—')}</span> <button type="button" class="btn small" data-hall-edit="${r._row}" data-hall-col="8">${duty ? '修改' : '填写'}</button></p>${r['备注'] ? `<p class="muted">备注:${esc(r['备注'])}</p>` : ''}</div>`;
|
||||
}).join('') || '<div class="empty">登记表暂无数据。</div>';
|
||||
} else {
|
||||
const data = await api(`/center/items?q=${encodeURIComponent($('#center-item-q').value)}`); centerItems = data.items; centerCanReview = data.can_review;
|
||||
$('#center-check-status').textContent = `${data.day} · ${data.checked_today ? '今日清点已完成' : '今日待清点,请逐项核对实际在库数量'}${data.approval_configured ? '' : ' · 负责人待配置,借出申请将保持待审批'}`;
|
||||
const data = await api(`/center/items?q=${encodeURIComponent($('#center-item-q').value)}`);
|
||||
$('#center-check-status').textContent = `${data.day} · ${data.checked_today ? '今日清点已完成' : '今日待清点,请逐项核对实际在库数量'}`;
|
||||
const canEditCheck = data.check?.user_id === state.me.id;
|
||||
$('#center-check').disabled = data.checked_today && !canEditCheck;
|
||||
$('#center-check').textContent = data.checked_today && canEditCheck ? '修改今日清点' : '完成今日清点';
|
||||
$('#center-items').innerHTML = data.items.map(item => `<div class="mcard"><b>${esc(item.name)}</b><p class="muted">总数 ${item.quantity} · 已借出 ${item.borrowed} · 在库 ${item.available}</p><button class="btn sm" data-borrow="${item.id}" ${item.available ? '' : 'disabled'}>申请借出</button></div>`).join('') || '<div class="empty">还没有物品,请先添加物品。</div>';
|
||||
$('#center-items').innerHTML = data.items.map(item => `<div class="mcard"><b>${esc(item.name)}</b><p class="muted">总数 ${item.quantity}${item.borrowed ? ` · 历史借出 ${item.borrowed}` : ''} · 在库 ${item.available}</p></div>`).join('') || '<div class="empty">还没有库存物品,可点击“添加物品”建立清点清单。</div>';
|
||||
const loans = await api(`/center/loans?status=${$('#center-loan-status').value}`);
|
||||
$('#center-loans').innerHTML = loans.items.map(r => `<div class="acard"><b>${esc(r.item_name)} × ${r.quantity}</b> <span class="tag ${r.returned_at ? 'attended' : 'joined'}">${({pending:'待审批',approved:'借出中',returned:'已归还',rejected:'已驳回'})[r.status] || r.status}</span><p class="muted">${esc(r.display_name)} · ${fmtDate(r.created_at)}</p><p>${esc(r.reason)}</p>${r.contact ? `<p class="muted">联系方式:${esc(r.contact)}</p>` : ''}<p class="muted">${esc(r.review_note || '')}</p>${r.status === 'pending' && centerCanReview ? `<button class="btn primary sm" data-review="${r.id}" data-action="approve">批准</button> <button class="btn sm" data-review="${r.id}" data-action="reject">驳回</button>` : ''}${r.status === 'approved' && r.user_id === state.me.id ? `<button class="btn sm" data-return="${r.id}">登记归还</button>` : ''}</div>`).join('') || '<div class="empty">暂无借用记录。</div>';
|
||||
$('#center-loans').innerHTML = loans.items.map(r => {
|
||||
const guest = r.user_id === null;
|
||||
const quantity = guest ? '' : ` × ${r.quantity}`;
|
||||
const context = guest ? `<p class="muted">${esc(r.guest_college || '')} · ${esc(r.guest_activity_name || '')}</p>` : '';
|
||||
return `<div class="acard"><b>${esc(r.item_name)}${quantity}</b> <span class="tag ${r.returned_at ? 'attended' : 'joined'}">${guest ? '免登录登记' : (({pending:'历史待处理',approved:'历史借出中',recorded:'已登记',returned:'历史已归还',rejected:'历史未借出'})[r.status] || r.status)}</span><p class="muted">${esc(r.display_name || '未知登记人')} · ${fmtDate(r.created_at)}</p>${context}<p>${esc(r.reason)}</p>${r.contact ? `<p class="muted">联系方式:${esc(r.contact)}</p>` : ''}${r.status === 'approved' && r.item_id && r.user_id === state.me.id ? `<button class="btn sm" data-return="${r.id}">登记归还</button>` : ''}</div>`;
|
||||
}).join('') || '<div class="empty">暂无借出登记。</div>';
|
||||
const checks = await api('/center/checks');
|
||||
$('#center-checks').innerHTML = checks.items.map(r => `<div class="acard"><b>${esc(r.day)}</b><p class="muted">${esc(r.display_name)} · ${fmtDate(r.created_at)}</p>${r.details.map(d => `<p>${esc(d.name)}:应在库 ${d.expected},实点 ${d.actual},借出 ${d.borrowed}</p>`).join('')}<p>${esc(r.note)}</p></div>`).join('') || '<p class="muted">暂无清点记录。</p>';
|
||||
}
|
||||
@@ -1462,10 +1615,124 @@
|
||||
history.replaceState(null, '', '#center-' + centerTab);
|
||||
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b === button));
|
||||
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
||||
$('#center-duty').classList.toggle('hidden', centerTab !== 'duty');
|
||||
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
||||
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
|
||||
loadCenter();
|
||||
}));
|
||||
$('#center-new').addEventListener('click', () => openActivityForm(null, 'center'));
|
||||
$('#center-hall-refresh').addEventListener('click', async () => {
|
||||
try { await api('/center/hall-log?refresh=true'); } finally { await loadCenter(); }
|
||||
});
|
||||
$('#center-hall-list').addEventListener('click', event => {
|
||||
const button = event.target.closest('[data-hall-edit]');
|
||||
if (!button) return;
|
||||
const row = Number(button.dataset.hallEdit);
|
||||
const column = Number(button.dataset.hallCol || 8);
|
||||
const card = button.closest('[data-hall-row]');
|
||||
const isDuty = column === 8;
|
||||
const current = card?.querySelector(isDuty ? '.hall-duty-value' : '.hall-contact-value')?.textContent.trim();
|
||||
centerForm(isDuty ? '填写值班人' : '填写联系人',
|
||||
`<p class="muted">填写后同步写入金山文档登记表,服务器会记录编辑人和修改内容。留空提交即清空该格。</p>
|
||||
<label>${isDuty ? '值班人及联系方式' : '使用单位联系人及联系方式'}<input name="duty" maxlength="200" value="${esc(current && current !== '—' ? current : '')}" placeholder="例如:张三 13800000000" /></label>`,
|
||||
async f => { await api('/center/hall-log/duty', { method: 'POST', body: { row, column, value: f.duty.value.trim() } }); toast('已保存并同步到金山文档'); });
|
||||
});
|
||||
function openLoanForm() {
|
||||
centerForm('登记借出',
|
||||
`<p class="muted">这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。</p>
|
||||
<label>借出物品<input name="item_name" required maxlength="100" placeholder="例如:投影仪、音箱" /></label>
|
||||
<label>数量<input name="quantity" type="number" min="1" max="100000" value="1" required /></label>
|
||||
<label>借出理由<textarea name="reason" required maxlength="500"></textarea></label>
|
||||
<label>联系方式<input name="contact" required maxlength="200" placeholder="电话、微信或邮箱" /></label>`,
|
||||
f => api('/center/loans', { method: 'POST', body: {
|
||||
item_name: f.item_name.value.trim(),
|
||||
quantity: Number(f.quantity.value),
|
||||
reason: f.reason.value,
|
||||
contact: f.contact.value,
|
||||
}}));
|
||||
}
|
||||
document.addEventListener('click', event => {
|
||||
const button = event.target.closest('#center-new-loan');
|
||||
if (!button || button.disabled) return;
|
||||
openLoanForm();
|
||||
});
|
||||
let centerDutyWeekStart = '';
|
||||
const centerDutyDate = (iso, withYear = true) => new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
...(withYear ? { year: 'numeric' } : {}),
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
}).format(new Date(iso + 'T00:00:00+08:00'));
|
||||
const centerDutyWeekText = data => `${centerDutyDate(data.week_start, false)}—${centerDutyDate(data.week_end)}`;
|
||||
function centerDutyAssignee(assignee) {
|
||||
return `<span class="center-duty-name">${esc(assignee.name)}${assignee.leave ? '<small>已请假</small>' : ''}</span>`;
|
||||
}
|
||||
async function loadCenterDuty() {
|
||||
const params = new URLSearchParams();
|
||||
if (centerDutyWeekStart) params.set('week_start', centerDutyWeekStart);
|
||||
const data = await api('/center/duty' + (params.size ? '?' + params : ''));
|
||||
centerDutyWeekStart = data.week_start;
|
||||
$('#center-duty-title').textContent = data.title;
|
||||
const currentText = data.current.length
|
||||
? `当前值班:${data.current.map(record => record.assignees.map(item => item.name).join('、')).join(';')}`
|
||||
: '当前没有正在进行的一楼值班';
|
||||
$('#center-duty-summary').textContent = `${data.week_type_label} · ${centerDutyWeekText(data)} · ${currentText}`;
|
||||
$('#center-duty-current-card').innerHTML = data.current.length
|
||||
? data.current.map(record => `<div class="center-duty-live"><div><span class="center-duty-live-dot"></span><b>${esc(record.weekday_label)} ${esc(record.slot.label)}</b><p>${record.assignees.map(centerDutyAssignee).join('、')}</p></div><span>${esc(record.slot.start)}—${esc(record.slot.end)}</span></div>`).join('')
|
||||
: '<div class="center-duty-idle"><b>当前时段空闲</b><span>可查看本周排班;请假须在值班日期开始前提交。</span></div>';
|
||||
const groups = new Map();
|
||||
for (const record of data.records) {
|
||||
if (!groups.has(record.date)) groups.set(record.date, []);
|
||||
groups.get(record.date).push(record);
|
||||
}
|
||||
$('#center-duty-list').innerHTML = [...groups.entries()].map(([day, records]) => {
|
||||
const first = records[0];
|
||||
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' }) === day;
|
||||
return `<article class="center-duty-day ${today ? 'is-today' : ''}">
|
||||
<header><b>${esc(first.weekday_label)}</b><span>${esc(centerDutyDate(day))}</span>${today ? '<em>今天</em>' : ''}</header>
|
||||
${records.map(record => {
|
||||
const own = record.assignees.find(item => item.name.replace(/\s+/g, '') === data.viewer_name.replace(/\s+/g, ''));
|
||||
let leaveControl = '';
|
||||
if (own) {
|
||||
if (!own.leave && record.viewer_can_leave) {
|
||||
leaveControl = `<button class="btn small center-duty-leave" type="button" data-duty-date="${record.date}" data-duty-slot="${record.slot.id}" data-duty-label="${esc(record.weekday_label + ' ' + record.slot.label)}">申请请假</button>`;
|
||||
} else {
|
||||
const reason = own.leave ? '已请假' : (record.can_leave_reason || '当前不可请假');
|
||||
leaveControl = `<button class="btn small" type="button" disabled title="${esc(reason)}">${esc(own.leave ? '已请假' : '申请请假')}</button>`;
|
||||
}
|
||||
}
|
||||
return `<div class="center-duty-slot ${record.status === 'active' ? 'is-active' : ''} ${record.status === 'past' ? 'is-past' : ''}">
|
||||
<div><b>${esc(record.slot.label)}</b><span>${esc(record.slot.start)}—${esc(record.slot.end)}</span></div>
|
||||
<div class="center-duty-people">${record.assignees.map(centerDutyAssignee).join('')}</div>
|
||||
${leaveControl}
|
||||
</div>`;
|
||||
}).join('')}
|
||||
</article>`;
|
||||
}).join('');
|
||||
}
|
||||
$('#center-duty-prev').addEventListener('click', () => {
|
||||
const day = new Date(centerDutyWeekStart + 'T00:00:00+08:00'); day.setDate(day.getDate() - 7);
|
||||
centerDutyWeekStart = day.toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' }); loadCenterDuty().catch(error => toast(error.message, true));
|
||||
});
|
||||
$('#center-duty-current').addEventListener('click', () => {
|
||||
centerDutyWeekStart = ''; loadCenterDuty().catch(error => toast(error.message, true));
|
||||
});
|
||||
$('#center-duty-next').addEventListener('click', () => {
|
||||
const day = new Date(centerDutyWeekStart + 'T00:00:00+08:00'); day.setDate(day.getDate() + 7);
|
||||
centerDutyWeekStart = day.toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' }); loadCenterDuty().catch(error => toast(error.message, true));
|
||||
});
|
||||
$('#center-duty-list').addEventListener('click', event => {
|
||||
const button = event.target.closest('[data-duty-date][data-duty-slot]');
|
||||
if (!button || button.disabled) return;
|
||||
centerForm('申请赋能中心一楼值班请假',
|
||||
`<p class="muted">${esc(button.dataset.dutyLabel)}。请假必须在值班日期开始前提交,提交后立即显示在排班中,不进入活动统计,也不记录缺勤。</p>
|
||||
<label>请假原因<textarea name="reason" required minlength="2" maxlength="300" placeholder="请简要说明原因"></textarea></label>`,
|
||||
f => api('/center/duty/leave', { method: 'POST', body: {
|
||||
duty_date: button.dataset.dutyDate,
|
||||
slot: button.dataset.dutySlot,
|
||||
reason: f.reason.value.trim(),
|
||||
}}));
|
||||
});
|
||||
for (const id of ['center-q', 'center-item-q']) $('#' + id).addEventListener('input', debounce(loadCenter, 300));
|
||||
for (const id of ['center-from', 'center-to', 'center-loan-status']) $('#' + id).addEventListener('change', loadCenter);
|
||||
$('#center-refresh').addEventListener('click', loadCenter);
|
||||
@@ -1479,17 +1746,7 @@
|
||||
});
|
||||
}
|
||||
$('#center-add-item').addEventListener('click', () => centerForm('添加一楼物品', '<label>物品名称<input name="item_name" required maxlength="100" /></label><label>物品总数<input name="quantity" type="number" min="0" max="100000" value="1" required /></label>', f => api('/center/items', { method: 'POST', body: { name: f.item_name.value, quantity: Number(f.quantity.value) } })));
|
||||
$('#center-items').addEventListener('click', event => {
|
||||
const button = event.target.closest('[data-borrow]'); if (!button || button.disabled) return;
|
||||
const item = centerItems.find(r => r.id === button.dataset.borrow);
|
||||
centerForm(`借出 · ${esc(item.name)}`, `<p class="muted">提交后等待负责人审批。联系方式仅本人和负责人可见,便于联系归还。</p><label>借出数量<input name="quantity" type="number" min="1" max="${item.available}" value="1" required /></label><label>申请理由<textarea name="reason" required maxlength="500"></textarea></label><label>联系方式<input name="contact" required maxlength="200" placeholder="电话、微信或邮箱" /></label>`, f => api(`/center/items/${item.id}/loans`, { method: 'POST', body: { quantity: Number(f.quantity.value), reason: f.reason.value, contact: f.contact.value } }));
|
||||
});
|
||||
$('#center-loans').addEventListener('click', async event => {
|
||||
const review = event.target.closest('[data-review]');
|
||||
if (review && !review.disabled) {
|
||||
centerForm(review.dataset.action === 'approve' ? '批准借出申请' : '驳回借出申请', '<label>审批说明<textarea name="note" maxlength="500"></textarea></label>', f => api(`/center/loans/${review.dataset.review}/review`, { method: 'POST', body: { action: review.dataset.action, note: f.note.value } }));
|
||||
return;
|
||||
}
|
||||
const button = event.target.closest('[data-return]'); if (!button || button.disabled) return;
|
||||
button.disabled = true;
|
||||
try { await api(`/center/loans/${button.dataset.return}/return`, { method: 'POST' }); await loadCenter(); }
|
||||
|
||||
Reference in New Issue
Block a user