限制一楼活动每次上传最多20张照片并保留历史材料

This commit is contained in:
2026-11-12 14:17:37 +08:00
parent 3404fff5fc
commit ddf3ba32c6
7 changed files with 80 additions and 11 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
## 活动记录
在一楼页面创建活动时默认选择“赋能中心一楼活动记录”,地点默认填“赋能中心一楼”。必须填写主题、时间,照片或 ZIP 至少提交一种。照片可直接从相册多选或拍照,支持 JPG、PNG、WebP,数量不限,每张最大 8MB、2400 万像素。逐张上传时显示“正在上传 3/7”及单张进度;失败重试会复用已成功上传的照片。直接上传接口每人24小时限额提高为1000张。
在一楼页面创建活动时默认选择“赋能中心一楼活动记录”,地点默认填“赋能中心一楼”。必须填写主题、时间,照片或 ZIP 至少提交一种。照片可直接从相册多选或拍照,支持 JPG、PNG、WebP,每次最多20张(含ZIP内照片),每张最大 8MB、2400 万像素。创建、编辑追加和成员补充材料均校验本次照片总数;历史照片保留,不占本次追加额度。逐张上传时显示“正在上传 3/7”及单张进度;失败重试会复用已成功上传的照片。直接上传接口每人24小时限额为1000张。
ZIP 为可选附件,仅在附 PDF、Word、Excel、PowerPoint、TXT、CSV 或 Markdown 等文档时需要打包,不要求包内有照片。ZIP 最大30MB,包内单个文档最大20MB,照片每张最大8MB,展开后总大小不超过100MB;支持文件夹,不支持空ZIP、加密ZIP、链接、不安全路径及可执行文件。旧版含照片的ZIP继续支持,包内照片会自动提取展示。
+1 -1
View File
@@ -322,7 +322,7 @@
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
<script src="/js/app.js?v=29"></script>
<script src="/js/app.js?v=30"></script>
</div>
</body>
</html>
+7 -3
View File
@@ -857,7 +857,7 @@
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>
<p class="muted">可直接多选相册照片或拍照,每次最多20张(含ZIP内照片),每张不超过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>`;
}
@@ -871,6 +871,8 @@
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);
@@ -880,6 +882,7 @@
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 || zip) box.classList.remove('hidden');
@@ -898,8 +901,9 @@
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 };
uploadedZip = { file: zip, id: result.id, photoCount: result.photo_ids.length };
}
if (files.length + (zip ? uploadedZip.photoCount : 0) > 20) throw new Error('每次最多上传20张照片(含ZIP内照片),请减少照片后重试');
meter.value = 100; label.textContent = '上传完成,正在保存记录…';
return { photo_ids: files.map(file => uploadedPhotos.get(file)), material_id: zip ? uploadedZip.id : null };
};
@@ -1009,7 +1013,7 @@
if (!f.photos.files.length && !f.materials.files.length && !(existing?.photo_ids || []).length && !existing?.material_id && !existing?.materials?.length) throw new Error('请至少选择照片或ZIP附件');
btn.textContent = '正在上传…';
const uploaded = await collectUploads();
body.photo_ids = [...new Set([...(existing?.photo_ids || []), ...uploaded.photo_ids])];
body.photo_ids = uploaded.photo_ids;
body.material_id = uploaded.material_id || existing?.material_id || null;
} else { body.photo_ids = []; body.material_id = null; }
if (!f.isConnected) return;
+10
View File
@@ -58,9 +58,18 @@ class MaterialIn(BaseModel):
photo_ids: list[str] = Field(default_factory=list)
MAX_PHOTOS_PER_UPLOAD = 20
def now_ms(): return int(time.time() * 1000)
def validate_photo_batch(ids, existing=()):
"""限制本次新增照片,历史照片不占本次额度。"""
if len(set(ids) - set(existing)) > MAX_PHOTOS_PER_UPLOAD:
raise HTTPException(422, '每次最多上传20张照片(含ZIP内照片)')
async def validate_photos(db, ids, owner_id, existing=(), allow_empty=False):
if (not ids and not allow_empty) or len(set(ids)) != len(ids):
raise HTTPException(422, '请至少上传照片或ZIP附件,照片不能重复')
@@ -141,6 +150,7 @@ def convert_package(raw):
file_count += 1
if entry.file_size>20*1024*1024:raise ValueError('包内单个文档不超过20MB')
if path.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}:
if len(photos) >= MAX_PHOTOS_PER_UPLOAD:raise ValueError('每次最多上传20张照片(含ZIP内照片)')
if entry.file_size>8*1024*1024:raise ValueError('包内单张照片不超过8MB')
photos.append(convert_photo(archive.read(entry)))
if not file_count:raise ValueError('ZIP附件不能为空')
+4 -1
View File
@@ -1671,6 +1671,7 @@ async def create_activity(payload: ActivityIn, request: Request, db: AsyncSessio
if payload.record_type == 'center':
if payload.material_id:
payload.photo_ids = list(dict.fromkeys([*payload.photo_ids, *await center.material_photos(db, payload.material_id, viewer['id'])]))
center.validate_photo_batch(payload.photo_ids)
await center.validate_photos(db, payload.photo_ids, viewer['id'], allow_empty=bool(payload.material_id))
payload.visibility = 'public'
payload.capacity = None
@@ -1756,6 +1757,7 @@ async def update_activity(
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'])]))
center.validate_photo_batch(photo_ids, existing_photos)
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, '请先选择赋能中心一楼活动记录')
@@ -1791,9 +1793,10 @@ async def add_activity_material(activity_id: str, payload: center.MaterialIn, db
raise HTTPException(409, '仅赋能中心一楼活动支持成员补充材料')
if not payload.photo_ids and not payload.material_id:
raise HTTPException(422, '请至少上传照片或ZIP附件')
package_photos = await center.material_photos(db, payload.material_id, viewer['id']) if payload.material_id else []
center.validate_photo_batch([*payload.photo_ids, *package_photos])
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.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()
+5 -5
View File
@@ -20,20 +20,20 @@ def package(entries=None):
class CenterExportTests(ApiTestCase):
async def test_material_with_over_100_photos_can_be_created_edited_and_downloaded(self):
async def test_material_with_20_photos_can_be_created_edited_and_downloaded(self):
owner=await register(self.client,'manyphotos');headers=auth(owner['token'])
image=io.BytesIO();Image.new('RGB',(20,20),'blue').save(image,'PNG')
raw=package([(f'照片/{i}.png',image.getvalue()) for i in range(101)])
raw=package([(f'照片/{i}.png',image.getvalue()) for i in range(20)])
with tempfile.TemporaryDirectory() as directory,patch.object(self.m,'_db_path',Path(directory)/'test.db'):
response=await self.client.post('/api/center/materials',headers=headers,content=raw)
self.assertEqual(response.status_code,200,response.text)
material=response.json();self.assertEqual(len(material['photo_ids']),101)
material=response.json();self.assertEqual(len(material['photo_ids']),20)
response=await self.client.post('/api/activities',headers=headers,json={
'title':'多照片一楼活动','start_at':self.m.now_ms(),'record_type':'center',
'material_id':material['id'],'photo_ids':material['photo_ids'],
})
self.assertEqual(response.status_code,200,response.text)
activity=response.json()['activity'];self.assertEqual(len(activity['photo_ids']),101)
activity=response.json()['activity'];self.assertEqual(len(activity['photo_ids']),20)
edited=await self.client.patch('/api/activities/'+activity['id'],headers=headers,json={
'description':'更新说明','photo_ids':material['photo_ids'],
})
@@ -43,7 +43,7 @@ class CenterExportTests(ApiTestCase):
self.assertEqual(downloaded.status_code,200);self.assertEqual(downloaded.content,raw)
last_photo=await self.client.get('/api/center/photos/'+material['photo_ids'][-1],headers=headers)
self.assertEqual(last_photo.status_code,200)
# 同一天已有超过100张照片,也可以继续提交ZIP材料。
# 单次20张后仍可继续补充其他材料。
second=await self.client.post('/api/center/materials',headers=headers,content=package())
self.assertEqual(second.status_code,200,second.text)
+52
View File
@@ -62,6 +62,58 @@ class DirectCenterPhotoTests(ApiTestCase):
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_twenty_photo_batch_limit_and_historical_photos_are_preserved(self):
owner=await register(self.client,'batchlimit');headers=auth(owner['token']);c=self.client
photos=await self.upload(owner,21)
body={'title':'照片上限','start_at':self.m.now_ms(),'record_type':'center','photo_ids':photos}
rejected=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(rejected.status_code,422,rejected.text);self.assertIn('20张',rejected.text)
body['photo_ids']=photos[:20]
result=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(result.status_code,200,result.text);aid=result.json()['activity']['id']
path='/api/activities/'+aid
rejected=await c.post(path+'/materials',headers=headers,json={'photo_ids':photos})
self.assertEqual(rejected.status_code,422,rejected.text)
result=await c.post(path+'/materials',headers=headers,json={'photo_ids':photos[20:]})
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),21)
# 历史记录超过20张,旧页面提交原照片、或只改说明都能保存。
for changes in ({'description':'只改说明'},{'photo_ids':photos}):
result=await c.patch(path,headers=headers,json=changes)
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),21)
extra=await self.upload(owner,21)
rejected=await c.patch(path,headers=headers,json={'photo_ids':extra})
self.assertEqual(rejected.status_code,422,rejected.text)
result=await c.patch(path,headers=headers,json={'photo_ids':extra[:20]})
self.assertEqual(result.status_code,200,result.text);self.assertEqual(len(result.json()['activity']['photo_ids']),41)
detail=(await c.get(path,headers=headers)).json()['activity']
self.assertEqual(set(detail['photo_ids']),set(photos+extra[:20]))
async def test_zip_and_direct_photos_share_twenty_photo_batch_limit(self):
owner=await register(self.client,'mixedlimit');headers=auth(owner['token']);c=self.client
raw=package([(f'{i}.png',image_bytes()) for i in range(21)])
rejected=await c.post('/api/center/materials',headers=headers,content=raw)
self.assertEqual(rejected.status_code,422,rejected.text);self.assertIn('20张',rejected.text)
material=(await c.post('/api/center/materials',headers=headers,content=package())).json()
photos=await self.upload(owner,20)
body={'title':'混合上限','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id'],'photo_ids':photos}
rejected=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(rejected.status_code,422,rejected.text)
body['photo_ids']=photos[:19]
result=await c.post('/api/activities',headers=headers,json=body)
self.assertEqual(result.status_code,200,result.text);aid=result.json()['activity']['id'];path='/api/activities/'+aid
self.assertEqual(len(result.json()['activity']['photo_ids']),20)
new_material=(await c.post('/api/center/materials',headers=headers,content=package())).json()
batch={'material_id':new_material['id'],'photo_ids':photos}
rejected=await c.post(path+'/materials',headers=headers,json=batch)
self.assertEqual(rejected.status_code,422,rejected.text)
batch['photo_ids']=await self.upload(owner,20)
rejected=await c.patch(path,headers=headers,json=batch)
self.assertEqual(rejected.status_code,422,rejected.text)
batch['photo_ids']=batch['photo_ids'][:19]
result=await c.post(path+'/materials',headers=headers,json=batch)
self.assertEqual(result.status_code,200,result.text)
self.assertEqual(len(result.json()['activity']['photo_ids']),40)
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: