From c9ec19f7e67f9739c3f7536e52f81dd98010e0c3 Mon Sep 17 00:00:00 2001 From: "mula.liu" Date: Wed, 4 Nov 2026 03:40:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(export):=20=E5=AF=BC=E5=87=BA=E7=9C=9F?= =?UTF-8?q?=E6=AD=A3=E8=B7=9F=E9=9A=8F=E9=A1=B5=E9=9D=A2=E7=AD=9B=E9=80=89?= =?UTF-8?q?=20+=20=E5=91=A8=E6=9C=9F=E6=8E=92=E5=BA=8F=E6=8C=89=20sort=5Fk?= =?UTF-8?q?ey=20+=20=E7=8A=B6=E6=80=81=E5=AD=97=E5=85=B8=E5=8E=BB=E9=87=8D?= =?UTF-8?q?=EF=BC=88=E5=A4=8D=E5=AE=A1=E6=89=B9=E6=AC=A1=20D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 后端 app/routers/export.py: - /export/projects 新增 owner(匹配主/其他负责人,走 all_owners)与 idle_only=1+周期三参 (「只看本周期未更新」,口径同页面 chip,缺周期宁全勿漏); - /export/updates、/export/custom-updates 新增 keyword(内容/摘要/子任务或客户/项目名命中)—— 前端 scopeQuery 本来就一直在发 keyword=,此前被 FastAPI 静默丢弃:屏上过滤过、导出全量; - /export/staff 新增 group / keyword; - 「最近更新周期」改按 Period.sort_key 排序(此前按 period_id 自增,补录历史周会拿错「最近」); - 两处手写 status_names 字典删除,统一用 constants.STATUS_MAP(第三处本来就用,防状态字典漂移); - 死 import 清理:Task / worst_status / _sort_by_entry(custom.py 中无调用者的函数体一并删)。 前端 web/app.js:自研产品导出带负责人与「只看未更新(+顶栏周期)」;人员导出带小组与关键字。 README:API 清单 4 条导出参数更新;导出功能表 3 行按实际联动口径改写。 测试:新增 test_导出精确跟随页面筛选(owner/idle/keyword×3/group);全套 101 passed。 :5173 冒烟 4 条新参数全 200。 --- README.md | 14 +- app/routers/custom.py | 5 - app/routers/export.py | 53 +++-- d.js | 480 ++++++++++++++++++++++++++++++++++++++++ p.js | 480 ++++++++++++++++++++++++++++++++++++++++ tests/test_ai_export.py | 32 +++ web/app.js | 14 +- 7 files changed, 1050 insertions(+), 28 deletions(-) create mode 100644 d.js create mode 100644 p.js diff --git a/README.md b/README.md index feb5f1d..5a011ef 100644 --- a/README.md +++ b/README.md @@ -428,10 +428,10 @@ python scripts/legacy/add_entry_date.py --force # 全部重算 |---|---|---| | 定制项目 | 定制项目明细(含区域、金额、进度、收入确认、入库时间、备注 + 合计行) | `GET /api/export/custom` | | 定制项目 | 定制项目周期记录(「项目总览」工具条「导出周期记录」,按顶栏所选周期 / 月份) | `GET /api/export/custom-updates` | -| 项目管理 | 项目管理清单(分类、负责人、状态、标签、子任务数等) | `GET /api/export/projects` | -| 工作看板 | 本周期(或本月)的执行记录明细(工具栏「导出 Excel」,不受负责人筛选影响) | `GET /api/export/updates` | +| 项目管理 | 项目管理清单(**跟随页面全部筛选**:分类 / 关键字 / 负责人 / 只看未更新(+顶栏周期) / 归档) | `GET /api/export/projects` | +| 工作看板 | 本周期(或本月)的执行记录明细(工具栏「导出 Excel」;跟随顶栏周期与搜索框关键字,不受负责人筛选影响) | `GET /api/export/updates` | | 每周工作 | 重点工作清单(工作内容 / 说明 / 预计完成时间 / 录入周 / 执行状态 / 是否延期 / 结果反馈 / 更新) | `GET /api/export/focus` | -| 人力资源库 | 花名册(含在管 / 定制项目数、合同额、待计收) | `GET /api/export/staff` | +| 人力资源库 | 花名册(跟随小组 / 关键字 / 归档筛选;含在管 / 定制项目数、合同额、待计收) | `GET /api/export/staff` | 导出的 xlsx 带表头样式、冻结首行、自动筛选,金额列按千分位格式;文件名含导出日期。 @@ -681,10 +681,10 @@ GET|PUT /api/settings AI 配置等(GET 需 settings 只读,PU # 导出(均返回 xlsx,筛选口径与页面对应) GET /api/export/custom ?region=&origin=&status=&risk=&accept_plan=&keyword=&archived=false|true|all(末尾带合计行) -GET /api/export/custom-updates ?period_id=|year&month -GET /api/export/projects ?category_id=&keyword=&archived=false|true|all(默认 false,与页面一致;搜归档项目记得 archived=all) -GET /api/export/updates ?period_id=|year&month&project_id= -GET /api/export/staff ?archived=false|true|all +GET /api/export/custom-updates ?period_id=|year&month&keyword= +GET /api/export/projects ?category_id=&keyword=&owner=&idle_only=1&period_id=|year&month&archived=false|true|all(默认 false 与页面一致;owner 匹配主/其他负责人;idle_only 需带周期;搜归档记得 archived=all) +GET /api/export/updates ?period_id=|year&month&project_id=&keyword=(匹配内容/摘要/子任务/项目名) +GET /api/export/staff ?archived=false|true|all&group=&keyword= GET /api/export/focus ?archived=false|true|all&status=&keyword= 导出与接口的差别:范围解析不出周期时导出给全量(让人把数据带走), 接口则返回空(避免把「没数据」看成「全周期数据」) diff --git a/app/routers/custom.py b/app/routers/custom.py index aa90bb8..c88b649 100644 --- a/app/routers/custom.py +++ b/app/routers/custom.py @@ -129,11 +129,6 @@ def _entry_key(cp: CustomProject) -> str: return cp.created_at.strftime("%Y-%m-%d") if cp.created_at else "" -def _sort_by_entry(projects): - """按入库时间倒序(新的在前),两者都取不到的排在最后。""" - return sorted(projects, key=lambda c: (_entry_key(c), c.id), reverse=True) - - def _sort_by_update(projects): """按「更新时间」倒序(最近变动的在前);无更新时间的回落到入库时间。""" def key(c): diff --git a/app/routers/export.py b/app/routers/export.py index 596cf4c..cb7802f 100644 --- a/app/routers/export.py +++ b/app/routers/export.py @@ -24,12 +24,11 @@ from ..models import ( Period, Project, Staff, - Task, Update, WeeklyFocus, + all_owners, ) -from .board import worst_status -from .custom import _sort_by_entry, _sort_by_update +from .custom import _sort_by_update router = APIRouter() @@ -129,6 +128,7 @@ def export_custom_updates( period_id: int | None = None, year: int | None = None, month: int | None = None, + keyword: str | None = None, db: Session = Depends(get_db), ): from .board import resolve_period_ids @@ -138,6 +138,11 @@ def export_custom_updates( if period_ids: q = q.filter(CustomUpdate.period_id.in_(period_ids)) ups = q.order_by(CustomUpdate.period_id, CustomUpdate.custom_project_id).all() + if keyword: + kw = keyword.strip() + ups = [u for u in ups if kw in (u.content or "") or kw in (u.summary or "") + or kw in (u.project.name if u.project else "") + or kw in (u.project.customer if u.project else "")] headers = [ "周期", "项目名称", "区域", "阶段", "执行情况", "进度(%)", @@ -177,6 +182,11 @@ def export_custom_updates( def export_projects( category_id: int | None = None, keyword: str | None = None, + owner: str | None = None, + idle_only: bool = False, + period_id: int | None = None, + year: int | None = None, + month: int | None = None, # 与其余导出统一:不传时默认只导在用项目 archived: str = Query("false", pattern="^(true|false|all)$"), db: Session = Depends(get_db), @@ -191,26 +201,32 @@ def export_projects( if keyword: q = q.filter(Project.name.contains(keyword)) projects = q.order_by(Project.is_key.desc(), Project.name).all() + if owner: + projects = [p for p in projects if owner in all_owners(p.owner, p.other_owners)] + if idle_only: + # 「只看未更新」与页面同口径:指定周期内没有执行记录的项目(周期缺省 = 不过滤,宁全勿漏) + from .board import resolve_period_ids + scope = resolve_period_ids(db, period_id, year, month) + if scope: + busy = {r[0] for r in db.query(Update.project_id).filter(Update.period_id.in_(scope)).distinct()} + projects = [p for p in projects if p.id not in busy] periods = {p.id: p for p in db.query(Period).all()} headers = [ "项目名称", "分类", "负责人", "状态", "重点", "进度(%)", "标签", "子任务数", "执行记录数", "最近更新周期", "归档", ] - status_names = { - "not_started": "未开始", "in_progress": "进行中", "done": "已完成", - "at_risk": "风险", "blocked": "阻塞", "paused": "暂停/终止", - } rows = [] for p in projects: - ups = sorted(p.updates, key=lambda u: u.period_id or 0, reverse=True) + # 最近周期按 sort_key 而不是自增 id:补录的历史周 id 大但时间早(与 weekly/board 同口径) + ups = sorted(p.updates, key=lambda u: periods[u.period_id].sort_key if u.period_id in periods else -1, reverse=True) last = periods.get(ups[0].period_id) if ups else None rows.append( [ p.name, p.category.name if p.category else "未分类", p.owner or "", - status_names.get(p.status, p.status), + STATUS_MAP.get(p.status, (p.status,))[0], "是" if p.is_key else "", round(p.progress or 0, 1), "、".join(t.name for t in p.tags), @@ -237,6 +253,7 @@ def export_updates( year: int | None = None, month: int | None = None, project_id: int | None = None, + keyword: str | None = None, db: Session = Depends(get_db), ): from .board import resolve_period_ids @@ -248,11 +265,11 @@ def export_updates( if project_id: q = q.filter(Update.project_id == project_id) ups = q.order_by(Update.period_id, Update.project_id, Update.id).all() - - status_names = { - "not_started": "未开始", "in_progress": "进行中", "done": "已完成", - "at_risk": "风险", "blocked": "阻塞", "paused": "暂停/终止", - } + if keyword: + # 看板工具栏的搜索框会带着它来导出:内容 / 摘要 / 子任务 / 项目名任一命中 + kw = keyword.strip() + ups = [u for u in ups if kw in (u.content or "") or kw in (u.summary or "") + or kw in (u.task.name if u.task else "") or kw in (u.project.name if u.project else "")] headers = [ "周期", "项目", "子任务", "执行情况", "进度(%)", "状态", "风险", "下一步", "来源", ] @@ -265,7 +282,7 @@ def export_updates( u.task.name if u.task else "", (u.content or "").replace("\n", " ")[:500], u.progress, - status_names.get(u.status, u.status), + STATUS_MAP.get(u.status, (u.status,))[0], (u.risk or "").replace("\n", " ")[:200], (u.next_step or "").replace("\n", " ")[:200], {"import": "导入", "ai": "AI整理", "manual": "手工"}.get(u.source, u.source), @@ -286,6 +303,8 @@ def export_updates( @router.get("/export/staff") def export_staff( archived: str = Query("false", pattern="^(true|false|all)$"), + group: str | None = None, + keyword: str | None = None, db: Session = Depends(get_db), ): from .staff import _workload @@ -295,7 +314,11 @@ def export_staff( q = q.filter(Staff.archived.is_(False)) elif archived == "true": q = q.filter(Staff.archived.is_(True)) + if group: + q = q.filter(Staff.group == group) members = q.order_by(Staff.sort_order, Staff.id).all() + if keyword: + members = [m for m in members if keyword.strip() in (m.name or "")] load = _workload(db) headers = [ diff --git a/d.js b/d.js new file mode 100644 index 0000000..fe66dac --- /dev/null +++ b/d.js @@ -0,0 +1,480 @@ +window.__ModuleLoader__.load({ + id: "@deepseek-ai/dsh-api-workspace-files", + factory: (require) => { + var module = { exports: {} }; + var exports = module.exports; + Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); + require("@deepseek-ai/cordis"); + //#region lib/types/client/change-feed.js + /** + * The follower key of one absolute path. + * @param path - an absolute path from a Host stat or change frame. + * @returns the path with `\\` normalized to `/`. + */ + function keyOf(path) { + return path.replace(/\\/g, "/"); + } + /** Notices of one follower, delivered in order and pulled by its consumer. */ + var Follower = class { + leave; + pending = []; + started = Promise.withResolvers(); + wake; + ended = false; + hostKey; + /** + * Resolves true after the Host acknowledges its subscription, or false if + * this follower ends before acknowledgement. + */ + ready = this.started.promise; + /** + * @param leave - unregisters this follower and its abort listener. + */ + constructor(leave) { + this.leave = leave; + } + /** + * Select the Host path for queued and future changes. + * @param absolutePath - the successful stat's absolute path. + */ + bind(absolutePath) { + this.hostKey = keyOf(absolutePath); + } + /** The Host acknowledged an active subscription and resolved workspace root. */ + start() { + this.started.resolve(true); + } + /** + * Queue one notice. + * @param notice - what the consumer receives next. + * @param key - normalized Host path for the change. + */ + push(notice, key) { + this.pending.push({ + key, + notice + }); + this.wake?.(); + } + /** Deliver what is queued, then finish. */ + end() { + this.ended = true; + this.started.resolve(false); + this.wake?.(); + } + /** Unregister even when the consumer has not started pulling notices. */ + dispose() { + this.leave(); + } + /** @inheritdoc */ + async *[Symbol.asyncIterator]() { + try { + while (true) { + const next = this.pending.shift(); + if (next !== void 0) { + if (next.notice.kind === "refresh" || this.hostKey === void 0 || next.key === this.hostKey) yield next.notice; + continue; + } + if (this.ended) return; + await new Promise((resolve) => { + this.wake = resolve; + }); + this.wake = void 0; + } + } finally { + this.dispose(); + } + } + }; + /** The stream and followers of one Session and requested path. */ + var SessionFeed = class { + onClose; + followers = /* @__PURE__ */ new Set(); + stream; + closed = false; + started = false; + acknowledged = false; + /** + * @param remote - the Remote face carrying `workspaceFiles.changes`. + * @param sessionId - the Session whose filesystem this feed observes. + * @param path - target path submitted to the Host. + * @param after - the previous feed of this target still closing, if any; the stream opens once it has settled. + * @param onClose - called once when the stream is gone, whatever the cause, with the dispose that is closing it. + */ + constructor(remote, sessionId, path, after, onClose) { + this.onClose = onClose; + this.stream = remote.$stream({ + name: `workspace file changes of ${sessionId}`, + open: (signal) => { + this.started = false; + return openAfter(after, () => remote.workspaceFiles.changes(sessionId, path, signal)); + }, + ended: () => /* @__PURE__ */ new Error(`workspace file changes of ${sessionId} ended`) + }); + this.pump(); + } + /** + * Register one resource address before its Host path is known. + * @param follower - receives changes and binds its path after stat. + */ + add(follower) { + this.followers.add(follower); + if (this.started) follower.start(); + } + /** + * Unregister one follower; the last one leaving disposes the stream. + * @param follower - the follower to drop. + */ + remove(follower) { + this.followers.delete(follower); + if (this.followers.size === 0) this.close(); + } + async pump() { + try { + for await (const item of this.stream) { + const frame = item.value; + switch (frame.kind) { + case "ready": + item.accept(); + this.started = true; + for (const follower of this.followers) { + follower.start(); + if (this.acknowledged) follower.push({ kind: "refresh" }, ""); + } + this.acknowledged = true; + break; + case "change": { + const key = keyOf(frame.change.absolutePath); + const notice = editOf(frame.change); + for (const follower of this.followers) follower.push(notice, key); + break; + } + default: assertNever(frame); + } + } + } catch {} finally { + this.close(); + } + } + close() { + if (this.closed) return; + this.closed = true; + const closed = this.stream.dispose(); + for (const follower of this.followers) follower.end(); + this.followers.clear(); + this.onClose(closed); + } + }; + /** + * Open a Host stream once a predecessor has finished closing. + * @param after - the predecessor's dispose, or nothing to wait for. + * @param open - opens the stream. + * @returns the stream's items. + */ + async function* openAfter(after, open) { + await after; + yield* open(); + } + /** + * The write one Host frame reports. + * @param frame - the Host frame. + * @returns the edit notice followers receive. + */ + function editOf(frame) { + return "absent" in frame ? { kind: "absent" } : { + kind: "changed", + version: frame.version + }; + } + function assertNever(frame) { + throw new Error(`Unexpected workspace file watch frame: ${JSON.stringify(frame)}`); + } + /** + * Per-target sharing of the Host's workspace file change streams. + * + * Owned by the provider; one instance serves every session of the Client. + */ + var ChangeFeed = class { + remote; + /** Live feeds only: a feed removes itself when its stream closes. */ + sessions = /* @__PURE__ */ new Map(); + /** Streams still closing, by Session and path; a successor waits for its predecessor. */ + closing = /* @__PURE__ */ new Map(); + /** + * @param remote - the Remote face carrying `$stream` and `workspaceFiles.changes`. + */ + constructor(remote) { + this.remote = remote; + } + /** + * Follow one resource in one session before its Host path is known. + * + * The follower is registered on call, not on first pull. Changes delivered + * to this Client are queued while stat is pending. The first follower starts + * target's local `changes` call. The iterable ends + * when `signal` aborts or when the target stream is gone; ending it early + * (`break`, `return`) unregisters the follower as well, and the last follower + * of a target disposes its stream. Await a true `ready` result before stat + * so the Host subscription is active, then bind each stat's absolute path. Until binding, + * any target invalidation can trigger a retry; after binding, only matching queued + * and live changes pass. + * @param sessionId - the Session providing the file's read authority. + * @param path - requested file path; followers share a stream only for the same Session and path. + * @param signal - ends the follow. + * @returns a single-consumer subscription with Host-path binding and explicit disposal. + */ + follow(sessionId, path, signal) { + const feed = signal.aborted ? void 0 : this.feedOf(sessionId, path); + const leave = () => { + signal.removeEventListener("abort", leave); + follower.end(); + feed?.remove(follower); + }; + const follower = new Follower(leave); + if (feed === void 0) follower.end(); + else { + feed.add(follower); + signal.addEventListener("abort", leave, { once: true }); + } + return follower; + } + /** + * Wait for every stream that is still closing, so an owner tearing down + * leaves no Host stream behind. + * @returns resolves once no stream of this feed is closing. + */ + async settle() { + await Promise.all(this.closing.values()); + } + feedOf(sessionId, path) { + const key = JSON.stringify([sessionId, path]); + const existing = this.sessions.get(key); + if (existing !== void 0) return existing; + const feed = new SessionFeed(this.remote, sessionId, path, this.closing.get(key), (closed) => { + this.sessions.delete(key); + const tracked = closed.then(() => void 0, () => void 0).then(() => { + if (this.closing.get(key) === tracked) this.closing.delete(key); + }); + this.closing.set(key, tracked); + }); + this.sessions.set(key, feed); + return feed; + } + }; + //#endregion + //#region ../../typert/protocol/lib/index.js + /** The one Remote failure class shared by owners, the Gateway, and consumers. */ + /** + * One Remote call failure: a real Error carrying its stable code and typed + * details. Owners throw it at the failure point; the Host Gateway encodes it + * onto the wire unchanged; the Client face rebuilds an instance for the + * `RemoteResult` error branch, so `throw result.error` keeps throw semantics. + * Discrimination is always by `code`, never by instanceof. + */ + var RemoteError = class extends Error { + code; + details; + /** Structural marker: cross-realm/bundle identification never uses instanceof. */ + isDSHRemoteError = true; + /** + * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}. + * @param message - human diagnostic carried across the wire. + * @param details - structured payload typed by the code. + * @param options - standard Error options (`cause` survives in-process only). + */ + constructor(code, message, details, options) { + super(message, options); + this.code = code; + this.details = details; + this.name = "RemoteError"; + } + }; + //#endregion + //#region ../../util/workspace-path/lib/index.js + /** + * The `dsh-resource://file/…` address grammar: how a file is named across the + * Sidebar and the resource model, built and parsed without touching a + * filesystem. + * @module + */ + /** The scheme and type every file address opens with. */ + const FILE_ADDRESS_PREFIX = "dsh-resource://file/"; + /** Whether a decoded first path segment is a Windows drive (`C:`). */ + function isDriveSegment(segment) { + return segment !== void 0 && /^[A-Za-z]:$/.test(segment); + } + /** + * Read a file address back into its parts without resolving `.` or `..`. + * Query and fragment suffixes are ignored; encoded path segments are decoded. + * @param address - a candidate address. + * @returns the parts, or `undefined` when the string is not a `dsh-resource://file/` URI in a known scope with a path, or a segment is not validly encoded. + */ + function parseFileAddress(address) { + try { + if (!address.startsWith(FILE_ADDRESS_PREFIX)) return void 0; + const end = address.search(/[?#]/); + const [scope, ...rest] = address.slice(20, end === -1 ? void 0 : end).split("/"); + if (scope === "session") { + const [id, ...segments] = rest; + if (id === void 0 || id === "" || segments.length === 0) return void 0; + return { + scope, + sessionId: decodeURIComponent(id), + path: segments.map(decodeURIComponent).join("/") + }; + } + if (scope === "absolute") { + const unc = rest[0] === "" && rest.length > 1; + const segments = (unc ? rest.slice(1) : rest).map(decodeURIComponent); + if (segments.length === 0 || segments[0] === "") return void 0; + if (unc) return { + scope, + path: `//${segments.join("/")}` + }; + return { + scope, + path: isDriveSegment(segments[0]) ? segments.join("/") : `/${segments.join("/")}` + }; + } + return; + } catch { + return; + } + } + //#endregion + //#region lib/types/client/provider.js + /** + * Build the `file` provider over one Remote face and one change feed. + * @param remote - the Remote face carrying `workspaceFiles.stat`. + * @param changes - target-scoped change streams shared by file resources. + * @returns the provider to register into `ctx.resources`. + */ + function createFileResourceProvider(remote, changes) { + return { + protocol: "file", + async *open(address, { signal }) { + const resolved = resolve(address); + if (!resolved.ok) { + yield resolved; + return; + } + const { sessionId, path } = resolved.value; + const notices = changes.follow(sessionId, path, signal); + const stat = () => remote.workspaceFiles.stat(sessionId, path, signal); + const aborted = () => signal.aborted; + let current; + try { + if (!await notices.ready) { + if (aborted()) return; + const result = await stat(); + if (!aborted()) yield result; + return; + } + if (aborted()) return; + const first = await stat(); + if (aborted()) return; + if (first.ok) { + notices.bind(first.value.absolutePath); + current = first.value; + yield { + ok: true, + value: current + }; + } else yield first; + for await (const notice of notices) { + if (aborted()) return; + if (current === void 0) { + if (notice.kind === "absent") continue; + } else if (notice.kind === "changed") { + if (notice.version === current.version) continue; + } + const again = await stat(); + if (aborted()) return; + if (!again.ok) { + current = void 0; + yield again; + continue; + } + notices.bind(again.value.absolutePath); + current = again.value; + yield { + ok: true, + value: current + }; + } + } finally { + notices.dispose(); + } + } + }; + } + /** + * Resolve one address to the Host call it stands for, or to the failure frame it earns. + * @param address - the full address, scheme included. + * @returns the Host file, or the `unsupported-address` / `unknown-workspace` failure. + */ + function resolve(address) { + const parsed = parseFileAddress(address); + if (parsed === void 0) return { + ok: false, + error: unsupportedAddress(address) + }; + if (parsed.scope === "session") return { + ok: true, + value: { + sessionId: parsed.sessionId, + path: parsed.path + } + }; + return { + ok: false, + error: unknownWorkspace(address) + }; + } + /** + * The failure frame's error for an address this provider does not serve. + * @param address - the offending address. + * @returns the typed error. + */ + function unsupportedAddress(address) { + return new RemoteError("workspace-file/unsupported-address", `${address} is not a dsh-resource://file/session// or dsh-resource://file/absolute/ address`, { address }); + } + /** + * The failure frame's error for an absolute address with no Session. + * @param address - the offending address. + * @returns the typed error. + */ + function unknownWorkspace(address) { + return new RemoteError("workspace-file/unknown-workspace", `${address} requires a dsh-resource://file/session// address`, { address }); + } + //#endregion + //#region lib/types/client/index.js + /** Required browser services: the resource model, the Remote carrier and its namespace. */ + const inject = [ + "resources", + "remote", + "remote.workspaceFiles" + ]; + /** + * Client plugin body: register the `file` provider for this plugin's lifetime. + * @param ctx - client root context carrying `resources` and the Remote face. + */ + function apply(ctx) { + const changes = new ChangeFeed(ctx.remote); + const provider = createFileResourceProvider(ctx.remote, changes); + ctx.effect(() => { + const release = ctx.resources.register(provider); + return async () => { + release(); + await changes.settle(); + }; + }, "workspace-files: file resource provider"); + } + //#endregion + exports.apply = apply; + exports.inject = inject; + return module.exports; + } +}); +; +//# sourceMappingURL=??@deepseek-ai/dsh-api-workspace-files/client.js.map&rev=6c462da1fc74 diff --git a/p.js b/p.js new file mode 100644 index 0000000..fe66dac --- /dev/null +++ b/p.js @@ -0,0 +1,480 @@ +window.__ModuleLoader__.load({ + id: "@deepseek-ai/dsh-api-workspace-files", + factory: (require) => { + var module = { exports: {} }; + var exports = module.exports; + Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); + require("@deepseek-ai/cordis"); + //#region lib/types/client/change-feed.js + /** + * The follower key of one absolute path. + * @param path - an absolute path from a Host stat or change frame. + * @returns the path with `\\` normalized to `/`. + */ + function keyOf(path) { + return path.replace(/\\/g, "/"); + } + /** Notices of one follower, delivered in order and pulled by its consumer. */ + var Follower = class { + leave; + pending = []; + started = Promise.withResolvers(); + wake; + ended = false; + hostKey; + /** + * Resolves true after the Host acknowledges its subscription, or false if + * this follower ends before acknowledgement. + */ + ready = this.started.promise; + /** + * @param leave - unregisters this follower and its abort listener. + */ + constructor(leave) { + this.leave = leave; + } + /** + * Select the Host path for queued and future changes. + * @param absolutePath - the successful stat's absolute path. + */ + bind(absolutePath) { + this.hostKey = keyOf(absolutePath); + } + /** The Host acknowledged an active subscription and resolved workspace root. */ + start() { + this.started.resolve(true); + } + /** + * Queue one notice. + * @param notice - what the consumer receives next. + * @param key - normalized Host path for the change. + */ + push(notice, key) { + this.pending.push({ + key, + notice + }); + this.wake?.(); + } + /** Deliver what is queued, then finish. */ + end() { + this.ended = true; + this.started.resolve(false); + this.wake?.(); + } + /** Unregister even when the consumer has not started pulling notices. */ + dispose() { + this.leave(); + } + /** @inheritdoc */ + async *[Symbol.asyncIterator]() { + try { + while (true) { + const next = this.pending.shift(); + if (next !== void 0) { + if (next.notice.kind === "refresh" || this.hostKey === void 0 || next.key === this.hostKey) yield next.notice; + continue; + } + if (this.ended) return; + await new Promise((resolve) => { + this.wake = resolve; + }); + this.wake = void 0; + } + } finally { + this.dispose(); + } + } + }; + /** The stream and followers of one Session and requested path. */ + var SessionFeed = class { + onClose; + followers = /* @__PURE__ */ new Set(); + stream; + closed = false; + started = false; + acknowledged = false; + /** + * @param remote - the Remote face carrying `workspaceFiles.changes`. + * @param sessionId - the Session whose filesystem this feed observes. + * @param path - target path submitted to the Host. + * @param after - the previous feed of this target still closing, if any; the stream opens once it has settled. + * @param onClose - called once when the stream is gone, whatever the cause, with the dispose that is closing it. + */ + constructor(remote, sessionId, path, after, onClose) { + this.onClose = onClose; + this.stream = remote.$stream({ + name: `workspace file changes of ${sessionId}`, + open: (signal) => { + this.started = false; + return openAfter(after, () => remote.workspaceFiles.changes(sessionId, path, signal)); + }, + ended: () => /* @__PURE__ */ new Error(`workspace file changes of ${sessionId} ended`) + }); + this.pump(); + } + /** + * Register one resource address before its Host path is known. + * @param follower - receives changes and binds its path after stat. + */ + add(follower) { + this.followers.add(follower); + if (this.started) follower.start(); + } + /** + * Unregister one follower; the last one leaving disposes the stream. + * @param follower - the follower to drop. + */ + remove(follower) { + this.followers.delete(follower); + if (this.followers.size === 0) this.close(); + } + async pump() { + try { + for await (const item of this.stream) { + const frame = item.value; + switch (frame.kind) { + case "ready": + item.accept(); + this.started = true; + for (const follower of this.followers) { + follower.start(); + if (this.acknowledged) follower.push({ kind: "refresh" }, ""); + } + this.acknowledged = true; + break; + case "change": { + const key = keyOf(frame.change.absolutePath); + const notice = editOf(frame.change); + for (const follower of this.followers) follower.push(notice, key); + break; + } + default: assertNever(frame); + } + } + } catch {} finally { + this.close(); + } + } + close() { + if (this.closed) return; + this.closed = true; + const closed = this.stream.dispose(); + for (const follower of this.followers) follower.end(); + this.followers.clear(); + this.onClose(closed); + } + }; + /** + * Open a Host stream once a predecessor has finished closing. + * @param after - the predecessor's dispose, or nothing to wait for. + * @param open - opens the stream. + * @returns the stream's items. + */ + async function* openAfter(after, open) { + await after; + yield* open(); + } + /** + * The write one Host frame reports. + * @param frame - the Host frame. + * @returns the edit notice followers receive. + */ + function editOf(frame) { + return "absent" in frame ? { kind: "absent" } : { + kind: "changed", + version: frame.version + }; + } + function assertNever(frame) { + throw new Error(`Unexpected workspace file watch frame: ${JSON.stringify(frame)}`); + } + /** + * Per-target sharing of the Host's workspace file change streams. + * + * Owned by the provider; one instance serves every session of the Client. + */ + var ChangeFeed = class { + remote; + /** Live feeds only: a feed removes itself when its stream closes. */ + sessions = /* @__PURE__ */ new Map(); + /** Streams still closing, by Session and path; a successor waits for its predecessor. */ + closing = /* @__PURE__ */ new Map(); + /** + * @param remote - the Remote face carrying `$stream` and `workspaceFiles.changes`. + */ + constructor(remote) { + this.remote = remote; + } + /** + * Follow one resource in one session before its Host path is known. + * + * The follower is registered on call, not on first pull. Changes delivered + * to this Client are queued while stat is pending. The first follower starts + * target's local `changes` call. The iterable ends + * when `signal` aborts or when the target stream is gone; ending it early + * (`break`, `return`) unregisters the follower as well, and the last follower + * of a target disposes its stream. Await a true `ready` result before stat + * so the Host subscription is active, then bind each stat's absolute path. Until binding, + * any target invalidation can trigger a retry; after binding, only matching queued + * and live changes pass. + * @param sessionId - the Session providing the file's read authority. + * @param path - requested file path; followers share a stream only for the same Session and path. + * @param signal - ends the follow. + * @returns a single-consumer subscription with Host-path binding and explicit disposal. + */ + follow(sessionId, path, signal) { + const feed = signal.aborted ? void 0 : this.feedOf(sessionId, path); + const leave = () => { + signal.removeEventListener("abort", leave); + follower.end(); + feed?.remove(follower); + }; + const follower = new Follower(leave); + if (feed === void 0) follower.end(); + else { + feed.add(follower); + signal.addEventListener("abort", leave, { once: true }); + } + return follower; + } + /** + * Wait for every stream that is still closing, so an owner tearing down + * leaves no Host stream behind. + * @returns resolves once no stream of this feed is closing. + */ + async settle() { + await Promise.all(this.closing.values()); + } + feedOf(sessionId, path) { + const key = JSON.stringify([sessionId, path]); + const existing = this.sessions.get(key); + if (existing !== void 0) return existing; + const feed = new SessionFeed(this.remote, sessionId, path, this.closing.get(key), (closed) => { + this.sessions.delete(key); + const tracked = closed.then(() => void 0, () => void 0).then(() => { + if (this.closing.get(key) === tracked) this.closing.delete(key); + }); + this.closing.set(key, tracked); + }); + this.sessions.set(key, feed); + return feed; + } + }; + //#endregion + //#region ../../typert/protocol/lib/index.js + /** The one Remote failure class shared by owners, the Gateway, and consumers. */ + /** + * One Remote call failure: a real Error carrying its stable code and typed + * details. Owners throw it at the failure point; the Host Gateway encodes it + * onto the wire unchanged; the Client face rebuilds an instance for the + * `RemoteResult` error branch, so `throw result.error` keeps throw semantics. + * Discrimination is always by `code`, never by instanceof. + */ + var RemoteError = class extends Error { + code; + details; + /** Structural marker: cross-realm/bundle identification never uses instanceof. */ + isDSHRemoteError = true; + /** + * @param code - stable failure code declared in {@link RemoteErrorDetailsMap}. + * @param message - human diagnostic carried across the wire. + * @param details - structured payload typed by the code. + * @param options - standard Error options (`cause` survives in-process only). + */ + constructor(code, message, details, options) { + super(message, options); + this.code = code; + this.details = details; + this.name = "RemoteError"; + } + }; + //#endregion + //#region ../../util/workspace-path/lib/index.js + /** + * The `dsh-resource://file/…` address grammar: how a file is named across the + * Sidebar and the resource model, built and parsed without touching a + * filesystem. + * @module + */ + /** The scheme and type every file address opens with. */ + const FILE_ADDRESS_PREFIX = "dsh-resource://file/"; + /** Whether a decoded first path segment is a Windows drive (`C:`). */ + function isDriveSegment(segment) { + return segment !== void 0 && /^[A-Za-z]:$/.test(segment); + } + /** + * Read a file address back into its parts without resolving `.` or `..`. + * Query and fragment suffixes are ignored; encoded path segments are decoded. + * @param address - a candidate address. + * @returns the parts, or `undefined` when the string is not a `dsh-resource://file/` URI in a known scope with a path, or a segment is not validly encoded. + */ + function parseFileAddress(address) { + try { + if (!address.startsWith(FILE_ADDRESS_PREFIX)) return void 0; + const end = address.search(/[?#]/); + const [scope, ...rest] = address.slice(20, end === -1 ? void 0 : end).split("/"); + if (scope === "session") { + const [id, ...segments] = rest; + if (id === void 0 || id === "" || segments.length === 0) return void 0; + return { + scope, + sessionId: decodeURIComponent(id), + path: segments.map(decodeURIComponent).join("/") + }; + } + if (scope === "absolute") { + const unc = rest[0] === "" && rest.length > 1; + const segments = (unc ? rest.slice(1) : rest).map(decodeURIComponent); + if (segments.length === 0 || segments[0] === "") return void 0; + if (unc) return { + scope, + path: `//${segments.join("/")}` + }; + return { + scope, + path: isDriveSegment(segments[0]) ? segments.join("/") : `/${segments.join("/")}` + }; + } + return; + } catch { + return; + } + } + //#endregion + //#region lib/types/client/provider.js + /** + * Build the `file` provider over one Remote face and one change feed. + * @param remote - the Remote face carrying `workspaceFiles.stat`. + * @param changes - target-scoped change streams shared by file resources. + * @returns the provider to register into `ctx.resources`. + */ + function createFileResourceProvider(remote, changes) { + return { + protocol: "file", + async *open(address, { signal }) { + const resolved = resolve(address); + if (!resolved.ok) { + yield resolved; + return; + } + const { sessionId, path } = resolved.value; + const notices = changes.follow(sessionId, path, signal); + const stat = () => remote.workspaceFiles.stat(sessionId, path, signal); + const aborted = () => signal.aborted; + let current; + try { + if (!await notices.ready) { + if (aborted()) return; + const result = await stat(); + if (!aborted()) yield result; + return; + } + if (aborted()) return; + const first = await stat(); + if (aborted()) return; + if (first.ok) { + notices.bind(first.value.absolutePath); + current = first.value; + yield { + ok: true, + value: current + }; + } else yield first; + for await (const notice of notices) { + if (aborted()) return; + if (current === void 0) { + if (notice.kind === "absent") continue; + } else if (notice.kind === "changed") { + if (notice.version === current.version) continue; + } + const again = await stat(); + if (aborted()) return; + if (!again.ok) { + current = void 0; + yield again; + continue; + } + notices.bind(again.value.absolutePath); + current = again.value; + yield { + ok: true, + value: current + }; + } + } finally { + notices.dispose(); + } + } + }; + } + /** + * Resolve one address to the Host call it stands for, or to the failure frame it earns. + * @param address - the full address, scheme included. + * @returns the Host file, or the `unsupported-address` / `unknown-workspace` failure. + */ + function resolve(address) { + const parsed = parseFileAddress(address); + if (parsed === void 0) return { + ok: false, + error: unsupportedAddress(address) + }; + if (parsed.scope === "session") return { + ok: true, + value: { + sessionId: parsed.sessionId, + path: parsed.path + } + }; + return { + ok: false, + error: unknownWorkspace(address) + }; + } + /** + * The failure frame's error for an address this provider does not serve. + * @param address - the offending address. + * @returns the typed error. + */ + function unsupportedAddress(address) { + return new RemoteError("workspace-file/unsupported-address", `${address} is not a dsh-resource://file/session// or dsh-resource://file/absolute/ address`, { address }); + } + /** + * The failure frame's error for an absolute address with no Session. + * @param address - the offending address. + * @returns the typed error. + */ + function unknownWorkspace(address) { + return new RemoteError("workspace-file/unknown-workspace", `${address} requires a dsh-resource://file/session// address`, { address }); + } + //#endregion + //#region lib/types/client/index.js + /** Required browser services: the resource model, the Remote carrier and its namespace. */ + const inject = [ + "resources", + "remote", + "remote.workspaceFiles" + ]; + /** + * Client plugin body: register the `file` provider for this plugin's lifetime. + * @param ctx - client root context carrying `resources` and the Remote face. + */ + function apply(ctx) { + const changes = new ChangeFeed(ctx.remote); + const provider = createFileResourceProvider(ctx.remote, changes); + ctx.effect(() => { + const release = ctx.resources.register(provider); + return async () => { + release(); + await changes.settle(); + }; + }, "workspace-files: file resource provider"); + } + //#endregion + exports.apply = apply; + exports.inject = inject; + return module.exports; + } +}); +; +//# sourceMappingURL=??@deepseek-ai/dsh-api-workspace-files/client.js.map&rev=6c462da1fc74 diff --git a/tests/test_ai_export.py b/tests/test_ai_export.py index 04ace1a..1ffd9b3 100644 --- a/tests/test_ai_export.py +++ b/tests/test_ai_export.py @@ -364,3 +364,35 @@ def test_项目导出含归档开关与统计列(h): assert "导出-已归档项目" not in names _, rows = _sheet(h.admin.get("/api/export/projects", params={"keyword": "归档", "archived": "all"})) assert [r[0] for r in rows[3:]] == ["导出-已归档项目"] # 搜归档项目要显式放开归档口径 + +def test_导出精确跟随页面筛选(h): + """导出参数必须接得住页面全部筛选(README「导出会带上页面当前的筛选条件」): + 自研导出补负责人 / 只看未更新,人员导出补小组 / 关键字,执行记录导出认关键字。""" + def names(path, **params): + _, rows = _sheet(h.admin.get(path, params=params)) + return [r[0] for r in rows[3:]] # 前两行标题/时间,第 3 行表头,之后是数据 + + pid = h.today_period_id + a = h.project("张三点甲", owners=["张三"]) + h.project("张王共管乙", owners=["张三", "王五"]) + h.project("李四丙", owners=["李四"]) + h.update(a["id"], pid, content="本周干了大事") + + assert set(names("/api/export/projects", owner="张三")) == {"张三点甲", "张王共管乙"} + assert names("/api/export/projects", owner="李四") == ["李四丙"] + idle = set(names("/api/export/projects", idle_only="true", period_id=pid)) + assert "李四丙" in idle and "张三点甲" not in idle # 本期有记录的剔出「未更新」 + + _, upd = _sheet(h.admin.get("/api/export/updates", params={"period_id": pid, "keyword": "没这个"})) + assert upd[3:] == [] + _, upd = _sheet(h.admin.get("/api/export/updates", params={"period_id": pid, "keyword": "干了大事"})) + assert len(upd[3:]) == 1 and upd[3][1] == "张三点甲" + + def staff_names(**params): + _, rows = _sheet(h.admin.get("/api/export/staff", params=params)) + return [r[1] for r in rows[3:]] # 人员表第 0 列是序号 + + h.staff("王五", group="定制产品组") + h.staff("赵六", group="平台组") + assert staff_names(group="定制产品组") == ["王五"] + assert staff_names(keyword="赵六") == ["赵六"] diff --git a/web/app.js b/web/app.js index bdd2fe0..63bba6b 100644 --- a/web/app.js +++ b/web/app.js @@ -1773,9 +1773,16 @@ $("#chkArchived").addEventListener("change", (e) => { state.showArchived = e.target.checked; renderProjects(); }); const bex = $("#btnExportProjects"); if (bex) bex.addEventListener("click", () => { + // 与页面当前筛选完全一致(README:导出带页面筛选):归档 / 分类 / 关键字 / 负责人 / 只看未更新 const q = ["archived=" + (state.showArchived ? "all" : "false")]; if (state.categoryId) q.push("category_id=" + state.categoryId); if (state.keyword) q.push("keyword=" + encodeURIComponent(state.keyword)); + if (state.projOwner) q.push("owner=" + encodeURIComponent(state.projOwner)); + if (state.projIdleOnly) { + q.push("idle_only=1"); + const sc = scopeQuery([]); // 带上顶栏周期,「未更新」才有对照区间 + if (sc) q.push(sc.slice(1)); + } download("/api/export/projects?" + q.join("&")); }); const bn = $("#btnNewProject"); @@ -3572,7 +3579,12 @@ const bn = $("#btnNewStaff"); if (bn) bn.addEventListener("click", () => openStaffDialog(null)); const bex = $("#btnExportStaff"); - if (bex) bex.addEventListener("click", () => download("/api/export/staff?archived=" + state.staffArchived)); + if (bex) bex.addEventListener("click", () => { + const q = ["archived=" + state.staffArchived]; + if (state.staffGroup) q.push("group=" + encodeURIComponent(state.staffGroup)); + if (state.keyword) q.push("keyword=" + encodeURIComponent(state.keyword)); + download("/api/export/staff?" + q.join("&")); + }); host.querySelectorAll("[data-sedit]").forEach((b) => b.addEventListener("click", () => { const m = d.items.find((x) => x.id === Number(b.dataset.sedit));