一楼活动改为ZIP材料提交,默认一楼分类并新增AI数据接口和导出

This commit is contained in:
2026-11-11 16:14:59 +08:00
parent 4f25f40915
commit e1e909d617
11 changed files with 397 additions and 35 deletions
+9 -2
View File
@@ -1,6 +1,7 @@
import io
import os
import tempfile
import zipfile
from pathlib import Path
from unittest.mock import patch
from PIL import Image
@@ -87,12 +88,17 @@ class CenterTests(ApiTestCase):
raw=io.BytesIO();Image.new('RGB',(10,10),'red').save(raw,'PNG')
with tempfile.TemporaryDirectory() as directory, patch.object(self.m,'_db_path',Path(directory)/'test.db'):
self.assertEqual((await c.post('/api/center/photos',headers=auth(owner['token']),content=b'<script>bad</script>')).status_code,422)
photo=(await c.post('/api/center/photos',headers=auth(owner['token']),content=raw.getvalue())).json()['id']
package=io.BytesIO()
with zipfile.ZipFile(package,'w') as archive:archive.writestr('活动照片.png',raw.getvalue());archive.writestr('材料说明.txt','活动材料')
material=(await c.post('/api/center/materials',headers=auth(owner['token']),content=package.getvalue())).json()
photo=material['photo_ids'][0]
payload={'title':'一楼活动','start_at':self.m.now_ms(),'record_type':'center','visibility':'private'}
self.assertEqual((await c.post('/api/activities',headers=auth(owner['token']),json=payload)).status_code,422)
response=await c.post('/api/activities',headers=auth(owner['token']),json={**payload,'photo_ids':[photo]})
response=await c.post('/api/activities',headers=auth(owner['token']),json={**payload,'material_id':material['id']})
self.assertEqual(response.status_code,200,response.text); activity=response.json()['activity']
self.assertEqual(activity['record_type'],'center')
self.assertEqual(activity['location'],'赋能中心一楼')
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).status_code,403)
self.assertEqual((await c.get(f'/api/center/photos/{photo}')).status_code,401)
self.assertEqual((await c.get(f'/api/center/photos/{photo}',headers=auth(other['token']))).status_code,403)
self.assertEqual((await c.get(f'/api/center/photos/{photo}',headers=auth(owner['token']))).status_code,200)
@@ -100,6 +106,7 @@ class CenterTests(ApiTestCase):
self.assertEqual(len((await c.get('/api/activities?record_type=normal',headers=auth(owner['token']))).json()['items']),0)
await c.patch('/api/activities/'+activity['id'],headers=auth(owner['token']),json={'visibility':'public'})
self.assertEqual((await c.get(f'/api/center/photos/{photo}',headers=auth(other['token']))).status_code,200)
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).content,package.getvalue())
async def test_missing_manager_keeps_requests_pending_and_cannot_approve(self):
self.assertEqual((await self.client.get('/api/center/items')).status_code,401)
+77
View File
@@ -0,0 +1,77 @@
import io
import json
import csv
import zipfile
import tempfile
from pathlib import Path
from unittest.mock import patch
from PIL import Image
from sqlalchemy import insert
from test_api import ApiTestCase, auth, register
from server.models import center_items, center_loans, center_checks
def package(entries=None):
image=io.BytesIO();Image.new('RGB',(20,20),'blue').save(image,'PNG')
output=io.BytesIO()
with zipfile.ZipFile(output,'w') as archive:
for name,data in (entries if entries is not None else [('照片.png',image.getvalue()),('材料.txt','材料说明')]):archive.writestr(name,data)
return output.getvalue()
class CenterExportTests(ApiTestCase):
async def test_api_auth_export_all_and_contact_redaction(self):
for path in ['/api/center/data','/api/center/schema','/api/center/export']:
self.assertEqual((await self.client.get(path)).status_code,401)
user=await register(self.client,'exportowner')
async with self.sessions() as db:
await db.execute(insert(center_items).values(id='item1',name='=测试物品',quantity=5,created_at=self.m.now_ms()))
await db.execute(insert(center_loans).values(id='loan1',item_id='item1',user_id=user['user']['id'],quantity=2,reason='活动使用',contact='secret@example.test',status='approved',created_at=self.m.now_ms()))
await db.execute(insert(center_checks).values(day='2026-11-11',user_id=user['user']['id'],details=json.dumps([{'name':'物品','expected':3,'actual':3,'borrowed':2}]),note='核对无误',created_at=self.m.now_ms()))
await db.commit()
headers=auth(user['token'])
response=await self.client.get('/api/center/data',headers=headers)
self.assertEqual(response.status_code,200,response.text)
data=response.json();self.assertEqual(data['data']['items'][0]['available'],3)
self.assertEqual(data['data']['checks'][0]['details'][0]['actual'],3)
self.assertNotIn('secret@example.test',response.text);self.assertNotIn(user['user']['email'],response.text)
self.assertFalse(data['contacts_included'])
exported=await self.client.get('/api/center/export?format=csv',headers=headers)
self.assertEqual(exported.status_code,200)
self.assertIn('.zip',exported.headers['Content-Disposition'])
with zipfile.ZipFile(io.BytesIO(exported.content)) as archive:
self.assertEqual(set(archive.namelist()),{'activities.csv','items.csv','loans.csv','checks.csv','metadata.json'})
rows=list(csv.DictReader(io.StringIO(archive.read('items.csv').decode('utf-8-sig'))))
self.assertEqual(rows[0]['name'],"'=测试物品")
self.assertNotIn('secret@example.test',archive.read('loans.csv').decode('utf-8-sig'))
self.assertEqual((await self.client.get('/api/center/schema',headers=headers)).json()['schema_version'],1)
async def test_pagination_and_export_are_not_silently_truncated(self):
user=await register(self.client,'exportpagination');headers=auth(user['token'])
async with self.sessions() as db:
await db.execute(insert(center_items),[dict(id=str(i),name=f'物品{i:03d}',quantity=1,created_at=self.m.now_ms()) for i in range(205)])
await db.commit()
first=(await self.client.get('/api/center/data?dataset=items&limit=100',headers=headers)).json()
self.assertEqual(len(first['data']['items']),100);self.assertEqual(first['pagination']['items']['next_offset'],100)
last=(await self.client.get('/api/center/data?dataset=items&limit=100&offset=200',headers=headers)).json()
self.assertEqual(len(last['data']['items']),5);self.assertIsNone(last['pagination']['items']['next_offset'])
exported=(await self.client.get('/api/center/export?dataset=items',headers=headers)).json()
self.assertEqual(len(exported['data']['items']),205)
self.assertEqual((await self.client.get('/api/center/data?date_from=2026-11-12&date_to=2026-11-11',headers=headers)).status_code,422)
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
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')])]:
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())
self.assertEqual(response.status_code,200,response.text);material=response.json()
self.assertEqual((await c.post('/api/activities',headers=auth(other['token']),json={'title':'冒用','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id']})).status_code,403)
created=await c.post('/api/activities',headers=auth(owner['token']),json={'title':'私密一楼活动','start_at':self.m.now_ms(),'record_type':'center','material_id':material['id'],'visibility':'private'})
self.assertEqual(created.status_code,200,created.text);activity=created.json()['activity']
result=(await c.get('/api/center/data?dataset=activities',headers=auth(owner['token']))).json()
self.assertEqual(result['data']['activities'][0]['material_id'],material['id'])
self.assertEqual(len((await c.get('/api/center/data?dataset=activities',headers=auth(other['token']))).json()['data']['activities']),0)
self.assertEqual((await c.get('/api/center/materials/'+material['id'],headers=auth(other['token']))).status_code,403)
await c.patch('/api/activities/'+activity['id'],headers=auth(owner['token']),json={'visibility':'public'})
self.assertEqual(len((await c.get('/api/center/data?dataset=activities&q=私密',headers=auth(other['token']))).json()['data']['activities']),1)