初版:上传接口(从线上实例导出,适配容器端口)
This commit is contained in:
@@ -0,0 +1,662 @@
|
||||
"""
|
||||
表单提交 API + 状态/进度/时间数据 API
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
from flask import Blueprint, request, jsonify
|
||||
from database import (
|
||||
get_form, get_preset, get_form_submissions, get_submitted_students,
|
||||
save_submission, delete_student_files, get_form_files,
|
||||
record_submission_history, get_submission_history,
|
||||
insert_business_metric,
|
||||
get_last_submission_by_token, archive_replaced_files,
|
||||
save_submission_version, update_version_file_ids, get_prev_version_id,
|
||||
get_student_versions, get_submission_version, delete_submission_version,
|
||||
get_version_archived_file, find_submission_id, build_status_students,
|
||||
)
|
||||
from utils.expiry import get_expiry_info
|
||||
from routes.auth import require_login
|
||||
from utils.helpers import get_client_ip
|
||||
from utils.webhooks import send_form_webhook
|
||||
|
||||
bp = Blueprint('submissions', __name__)
|
||||
|
||||
# "加载上次填写"功能:客户端提交时上送的设备令牌 cookie 名
|
||||
DEVICE_TOKEN_COOKIE = 'fs_device_token'
|
||||
|
||||
|
||||
def _check_form_manage_permission(form_id):
|
||||
"""校验当前登录用户是否有权管理该表单(admin 或被授权管理者)。
|
||||
返回错误消息字符串,通过则返回 None。"""
|
||||
from database import get_session, get_user
|
||||
session_id = request.cookies.get('session_id')
|
||||
session_data = get_session(session_id)
|
||||
if not session_data:
|
||||
return '未登录'
|
||||
user = get_user(session_data['username'])
|
||||
managed_forms = user.get('managed_forms', []) if user else []
|
||||
if session_data['role'] != 'admin' and form_id not in managed_forms:
|
||||
return '无权管理此表单'
|
||||
return None
|
||||
|
||||
|
||||
@bp.route('/get_students', methods=['GET'])
|
||||
def get_students():
|
||||
"""获取学生信息(不含身份证)"""
|
||||
try:
|
||||
form_id = request.args.get('formId', '')
|
||||
if form_id:
|
||||
form = get_form(form_id)
|
||||
if form:
|
||||
verify_digits = form.get('verifyDigits', 2)
|
||||
preset_id = form.get('presetId')
|
||||
if preset_id:
|
||||
preset = get_preset(preset_id)
|
||||
if preset:
|
||||
students = {}
|
||||
for s in preset.get('students', []):
|
||||
student_id = s.get('id', '')
|
||||
if len(student_id) >= verify_digits:
|
||||
tail = student_id[-verify_digits:]
|
||||
students[tail] = {
|
||||
"id": student_id,
|
||||
"name": s.get('name', '')
|
||||
}
|
||||
return jsonify(students)
|
||||
return jsonify({})
|
||||
except Exception as e:
|
||||
print(f"get_students 接口异常: {str(e)}")
|
||||
return jsonify(error=f'服务器错误: {str(e)}'), 500
|
||||
|
||||
|
||||
@bp.route('/get_verify_value', methods=['POST'])
|
||||
def get_verify_value():
|
||||
"""在服务端比对覆盖验证信息,不向客户端返回答案。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
tail = str(payload.get('studentId', '')).strip()
|
||||
form_id = str(payload.get('formId', '')).strip()
|
||||
candidate = str(payload.get('value', '')).strip().upper()
|
||||
|
||||
if form_id and tail and candidate:
|
||||
form = get_form(form_id)
|
||||
if form:
|
||||
preset_id = form.get('presetId')
|
||||
verify_config = form.get('overwriteVerify') or {}
|
||||
if preset_id and verify_config.get('enabled') and tail in get_submitted_students(form_id):
|
||||
verify_field = verify_config.get('field', 'idCard')
|
||||
custom_field_name = verify_config.get('customFieldName', '')
|
||||
digits = int(verify_config.get('digits', 4))
|
||||
preset = get_preset(preset_id)
|
||||
if preset:
|
||||
preset_verify_digits = preset.get(
|
||||
'config', {}).get('verifyDigits', 2)
|
||||
for s in preset.get('students', []):
|
||||
student_id = s.get('id', '')
|
||||
if len(student_id) >= preset_verify_digits and student_id[-preset_verify_digits:] == tail:
|
||||
value = ''
|
||||
if verify_field == 'idCard':
|
||||
value = s.get('idCard', '')
|
||||
elif verify_field == 'phone':
|
||||
value = s.get('phone', '')
|
||||
elif verify_field == 'custom' and custom_field_name:
|
||||
value = s.get('extra', {}).get(
|
||||
custom_field_name, '') or s.get(custom_field_name, '')
|
||||
|
||||
if value:
|
||||
expected = str(value).upper()[-digits:]
|
||||
return jsonify(success=candidate == expected)
|
||||
|
||||
return jsonify(success=False)
|
||||
|
||||
|
||||
@bp.route('/check_submission', methods=['GET'])
|
||||
def check_submission():
|
||||
"""检查提交状态"""
|
||||
tail = request.args.get('studentId', '').strip()
|
||||
form_id = request.args.get('formId', 'default')
|
||||
|
||||
submitted_students = get_submitted_students(form_id)
|
||||
return jsonify(exists=tail in submitted_students)
|
||||
|
||||
|
||||
@bp.route('/api/submit', methods=['POST'])
|
||||
def submit_form():
|
||||
"""通用表单提交接口 - BLOB存储版本"""
|
||||
try:
|
||||
form_id = request.form.get('formId', 'default')
|
||||
tail = request.form.get('studentId', '').strip()
|
||||
|
||||
form = get_form(form_id)
|
||||
if not form:
|
||||
return jsonify(success=False, message='表单配置不存在或已过期'), 400
|
||||
|
||||
# 检查表单是否已过期
|
||||
expiry_info = get_expiry_info(form.get('createdAt', ''), form.get('expiresAt'))
|
||||
if expiry_info and expiry_info.get('is_expired'):
|
||||
return jsonify(success=False, message='表单已过期,无法提交'), 410
|
||||
|
||||
# 检查是否已停止收集
|
||||
if form.get('collecting', True) is False:
|
||||
return jsonify(success=False, message='此页面已停止收集信息,如有问题请联系管理员'), 423
|
||||
|
||||
# 身份判定:名单模式按预设匹配学号;匿名模式(表单未选预设)按设备令牌生成伪ID
|
||||
student_name = None
|
||||
full_id = None
|
||||
preset_id = form.get('presetId')
|
||||
form_verify_digits = form.get('verifyDigits', 2)
|
||||
anonymous_mode = not preset_id
|
||||
device_token = (request.form.get('device_token') or '').strip()[:128]
|
||||
|
||||
if anonymous_mode:
|
||||
if device_token:
|
||||
# 伪ID = anon_ + 设备令牌:save_submission 按 student_id upsert,
|
||||
# 同设备自然覆盖;文件/版本/历史按 student_id 分组逻辑全部穿透复用
|
||||
full_id = 'anon_' + device_token
|
||||
else:
|
||||
# 令牌缺失(cookie 被禁)退化为按客户端 IP 粗粒度识别(NAT 下可能合并多人)
|
||||
import hashlib
|
||||
full_id = 'anon_ip_' + hashlib.md5(
|
||||
(get_client_ip() or '').encode('utf-8')).hexdigest()[:16]
|
||||
student_name = '匿名用户'
|
||||
tail = ''
|
||||
else:
|
||||
if preset_id:
|
||||
preset = get_preset(preset_id)
|
||||
if preset:
|
||||
verify_digits = form.get('verifyDigits', 2)
|
||||
for s in preset.get('students', []):
|
||||
student_id = s.get('id', '')
|
||||
if len(student_id) >= verify_digits and student_id[-verify_digits:] == tail:
|
||||
student_name = s.get('name')
|
||||
full_id = student_id
|
||||
break
|
||||
|
||||
if not student_name:
|
||||
if len(tail) != form_verify_digits:
|
||||
return jsonify(success=False, message=f'学号后{form_verify_digits}位长度不正确,请输入{form_verify_digits}位数字'), 400
|
||||
return jsonify(success=False, message='无效学号'), 400
|
||||
|
||||
# 检查是否已提交
|
||||
if anonymous_mode:
|
||||
is_overwrite = find_submission_id(form_id, full_id) is not None
|
||||
else:
|
||||
submitted_students = get_submitted_students(form_id)
|
||||
is_overwrite = tail in submitted_students
|
||||
|
||||
# 禁止重复提交策略(名单/匿名模式均生效)
|
||||
if is_overwrite and form.get('duplicatePolicy') == 'once':
|
||||
if anonymous_mode:
|
||||
message = '此表单不允许重复提交,该设备已提交过'
|
||||
else:
|
||||
message = f'学号后{form_verify_digits}位({tail})已提交过,此表单不允许重复提交'
|
||||
return jsonify(success=False, message=message), 409
|
||||
|
||||
# 覆盖验证(匿名模式无名单可比对,不适用)
|
||||
if is_overwrite and preset_id:
|
||||
verify_config = form.get('overwriteVerify')
|
||||
if verify_config and verify_config.get('enabled'):
|
||||
verify_field = verify_config.get('field', 'idCard')
|
||||
verify_digits_count = verify_config.get('digits', 4)
|
||||
verify_label = verify_config.get('label', '验证信息')
|
||||
|
||||
user_verify_value = request.form.get('verifyTail', '').strip(
|
||||
) or request.form.get('idCardTail', '').strip()
|
||||
user_verify_value = user_verify_value.upper()
|
||||
|
||||
if not user_verify_value:
|
||||
return jsonify(success=False, message=f'覆盖提交需要验证{verify_label}后{verify_digits_count}位'), 400
|
||||
|
||||
real_verify_value = ''
|
||||
field_mapping = {
|
||||
'idCard': 'idCard',
|
||||
'phone': 'phone',
|
||||
'custom': verify_config.get('customFieldName', '')
|
||||
}
|
||||
preset_field_name = field_mapping.get(
|
||||
verify_field, verify_field)
|
||||
|
||||
if preset_id:
|
||||
preset = get_preset(preset_id)
|
||||
if preset:
|
||||
preset_verify_digits = preset.get(
|
||||
'config', {}).get('verifyDigits', 2)
|
||||
for s in preset.get('students', []):
|
||||
student_id = s.get('id', '')
|
||||
if len(student_id) >= preset_verify_digits and student_id[-preset_verify_digits:] == tail:
|
||||
if verify_field == 'idCard':
|
||||
real_verify_value = s.get('idCard', '')
|
||||
elif verify_field == 'phone':
|
||||
real_verify_value = s.get('phone', '')
|
||||
elif verify_field == 'custom' and preset_field_name:
|
||||
real_verify_value = s.get('extra', {}).get(
|
||||
preset_field_name, '') or s.get(preset_field_name, '')
|
||||
|
||||
if real_verify_value:
|
||||
real_verify_value = str(
|
||||
real_verify_value).upper()[-verify_digits_count:]
|
||||
break
|
||||
|
||||
if user_verify_value != real_verify_value:
|
||||
return jsonify(success=False, message=f'{verify_label}后{verify_digits_count}位验证失败'), 403
|
||||
|
||||
# 提交内容快照(供历史版本归档)
|
||||
student_data = {}
|
||||
non_file_fields = [f for f in form['fields'] if f['type'] not in ('file', 'page_break')]
|
||||
for field in non_file_fields:
|
||||
field_name = field['name']
|
||||
field_value = request.form.get(field_name, '')
|
||||
if field_value:
|
||||
student_data[field_name] = field_value
|
||||
|
||||
# 归档历史版本:每次提交(含覆盖)都留档一份快照
|
||||
version_id = save_submission_version(
|
||||
form_id, full_id, student_name, tail,
|
||||
student_data, is_overwrite=is_overwrite,
|
||||
ip_address=get_client_ip()
|
||||
)
|
||||
|
||||
# 覆盖提交:keep_files 指定的沿用为当前文件,其余旧文件归档到上一版本
|
||||
kept_file_ids = []
|
||||
if is_overwrite:
|
||||
try:
|
||||
import json as _json
|
||||
keep_map = _json.loads(request.form.get('keep_files') or '{}')
|
||||
if isinstance(keep_map, dict):
|
||||
kept_file_ids = list(keep_map.values())
|
||||
except (ValueError, TypeError):
|
||||
kept_file_ids = []
|
||||
prev_version_id = get_prev_version_id(form_id, full_id, version_id)
|
||||
archive_replaced_files(form_id, full_id, kept_file_ids, prev_version_id)
|
||||
|
||||
uploaded_files = []
|
||||
new_file_ids = []
|
||||
file_fields = [f for f in form['fields'] if f['type'] == 'file']
|
||||
has_multiple_files = len(file_fields) > 1
|
||||
|
||||
# 设备令牌已在身份判定段读取;空值存 NULL(仅作"加载上次填写"召回用)
|
||||
submission_id = save_submission(
|
||||
form_id, full_id, student_name, tail,
|
||||
is_overwrite=is_overwrite,
|
||||
ip_address=get_client_ip(),
|
||||
data=student_data,
|
||||
device_token=device_token or None
|
||||
)
|
||||
|
||||
# 处理文件上传 - 存储为BLOB
|
||||
from database import save_file
|
||||
for field in form['fields']:
|
||||
if field['type'] == 'file':
|
||||
file = request.files.get(field['name'])
|
||||
if file and file.filename:
|
||||
ext = file.filename.rsplit('.', 1)[-1].lower()
|
||||
|
||||
field_allowed_exts = field.get('allowedExts', [])
|
||||
if not field_allowed_exts:
|
||||
field_allowed_exts = form.get('allowedExts', [])
|
||||
|
||||
if field_allowed_exts and ext not in field_allowed_exts:
|
||||
return jsonify(success=False, message=f'不支持的格式: {ext}'), 400
|
||||
|
||||
file.seek(0, os.SEEK_END)
|
||||
size = file.tell()
|
||||
file.seek(0)
|
||||
|
||||
if size > form['maxSize']:
|
||||
return jsonify(success=False, message='文件大小超过限制'), 400
|
||||
|
||||
if anonymous_mode:
|
||||
# 匿名文件名:匿名_ + 设备令牌前4位(仅展示名,磁盘按 fileId 存放)
|
||||
base_name = f"匿名_{full_id[5:9]}"
|
||||
else:
|
||||
base_name = f"{student_name}{full_id}"
|
||||
if has_multiple_files:
|
||||
filename = f"{base_name}_{field['name']}.{ext}"
|
||||
else:
|
||||
filename = f"{base_name}.{ext}"
|
||||
|
||||
file_data = file.read()
|
||||
mime_type = file.content_type or 'application/octet-stream'
|
||||
|
||||
file_id = save_file(
|
||||
form_id=form_id,
|
||||
file_data=file_data,
|
||||
filename=filename,
|
||||
original_name=file.filename,
|
||||
mime_type=mime_type,
|
||||
field_name=field['name'],
|
||||
submission_id=submission_id
|
||||
)
|
||||
new_file_ids.append(file_id)
|
||||
uploaded_files.append(filename)
|
||||
try:
|
||||
insert_business_metric('files_uploaded', len(file_data))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 版本文件清单 = 沿用保留的旧文件 + 本次新上传的文件
|
||||
update_version_file_ids(version_id, kept_file_ids + new_file_ids)
|
||||
|
||||
# 记录提交历史
|
||||
record_submission_history(
|
||||
form_id, full_id,
|
||||
submission_type='overwrite' if is_overwrite else 'first',
|
||||
ip_address=get_client_ip()
|
||||
)
|
||||
|
||||
try:
|
||||
insert_business_metric('form_submissions', 1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 每个表单显式启用后通知;请求失败不影响已保存的提交。
|
||||
who = f"{student_name}(设备:{full_id[5:9]})" if anonymous_mode else f"{student_name}(学号:{tail})"
|
||||
send_form_webhook(form, who, is_overwrite=is_overwrite, uploaded_files=uploaded_files)
|
||||
|
||||
return jsonify(success=True, message=f'{"覆盖" if is_overwrite else "提交"}成功', overwrite=is_overwrite)
|
||||
|
||||
except Exception as e:
|
||||
print(f"提交接口异常: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
|
||||
|
||||
|
||||
@bp.route('/api/last_submission/check')
|
||||
def last_submission_check():
|
||||
"""静默检查:该设备(cookie 令牌)在此表单下是否有提交记录。
|
||||
只返回存在性与时间,不返回任何内容数据;无效令牌由前端静默清除 cookie。"""
|
||||
try:
|
||||
form_id = request.args.get('formId', '')
|
||||
token = request.cookies.get(DEVICE_TOKEN_COOKIE, '').strip()
|
||||
if not form_id or not token:
|
||||
return jsonify(exists=False)
|
||||
sub = get_last_submission_by_token(form_id, token)
|
||||
if not sub:
|
||||
return jsonify(exists=False)
|
||||
return jsonify(exists=True, submittedAt=sub['submitted_at'])
|
||||
except Exception as e:
|
||||
print(f"last_submission/check 异常: {str(e)}")
|
||||
return jsonify(exists=False)
|
||||
|
||||
|
||||
@bp.route('/api/last_submission/load', methods=['POST'])
|
||||
def last_submission_load():
|
||||
"""加载上次提交内容:必须携带 cookie 令牌 + 尾号,两者同时匹配才返回数据。"""
|
||||
try:
|
||||
payload = request.get_json(silent=True) or {}
|
||||
form_id = str(payload.get('formId', '')).strip()
|
||||
tail = str(payload.get('tail', '')).strip()
|
||||
token = request.cookies.get(DEVICE_TOKEN_COOKIE, '').strip()
|
||||
|
||||
if not form_id or not token:
|
||||
return jsonify(success=False, message='没有可用的提交记录'), 404
|
||||
|
||||
sub = get_last_submission_by_token(form_id, token)
|
||||
if not sub:
|
||||
return jsonify(success=False, message='没有找到对应的提交记录'), 404
|
||||
if sub['tail'] != tail:
|
||||
return jsonify(success=False, message='尾号与上次提交不一致,无法加载'), 403
|
||||
|
||||
files = get_form_files(form_id, sub['student_id'], sub['student_name'])
|
||||
manifest = [{
|
||||
'id': f['id'],
|
||||
'fieldName': f['field_name'],
|
||||
'originalName': f['original_name'] or f['filename'],
|
||||
'fileSize': f['file_size'],
|
||||
} for f in files]
|
||||
|
||||
return jsonify(success=True, values=sub['data'], files=manifest,
|
||||
submittedAt=sub['submitted_at'])
|
||||
except Exception as e:
|
||||
print(f"last_submission/load 异常: {str(e)}")
|
||||
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
|
||||
|
||||
|
||||
@bp.route('/api/admin/submission_history')
|
||||
@require_login
|
||||
def admin_submission_history():
|
||||
"""管理端:查看某学生此表单的全部历史提交版本(含文件清单,不含二进制)。"""
|
||||
try:
|
||||
form_id = request.args.get('formId', '').strip()
|
||||
student_id = request.args.get('studentId', '').strip()
|
||||
if not form_id or not student_id:
|
||||
return jsonify(success=False, message='缺少参数'), 400
|
||||
if not get_form(form_id):
|
||||
return jsonify(success=False, message='表单不存在'), 404
|
||||
|
||||
perm_error = _check_form_manage_permission(form_id)
|
||||
if perm_error:
|
||||
return jsonify(success=False, message=perm_error), 403
|
||||
|
||||
versions = get_student_versions(form_id, student_id)
|
||||
return jsonify(success=True, versions=versions)
|
||||
except Exception as e:
|
||||
print(f"submission_history 接口异常: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
|
||||
|
||||
|
||||
@bp.route('/api/admin/delete_submission_version/<int:version_id>', methods=['POST'])
|
||||
@require_login
|
||||
def admin_delete_submission_version(version_id):
|
||||
"""管理端:删除一条历史提交版本。
|
||||
非最新条仅删快照及归档附件;最新条会同时清除该学生的当前提交与现存文件。"""
|
||||
try:
|
||||
version = get_submission_version(version_id)
|
||||
if not version:
|
||||
return jsonify(success=False, message='记录不存在'), 404
|
||||
|
||||
perm_error = _check_form_manage_permission(version['form_id'])
|
||||
if perm_error:
|
||||
return jsonify(success=False, message=perm_error), 403
|
||||
|
||||
result = delete_submission_version(version_id)
|
||||
return jsonify(success=True,
|
||||
deletedCurrent=result.get('deletedCurrent', False),
|
||||
deletedCurrentFiles=result.get('deletedCurrentFiles', 0))
|
||||
except Exception as e:
|
||||
print(f"delete_submission_version 接口异常: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify(success=False, message=f'服务器错误: {str(e)}'), 500
|
||||
|
||||
|
||||
@bp.route('/api/admin/download_version_file/<int:vfile_id>')
|
||||
@require_login
|
||||
def admin_download_version_file(vfile_id):
|
||||
"""管理端:下载历史版本中的归档附件。"""
|
||||
try:
|
||||
record = get_version_archived_file(vfile_id)
|
||||
if not record:
|
||||
return jsonify(error='文件不存在'), 404
|
||||
|
||||
perm_error = _check_form_manage_permission(record['form_id'])
|
||||
if perm_error:
|
||||
return jsonify(error=perm_error), 403
|
||||
|
||||
from urllib.parse import quote
|
||||
import io as _io
|
||||
from flask import send_file
|
||||
|
||||
display_filename = record['original_name'] or record['filename']
|
||||
mime_type = record['mime_type'] or 'application/octet-stream'
|
||||
ascii_filename = display_filename.encode('ascii', 'ignore').decode() or 'download'
|
||||
encoded_filename = quote(display_filename, safe='')
|
||||
|
||||
response = send_file(
|
||||
_io.BytesIO(record['file_data']),
|
||||
mimetype=mime_type,
|
||||
as_attachment=True,
|
||||
download_name=ascii_filename
|
||||
)
|
||||
disposition = f"attachment; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
|
||||
response.headers['Content-Disposition'] = disposition
|
||||
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
|
||||
return response
|
||||
except Exception as e:
|
||||
print(f"download_version_file 接口异常: {str(e)}")
|
||||
return jsonify(error=f'服务器错误: {str(e)}'), 500
|
||||
|
||||
|
||||
@bp.route('/api/status_data')
|
||||
def api_status_data():
|
||||
"""返回学生提交状态数据"""
|
||||
try:
|
||||
form_id = request.args.get('formId', 'default')
|
||||
form = get_form(form_id)
|
||||
|
||||
if not form:
|
||||
return jsonify(error='表单不存在'), 404
|
||||
|
||||
expiry_info = get_expiry_info(form.get('createdAt', ''), form.get('expiresAt'))
|
||||
submissions = get_form_submissions(form_id)
|
||||
|
||||
# 名单模式按名单对齐;匿名模式每条提交一个身份
|
||||
students = build_status_students(form, submissions)
|
||||
submitted_count = len(submissions) if not form.get('presetId') else len(
|
||||
{s['tail'] for s in submissions})
|
||||
|
||||
return jsonify({
|
||||
"formTitle": form.get('title', '未命名表单'),
|
||||
"formId": form_id,
|
||||
"total": len(students),
|
||||
"submitted": submitted_count,
|
||||
"students": students,
|
||||
"expiryInfo": expiry_info,
|
||||
"showProgress": form.get('showProgress', True)
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
print(f"获取状态数据失败: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return jsonify(error=f"服务器错误: {str(e)}"), 500
|
||||
|
||||
|
||||
@bp.route('/api/progress/<form_id>')
|
||||
def api_get_progress(form_id):
|
||||
"""获取表单进度(公开接口)"""
|
||||
try:
|
||||
form = get_form(form_id)
|
||||
if not form:
|
||||
return jsonify(error='表单不存在'), 404
|
||||
|
||||
if not form.get('showProgress', True):
|
||||
return jsonify(error='该表单未开启进度显示'), 403
|
||||
|
||||
submissions = get_form_submissions(form_id)
|
||||
preset_id = form.get('presetId')
|
||||
|
||||
total = 0
|
||||
if preset_id:
|
||||
preset = get_preset(preset_id)
|
||||
if preset:
|
||||
total = len(preset.get('students', []))
|
||||
|
||||
students = []
|
||||
if preset_id:
|
||||
preset = get_preset(preset_id)
|
||||
if preset:
|
||||
verify_digits = preset.get('config', {}).get('verifyDigits', 2)
|
||||
for s in preset.get('students', []):
|
||||
student_id = s.get('id', '')
|
||||
if len(student_id) >= verify_digits:
|
||||
tail = student_id[-verify_digits:]
|
||||
submitted = any(
|
||||
sub['tail'] == tail for sub in submissions)
|
||||
students.append({
|
||||
'tail': tail,
|
||||
'name': s.get('name', ''),
|
||||
'submitted': submitted
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'formTitle': form.get('title', '未命名表单'),
|
||||
'total': total,
|
||||
'submitted': len(submissions),
|
||||
'progress': round(len(submissions) / total * 100, 1) if total > 0 else 0,
|
||||
'students': students
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(error=str(e)), 500
|
||||
|
||||
|
||||
@bp.route('/api/submission_times/<form_id>')
|
||||
@require_login
|
||||
def api_submission_times(form_id):
|
||||
"""获取表单提交时间数据,用于趋势图表"""
|
||||
try:
|
||||
form = get_form(form_id)
|
||||
if not form:
|
||||
return jsonify(error='表单不存在'), 404
|
||||
|
||||
created_at_str = form.get('createdAt', '')
|
||||
if not created_at_str:
|
||||
return jsonify(error='表单创建时间未知'), 400
|
||||
|
||||
if created_at_str.endswith('Z'):
|
||||
created_at_str = created_at_str[:-1] + '+00:00'
|
||||
created_at = datetime.fromisoformat(created_at_str)
|
||||
now = datetime.now()
|
||||
|
||||
time_data = get_submission_history(form_id)
|
||||
|
||||
raw_times = []
|
||||
overwrite_times = []
|
||||
for student_id, data in time_data.items():
|
||||
first_submit = data.get('first_submit')
|
||||
if first_submit:
|
||||
raw_times.append(first_submit)
|
||||
for record in data.get('submissions', []):
|
||||
if record.get('type') == 'overwrite':
|
||||
overwrite_times.append(record['time'])
|
||||
|
||||
time_slots = []
|
||||
current_slot = created_at
|
||||
while current_slot <= now + timedelta(minutes=20):
|
||||
time_slots.append(current_slot)
|
||||
current_slot += timedelta(minutes=20)
|
||||
|
||||
if len(time_slots) == 0:
|
||||
time_slots = [created_at, now]
|
||||
|
||||
slot_counts = []
|
||||
slot_labels = []
|
||||
|
||||
for i in range(len(time_slots) - 1):
|
||||
slot_start = time_slots[i]
|
||||
slot_end = time_slots[i + 1]
|
||||
|
||||
count = 0
|
||||
for student_id, data in time_data.items():
|
||||
first_submit = data.get('first_submit')
|
||||
if first_submit:
|
||||
submit_time = datetime.fromisoformat(
|
||||
first_submit.replace('Z', '+00:00').replace('+00:00', ''))
|
||||
if slot_start <= submit_time < slot_end:
|
||||
count += 1
|
||||
|
||||
slot_counts.append(count)
|
||||
slot_labels.append(slot_start.strftime('%H:%M'))
|
||||
|
||||
cumulative_counts = []
|
||||
total = 0
|
||||
for count in slot_counts:
|
||||
total += count
|
||||
cumulative_counts.append(total)
|
||||
|
||||
return jsonify({
|
||||
'formId': form_id,
|
||||
'createdAt': created_at.isoformat(),
|
||||
'timeLabels': slot_labels,
|
||||
'slotCounts': slot_counts,
|
||||
'cumulativeCounts': cumulative_counts,
|
||||
'totalSubmissions': len(time_data),
|
||||
'rawTimes': raw_times,
|
||||
'overwriteTimes': overwrite_times
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify(error=f"服务器错误: {str(e)}"), 500
|
||||
Reference in New Issue
Block a user