展厅登记支持在线填写值班人并记录编辑日志
This commit is contained in:
Vendored
+1
@@ -59,6 +59,7 @@ textarea { width: 100%; resize: vertical; }
|
||||
.btn:hover { border-color: var(--primary); color: var(--primary); }
|
||||
.btn.primary { background: var(--primary); border-color: var(--primary); color: var(--primary-ink); }
|
||||
.btn.primary:hover { background: #205640; border-color: #205640; color: #fff; }
|
||||
.btn.small { padding: 4px 12px; font-size: 13px; }
|
||||
.btn.danger { color: var(--bad); border-color: #f2c4c4; }
|
||||
.btn.danger:hover { background: var(--bad-soft); }
|
||||
.btn.ghost { border-color: transparent; background: transparent; }
|
||||
|
||||
Vendored
+2
-2
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WorkLog · 活动记录</title>
|
||||
<meta name="theme-color" content="#f5f7f5" />
|
||||
<link rel="stylesheet" href="/assets/styles.css?v=26" />
|
||||
<link rel="stylesheet" href="/assets/styles.css?v=27" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
@@ -341,7 +341,7 @@
|
||||
|
||||
<div id="toast" class="toast hidden" role="status" aria-live="polite"></div>
|
||||
|
||||
<script src="/js/app.js?v=42"></script>
|
||||
<script src="/js/app.js?v=43"></script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Vendored
+15
-1
@@ -1568,7 +1568,10 @@
|
||||
$('#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>';
|
||||
$('#center-hall-list').innerHTML = hall.records.filter(r => Object.keys(r).some(k => k !== '_row' && r[k])).map(r => {
|
||||
const duty = r['赋能部值班人员及联系方式'] || '';
|
||||
return `<div class="acard" data-hall-row="${r._row}"><b>${esc(r['使用事项'] || '未填写使用事项')}</b> <span class="tag joined">${esc(r['使用场地'] || '')}</span><p class="muted">${esc(r['日期'] || '')} ${esc(r['时间'] || '')} · ${esc(r['使用单位'] || '')}</p><p>参加人数:${esc(r['参加人数'] || '—')}</p><p>值班人:<span class="hall-duty-value">${esc(duty || '—')}</span> <button type="button" class="btn small" data-hall-edit="${r._row}">${duty ? '修改' : '填写'}</button></p>${r['备注'] ? `<p class="muted">备注:${esc(r['备注'])}</p>` : ''}${r['使用单位联系人及联系方式'] ? `<p class="muted">联系人:${esc(r['使用单位联系人及联系方式'])}</p>` : ''}</div>`;
|
||||
}).join('') || '<div class="empty">登记表暂无数据。</div>';
|
||||
} else {
|
||||
const data = await api(`/center/items?q=${encodeURIComponent($('#center-item-q').value)}`);
|
||||
$('#center-check-status').textContent = `${data.day} · ${data.checked_today ? '今日清点已完成' : '今日待清点,请逐项核对实际在库数量'}`;
|
||||
@@ -1601,6 +1604,17 @@
|
||||
$('#center-hall-refresh').addEventListener('click', async () => {
|
||||
try { await api('/center/hall-log?refresh=true'); } finally { await loadCenter(); }
|
||||
});
|
||||
$('#center-hall-list').addEventListener('click', event => {
|
||||
const button = event.target.closest('[data-hall-edit]');
|
||||
if (!button) return;
|
||||
const row = Number(button.dataset.hallEdit);
|
||||
const card = button.closest('[data-hall-row]');
|
||||
const current = card?.querySelector('.hall-duty-value')?.textContent.trim();
|
||||
centerForm('填写值班人',
|
||||
`<p class="muted">填写后同步写入金山文档登记表,服务器会记录编辑人和修改内容。留空提交即清空该格。</p>
|
||||
<label>值班人及联系方式<input name="duty" maxlength="200" value="${esc(current && current !== '—' ? current : '')}" placeholder="例如:张三 13800000000" /></label>`,
|
||||
async f => { await api('/center/hall-log/duty', { method: 'POST', body: { row, value: f.duty.value.trim() } }); toast('已保存并同步到金山文档'); });
|
||||
});
|
||||
function openLoanForm() {
|
||||
centerForm('登记借出',
|
||||
`<p class="muted">这里只保存借出记录,不占用库存,也不要求物品已加入库存清单。借出理由全员可见,联系方式仅本人可见。</p>
|
||||
|
||||
@@ -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