新增材料上传进度,一楼活动全员可见仅作记录并支持成员补充材料

This commit is contained in:
2026-11-11 18:31:00 +08:00
parent d2cb824fa2
commit 04fd4b9bfc
12 changed files with 389 additions and 57 deletions
+5
View File
@@ -582,6 +582,11 @@ button:focus-visible, a:focus-visible, [tabindex]:focus-visible { outline: 3px s
.activity-photos { display:flex; gap:10px; flex-wrap:wrap; margin:14px 0; }
.activity-photos:empty { display:none; }
.activity-materials { margin:12px 0; display:flex; flex-direction:column; gap:8px; }
.activity-materials > div { display:flex; flex-wrap:wrap; align-items:center; gap:8px; }
.upload-progress { margin:16px 0; padding:12px 14px; border:1px solid var(--line); border-radius:10px; background:var(--primary-soft); }
.upload-progress p { margin:0 0 8px; font-size:13px; overflow-wrap:anywhere; }
.upload-progress progress { display:block; width:100%; height:12px; accent-color:var(--primary); }
.activity-photos img { width:120px; height:90px; object-fit:cover; border-radius:8px; border:1px solid var(--line); cursor:zoom-in; }
.center-toolbar { margin-bottom:24px; }
.center-export { margin:0 0 24px; padding:16px 20px; border:1px solid var(--line); background:var(--card); border-radius:12px; }
+2 -2
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WorkLog · 活动记录</title>
<meta name="theme-color" content="#f5f7f5" />
<link rel="stylesheet" href="/assets/styles.css?v=18" />
<link rel="stylesheet" href="/assets/styles.css?v=19" />
</head>
<body>
<div id="app">
@@ -309,7 +309,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=26"></script>
<script src="/js/app.js?v=27"></script>
</div>
</body>
</html>
+141 -24
View File
@@ -394,9 +394,10 @@
};
function activityCard(a, opts = {}) {
const mine = a.my_participation;
const isCenter = a.record_type === 'center';
const mine = isCenter ? null : a.my_participation;
const isOrganizer = a.organizer_id === state.me.id;
const full = a.capacity && a.participant_count >= a.capacity;
const full = !isCenter && a.capacity && a.participant_count >= a.capacity;
const statusTag = mine
? `<span class="tag ${mine.status}">${STATUS_LABEL[mine.status] || mine.status}</span>`
: "";
@@ -411,8 +412,9 @@
? `<span class="face more">+${a.participant_count - 6}</span>` : "";
const actions = [];
if (isCenter) actions.push('<button class="btn primary sm" data-act="materials">补充材料</button>');
// "我也参加过":点击直接加入
if (!mine && a.visibility === "public" && !full) {
if (!isCenter && !mine && a.visibility === "public" && !full) {
actions.push(`<button class="btn primary sm" data-act="claim">我也参加过</button>`);
}
if (mine && !isOrganizer) {
@@ -438,12 +440,11 @@
</div>
${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>' : ''}
${a.material_id ? `<button class="btn sm" data-material="${esc(a.material_id)}">下载材料 ZIP</button>` : ''}
${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>` : ''}
<div class="acard-foot">
<div class="faces">
${faces}${more}
<span class="faces-label">${a.participant_count} 人${opts.showOrganizer && a.organizer ? ` · ${esc(a.organizer.display_name)} 记录` : ""}</span>
${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>`}
</div>
<div class="acard-actions">${actions.join("")}</div>
</div>
@@ -460,6 +461,7 @@
e.stopPropagation();
const act = btn.dataset.act;
if (act === "open") return openDetail(id);
if (act === 'materials') return openMaterialForm(activity);
if (act === "claim") {
try { await api(`/activities/${id}/claim`, { method: "POST" }); toast("已加入这条记录"); refreshCurrent(); }
catch (err) { toast(err.message, true); }
@@ -792,7 +794,87 @@
return mask;
}
const escListener = (e) => { if (e.key === "Escape") closeModal(); };
const closeModal = () => { $("#modal-root").innerHTML = ""; document.removeEventListener("keydown", escListener); };
let materialUpload = null;
const closeModal = () => {
if (materialUpload) materialUpload.abort();
$("#modal-root").innerHTML = ""; document.removeEventListener("keydown", escListener);
};
function uploadMaterial(file, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
materialUpload = xhr;
xhr.open('POST', '/api/center/materials');
xhr.setRequestHeader('Authorization', `Bearer ${getToken()}`);
xhr.setRequestHeader('Content-Type', 'application/zip');
xhr.timeout = 10 * 60 * 1000;
xhr.upload.onprogress = event => onProgress(event.loaded, event.lengthComputable ? event.total : file.size);
xhr.upload.onload = () => onProgress(file.size, file.size);
xhr.onload = () => {
let result;
try { result = JSON.parse(xhr.responseText); } catch { result = {}; }
if (xhr.status >= 200 && xhr.status < 300 && result.id) resolve(result);
else reject(new Error(xhr.status === 413 ? '材料包过大,请提交30MB以内的ZIP' : apiErrorMessage(result.detail, xhr.status)));
};
xhr.onerror = () => reject(new Error('上传失败,请检查网络后重试'));
xhr.ontimeout = () => reject(new Error('上传超时,请重试'));
xhr.onabort = () => reject(new Error('上传已取消'));
xhr.onloadend = () => { if (materialUpload === xhr) materialUpload = null; };
onProgress(0, file.size);
xhr.send(file);
});
}
function materialButtons(activity) {
const packages = activity.materials?.length ? activity.materials : activity.material_id ? [{ id: activity.material_id }] : [];
return packages.length ? `<div class="activity-materials">${packages.map((item, i) => `<div><button class="btn sm" data-material="${esc(item.id)}">下载材料 ZIP${packages.length > 1 ? ` ${i + 1}` : ''}</button>${item.uploader_name ? `<span class="muted">${esc(item.uploader_name)} · ${fmtDate(item.created_at)}</span>` : ''}</div>`).join('')}</div>` : '';
}
function renderUploadProgress(label, meter, loaded, total) {
const percent = total ? Math.min(100, Math.floor(loaded / total * 100)) : 0;
if (loaded >= total && total > 0) {
meter.removeAttribute('value');
label.textContent = '上传完成,正在校验材料并处理照片…';
} else {
meter.value = percent;
const size = bytes => (bytes / 1024 / 1024).toFixed(1) + ' MB';
label.textContent = `正在上传 ${percent}% · ${size(loaded)} / ${size(total)}`;
}
}
function openMaterialForm(activity) {
modal(`<h3>补充活动材料</h3><p class="modal-sub muted">${esc(activity.title)} · 所有登录成员均可补充材料,无需参加活动。已有材料会保留。</p>
<form id="material-form"><label>ZIP材料包<input name="materials" type="file" accept=".zip,application/zip" required /></label>
<p class="muted">最大30MB,包内至少1张活动照片,照片数量不限,可附文档。</p>
<div class="upload-progress hidden" id="material-progress"><p id="material-status" role="status" aria-live="polite"></p><progress id="material-meter" max="100" value="0" aria-labelledby="material-status"></progress></div>
<div class="form-error" id="material-error"></div><div class="form-actions"><button type="button" class="btn" id="material-cancel">取消</button><button type="submit" class="btn primary">上传并保存</button></div>
</form>`);
const form = $('#material-form');
const box = $('#material-progress'), label = $('#material-status'), meter = $('#material-meter'), errorBox = $('#material-error');
let uploaded = null;
$('#material-cancel').addEventListener('click', closeModal);
form.materials.addEventListener('change', () => { uploaded = null; box.classList.add('hidden'); });
form.addEventListener('submit', async event => {
event.preventDefault();
const button = form.querySelector('[type=submit]');
if (button.disabled) return;
const file = form.materials.files[0];
errorBox.textContent = '';
if (!file || file.size > 30 * 1024 * 1024 || !file.name.toLowerCase().endsWith('.zip')) { errorBox.textContent = '请提交30MB以内的ZIP材料包'; return; }
button.disabled = true; form.materials.disabled = true; box.classList.remove('hidden');
try {
button.textContent = '正在上传…';
if (!uploaded) uploaded = await uploadMaterial(file, (loaded, total) => renderUploadProgress(label, meter, loaded, total));
if (!form.isConnected) return;
meter.value = 100; label.textContent = '材料上传成功,正在保存…'; button.textContent = '正在保存…';
await api(`/activities/${activity.id}/materials`, { method: 'POST', body: { material_id: uploaded.id } });
closeModal(); toast('补充材料已保存'); refreshCurrent();
} catch (error) {
errorBox.textContent = error.message; label.textContent = uploaded ? '材料已上传,保存失败,可重试。' : '上传未完成,可重试。'; meter.value = uploaded ? 100 : 0;
button.disabled = false; form.materials.disabled = false; button.textContent = '上传并保存';
}
});
}
// ---- 新建 / 编辑活动
function openActivityForm(existing = null, defaultType = 'normal') {
@@ -809,7 +891,12 @@
</div>
<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"><label>活动材料 ZIP(必填)<input name="materials" type="file" accept=".zip,application/zip" /></label><p class="muted">最大30MB,包内须至少含1张活动照片,照片数量不限,可附PDF、Office或文本材料。编辑时不选新包会保留原材料。</p><p id="act-material-name" class="muted"></p><div id="act-photo-preview" class="activity-photos">${(existing?.photo_ids || []).map(id => `<img data-photo="${esc(id)}" alt="活动照片" />`).join('')}</div></div>
<label class="checkline"><input type="checkbox" name="visibility" ${!existing || existing.visibility === "public" ? "checked" : ""} /> 公开活动(所有人可见;不勾选则仅参加者可见)</label>
<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">
<p id="act-upload-status" role="status" aria-live="polite"></p>
<progress id="act-upload-meter" max="100" value="0" aria-labelledby="act-upload-status"></progress>
</div>
<div class="form-error" id="act-error"></div>
<div class="form-actions">
<button type="button" class="btn" id="act-cancel">取消</button>
@@ -817,22 +904,35 @@
</div>
</form>`);
const activityForm = $('#act-form');
const progressBox = $('#act-upload-progress');
const progressLabel = $('#act-upload-status');
const progressMeter = $('#act-upload-meter');
const errorBox = $('#act-error');
let uploadedMaterial = null;
activityForm.record_type.value = existing?.record_type || defaultType;
activityForm.record_type.disabled = state.view === 'center';
const togglePhotos = () => {
const isCenter = activityForm.record_type.value === 'center';
$('#act-photo-fields').classList.toggle('hidden', !isCenter);
$('#act-visibility').classList.toggle('hidden', isCenter);
$('#act-center-policy').classList.toggle('hidden', !isCenter);
activityForm.visibility.disabled = isCenter;
if (isCenter && !activityForm.location.value.trim()) activityForm.location.value = '赋能中心一楼';
};
activityForm.record_type.addEventListener('change', togglePhotos); togglePhotos();
loadPhotos($('#act-photo-preview'));
activityForm.materials.addEventListener('change', () => { $('#act-material-name').textContent = activityForm.materials.files[0]?.name || ''; });
activityForm.materials.addEventListener('change', () => {
$('#act-material-name').textContent = activityForm.materials.files[0]?.name || '';
uploadedMaterial = null; progressBox.classList.add('hidden');
});
$("#act-cancel").addEventListener("click", closeModal);
$("#act-form").addEventListener("submit", async (e) => {
e.preventDefault();
const f = e.target;
const btn = $("#act-submit");
if (btn.disabled) return;
errorBox.textContent = '';
const startMs = f.start_at.value ? new Date(f.start_at.value).getTime() : 0;
if (!startMs) { $("#act-error").textContent = "请选择开始时间"; return; }
const body = {
@@ -840,23 +940,33 @@
start_at: startMs,
location: f.location.value.trim(),
description: f.description.value.trim(),
visibility: f.visibility.checked ? "public" : "private",
visibility: f.record_type.value === 'center' || f.visibility.checked ? "public" : "private",
record_type: f.record_type.value,
};
btn.disabled = true;
const typeWasDisabled = f.record_type.disabled;
f.record_type.disabled = true;
f.materials.disabled = true;
try {
const file = f.materials.files[0];
if (body.record_type === 'center') {
body.material_id = existing?.material_id || null;
if (file) {
if (file.size > 30 * 1024 * 1024 || !file.name.toLowerCase().endsWith('.zip')) throw new Error('请提交30MB以内的ZIP材料包');
const response = await fetch('/api/center/materials', { method: 'POST', headers: { Authorization: `Bearer ${getToken()}`, 'Content-Type': 'application/zip' }, body: file });
const result = await response.json();
if (!response.ok) throw new Error(typeof result.detail === 'string' ? result.detail : '材料包上传失败');
body.material_id = result.id;
progressBox.classList.remove('hidden');
btn.textContent = '正在上传…';
if (uploadedMaterial?.file !== file) {
const result = await uploadMaterial(file, (loaded, total) => renderUploadProgress(progressLabel, progressMeter, loaded, total));
uploadedMaterial = { file, id: result.id };
}
body.material_id = uploadedMaterial.id;
progressMeter.value = 100;
progressLabel.textContent = '材料上传成功,正在保存活动记录…';
}
if (!body.material_id && !(existing?.photo_ids || []).length) throw new Error('请上传包含活动照片的ZIP材料包');
} else { body.photo_ids = []; body.material_id = null; }
if (!f.isConnected) return;
btn.textContent = '正在保存…';
if (isEdit) {
await api(`/activities/${existing.id}`, { method: "PATCH", body });
toast("已保存");
@@ -867,8 +977,13 @@
closeModal();
refreshCurrent();
} catch (err) {
$("#act-error").textContent = err.message;
errorBox.textContent = err.message;
progressMeter.value = uploadedMaterial ? 100 : 0;
if (!progressBox.classList.contains('hidden')) progressLabel.textContent = uploadedMaterial ? '材料已上传,记录保存失败,可重试。' : '上传未完成,可重试。';
btn.disabled = false;
f.record_type.disabled = typeWasDisabled;
f.materials.disabled = false;
btn.textContent = isEdit ? '保存修改' : '提交记录';
}
});
}
@@ -879,10 +994,11 @@
try { data = await api(`/activities/${id}`); } catch (err) { toast(err.message, true); return; }
const a = data.activity;
const canEdit = data.can_edit;
const mine = a.my_participation;
const full = a.capacity && a.participant_count >= a.capacity;
const isCenter = a.record_type === 'center';
const mine = isCenter ? null : a.my_participation;
const full = !isCenter && a.capacity && a.participant_count >= a.capacity;
const rows = a.participants.map((p) => {
const rows = (isCenter ? [] : a.participants).map((p) => {
const isSelfRow = p.user_id === state.me.id;
const canManage = canEdit || isSelfRow;
const statusSel = canManage
@@ -903,12 +1019,13 @@
</li>`;
}).join("");
const claimBtn = !mine && a.visibility === "public" && !full
const claimBtn = !isCenter && !mine && a.visibility === "public" && !full
? `<button class="btn primary" id="d-claim">我也参加过</button>` : "";
const leaveBtn = mine && !canEdit
? `<button class="btn" id="d-leave">退出</button>` : "";
const editBtn = canEdit ? `<button class="btn" id="d-edit">编辑</button>` : "";
const delBtn = canEdit ? `<button class="btn danger" id="d-del">删除</button>` : "";
const materialsBtn = isCenter ? '<button class="btn primary" id="d-materials">补充材料</button>' : '';
const noteRow = mine
? `<label>我的备注
<input id="d-note" maxlength="500" value="${esc(mine.note || "")}" placeholder="如:带了水和球拍" /></label>`
@@ -930,16 +1047,15 @@
<div><span class="lbl">时间</span>📅 ${fmtDate(a.start_at)}${a.start_at >= Date.now() ? "(未开始)" : ""}</div>
<div><span class="lbl">地点</span>📍 ${a.location ? esc(a.location) : "未填写"}</div>
<div><span class="lbl">记录人</span>${esc(a.organizer?.display_name || "未知")}</div>
<div><span class="lbl">人数</span>${a.participant_count}${a.capacity ? ` / ${a.capacity}` : ""} · 已参加 ${a.attended_count}</div>
${isCenter ? '<div><span class="lbl">类型</span>仅作记录 · 全员可见 · 无需参加</div>' : `<div><span class="lbl">人数</span>${a.participant_count}${a.capacity ? ` / ${a.capacity}` : ""} · 已参加 ${a.attended_count}</div>`}
</div>
${a.description ? `<div class="detail-desc">${esc(a.description)}</div>` : ""}
${a.material_id ? `<button class="btn sm" data-material="${esc(a.material_id)}">下载材料 ZIP</button>` : ''}
${materialButtons(a)}
<div class="activity-photos">${(a.photo_ids || []).map(id => `<img data-photo="${esc(id)}" alt="活动照片" />`).join('')}</div>
${noteRow}
<h4 style="margin:14px 0 2px">一起参加过(${a.participant_count})</h4>
<ul class="p-list">${rows || '<li class="muted">还没有其他人的参加记录</li>'}</ul>
${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">
${claimBtn}${leaveBtn}${editBtn}${delBtn}
${materialsBtn}${claimBtn}${leaveBtn}${editBtn}${delBtn}
</div>`);
$("#d-close").addEventListener("click", closeModal);
@@ -951,6 +1067,7 @@
};
const on = (sel, fn) => { const el = $(sel); if (el) el.addEventListener("click", fn); };
on('#d-materials', () => openMaterialForm(a));
on("#d-claim", async () => { try { await api(`/activities/${id}/claim`, { method: "POST" }); toast("已加入这条记录"); reload(); } catch (err) { toast(err.message, true); } });
on("#d-leave", async () => {
if (!confirm("确定退出这条活动吗?")) return;