feat: export center activities with photos to Word

This commit is contained in:
2026-12-02 15:32:35 +08:00
parent 626a683876
commit 3489b5f8fa
6 changed files with 92 additions and 13 deletions
+3 -3
View File
@@ -166,13 +166,13 @@
<p class="muted">导出当前账号可见的数据,隐藏联系方式。照片与材料包以引用形式提供,全部CSV打包为ZIP。</p> <p class="muted">导出当前账号可见的数据,隐藏联系方式。照片与材料包以引用形式提供,全部CSV打包为ZIP。</p>
<div class="filters center-toolbar"> <div class="filters center-toolbar">
<label>数据范围<select id="center-export-dataset"><option value="all">全部一楼数据</option><option value="activities">一楼活动记录</option><option value="items">物品库存</option><option value="loans">借用记录</option><option value="checks">每日清点</option><option value="duty_leaves">值班请假</option></select></label> <label>数据范围<select id="center-export-dataset"><option value="all">全部一楼数据</option><option value="activities">一楼活动记录</option><option value="items">物品库存</option><option value="loans">借用记录</option><option value="checks">每日清点</option><option value="duty_leaves">值班请假</option></select></label>
<label>格式<select id="center-export-format"><option value="json">JSON(适合AI)</option><option value="csv">CSV(全部时为ZIP)</option></select></label> <label>格式<select id="center-export-format"><option value="json">JSON(适合AI)</option><option value="csv">CSV(全部时为ZIP)</option><option value="word_activities">Word(活动名+图片)</option></select></label>
<label>关键词<input id="center-export-q" type="search" placeholder="主题、物品、申请理由" /></label> <label>关键词<input id="center-export-q" type="search" placeholder="主题、物品、申请理由" /></label>
<label>从<input id="center-export-from" type="date" /></label><label>至<input id="center-export-to" type="date" /></label> <label>从<input id="center-export-from" type="date" /></label><label>至<input id="center-export-to" type="date" /></label>
<label>借用状态<select id="center-export-loan-status"><option value="all">全部状态</option><option value="recorded">已登记借出</option><option value="approved">历史库存借出</option><option value="returned">历史已归还</option></select></label> <label>借用状态<select id="center-export-loan-status"><option value="all">全部状态</option><option value="recorded">已登记借出</option><option value="approved">历史库存借出</option><option value="returned">历史已归还</option></select></label>
<button id="center-export-download" class="btn primary" type="button">下载数据</button> <button id="center-export-download" class="btn primary" type="button">下载数据</button>
</div> </div>
<p class="muted" id="center-export-status" role="status"></p> <p class="muted" id="center-export-status" role="status">Word 格式仅导出当前可见的一楼活动,每个活动包含活动名称和照片,合并为一个 DOCX。</p>
<p class="muted">程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。</p> <p class="muted">程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。</p>
</details> </details>
<div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="tutorials">设备教程</button><button class="tab" data-center-tab="duty">一楼值班</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button></div> <div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="tutorials">设备教程</button><button class="tab" data-center-tab="duty">一楼值班</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button></div>
@@ -366,7 +366,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=50"></script> <script src="/js/app.js?v=51"></script>
</div> </div>
</body> </body>
</html> </html>
+9 -2
View File
@@ -1534,11 +1534,18 @@
}); });
$('#center-export-download').addEventListener('click', async () => { $('#center-export-download').addEventListener('click', async () => {
const button = $('#center-export-download');button.disabled=true;$('#center-export-status').textContent='正在准备导出…'; const button = $('#center-export-download');button.disabled=true;$('#center-export-status').textContent='正在准备导出…';
const params = new URLSearchParams({ dataset:$('#center-export-dataset').value, format:$('#center-export-format').value }); const dataset = $('#center-export-dataset').value;
const format = $('#center-export-format').value;
if (format === 'word_activities') $('#center-export-dataset').value = 'activities';
const params = new URLSearchParams({ dataset: format === 'word_activities' ? 'activities' : dataset, format });
for (const [id,key] of [['q','q'],['from','date_from'],['to','date_to'],['loan-status','loan_status']]) { for (const [id,key] of [['q','q'],['from','date_from'],['to','date_to'],['loan-status','loan_status']]) {
const value=$('#center-export-'+id).value;if(value)params.set(key,value); const value=$('#center-export-'+id).value;if(value)params.set(key,value);
} }
try { await downloadCenterFile('/api/center/export?'+params,'center-export.json');$('#center-export-status').textContent='已下载,文件不包含联系方式,照片与材料包以引用形式提供。'; } try {
const filename = format === 'word_activities' ? '一楼活动照片.docx' : `center-export.${format === 'csv' ? ($('#center-export-dataset').value === 'all' ? 'zip' : 'csv') : 'json'}`;
await downloadCenterFile('/api/center/export?'+params,filename);
$('#center-export-status').textContent = format === 'word_activities' ? '已下载 Word 文件,包含当前筛选范围内所有可见活动的名称和照片。' : '已下载,文件不包含联系方式,照片与材料包以引用形式提供。';
}
catch (error) { $('#center-export-status').textContent=error.message; } catch (error) { $('#center-export-status').textContent=error.message; }
finally {button.disabled=false;} finally {button.disabled=false;}
}); });
+1
View File
@@ -5,6 +5,7 @@ aiosqlite>=0.20,<1
aiosmtplib>=3,<6 aiosmtplib>=3,<6
pydantic>=2.7,<3 pydantic>=2.7,<3
Pillow>=11,<13 Pillow>=11,<13
python-docx>=1.1,<2
rapidocr>=3.10,<3.11 rapidocr>=3.10,<3.11
onnxruntime>=1.20,<2 onnxruntime>=1.20,<2
# 仅测试时需要 # 仅测试时需要
+41 -3
View File
@@ -2,12 +2,17 @@
import csv import csv
import io import io
import json import json
import re
import zipfile import zipfile
from datetime import date, datetime, time, timedelta from datetime import date, datetime, time, timedelta
from typing import Literal, Optional from typing import Literal, Optional
from fastapi import Depends, HTTPException, Query from fastapi import Depends, HTTPException, Query
from fastapi.responses import Response from fastapi.responses import Response
from PIL import Image
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches
from sqlalchemy import select, func, or_, case from sqlalchemy import select, func, or_, case
from .duty import BEIJING from .duty import BEIJING
from . import center from . import center
@@ -65,7 +70,37 @@ def csv_bytes(kind, rows):
return buffer.getvalue().encode('utf-8-sig') return buffer.getvalue().encode('utf-8-sig')
def install(app, get_db, current_user, visible_clause): def docx_bytes(rows, photo_root):
document = Document()
document.add_heading('赋能中心一楼活动记录', level=0)
for index, row in enumerate(rows, 1):
document.add_heading(f'{index}. {row["title"]}', level=1)
photos = []
for photo_id in row.get('photo_ids') or []:
if not re.fullmatch(r'[0-9a-f]{32}', photo_id):
continue
path = photo_root() / (photo_id + '.jpg')
if not path.is_file():
continue
with Image.open(path) as image:
width, height = image.size
width_inches = 6.0
height_inches = width_inches * height / width if width else 4.5
if height_inches > 7.5:
height_inches = 7.5
width_inches = height_inches * width / height if height else 6.0
paragraph = document.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
paragraph.add_run().add_picture(str(path), width=Inches(width_inches), height=Inches(height_inches))
photos.append(photo_id)
if not photos:
document.add_paragraph('(暂无照片)')
output = io.BytesIO()
document.save(output)
return output.getvalue()
def install(app, get_db, current_user, visible_clause, photo_root):
@app.get('/api/center/schema') @app.get('/api/center/schema')
async def schema(viewer=Depends(current_user)): async def schema(viewer=Depends(current_user)):
return { return {
@@ -87,7 +122,7 @@ def install(app, get_db, current_user, visible_clause):
'duty_leave_endpoint':'POST /api/center/duty/leave(仅排班成员本人可提交)', 'duty_leave_endpoint':'POST /api/center/duty/leave(仅排班成员本人可提交)',
'filters':{'dataset':['all',*FIELDS], 'q':'活动主题/地点/描述,物品名称,借用物品/理由/免登录姓名/学院/活动名称,清点备注/日期,值班姓名/事由', 'date_from':'YYYY-MM-DD,含当日,北京时间', 'date_to':'YYYY-MM-DD,含当日,北京时间', 'loan_status':['all','recorded','approved','borrowed(approved 的兼容别名)','returned']}, 'filters':{'dataset':['all',*FIELDS], 'q':'活动主题/地点/描述,物品名称,借用物品/理由/免登录姓名/学院/活动名称,清点备注/日期,值班姓名/事由', 'date_from':'YYYY-MM-DD,含当日,北京时间', 'date_to':'YYYY-MM-DD,含当日,北京时间', 'loan_status':['all','recorded','approved','borrowed(approved 的兼容别名)','returned']},
'semantics':{'timestamps':'数据行中的 *_at 为 Unix 毫秒时间戳,空值为null;generated_at 为带时区的 ISO 8601 字符串', 'inventory':'quantity=物品总数,borrowed/available只统计升级前的历史库存借出记录;新的借出登记与物品库存完全独立', 'loans':'status=recorded 表示仅登记借出;item_id 为空时 item_name 为登记人填写的物品名称;borrower_type=member 表示登录成员登记,guest 表示登录页免登录登记;新登记不扣减库存,也不要求物品已加入库存清单', 'date_filter':'活动按开始时间、借用按登记时间、清点按清点日期、值班请假按值班日期筛选;库存是当前状态,不受日期筛选影响', 'photos':'materials包含原材料和成员补充材料、上传人及关联时间;照片ID合并全部材料,下载需登录;旧照片记录的material_id可为null', 'privacy':'一楼活动全体登录成员可见,仅作记录,不参与参加和发起统计;借用联系方式、账号邮箱和手机号均不导出', 'checks':'details 中 expected=应在库,actual=实点在库;历史 borrowed 为当时占用的库存数量', 'duty':'单双周从2026-11-16起交替;请假必须在值班日期开始前提交;请假不进入活动统计,也不记录缺勤'}, 'semantics':{'timestamps':'数据行中的 *_at 为 Unix 毫秒时间戳,空值为null;generated_at 为带时区的 ISO 8601 字符串', 'inventory':'quantity=物品总数,borrowed/available只统计升级前的历史库存借出记录;新的借出登记与物品库存完全独立', 'loans':'status=recorded 表示仅登记借出;item_id 为空时 item_name 为登记人填写的物品名称;borrower_type=member 表示登录成员登记,guest 表示登录页免登录登记;新登记不扣减库存,也不要求物品已加入库存清单', 'date_filter':'活动按开始时间、借用按登记时间、清点按清点日期、值班请假按值班日期筛选;库存是当前状态,不受日期筛选影响', 'photos':'materials包含原材料和成员补充材料、上传人及关联时间;照片ID合并全部材料,下载需登录;旧照片记录的material_id可为null', 'privacy':'一楼活动全体登录成员可见,仅作记录,不参与参加和发起统计;借用联系方式、账号邮箱和手机号均不导出', 'checks':'details 中 expected=应在库,actual=实点在库;历史 borrowed 为当时占用的库存数量', 'duty':'单双周从2026-11-16起交替;请假必须在值班日期开始前提交;请假不进入活动统计,也不记录缺勤'},
'download':{'json':'完整匹配数据,不受分页参数影响;all包含全部五个数据集','csv':'单一数据集为CSV;all为ZIP,内含五个CSV,UTF-8 BOM;嵌套字段为JSON字符串'}, 'download':{'json':'完整匹配数据,不受分页参数影响;all包含全部五个数据集','csv':'单一数据集为CSV;all为ZIP,内含五个CSV,UTF-8 BOM;嵌套字段为JSON字符串','word_activities':'dataset=activities 时导出Word,仅包含活动名称和照片,所有活动合并到一个DOCX'},
} }
async def collect(db, viewer, dataset, q, start, end, loan_status, limit=None, offset=0): async def collect(db, viewer, dataset, q, start, end, loan_status, limit=None, offset=0):
@@ -150,10 +185,13 @@ def install(app, get_db, current_user, visible_clause):
return await collect(db,viewer,dataset,q,date_from,date_to,loan_status,limit,offset) return await collect(db,viewer,dataset,q,date_from,date_to,loan_status,limit,offset)
@app.get('/api/center/export') @app.get('/api/center/export')
async def export(dataset:Dataset='all',format:Literal['json','csv']='json',q:str=Query('',max_length=200),date_from:Optional[date]=None,date_to:Optional[date]=None,loan_status:LoanStatus='all',db=Depends(get_db),viewer=Depends(current_user)): async def export(dataset:Dataset='all',format:Literal['json','csv','word_activities']='json',q:str=Query('',max_length=200),date_from:Optional[date]=None,date_to:Optional[date]=None,loan_status:LoanStatus='all',db=Depends(get_db),viewer=Depends(current_user)):
if format == 'word_activities' and dataset != 'activities':
raise HTTPException(422, 'Word 导出仅支持一楼活动记录')
payload=await collect(db,viewer,dataset,q,date_from,date_to,loan_status) payload=await collect(db,viewer,dataset,q,date_from,date_to,loan_status)
stamp=datetime.now(BEIJING).strftime('%Y%m%d-%H%M%S') stamp=datetime.now(BEIJING).strftime('%Y%m%d-%H%M%S')
if format=='json':body=json.dumps(payload,ensure_ascii=False,indent=2).encode('utf-8');extension='json';mime='application/json' if format=='json':body=json.dumps(payload,ensure_ascii=False,indent=2).encode('utf-8');extension='json';mime='application/json'
elif format=='word_activities':body=docx_bytes(payload['data']['activities'],photo_root);extension='docx';mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
elif dataset!='all':body=csv_bytes(dataset,payload['data'][dataset]);extension='csv';mime='text/csv; charset=utf-8' elif dataset!='all':body=csv_bytes(dataset,payload['data'][dataset]);extension='csv';mime='text/csv; charset=utf-8'
else: else:
buffer=io.BytesIO() buffer=io.BytesIO()
+1 -1
View File
@@ -769,7 +769,7 @@ async def _migrate_center_loan_schema(conn) -> None:
app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan) app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan)
center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause) center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause)
center_duty.install(app, get_db, current_user) center_duty.install(app, get_db, current_user)
center_export.install(app, get_db, current_user, visible_clause) center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads')
def timetable_collectors(): def timetable_collectors():
values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS') values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS')
+37 -4
View File
@@ -6,6 +6,7 @@ import tempfile
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
from PIL import Image from PIL import Image
from docx import Document
from sqlalchemy import insert from sqlalchemy import insert
from test_api import ApiTestCase, auth, register from test_api import ApiTestCase, auth, register
from server.models import center_items, center_loans, center_checks from server.models import center_items, center_loans, center_checks
@@ -88,10 +89,42 @@ class CenterExportTests(ApiTestCase):
self.assertEqual(guest_csv['guest_college'],'艺术学院') self.assertEqual(guest_csv['guest_college'],'艺术学院')
self.assertNotIn('secret@example.test',archive.read('loans.csv').decode('utf-8-sig')) self.assertNotIn('secret@example.test',archive.read('loans.csv').decode('utf-8-sig'))
self.assertNotIn('13900000777',archive.read('loans.csv').decode('utf-8-sig')) self.assertNotIn('13900000777',archive.read('loans.csv').decode('utf-8-sig'))
recorded=(await self.client.get('/api/center/data?dataset=loans&loan_status=recorded&q=独立登记',headers=headers)).json()
self.assertEqual(len(recorded['data']['loans']),1) async def test_word_export_combines_visible_activities_and_photos(self):
self.assertEqual(recorded['data']['loans'][0]['item_name'],'=独立登记物品') owner=await register(self.client,'wordexport');headers=auth(owner['token'])
self.assertEqual((await self.client.get('/api/center/schema',headers=headers)).json()['schema_version'],4) image=io.BytesIO();Image.new('RGB',(40,30),'green').save(image,'PNG')
directory=Path(self.m._db_path).parent
uploads=directory/'uploads';uploads.mkdir(parents=True,exist_ok=True)
photo_id='a'*32
(uploads/(photo_id+'.jpg')).write_bytes(image.getvalue())
stamp=self.m.now_ms()
async with self.m.SessionLocal() as db:
for activity_id,title in (('word-one','Word导出活动'),('word-two','无照片活动')):
await db.execute(insert(self.m.activities).values(
id=activity_id,title=title,start_at=stamp,location='',description='不应写入Word',
visibility='public',capacity=0,status='active',organizer_id=owner['user']['id'],
created_at=stamp,updated_at=stamp,
))
await db.execute(insert(self.m.center_activity_meta).values(
activity_id='word-one',photo_ids=json.dumps([photo_id]),material_id=None,
))
await db.execute(insert(self.m.center_activity_meta).values(
activity_id='word-two',photo_ids=json.dumps(['not-a-photo-id']),material_id=None,
))
await db.commit()
response=await self.client.get('/api/center/export?dataset=activities&format=word_activities',headers=headers)
self.assertEqual(response.status_code,200,response.text)
mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
self.assertEqual(response.headers['content-type'],mime)
self.assertTrue(response.headers['content-disposition'].endswith('.docx"'))
document=Document(io.BytesIO(response.content))
text='\n'.join(paragraph.text for paragraph in document.paragraphs)
self.assertIn('Word导出活动',text)
self.assertIn('无照片活动',text)
self.assertNotIn('不应写入Word',text)
self.assertEqual(len(document.inline_shapes),1)
response=await self.client.get('/api/center/export?dataset=items&format=word_activities',headers=headers)
self.assertEqual(response.status_code,422)
async def test_pagination_and_export_are_not_silently_truncated(self): async def test_pagination_and_export_are_not_silently_truncated(self):
user=await register(self.client,'exportpagination');headers=auth(user['token']) user=await register(self.client,'exportpagination');headers=auth(user['token'])