赋能中心新增展厅使用登记实时读取
This commit is contained in:
Vendored
+6
-2
@@ -175,7 +175,7 @@
|
|||||||
<p class="muted" id="center-export-status" role="status"></p>
|
<p class="muted" id="center-export-status" role="status"></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="assets">物品清点与借出</button></div>
|
<div class="tabs center-tabs"><button class="tab active" data-center-tab="records">活动记录</button><button class="tab" data-center-tab="assets">物品清点与借出</button><button class="tab" data-center-tab="hall">展厅使用登记</button></div>
|
||||||
<section id="center-records">
|
<section id="center-records">
|
||||||
<div class="filters center-toolbar"><input id="center-q" type="search" aria-label="搜索活动主题" placeholder="搜索活动主题" /><input id="center-from" type="date" aria-label="活动起始日期" /><input id="center-to" type="date" aria-label="活动截止日期" /><button id="center-new" class="btn primary">+ 记录一楼活动</button></div>
|
<div class="filters center-toolbar"><input id="center-q" type="search" aria-label="搜索活动主题" placeholder="搜索活动主题" /><input id="center-from" type="date" aria-label="活动起始日期" /><input id="center-to" type="date" aria-label="活动截止日期" /><button id="center-new" class="btn primary">+ 记录一楼活动</button></div>
|
||||||
<div id="center-record-list" class="card-list"></div>
|
<div id="center-record-list" class="card-list"></div>
|
||||||
@@ -189,6 +189,10 @@
|
|||||||
<div id="center-loans" class="card-list"></div>
|
<div id="center-loans" class="card-list"></div>
|
||||||
<details class="center-history"><summary>每日清点记录</summary><div id="center-checks"></div></details>
|
<details class="center-history"><summary>每日清点记录</summary><div id="center-checks"></div></details>
|
||||||
</section>
|
</section>
|
||||||
|
<section id="center-hall" class="hidden">
|
||||||
|
<div class="filters center-toolbar"><button id="center-hall-refresh" class="btn">刷新登记数据</button><a id="center-hall-link" class="btn" href="#" target="_blank" rel="noopener">打开金山文档</a><span id="center-hall-status" class="muted" role="status"></span></div>
|
||||||
|
<div id="center-hall-list" class="card-list"></div>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
<main id="timetables-view" class="view hidden">
|
<main id="timetables-view" class="view hidden">
|
||||||
@@ -337,7 +341,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=41"></script>
|
<script src="/js/app.js?v=42"></script>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Vendored
+14
-2
@@ -1538,11 +1538,12 @@
|
|||||||
let centerRecords = [];
|
let centerRecords = [];
|
||||||
function openCenterFromHash() {
|
function openCenterFromHash() {
|
||||||
if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
|
if (state.me && location.hash === '#timetables') { show('timetables'); return true; }
|
||||||
if (!state.me || !['#center', '#center-records', '#center-assets'].includes(location.hash)) return false;
|
if (!state.me || !['#center', '#center-records', '#center-assets', '#center-hall'].includes(location.hash)) return false;
|
||||||
centerTab = location.hash === '#center-assets' ? 'assets' : 'records';
|
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));
|
$$('[data-center-tab]').forEach(button => button.classList.toggle('active', button.dataset.centerTab === centerTab));
|
||||||
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
||||||
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
||||||
|
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
|
||||||
show('center');
|
show('center');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -1561,6 +1562,13 @@
|
|||||||
const data = await api(`/activities?${p}`); centerRecords = data.items;
|
const data = await api(`/activities?${p}`); centerRecords = data.items;
|
||||||
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录活动时请上传照片。</div>';
|
$('#center-record-list').innerHTML = data.items.map(a => activityCard(a)).join('') || '<div class="empty">暂无匹配的一楼活动,记录活动时请上传照片。</div>';
|
||||||
bindCardEvents($('#center-record-list'));
|
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 => `<div class="acard"><b>${esc(r['使用事项'] || '未填写使用事项')}</b> <span class="tag joined">${esc(r['使用场地'] || '')}</span><p class="muted">${esc(r['日期'] || '')} ${esc(r['时间'] || '')} · ${esc(r['使用单位'] || '')}</p><p>参加人数:${esc(r['参加人数'] || '—')};赋能部值班:${esc(r['赋能部值班人员及联系方式'] || '—')}</p>${r['备注'] ? `<p class="muted">备注:${esc(r['备注'])}</p>` : ''}${r['使用单位联系人及联系方式'] ? `<p class="muted">联系人:${esc(r['使用单位联系人及联系方式'])}</p>` : ''}</div>`).join('') || '<div class="empty">登记表暂无数据。</div>';
|
||||||
} else {
|
} else {
|
||||||
const data = await api(`/center/items?q=${encodeURIComponent($('#center-item-q').value)}`);
|
const data = await api(`/center/items?q=${encodeURIComponent($('#center-item-q').value)}`);
|
||||||
$('#center-check-status').textContent = `${data.day} · ${data.checked_today ? '今日清点已完成' : '今日待清点,请逐项核对实际在库数量'}`;
|
$('#center-check-status').textContent = `${data.day} · ${data.checked_today ? '今日清点已完成' : '今日待清点,请逐项核对实际在库数量'}`;
|
||||||
@@ -1586,9 +1594,13 @@
|
|||||||
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b === button));
|
$$('[data-center-tab]').forEach(b => b.classList.toggle('active', b === button));
|
||||||
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
$('#center-records').classList.toggle('hidden', centerTab !== 'records');
|
||||||
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
$('#center-assets').classList.toggle('hidden', centerTab !== 'assets');
|
||||||
|
$('#center-hall').classList.toggle('hidden', centerTab !== 'hall');
|
||||||
loadCenter();
|
loadCenter();
|
||||||
}));
|
}));
|
||||||
$('#center-new').addEventListener('click', () => openActivityForm(null, 'center'));
|
$('#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() {
|
function openLoanForm() {
|
||||||
centerForm('登记借出',
|
centerForm('登记借出',
|
||||||
`<p class="muted">这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。</p>
|
`<p class="muted">这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。</p>
|
||||||
|
|||||||
@@ -260,6 +260,13 @@ def convert_package(raw):
|
|||||||
|
|
||||||
|
|
||||||
def install(app, get_db, current_user, photo_root, visible_clause):
|
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')
|
@app.post('/api/center/materials')
|
||||||
async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)):
|
async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)):
|
||||||
raw=bytearray()
|
raw=bytearray()
|
||||||
|
|||||||
@@ -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
|
||||||
Reference in New Issue
Block a user