支持一楼活动照片多选直传,ZIP改为可选文档附件
This commit is contained in:
@@ -4,15 +4,17 @@
|
|||||||
|
|
||||||
## 活动记录
|
## 活动记录
|
||||||
|
|
||||||
在一楼页面创建活动时默认选择“赋能中心一楼活动记录”,地点默认填“赋能中心一楼”。此类记录必须填写主题、时间,并提交一个 ZIP 材料包,最大 30MB。ZIP 内须至少含 1 张 JPG、PNG 或 WebP 照片,照片数量不限,每张最大 8MB、2400 万像素;可附 PDF、Word、Excel、PowerPoint、TXT、CSV 或 Markdown 材料,单个文档最大 20MB。支持文件夹,展开后总大小不超过 100MB;不支持加密 ZIP、链接、不安全路径及可执行文件。ZIP 上传不再按照片数量计算每日限额。
|
在一楼页面创建活动时默认选择“赋能中心一楼活动记录”,地点默认填“赋能中心一楼”。必须填写主题、时间,照片或 ZIP 至少提交一种。照片可直接从相册多选或拍照,支持 JPG、PNG、WebP,数量不限,每张最大 8MB、2400 万像素。逐张上传时显示“正在上传 3/7”及单张进度;失败重试会复用已成功上传的照片。直接上传接口每人24小时限额提高为1000张。
|
||||||
|
|
||||||
|
ZIP 为可选附件,仅在附 PDF、Word、Excel、PowerPoint、TXT、CSV 或 Markdown 等文档时需要打包,不要求包内有照片。ZIP 最大30MB,包内单个文档最大20MB,照片每张最大8MB,展开后总大小不超过100MB;支持文件夹,不支持空ZIP、加密ZIP、链接、不安全路径及可执行文件。旧版含照片的ZIP继续支持,包内照片会自动提取展示。
|
||||||
|
|
||||||
一楼活动统一为全体登录成员可见的纯记录,不接受参加、退出或参加状态变更,不计入成员参加、出席、发起及普通活动概览统计,也不会发送带参加按钮的活动邮件。创建和编辑时即使提交私密或人数限制,后端也会统一为公开且无名额。旧一楼记录在启动时统一为公开,历史参加数据保留存档,不再显示或统计,旧参加邮件链接失效。普通活动保留原有参加规则。
|
一楼活动统一为全体登录成员可见的纯记录,不接受参加、退出或参加状态变更,不计入成员参加、出席、发起及普通活动概览统计,也不会发送带参加按钮的活动邮件。创建和编辑时即使提交私密或人数限制,后端也会统一为公开且无名额。旧一楼记录在启动时统一为公开,历史参加数据保留存档,不再显示或统计,旧参加邮件链接失效。普通活动保留原有参加规则。
|
||||||
|
|
||||||
页面会从包内提取照片,转换为 JPEG、缩小到最长边 2400px 并移除预览照片的 EXIF 信息;原始 ZIP 原样保留,可在活动卡片或详情中下载。活动墙可按普通 / 一楼活动筛选;一楼入口可按主题和起止日期筛选。上传显示实际传输百分比和已传大小,传输结束后显示校验和照片处理状态,再保存记录。失败可重试;材料已上传而保存失败时,重试会复用已上传材料。取消或关闭上传弹层会中止正在传输的文件。
|
页面会从包内提取照片,转换为 JPEG、缩小到最长边 2400px 并移除预览照片的 EXIF 信息;原始 ZIP 原样保留,可在活动卡片或详情中下载。活动墙可按普通 / 一楼活动筛选;一楼入口可按主题和起止日期筛选。上传显示实际传输百分比和已传大小,传输结束后显示校验和照片处理状态,再保存记录。失败可重试;材料已上传而保存失败时,重试会复用已上传材料。取消或关闭上传弹层会中止正在传输的文件。
|
||||||
|
|
||||||
任何登录成员均可在一楼活动卡片或详情点击“补充材料”,上传 ZIP 后追加到该记录,显示上传人和时间,不需要参加活动。补充材料、记录人编辑时上传的新包及原材料都会保留,可分别下载,照片合并展示。活动名称、时间、地点等仍仅由记录人修改。历史照片记录继续显示、可编辑,无须重新提交。尚未关联到活动的文件仅上传人可访问。
|
任何登录成员均可在一楼活动卡片或详情点击“补充材料”,多选照片或选择可选ZIP追加到该记录,不需要参加活动。各份ZIP显示上传人和时间,可分别下载;直接上传的照片合并展示,未附ZIP时仅显示照片墙,不显示ZIP下载按钮。编辑或多人同时补充会保留已有照片和附件。活动名称、时间、地点等仍仅由记录人修改。历史照片记录继续显示、可编辑,无须重新提交。尚未关联到活动的文件仅上传人可访问。
|
||||||
|
|
||||||
成员补充接口为 `POST /api/activities/{activity_id}/materials`,使用本人 Bearer 登录令牌和 JSON `{"material_id":"本人刚上传的材料ID"}`。材料先通过 `POST /api/center/materials` 以 ZIP 原始字节上传。关联接口仅允许一楼活动、验证材料归属并防止重复关联;同一个包重复提交不会新增副本。
|
照片逐张调用 `POST /api/center/photos`(图片原始字节),ZIP调用 `POST /api/center/materials`(ZIP原始字节)。创建或编辑活动传 `photo_ids`,`material_id` 可选。成员补充接口为 `POST /api/activities/{activity_id}/materials`,使用本人 Bearer 登录令牌及 JSON `{"photo_ids":["本人照片ID"],"material_id":"可选ZIP材料ID"}`,二者至少一个非空。关联接口仅允许一楼活动、验证新照片及ZIP归属并防止重复关联;同一批照片或附件重复提交不会新增副本。
|
||||||
|
|
||||||
材料和预览照片文件保存在业务数据库同目录的 `uploads/`,更新或备份部署时必须保留;数据库定时备份不包含材料文件,需要同时备份整个 data 目录。
|
材料和预览照片文件保存在业务数据库同目录的 `uploads/`,更新或备份部署时必须保留;数据库定时备份不包含材料文件,需要同时备份整个 data 目录。
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
## 功能
|
## 功能
|
||||||
|
|
||||||
- **课表收取**:单周、双周分别上传课表图片,每人每类只保留一份,可修改替换。本地自动识别为值班时段表,由本人核对后导出 JSON / CSV;课表仅本人及指定收取负责人可查看,其他成员只见提交状态。详见 [TIMETABLES.md](TIMETABLES.md)。
|
- **课表收取**:单周、双周分别上传课表图片,每人每类只保留一份,可修改替换。本地自动识别为值班时段表,由本人核对后导出 JSON / CSV;课表仅本人及指定收取负责人可查看,其他成员只见提交状态。详见 [TIMETABLES.md](TIMETABLES.md)。
|
||||||
- **赋能中心一楼**:全员可见的纯记录,不接受参加、不计入参加统计;上传 ZIP 显示进度,所有登录成员可补充材料,保留各份材料及上传人信息。自动展示照片,支持 AI 读取接口及 JSON / CSV 导出;另有每日物品清点、借出申请、负责人审批和归还。负责人暂未配置,申请保持待审批。详细规则见 [CENTER.md](CENTER.md)。
|
- **赋能中心一楼**:全员可见的纯记录,不接受参加、不计入参加统计;照片可多选直传并显示逐张进度,ZIP为可选文档附件。所有登录成员可补充照片和附件,保留已有材料及上传人信息。支持 AI 读取接口及 JSON / CSV 导出;另有每日物品清点、借出申请、负责人审批和归还。负责人暂未配置,申请保持待审批。详细规则见 [CENTER.md](CENTER.md)。
|
||||||
- **邮箱换绑**:登录后在账号设置中验证新邮箱即可更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。
|
- **邮箱换绑**:登录后在账号设置中验证新邮箱即可更换绑定地址;新邮箱须未被其他账号占用。账号及活动记录保留,当前会话保留、其他设备退出,原邮箱未使用验证码失效;后续使用新邮箱登录并接收提醒。
|
||||||
- **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。
|
- **值班提醒**:读取单双周值班 JSON,按 2026-11-06 单周周五为基准循环,北京时间前一天 18:00 汇总提醒,并在每个值班时段开始前一小时再次发送邮件;邮箱匹配、预览和部署说明见 [duty/README.md](duty/README.md)。
|
||||||
- **账号体系**:注册时设置密码,通过邮箱+密码登录;也可选邮箱验证码登录,忘记密码后可凭邮箱验证码重设。注册需填写姓名、所属部门、邮箱和手机号,Bearer 会话默认 30 天有效,可改个人资料
|
- **账号体系**:注册时设置密码,通过邮箱+密码登录;也可选邮箱验证码登录,忘记密码后可凭邮箱验证码重设。注册需填写姓名、所属部门、邮箱和手机号,Bearer 会话默认 30 天有效,可改个人资料
|
||||||
|
|||||||
Vendored
+1
-1
@@ -322,7 +322,7 @@
|
|||||||
|
|
||||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||||
|
|
||||||
<script src="/js/app.js?v=28"></script>
|
<script src="/js/app.js?v=29"></script>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Vendored
+69
-34
@@ -827,7 +827,7 @@
|
|||||||
let result;
|
let result;
|
||||||
try { result = JSON.parse(xhr.responseText); } catch { result = {}; }
|
try { result = JSON.parse(xhr.responseText); } catch { result = {}; }
|
||||||
if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable)) resolve(result);
|
if (xhr.status >= 200 && xhr.status < 300 && (result.id || result.timetable)) resolve(result);
|
||||||
else reject(new Error(xhr.status === 413 ? (contentType === 'application/zip' ? '材料包过大,请提交30MB以内的ZIP' : '课表图片最大10MB') : apiErrorMessage(result.detail, xhr.status)));
|
else reject(new Error(xhr.status === 413 ? (typeof result.detail === 'string' ? result.detail : '上传文件过大,请检查大小限制') : apiErrorMessage(result.detail, xhr.status)));
|
||||||
};
|
};
|
||||||
xhr.onerror = () => reject(new Error('上传失败,请检查网络后重试'));
|
xhr.onerror = () => reject(new Error('上传失败,请检查网络后重试'));
|
||||||
xhr.ontimeout = () => reject(new Error('上传超时,请重试'));
|
xhr.ontimeout = () => reject(new Error('上传超时,请重试'));
|
||||||
@@ -855,36 +855,83 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function centerUploadFields(prefix) {
|
||||||
|
return `<label>活动照片<input name="photos" type="file" accept="image/jpeg,image/png,image/webp" multiple /></label>
|
||||||
|
<p class="muted">可直接多选相册照片或拍照,每张不超过8MB。照片数量不限。</p><div id="${prefix}-selected-photos" class="activity-photos"></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>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindCenterUploads(form, box, label, meter, prefix) {
|
||||||
|
const uploadedPhotos = new Map();
|
||||||
|
let uploadedZip = null;
|
||||||
|
let previewUrls = [];
|
||||||
|
const clearPreview = () => { previewUrls.forEach(url => URL.revokeObjectURL(url)); previewUrls = []; };
|
||||||
|
modalCleanup = clearPreview;
|
||||||
|
form.photos.addEventListener('change', () => {
|
||||||
|
clearPreview();
|
||||||
|
const preview = $('#' + prefix + '-selected-photos'); preview.replaceChildren();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
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.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 || zip) box.classList.remove('hidden');
|
||||||
|
for (let i = 0; i < files.length; i++) {
|
||||||
|
if (!form.isConnected) throw new Error('上传已取消');
|
||||||
|
const file = files[i];
|
||||||
|
if (!uploadedPhotos.has(file)) {
|
||||||
|
const result = await uploadFile('/api/center/photos', 'POST', file, (loaded, total) => {
|
||||||
|
const percent = total ? Math.min(100, Math.floor(loaded / total * 100)) : 0;
|
||||||
|
if (total && loaded >= total) { meter.removeAttribute('value'); label.textContent = `正在上传 ${i+1}/${files.length} · 正在处理照片…`; }
|
||||||
|
else { meter.value = percent; label.textContent = `正在上传 ${i+1}/${files.length} · ${percent}%`; }
|
||||||
|
}, file.type || 'application/octet-stream');
|
||||||
|
uploadedPhotos.set(file, result.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (zip && uploadedZip?.file !== zip) {
|
||||||
|
if (!form.isConnected) throw new Error('上传已取消');
|
||||||
|
const result = await uploadMaterial(zip, (loaded, total) => renderUploadProgress(label, meter, loaded, total, 'ZIP已上传,正在校验附件…'));
|
||||||
|
uploadedZip = { file: zip, id: result.id };
|
||||||
|
}
|
||||||
|
meter.value = 100; label.textContent = '上传完成,正在保存记录…';
|
||||||
|
return { photo_ids: files.map(file => uploadedPhotos.get(file)), material_id: zip ? uploadedZip.id : null };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function openMaterialForm(activity) {
|
function openMaterialForm(activity) {
|
||||||
modal(`<h3>补充活动材料</h3><p class="modal-sub muted">${esc(activity.title)} · 所有登录成员均可补充材料,无需参加活动。已有材料会保留。</p>
|
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>
|
<form id="material-form">${centerUploadFields('material')}<p class="muted">照片和ZIP至少选择一种,补充内容会追加到活动中。</p>
|
||||||
<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="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>
|
<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>`);
|
</form>`);
|
||||||
const form = $('#material-form');
|
const form = $('#material-form');
|
||||||
const box = $('#material-progress'), label = $('#material-status'), meter = $('#material-meter'), errorBox = $('#material-error');
|
const box = $('#material-progress'), label = $('#material-status'), meter = $('#material-meter'), errorBox = $('#material-error');
|
||||||
let uploaded = null;
|
const collectUploads = bindCenterUploads(form, box, label, meter, 'material');
|
||||||
$('#material-cancel').addEventListener('click', closeModal);
|
$('#material-cancel').addEventListener('click', closeModal);
|
||||||
form.materials.addEventListener('change', () => { uploaded = null; box.classList.add('hidden'); });
|
|
||||||
form.addEventListener('submit', async event => {
|
form.addEventListener('submit', async event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const button = form.querySelector('[type=submit]');
|
const button = form.querySelector('[type=submit]');
|
||||||
if (button.disabled) return;
|
if (button.disabled) return;
|
||||||
const file = form.materials.files[0];
|
|
||||||
errorBox.textContent = '';
|
errorBox.textContent = '';
|
||||||
if (!file || file.size > 30 * 1024 * 1024 || !file.name.toLowerCase().endsWith('.zip')) { errorBox.textContent = '请提交30MB以内的ZIP材料包'; return; }
|
if (!form.photos.files.length && !form.materials.files.length) { errorBox.textContent = '请至少选择照片或ZIP附件'; return; }
|
||||||
button.disabled = true; form.materials.disabled = true; box.classList.remove('hidden');
|
button.disabled = true; form.materials.disabled = true; form.photos.disabled = true;
|
||||||
try {
|
try {
|
||||||
button.textContent = '正在上传…';
|
button.textContent = '正在上传…';
|
||||||
if (!uploaded) uploaded = await uploadMaterial(file, (loaded, total) => renderUploadProgress(label, meter, loaded, total));
|
const uploaded = await collectUploads();
|
||||||
if (!form.isConnected) return;
|
if (!form.isConnected) return;
|
||||||
meter.value = 100; label.textContent = '材料上传成功,正在保存…'; button.textContent = '正在保存…';
|
meter.value = 100; label.textContent = '材料上传成功,正在保存…'; button.textContent = '正在保存…';
|
||||||
await api(`/activities/${activity.id}/materials`, { method: 'POST', body: { material_id: uploaded.id } });
|
await api(`/activities/${activity.id}/materials`, { method: 'POST', body: uploaded });
|
||||||
closeModal(); toast('补充材料已保存'); refreshCurrent();
|
closeModal(); toast('补充材料已保存'); refreshCurrent();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorBox.textContent = error.message; label.textContent = uploaded ? '材料已上传,保存失败,可重试。' : '上传未完成,可重试。'; meter.value = uploaded ? 100 : 0;
|
errorBox.textContent = error.message; label.textContent = '提交未完成,可重试;已上传成功的照片会复用。'; meter.value = 0;
|
||||||
button.disabled = false; form.materials.disabled = false; button.textContent = '上传并保存';
|
button.disabled = false; form.materials.disabled = false; form.photos.disabled = false; button.textContent = '上传并保存';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -903,7 +950,7 @@
|
|||||||
<label>地点<input name="location" maxlength="120" value="${esc(existing?.location || "")}" placeholder="如:3 号会议室" /></label>
|
<label>地点<input name="location" maxlength="120" value="${esc(existing?.location || "")}" placeholder="如:3 号会议室" /></label>
|
||||||
</div>
|
</div>
|
||||||
<label>备注 <span class="hint-inline">(选填)</span><textarea name="description" rows="3" maxlength="2000" placeholder="做什么、带什么、注意事项…">${esc(existing?.description || "")}</textarea></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"><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>
|
<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>
|
||||||
<label class="checkline" id="act-visibility"><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>
|
<p id="act-center-policy" class="muted hidden">全员可见,仅作活动记录,无需参加,也不计入参加统计。</p>
|
||||||
<div id="act-upload-progress" class="upload-progress hidden">
|
<div id="act-upload-progress" class="upload-progress hidden">
|
||||||
@@ -921,7 +968,7 @@
|
|||||||
const progressLabel = $('#act-upload-status');
|
const progressLabel = $('#act-upload-status');
|
||||||
const progressMeter = $('#act-upload-meter');
|
const progressMeter = $('#act-upload-meter');
|
||||||
const errorBox = $('#act-error');
|
const errorBox = $('#act-error');
|
||||||
let uploadedMaterial = null;
|
const collectUploads = bindCenterUploads(activityForm, progressBox, progressLabel, progressMeter, 'act');
|
||||||
activityForm.record_type.value = existing?.record_type || defaultType;
|
activityForm.record_type.value = existing?.record_type || defaultType;
|
||||||
activityForm.record_type.disabled = state.view === 'center';
|
activityForm.record_type.disabled = state.view === 'center';
|
||||||
const togglePhotos = () => {
|
const togglePhotos = () => {
|
||||||
@@ -934,10 +981,6 @@
|
|||||||
};
|
};
|
||||||
activityForm.record_type.addEventListener('change', togglePhotos); togglePhotos();
|
activityForm.record_type.addEventListener('change', togglePhotos); togglePhotos();
|
||||||
loadPhotos($('#act-photo-preview'));
|
loadPhotos($('#act-photo-preview'));
|
||||||
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-cancel").addEventListener("click", closeModal);
|
||||||
$("#act-form").addEventListener("submit", async (e) => {
|
$("#act-form").addEventListener("submit", async (e) => {
|
||||||
@@ -960,23 +1003,14 @@
|
|||||||
const typeWasDisabled = f.record_type.disabled;
|
const typeWasDisabled = f.record_type.disabled;
|
||||||
f.record_type.disabled = true;
|
f.record_type.disabled = true;
|
||||||
f.materials.disabled = true;
|
f.materials.disabled = true;
|
||||||
|
f.photos.disabled = true;
|
||||||
try {
|
try {
|
||||||
const file = f.materials.files[0];
|
|
||||||
if (body.record_type === 'center') {
|
if (body.record_type === 'center') {
|
||||||
body.material_id = existing?.material_id || null;
|
if (!f.photos.files.length && !f.materials.files.length && !(existing?.photo_ids || []).length && !existing?.material_id && !existing?.materials?.length) throw new Error('请至少选择照片或ZIP附件');
|
||||||
if (file) {
|
|
||||||
if (file.size > 30 * 1024 * 1024 || !file.name.toLowerCase().endsWith('.zip')) throw new Error('请提交30MB以内的ZIP材料包');
|
|
||||||
progressBox.classList.remove('hidden');
|
|
||||||
btn.textContent = '正在上传…';
|
btn.textContent = '正在上传…';
|
||||||
if (uploadedMaterial?.file !== file) {
|
const uploaded = await collectUploads();
|
||||||
const result = await uploadMaterial(file, (loaded, total) => renderUploadProgress(progressLabel, progressMeter, loaded, total));
|
body.photo_ids = [...new Set([...(existing?.photo_ids || []), ...uploaded.photo_ids])];
|
||||||
uploadedMaterial = { file, id: result.id };
|
body.material_id = uploaded.material_id || existing?.material_id || null;
|
||||||
}
|
|
||||||
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; }
|
} else { body.photo_ids = []; body.material_id = null; }
|
||||||
if (!f.isConnected) return;
|
if (!f.isConnected) return;
|
||||||
btn.textContent = '正在保存…';
|
btn.textContent = '正在保存…';
|
||||||
@@ -991,11 +1025,12 @@
|
|||||||
refreshCurrent();
|
refreshCurrent();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
errorBox.textContent = err.message;
|
errorBox.textContent = err.message;
|
||||||
progressMeter.value = uploadedMaterial ? 100 : 0;
|
progressMeter.value = 0;
|
||||||
if (!progressBox.classList.contains('hidden')) progressLabel.textContent = uploadedMaterial ? '材料已上传,记录保存失败,可重试。' : '上传未完成,可重试。';
|
if (!progressBox.classList.contains('hidden')) progressLabel.textContent = '提交未完成,可重试;已上传成功的照片会复用。';
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
f.record_type.disabled = typeWasDisabled;
|
f.record_type.disabled = typeWasDisabled;
|
||||||
f.materials.disabled = false;
|
f.materials.disabled = false;
|
||||||
|
f.photos.disabled = false;
|
||||||
btn.textContent = isEdit ? '保存修改' : '提交记录';
|
btn.textContent = isEdit ? '保存修改' : '提交记录';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+10
-8
@@ -54,15 +54,16 @@ class ReviewIn(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class MaterialIn(BaseModel):
|
class MaterialIn(BaseModel):
|
||||||
material_id: str = Field(min_length=32, max_length=32)
|
material_id: str | None = Field(default=None, min_length=32, max_length=32)
|
||||||
|
photo_ids: list[str] = Field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
def now_ms(): return int(time.time() * 1000)
|
def now_ms(): return int(time.time() * 1000)
|
||||||
|
|
||||||
|
|
||||||
async def validate_photos(db, ids, owner_id, existing=()):
|
async def validate_photos(db, ids, owner_id, existing=(), allow_empty=False):
|
||||||
if not ids or len(set(ids)) != len(ids):
|
if (not ids and not allow_empty) or len(set(ids)) != len(ids):
|
||||||
raise HTTPException(422, '一楼活动须至少上传1张照片,照片不能重复')
|
raise HTTPException(422, '请至少上传照片或ZIP附件,照片不能重复')
|
||||||
rows = (await db.execute(select(center_photos).where(center_photos.c.id.in_(ids)))).mappings().all()
|
rows = (await db.execute(select(center_photos).where(center_photos.c.id.in_(ids)))).mappings().all()
|
||||||
if len(rows) != len(ids) or any(r['owner_id'] != owner_id and r['id'] not in existing for r in rows):
|
if len(rows) != len(ids) or any(r['owner_id'] != owner_id and r['id'] not in existing for r in rows):
|
||||||
raise HTTPException(403, '照片不存在或不属于当前账号')
|
raise HTTPException(403, '照片不存在或不属于当前账号')
|
||||||
@@ -71,7 +72,7 @@ async def validate_photos(db, ids, owner_id, existing=()):
|
|||||||
async def save_meta(db, activity_id, kind, photo_ids, owner_id, material_id=None):
|
async def save_meta(db, activity_id, kind, photo_ids, owner_id, material_id=None):
|
||||||
if kind != 'center':
|
if kind != 'center':
|
||||||
return
|
return
|
||||||
await validate_photos(db, photo_ids, owner_id)
|
await validate_photos(db, photo_ids, owner_id, allow_empty=bool(material_id))
|
||||||
await db.execute(insert(center_activity_meta).values(activity_id=activity_id, photo_ids=json.dumps(photo_ids),material_id=material_id))
|
await db.execute(insert(center_activity_meta).values(activity_id=activity_id, photo_ids=json.dumps(photo_ids),material_id=material_id))
|
||||||
if material_id: await link_material(db, activity_id, material_id)
|
if material_id: await link_material(db, activity_id, material_id)
|
||||||
|
|
||||||
@@ -123,7 +124,7 @@ def convert_photo(raw):
|
|||||||
|
|
||||||
|
|
||||||
def convert_package(raw):
|
def convert_package(raw):
|
||||||
photos=[];names=set()
|
photos=[];names=set();file_count=0
|
||||||
allowed={'.jpg','.jpeg','.png','.webp','.pdf','.doc','.docx','.xls','.xlsx','.ppt','.pptx','.txt','.csv','.md'}
|
allowed={'.jpg','.jpeg','.png','.webp','.pdf','.doc','.docx','.xls','.xlsx','.ppt','.pptx','.txt','.csv','.md'}
|
||||||
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
|
||||||
entries=archive.infolist()
|
entries=archive.infolist()
|
||||||
@@ -137,11 +138,12 @@ def convert_package(raw):
|
|||||||
if entry.is_dir():continue
|
if entry.is_dir():continue
|
||||||
if name.startswith('__MACOSX/') or path.name=='.DS_Store':continue
|
if name.startswith('__MACOSX/') or path.name=='.DS_Store':continue
|
||||||
if path.suffix.lower() not in allowed:raise ValueError('ZIP只支持图片、PDF、Office文档和文本材料')
|
if path.suffix.lower() not in allowed:raise ValueError('ZIP只支持图片、PDF、Office文档和文本材料')
|
||||||
|
file_count += 1
|
||||||
if entry.file_size>20*1024*1024:raise ValueError('包内单个文档不超过20MB')
|
if entry.file_size>20*1024*1024:raise ValueError('包内单个文档不超过20MB')
|
||||||
if path.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}:
|
if path.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}:
|
||||||
if entry.file_size>8*1024*1024:raise ValueError('包内单张照片不超过8MB')
|
if entry.file_size>8*1024*1024:raise ValueError('包内单张照片不超过8MB')
|
||||||
photos.append(convert_photo(archive.read(entry)))
|
photos.append(convert_photo(archive.read(entry)))
|
||||||
if not photos:raise ValueError('ZIP内至少需要1张JPG、PNG或WebP活动照片')
|
if not file_count:raise ValueError('ZIP附件不能为空')
|
||||||
return photos
|
return photos
|
||||||
|
|
||||||
|
|
||||||
@@ -190,7 +192,7 @@ def install(app, get_db, current_user, photo_root, visible_clause, approver_emai
|
|||||||
raw.extend(chunk)
|
raw.extend(chunk)
|
||||||
if len(raw) > 8 * 1024 * 1024: raise HTTPException(413, '每张照片最大8MB')
|
if len(raw) > 8 * 1024 * 1024: raise HTTPException(413, '每张照片最大8MB')
|
||||||
count = (await db.execute(select(func.count()).select_from(center_photos).where(center_photos.c.owner_id == viewer['id'], center_photos.c.created_at > now_ms() - 86400000))).scalar()
|
count = (await db.execute(select(func.count()).select_from(center_photos).where(center_photos.c.owner_id == viewer['id'], center_photos.c.created_at > now_ms() - 86400000))).scalar()
|
||||||
if count >= 100: raise HTTPException(429, '今日照片上传已达100张')
|
if count >= 1000: raise HTTPException(429, '今日照片上传已达1000张')
|
||||||
try: data = await asyncio.to_thread(convert_photo, bytes(raw))
|
try: data = await asyncio.to_thread(convert_photo, bytes(raw))
|
||||||
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP,最大24百万像素') from exc
|
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP,最大24百万像素') from exc
|
||||||
key = uuid.uuid4().hex
|
key = uuid.uuid4().hex
|
||||||
|
|||||||
+20
-5
@@ -1669,8 +1669,9 @@ async def create_activity(payload: ActivityIn, request: Request, db: AsyncSessio
|
|||||||
"""记录一场活动:创建即对外生效(公开活动直接出现在活动墙)。
|
"""记录一场活动:创建即对外生效(公开活动直接出现在活动墙)。
|
||||||
防重复提交:60 秒内同一账号提交同名的活动直接返回已有那条。"""
|
防重复提交:60 秒内同一账号提交同名的活动直接返回已有那条。"""
|
||||||
if payload.record_type == 'center':
|
if payload.record_type == 'center':
|
||||||
if not payload.material_id: raise HTTPException(422, '一楼活动须提交包含照片的ZIP材料包')
|
if payload.material_id:
|
||||||
payload.photo_ids = await center.material_photos(db, payload.material_id, viewer['id'])
|
payload.photo_ids = list(dict.fromkeys([*payload.photo_ids, *await center.material_photos(db, payload.material_id, viewer['id'])]))
|
||||||
|
await center.validate_photos(db, payload.photo_ids, viewer['id'], allow_empty=bool(payload.material_id))
|
||||||
payload.visibility = 'public'
|
payload.visibility = 'public'
|
||||||
payload.capacity = None
|
payload.capacity = None
|
||||||
elif payload.photo_ids: raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
elif payload.photo_ids: raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
||||||
@@ -1741,6 +1742,7 @@ async def get_activity(activity_id: str, db: AsyncSession = Depends(get_db), vie
|
|||||||
async def update_activity(
|
async def update_activity(
|
||||||
activity_id: str, payload: ActivityPatch, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)
|
activity_id: str, payload: ActivityPatch, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)
|
||||||
) -> dict:
|
) -> dict:
|
||||||
|
await db.execute(text('BEGIN IMMEDIATE'))
|
||||||
row = await fetch_activity(db, activity_id)
|
row = await fetch_activity(db, activity_id)
|
||||||
if row["organizer_id"] != viewer["id"]:
|
if row["organizer_id"] != viewer["id"]:
|
||||||
raise HTTPException(status_code=403, detail="只有发起人可以修改该活动")
|
raise HTTPException(status_code=403, detail="只有发起人可以修改该活动")
|
||||||
@@ -1749,9 +1751,13 @@ async def update_activity(
|
|||||||
kind = changes.pop('record_type', 'center' if old_meta else 'normal')
|
kind = changes.pop('record_type', 'center' if old_meta else 'normal')
|
||||||
material_id = changes.pop('material_id', old_meta['material_id'] if old_meta else None)
|
material_id = changes.pop('material_id', old_meta['material_id'] if old_meta else None)
|
||||||
photo_ids = changes.pop('photo_ids', json.loads(old_meta['photo_ids']) if old_meta else [])
|
photo_ids = changes.pop('photo_ids', json.loads(old_meta['photo_ids']) if old_meta else [])
|
||||||
if kind == 'center' and material_id: photo_ids = await center.material_photos(db, material_id, viewer['id'])
|
if kind == 'center':
|
||||||
if kind == 'center' and not old_meta and not material_id: raise HTTPException(422, '一楼活动须提交包含照片的ZIP材料包')
|
packages = await center.activity_materials(db, [activity_id]) if old_meta else {}
|
||||||
if kind == 'center': await center.validate_photos(db, photo_ids, viewer['id'], json.loads(old_meta['photo_ids']) if old_meta else [])
|
existing_photos = list(dict.fromkeys([*(json.loads(old_meta['photo_ids']) if old_meta else []), *(photo for package in packages.get(activity_id, []) for photo in package['photo_ids'])]))
|
||||||
|
if material_id:
|
||||||
|
photo_ids = list(dict.fromkeys([*photo_ids, *await center.material_photos(db, material_id, viewer['id'])]))
|
||||||
|
photo_ids = list(dict.fromkeys([*existing_photos, *photo_ids]))
|
||||||
|
await center.validate_photos(db, photo_ids, viewer['id'], existing_photos, allow_empty=bool(material_id or packages.get(activity_id)))
|
||||||
elif photo_ids and payload.record_type != 'normal': raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
elif photo_ids and payload.record_type != 'normal': raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
||||||
if old_meta and old_meta['material_id']:
|
if old_meta and old_meta['material_id']:
|
||||||
await center.link_material(db, activity_id, old_meta['material_id'])
|
await center.link_material(db, activity_id, old_meta['material_id'])
|
||||||
@@ -1779,11 +1785,20 @@ async def update_activity(
|
|||||||
|
|
||||||
@app.post('/api/activities/{activity_id}/materials')
|
@app.post('/api/activities/{activity_id}/materials')
|
||||||
async def add_activity_material(activity_id: str, payload: center.MaterialIn, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
async def add_activity_material(activity_id: str, payload: center.MaterialIn, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||||||
|
await db.execute(text('BEGIN IMMEDIATE'))
|
||||||
row = await fetch_activity(db, activity_id)
|
row = await fetch_activity(db, activity_id)
|
||||||
if not await is_center_activity(db, activity_id):
|
if not await is_center_activity(db, activity_id):
|
||||||
raise HTTPException(409, '仅赋能中心一楼活动支持成员补充材料')
|
raise HTTPException(409, '仅赋能中心一楼活动支持成员补充材料')
|
||||||
|
if not payload.photo_ids and not payload.material_id:
|
||||||
|
raise HTTPException(422, '请至少上传照片或ZIP附件')
|
||||||
|
await center.validate_photos(db, payload.photo_ids, viewer['id'], allow_empty=bool(payload.material_id))
|
||||||
|
if payload.material_id:
|
||||||
await center.material_photos(db, payload.material_id, viewer['id'])
|
await center.material_photos(db, payload.material_id, viewer['id'])
|
||||||
await center.link_material(db, activity_id, payload.material_id)
|
await center.link_material(db, activity_id, payload.material_id)
|
||||||
|
if payload.photo_ids:
|
||||||
|
meta = (await db.execute(select(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id))).mappings().one()
|
||||||
|
photos = list(dict.fromkeys([*json.loads(meta['photo_ids']), *payload.photo_ids]))
|
||||||
|
await db.execute(update(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id).values(photo_ids=json.dumps(photos)))
|
||||||
await db.commit()
|
await db.commit()
|
||||||
return {'activity': (await serialize_activities(db, [row], viewer['id']))[0]}
|
return {'activity': (await serialize_activities(db, [row], viewer['id']))[0]}
|
||||||
|
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ class CenterExportTests(ApiTestCase):
|
|||||||
async def test_material_zip_validation_and_export_visible_activities_only(self):
|
async def test_material_zip_validation_and_export_visible_activities_only(self):
|
||||||
owner=await register(self.client,'materialsowner');other=await register(self.client,'materialsother');c=self.client
|
owner=await register(self.client,'materialsowner');other=await register(self.client,'materialsother');c=self.client
|
||||||
with tempfile.TemporaryDirectory() as directory,patch.object(self.m,'_db_path',Path(directory)/'test.db'):
|
with tempfile.TemporaryDirectory() as directory,patch.object(self.m,'_db_path',Path(directory)/'test.db'):
|
||||||
for raw in [b'not zip',package([('../bad.txt','bad')]),package([('only.txt','no photos')]),package([('script.exe','bad')])]:
|
for raw in [b'not zip',package([('../bad.txt','bad')]),package([]),package([('script.exe','bad')])]:
|
||||||
self.assertEqual((await c.post('/api/center/materials',headers=auth(owner['token']),content=raw)).status_code,422)
|
self.assertEqual((await c.post('/api/center/materials',headers=auth(owner['token']),content=raw)).status_code,422)
|
||||||
response=await c.post('/api/center/materials',headers=auth(owner['token']),content=package())
|
response=await c.post('/api/center/materials',headers=auth(owner['token']),content=package())
|
||||||
self.assertEqual(response.status_code,200,response.text);material=response.json()
|
self.assertEqual(response.status_code,200,response.text);material=response.json()
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import asyncio
|
||||||
|
import io
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
from sqlalchemy import insert, select
|
||||||
|
from test_api import ApiTestCase, auth, register
|
||||||
|
from test_center_export import package
|
||||||
|
from test_timetables import image_bytes
|
||||||
|
from server.models import center_photos
|
||||||
|
|
||||||
|
|
||||||
|
class DirectCenterPhotoTests(ApiTestCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.files=tempfile.TemporaryDirectory();self.root=Path(self.files.name)
|
||||||
|
self.path_patch=patch.object(self.m,'_db_path',self.root/'test.db');self.path_patch.start()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.path_patch.stop();self.files.cleanup();super().tearDown()
|
||||||
|
|
||||||
|
async def upload(self,user,count=1):
|
||||||
|
ids=[]
|
||||||
|
for _ in range(count):
|
||||||
|
result=await self.client.post('/api/center/photos',headers=auth(user['token']),content=image_bytes())
|
||||||
|
self.assertEqual(result.status_code,200,result.text);ids.append(result.json()['id'])
|
||||||
|
return ids
|
||||||
|
|
||||||
|
async def test_photo_only_creation_supplement_and_edit_preserve_all_members_photos(self):
|
||||||
|
owner=await register(self.client,'directowner');member=await register(self.client,'directmember')
|
||||||
|
c=self.client;oh=auth(owner['token']);mh=auth(member['token'])
|
||||||
|
photos=await self.upload(owner,7)
|
||||||
|
self.assertEqual((await c.get('/api/center/photos/'+photos[0],headers=mh)).status_code,403)
|
||||||
|
response=await c.post('/api/activities',headers=oh,json={'title':'直接上传照片','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos})
|
||||||
|
self.assertEqual(response.status_code,200,response.text);activity=response.json()['activity'];aid=activity['id']
|
||||||
|
self.assertEqual(activity['photo_ids'],photos);self.assertIsNone(activity['material_id']);self.assertEqual(activity['materials'],[])
|
||||||
|
self.assertEqual(activity['participant_count'],0)
|
||||||
|
self.assertEqual((await c.get('/api/center/photos/'+photos[0],headers=mh)).status_code,200)
|
||||||
|
self.assertEqual((await c.post('/api/activities',headers=mh,json={'title':'冒用照片','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos})).status_code,403)
|
||||||
|
extra=await self.upload(member,2)
|
||||||
|
for _ in range(2):
|
||||||
|
result=await c.post('/api/activities/'+aid+'/materials',headers=mh,json={'photo_ids':extra})
|
||||||
|
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),9)
|
||||||
|
result=await c.patch('/api/activities/'+aid,headers=oh,json={'description':'从旧页面保存','photo_ids':photos})
|
||||||
|
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),9)
|
||||||
|
exported=(await c.get('/api/center/data?dataset=activities',headers=mh)).json()['data']['activities'][0]
|
||||||
|
self.assertEqual(len(exported['photo_ids']),9);self.assertIsNone(exported['material_url']);self.assertEqual(exported['materials'],[])
|
||||||
|
self.assertEqual((await c.post('/api/activities/'+aid+'/materials',headers=mh,json={})).status_code,422)
|
||||||
|
self.assertEqual((await c.post('/api/activities/'+aid+'/materials',headers=mh,json={'photo_ids':photos})).status_code,403)
|
||||||
|
|
||||||
|
async def test_document_only_zip_and_mixed_photos_are_optional_independent_inputs(self):
|
||||||
|
owner=await register(self.client,'documentsowner');c=self.client;headers=auth(owner['token'])
|
||||||
|
uploaded=await c.post('/api/center/materials',headers=headers,content=package([('说明.txt','活动说明')]))
|
||||||
|
self.assertEqual(uploaded.status_code,200,uploaded.text);material=uploaded.json();self.assertEqual(material['photo_ids'],[])
|
||||||
|
response=await c.post('/api/activities',headers=headers,json={'title':'文档活动','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id']})
|
||||||
|
self.assertEqual(response.status_code,200,response.text);self.assertEqual(response.json()['activity']['photo_ids'],[])
|
||||||
|
photos=await self.upload(owner,2)
|
||||||
|
response=await c.post('/api/activities',headers=headers,json={'title':'照片和文档','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id'],'photo_ids':photos})
|
||||||
|
self.assertEqual(response.status_code,200,response.text);self.assertEqual(response.json()['activity']['photo_ids'],photos)
|
||||||
|
self.assertEqual(len(response.json()['activity']['materials']),1)
|
||||||
|
aid=response.json()['activity']['id']
|
||||||
|
more=await c.post('/api/center/materials',headers=headers,content=package([('补充.md','补充文档')]))
|
||||||
|
self.assertEqual((await c.post('/api/activities/'+aid+'/materials',headers=headers,json={'material_id':more.json()['id']})).status_code,200)
|
||||||
|
|
||||||
|
async def test_daily_allowance_allows_more_than_100_and_keeps_1000_limit(self):
|
||||||
|
owner=await register(self.client,'photolimit');uid=owner['user']['id']
|
||||||
|
async with self.sessions() as db:
|
||||||
|
await db.execute(insert(center_photos),[{'id':f'{i:032x}','owner_id':uid,'created_at':self.m.now_ms()} for i in range(100)])
|
||||||
|
await db.commit()
|
||||||
|
await self.upload(owner)
|
||||||
|
async with self.sessions() as db:
|
||||||
|
await db.execute(insert(center_photos),[{'id':f'{i:032x}','owner_id':uid,'created_at':self.m.now_ms()} for i in range(100,999)])
|
||||||
|
await db.commit()
|
||||||
|
result=await self.client.post('/api/center/photos',headers=auth(owner['token']),content=image_bytes())
|
||||||
|
self.assertEqual(result.status_code,429)
|
||||||
|
|
||||||
|
async def test_concurrent_supplements_do_not_overwrite_each_other(self):
|
||||||
|
engine=self.m.create_async_engine('sqlite+aiosqlite:///'+(self.root/'concurrent.db').as_posix())
|
||||||
|
try:
|
||||||
|
async with engine.begin() as conn:await conn.run_sync(self.m.metadata.create_all)
|
||||||
|
sessions=self.m.async_sessionmaker(engine,expire_on_commit=False)
|
||||||
|
with patch.object(self.m,'SessionLocal',sessions):
|
||||||
|
owner=await register(self.client,'concurrentphotos');photos=await self.upload(owner,3);headers=auth(owner['token'])
|
||||||
|
activity=(await self.client.post('/api/activities',headers=headers,json={'title':'并发补充','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos[:1]})).json()['activity']
|
||||||
|
path='/api/activities/'+activity['id']+'/materials'
|
||||||
|
results=await asyncio.gather(*(self.client.post(path,headers=headers,json={'photo_ids':[photo]}) for photo in photos[1:]))
|
||||||
|
self.assertTrue(all(result.status_code==200 for result in results))
|
||||||
|
detail=(await self.client.get('/api/activities/'+activity['id'],headers=headers)).json()['activity']
|
||||||
|
self.assertEqual(set(detail['photo_ids']),set(photos))
|
||||||
|
finally:await engine.dispose()
|
||||||
Reference in New Issue
Block a user