From 1d4d14856048183ae7af0a2de32bcb5294041831 Mon Sep 17 00:00:00 2001 From: soehi <811446351@qq.com> Date: Fri, 20 Nov 2026 11:59:02 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B5=8B=E8=83=BD=E4=B8=AD=E5=BF=83=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=B1=95=E5=8E=85=E4=BD=BF=E7=94=A8=E7=99=BB=E8=AE=B0?= =?UTF-8?q?=E5=AE=9E=E6=97=B6=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dist/index.html | 8 ++- dist/js/app.js | 16 +++++- server/center.py | 7 +++ server/hall_log.py | 130 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 157 insertions(+), 4 deletions(-) create mode 100644 server/hall_log.py diff --git a/dist/index.html b/dist/index.html index 4619708..c1ea106 100644 --- a/dist/index.html +++ b/dist/index.html @@ -175,7 +175,7 @@

程序读取:GET /api/center/data;字段说明:GET /api/center/schema。均需使用本人登录令牌。

-
+
@@ -189,6 +189,10 @@
每日清点记录
+
@@ -337,7 +341,7 @@ - + diff --git a/dist/js/app.js b/dist/js/app.js index 1bb66f6..5439c70 100644 --- a/dist/js/app.js +++ b/dist/js/app.js @@ -1538,11 +1538,12 @@ let centerRecords = []; function openCenterFromHash() { if (state.me && location.hash === '#timetables') { show('timetables'); return true; } - if (!state.me || !['#center', '#center-records', '#center-assets'].includes(location.hash)) return false; - centerTab = location.hash === '#center-assets' ? 'assets' : 'records'; + if (!state.me || !['#center', '#center-records', '#center-assets', '#center-hall'].includes(location.hash)) return false; + centerTab = location.hash === '#center-assets' ? 'assets' : location.hash === '#center-hall' ? 'hall' : 'records'; $$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab)); $('#center-records').classList.toggle('hidden', centerTab !== 'records'); $('#center-assets').classList.toggle('hidden', centerTab !== 'assets'); + $('#center-hall').classList.toggle('hidden', centerTab !== 'hall'); show('center'); return true; } @@ -1561,6 +1562,13 @@ const data = await api(`/activities?${p}`); centerRecords = data.items; $('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '
暂无匹配的一楼活动,记录活动时请上传照片。
'; bindCardEvents($('#center-record-list')); + } else if (centerTab === 'hall') { + $('#center-hall-status').textContent = '正在读取金山文档登记表…'; + const hall = await api('/center/hall-log'); + $('#center-hall-link').href = hall.link; + $('#center-hall-link').classList.toggle('hidden', !hall.link); + $('#center-hall-status').textContent = hall.ok ? `共 ${hall.count} 条登记,更新于 ${fmtDate(hall.fetched_at)}(60 秒缓存)` : `读取失败:${hall.error}`; + $('#center-hall-list').innerHTML = hall.records.map(r => `
${esc(r['使用事项'] || '未填写使用事项')} ${esc(r['使用场地'] || '')}

${esc(r['日期'] || '')} ${esc(r['时间'] || '')} · ${esc(r['使用单位'] || '')}

参加人数:${esc(r['参加人数'] || '—')};赋能部值班:${esc(r['赋能部值班人员及联系方式'] || '—')}

${r['备注'] ? `

备注:${esc(r['备注'])}

` : ''}${r['使用单位联系人及联系方式'] ? `

联系人:${esc(r['使用单位联系人及联系方式'])}

` : ''}
`).join('') || '
登记表暂无数据。
'; } else { const data = await api(`/center/items?q=${encodeURIComponent($('#center-item-q').value)}`); $('#center-check-status').textContent = `${data.day} · ${data.checked_today ? '今日清点已完成' : '今日待清点,请逐项核对实际在库数量'}`; @@ -1586,9 +1594,13 @@ $$('[data-center-tab]').forEach(b => b.classList.toggle('active', b === button)); $('#center-records').classList.toggle('hidden', centerTab !== 'records'); $('#center-assets').classList.toggle('hidden', centerTab !== 'assets'); + $('#center-hall').classList.toggle('hidden', centerTab !== 'hall'); loadCenter(); })); $('#center-new').addEventListener('click', () => openActivityForm(null, 'center')); + $('#center-hall-refresh').addEventListener('click', async () => { + try { await api('/center/hall-log?refresh=true'); } finally { await loadCenter(); } + }); function openLoanForm() { centerForm('登记借出', `

这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。

diff --git a/server/center.py b/server/center.py index 32f6734..83806f6 100644 --- a/server/center.py +++ b/server/center.py @@ -260,6 +260,13 @@ def convert_package(raw): def install(app, get_db, current_user, photo_root, visible_clause): + from .hall_log import snapshot as hall_log_snapshot + + @app.get('/api/center/hall-log') + async def hall_log(refresh: bool = False, viewer=Depends(current_user)): + """赋能中心展厅使用登记(实时读取金山文档在线表格)。""" + return await hall_log_snapshot(force=refresh) + @app.post('/api/center/materials') async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)): raw=bytearray() diff --git a/server/hall_log.py b/server/hall_log.py new file mode 100644 index 0000000..ae2a3f1 --- /dev/null +++ b/server/hall_log.py @@ -0,0 +1,130 @@ +"""赋能中心展厅使用登记:实时读取金山文档在线表格。""" +from __future__ import annotations + +import asyncio +import json +import os +import shutil +import time +import urllib.request +from typing import Any + + +DEFAULT_LINK_ID = 'cnC7HwRAxKf9' +ENDPOINT = 'https://mcp-center.wps.cn/skill_hub/api/v1/tool' +CACHE_TTL_SECONDS = 60 +MAX_ROWS = 500 +FIELDS = ['序号', '日期', '时间', '使用场地', '参加人数', '使用事项', '使用单位', '使用单位联系人及联系方式', '赋能部值班人员及联系方式', '备注'] +_cache: dict[str, Any] = {'fetched_at': 0.0, 'payload': None, 'error': None} +_lock = asyncio.Lock() + + +def _cli_path() -> str | None: + return shutil.which('kdocs-cli') or (r'C:\Users\ASUS\AppData\Local\kdocs-cli\kdocs-cli.exe' if os.name == 'nt' else None) + + +def _call_tool(tool: str, args: dict, token: str | None) -> dict: + body = json.dumps({'tool': tool, 'args': args}, ensure_ascii=False).encode('utf-8') + headers = {'Content-Type': 'application/json'} + if token: + headers['Authorization'] = f'Bearer {token}' + request = urllib.request.Request(ENDPOINT, data=body, headers=headers, method='POST') + with urllib.request.urlopen(request, timeout=15) as response: + payload = json.loads(response.read().decode('utf-8')) + if isinstance(payload, dict) and payload.get('code') not in (None, 0): + raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}") + return payload + + +def _parse_grid(cells: list[dict], row_to: int, col_to: int) -> list[list[str]]: + grid = [['' for _ in range(col_to + 1)] for _ in range(row_to + 1)] + for cell in cells: + row, col = cell.get('rowFrom', 0), cell.get('colFrom', 0) + if row <= row_to and col <= col_to: + grid[row][col] = str(cell.get('cellText', '') or '').strip() + return grid + + +def fetch_rows(link_id: str = DEFAULT_LINK_ID) -> list[dict[str, str]]: + """读取展厅使用登记表,返回去掉空行的记录列表。""" + token = os.getenv('KINGSOFT_DOCS_TOKEN') or None + cli = _cli_path() + sheets = _call_tool('sheet.get_sheets_info', {'link_id': link_id}, token) + info = sheets['data']['detail']['sheetsInfo'][0] + sheet_id = info['sheetId'] + row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS) + col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1) + data = _call_tool('sheet.get_range_data', {'link_id': link_id, 'worksheet_id': sheet_id, + 'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}}, token) + 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:]: + 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()): + records.append(values) + return records + + +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) + if payload.get('code') != 0: + raise RuntimeError(f"金山文档接口返回 {payload.get('code')}: {payload.get('message')}") + info = payload['data']['detail']['sheetsInfo'][0] + sheet_id = info['sheetId'] + row_to = min(info.get('rowTo', 0), 1 + MAX_ROWS) + col_to = min(info.get('colTo', len(FIELDS) - 1), len(FIELDS) - 1) + args = {'link_id': link_id, 'worksheet_id': sheet_id, 'range': {'rowFrom': 0, 'rowTo': row_to, 'colFrom': 0, 'colTo': col_to}} + data_raw = _run_cli(cli, None, ['sheet', 'get-range-data', json.dumps(args, ensure_ascii=False)]) + data = json.loads(data_raw) + if data.get('code') != 0: + raise RuntimeError(f"金山文档接口返回 {data.get('code')}: {data.get('message')}") + 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:]: + 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()): + records.append(values) + return records + + +def _run_cli(cli: str, link_id: str | None, command: list[str] | None = None) -> str: + import subprocess + args = [cli] + if command: + args.extend(command) + else: + args.extend(['sheet', 'get-sheets-info', json.dumps({'link_id': link_id}, ensure_ascii=False)]) + completed = subprocess.run(args, capture_output=True, timeout=20) + if completed.returncode != 0: + raise RuntimeError(f'金山文档命令行工具调用失败: {completed.stderr.decode("utf-8", "ignore").strip()[:200]}') + return completed.stdout.decode('utf-8', 'ignore') + + +async def snapshot(force: bool = False) -> dict: + """带 60 秒缓存的登记表快照,避免每次页面刷新都请求外部接口。""" + async with _lock: + now = time.monotonic() + if not force and _cache['payload'] is not None and now - _cache['fetched_at'] < CACHE_TTL_SECONDS: + return _cache['payload'] + link_id = os.getenv('WORKLOG_HALL_LOG_LINK_ID') or DEFAULT_LINK_ID + try: + token = os.getenv('KINGSOFT_DOCS_TOKEN') + if token: + rows = await asyncio.to_thread(fetch_rows, link_id) + else: + rows = await asyncio.to_thread(fetch_via_cli, link_id) + payload = {'ok': True, 'fetched_at': int(time.time() * 1000), 'link': f'https://www.kdocs.cn/l/{link_id}', 'records': rows, 'count': len(rows)} + _cache.update(fetched_at=now, payload=payload, error=None) + return payload + except Exception as exc: + message = str(exc) or exc.__class__.__name__ + stale = _cache['payload'] if now - _cache['fetched_at'] < 600 else None + payload = {'ok': False, 'error': message, 'fetched_at': int(time.time() * 1000), 'records': stale['records'] if stale else [], 'count': len(stale['records']) if stale else 0} + _cache.update(fetched_at=now, payload=payload, error=message) + return payload