展厅登记支持在线填写值班人并记录编辑日志
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
@@ -261,12 +262,25 @@ def convert_package(raw):
|
||||
|
||||
def install(app, get_db, current_user, photo_root, visible_clause):
|
||||
from .hall_log import snapshot as hall_log_snapshot
|
||||
from .hall_log import write_cell as hall_log_write
|
||||
|
||||
@app.get('/api/center/hall-log')
|
||||
async def hall_log(refresh: bool = False, viewer=Depends(current_user)):
|
||||
"""赋能中心展厅使用登记(实时读取金山文档在线表格)。"""
|
||||
return await hall_log_snapshot(force=refresh)
|
||||
|
||||
class HallLogDutyIn(BaseModel):
|
||||
row: int = Field(ge=2, le=502)
|
||||
value: str = Field(default='', max_length=200)
|
||||
|
||||
@app.post('/api/center/hall-log/duty')
|
||||
async def hall_log_duty(payload: HallLogDutyIn, viewer=Depends(current_user)):
|
||||
"""填写展厅登记的"值班人"列,写回金山文档并留编辑日志。"""
|
||||
editor = viewer.get('display_name') or viewer.get('username') or viewer['id']
|
||||
await asyncio.to_thread(hall_log_write, os.getenv('WORKLOG_HALL_LOG_LINK_ID') or 'cnC7HwRAxKf9', payload.row, 8, payload.value.strip(), editor)
|
||||
await hall_log_snapshot(force=True)
|
||||
return {'ok': True, 'row': payload.row, 'value': payload.value.strip(), 'editor': editor}
|
||||
|
||||
@app.post('/api/center/materials')
|
||||
async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)):
|
||||
raw=bytearray()
|
||||
|
||||
+40
-4
@@ -5,9 +5,12 @@ import asyncio
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
DEFAULT_LINK_ID = 'cnC7HwRAxKf9'
|
||||
@@ -15,6 +18,7 @@ ENDPOINT = 'https://mcp-center.wps.cn/skill_hub/api/v1/tool'
|
||||
CACHE_TTL_SECONDS = 60
|
||||
MAX_ROWS = 500
|
||||
FIELDS = ['序号', '日期', '时间', '使用场地', '参加人数', '使用事项', '使用单位', '使用单位联系人及联系方式', '赋能部值班人员及联系方式', '备注']
|
||||
LOG_DIR = Path(__file__).resolve().parent.parent / 'logs'
|
||||
_cache: dict[str, Any] = {'fetched_at': 0.0, 'payload': None, 'error': None}
|
||||
_lock = asyncio.Lock()
|
||||
|
||||
@@ -59,19 +63,50 @@ def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
||||
grid = _parse_grid(data['data']['detail']['rangeData'], row_to, col_to)
|
||||
header = grid[1] if len(grid) > 1 else FIELDS
|
||||
records = []
|
||||
for row in grid[2:]:
|
||||
for offset, row in enumerate(grid[2:]):
|
||||
values = {header[i] if i < len(header) else f'列{i+1}': value for i, value in enumerate(row)}
|
||||
if any(value.strip() for value in values.values()):
|
||||
values['_row'] = offset + 2 # 0 基索引:跳过标题和表头
|
||||
records.append(values)
|
||||
return records
|
||||
|
||||
|
||||
def write_cell(link_id: str, row_index: int, col_index: int, value: str, editor: str) -> None:
|
||||
"""写入一个单元格(0 基索引),并记录谁改了什么。"""
|
||||
token = os.getenv('KINGSOFT_DOCS_TOKEN')
|
||||
op = {'opType': 'formula', 'rowFrom': row_index, 'rowTo': row_index, 'colFrom': col_index, 'colTo': col_index, 'formula': value}
|
||||
if token:
|
||||
_call_tool('sheet.update_range_data', {'link_id': link_id, 'worksheet_id': 1, 'range_data': [op]}, token)
|
||||
else:
|
||||
cli = _cli_path()
|
||||
if not cli:
|
||||
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
|
||||
args = json.dumps({'link_id': link_id, 'worksheet_id': 1, 'range_data': [op]}, ensure_ascii=False)
|
||||
completed = subprocess.run([cli, 'sheet', 'update-range-data', args], capture_output=True, timeout=20)
|
||||
if completed.returncode != 0:
|
||||
raise RuntimeError(f'金山文档写入失败: {completed.stderr.decode("utf-8", "ignore").strip()[:200]}')
|
||||
payload = json.loads(completed.stdout.decode('utf-8', 'ignore'))
|
||||
if payload.get('code') != 0:
|
||||
raise RuntimeError(f"金山文档写入返回 {payload.get('code')}: {payload.get('message')}")
|
||||
_log_edit(editor, row_index, col_index, value)
|
||||
|
||||
|
||||
def _log_edit(editor: str, row_index: int, col_index: int, value: str) -> None:
|
||||
line = f"{datetime.now():%Y-%m-%d %H:%M:%S} | {editor} | 行{row_index + 1} 列{col_index + 1} ({FIELDS[col_index] if col_index < len(FIELDS) else '未知列'}) | 新值: {value or '(清空)'}"
|
||||
try:
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with (LOG_DIR / 'hall-log-edits.log').open('a', encoding='utf-8') as fh:
|
||||
fh.write(line + '\n')
|
||||
except OSError:
|
||||
print(f'[hall-log] 写日志失败: {line}', flush=True)
|
||||
print(f'[hall-log] {line}', flush=True)
|
||||
|
||||
|
||||
def fetch_via_cli(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
||||
cli = _cli_path()
|
||||
if not cli:
|
||||
raise RuntimeError('未找到金山文档命令行工具,请配置 KINGSOFT_DOCS_TOKEN 环境变量')
|
||||
subprocess = _run_cli(cli, link_id)
|
||||
payload = json.loads(subprocess)
|
||||
payload = json.loads(_run_cli(cli, link_id))
|
||||
if payload.get('code') != 0:
|
||||
raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}")
|
||||
info = payload['data']['detail']['sheetsInfo'][0]
|
||||
@@ -86,9 +121,10 @@ def fetch_via_cli(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]:
|
||||
grid = _parse_grid(data['data']['detail']['rangeData'], row_to, col_to)
|
||||
header = grid[1] if len(grid) > 1 else FIELDS
|
||||
records = []
|
||||
for row in grid[2:]:
|
||||
for offset, row in enumerate(grid[2:]):
|
||||
values = {header[i] if i < len(header) else f'列{i+1}': value for i, value in enumerate(row)}
|
||||
if any(value.strip() for value in values.values()):
|
||||
values['_row'] = offset + 2
|
||||
records.append(values)
|
||||
return records
|
||||
|
||||
|
||||
Reference in New Issue
Block a user