Author SHA1 Message Date
wuzilong 1ae8603045 fix: 调整证件提醒标题并取消微信通知的 Web 跳转,以保留纯提醒和小程序入口。 2026-10-30 12:19:01 +08:00
wuzilong cd99b040aa feat: 新增现场日历并将四类日历的起止地改为选填,以支持现场派车记录。 2026-10-30 11:58:48 +08:00
wuzilong 0453e90000 fix: 压缩合同与报价单 PDF 并按实际内容分页,避免文件过大和空白尾页。 2026-10-30 11:40:08 +08:00
wuzilong 120b743a39 chore: 清理废弃工程产物并统一开发规范,以减少仓库噪音。 2026-10-30 10:53:10 +08:00
wuzilongandCursor 13570a2aee fix: exclude off-shelf products from dispatch calendar options.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:58:12 +08:00
wuzilongandCursor 677f1b4c5a chore: refresh graph after other calendar kind.
Mark dispatch calendar other-kind implementation plan complete.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:46:20 +08:00
wuzilongandCursor 09c10fc9d7 feat: add other dispatch calendar tab on web and h5.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:43:30 +08:00
wuzilongandCursor ebe346110a docs(sql): note other kind on dispatch calendar_kind.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:40:40 +08:00
wuzilongandCursor 0eba80d93c feat: allow dispatch calendar kind other on backend.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:36:52 +08:00
wuzilongandCursor 088ed0f871 docs: add implementation plan for other dispatch calendar tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:35:39 +08:00
wuzilongandCursor b0b7e34051 docs: add design for dispatch calendar other kind tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 16:34:00 +08:00
wuzilong 6f4d4d2c59 fix: 统一计划产品计量单位并兼容历史吨单位,避免保存时关联校验失败。 2026-10-29 16:16:25 +08:00
wuzilong 75d7da3d3d chore: 同步代码知识图谱,更新当前模块依赖与报告。 2026-10-29 15:43:43 +08:00
wuzilong 94727cdca9 fix: 保留合同表格调整后的列宽行高并修复导出水印,确保保存与导出布局一致。 2026-10-29 15:43:42 +08:00
wuzilong 027d1751a3 fix: 增加周五证件到期微信汇总通知,保持说明与发送规则一致。 2026-10-29 15:43:30 +08:00
wuzilongandCursor 3aa0f0ff2e feat: 合同富文本改为表头调列宽、首列调行高,避免拖拽把邻列挤窄。
产品表按像素列宽重排,水印改到页面右下角,打开编辑时不再铺满整表绿线。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 11:57:39 +08:00
wuzilongandCursor bde19c0644 feat: 锁定执行中计划并按装卸明细差量归档库存,补齐派车日历数量与酸碱类型。
执行中的运输计划不再随意改单;库存流水记到装卸产品明细;手工派车日历区分酸碱并记录数量。同时收紧合同附件与子表的差量保存,并清理已废弃的 bak 备份目录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 07:59:53 +08:00
wuzilongandCursor e7c1762113 fix: 小程序服务号绑定先打开门户域名再跳转微信授权。
web-view 不能直接打开 open.weixin.qq.com,移动端改为打开已配置的业务域名中转页。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 01:44:40 +08:00
wuzilong 459b820f95 chore: 保存恢复本会话改动前的工作区检查点。 2026-10-27 21:56:45 +08:00
wuzilong d104ef86d2 提交 2026-10-23 23:07:00 +08:00
wuzilong 5b00081d83 提交 2026-10-23 02:46:55 +08:00
wuzilong c279472994 提交 2026-10-22 16:24:46 +08:00
wuzilong 97cbba3b05 提交 2026-10-21 05:04:56 +08:00
wuzilongandCursor cdfdf3c1cf feat: highlight list cells selected for excel copy
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:53:51 +08:00
wuzilongandCursor bf0099c2ad feat: add excel copy toggle beside the list refresh icon
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:46:01 +08:00
wuzilongandCursor 52d94b94dd fix: keep native copy inside text fields during excel selection
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:41:43 +08:00
wuzilongandCursor 9b830bce94 fix: block select-all and header filters while excel copy is on
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:32:30 +08:00
wuzilongandCursor e33a1fbd39 feat: copy visible list cells as an excel sheet from ListTable
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:21:21 +08:00
wuzilongandCursor e1e6c55316 fix: turn bare carriage returns into spaces in excel cells
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:13:52 +08:00
wuzilongandCursor aae4465f6c feat: add pure helpers for list excel row and column copy
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 19:06:54 +08:00
wuzilong 9177e1b7f1 提交“ 2026-10-19 18:28:02 +08:00
wuzilong 5d9fb5ce19 提交“ 2026-10-19 18:27:18 +08:00
wuzilongandCursor 4fd178499e feat(web-admin): unify CRM confirm dialogs for customer and product.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:26:56 +08:00
wuzilongandCursor 5c791b00cb fix(web-admin): align product danger confirm layout with demo B.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:22:34 +08:00
wuzilongandCursor d0b6320c0f chore: update web-admin graphify after product confirm dialog.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:20:48 +08:00
wuzilongandCursor 2df45ebbfa test(web-admin): add product confirm dialog source contract checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:19:54 +08:00
wuzilongandCursor 1b7007c773 feat(web-admin): wire product pages to scheme A/B confirm dialogs.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:16:17 +08:00
wuzilongandCursor 321e0d05fa style(web-admin): style product confirm dialog for scheme A/B.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:14:46 +08:00
wuzilongandCursor 6821cd6a03 feat(web-admin): add product confirm dialog option builder for scheme A/B.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:10:45 +08:00
wuzilongandCursor f404592d44 docs: add mp CRM product confirm dialog implementation plan.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:09:19 +08:00
wuzilongandCursor 3138666ae2 docs: add mp CRM product confirm dialog design (delete B, other A).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:07:45 +08:00
wuzilongandCursor ef71e842ee fix(web-admin): stick category header tools with MpBusinessHeader.
Move expand-all and add into a header actions slot so they remain visible while scrolling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:40:35 +08:00
wuzilongandCursor efe7f77a66 docs: mark product category tree style design as implemented.
Refresh graphify after the mp category list style change.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:37:15 +08:00
wuzilongandCursor 44febe06f0 style(web-admin): restyle mp product category list as unified tree.
Match scheme A indent-expand demo with sanqiang tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:35:07 +08:00
wuzilongandCursor 3c154d69ee fix(web-admin): restore category parent tree-select and delete tip.
Keep Vant sheet/form shell while fixing parent UX and creator-delete feedback.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:32:35 +08:00
wuzilongandCursor 5d943cf76b feat(web-admin): wire category tree list markup for scheme A.
Add expand-all control, row meta, and inline add-child on the mp category page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:26:54 +08:00
wuzilongandCursor ffd25d93e9 feat(web-admin): add product category tree expand helpers.
Centralize expand-id collection and child meta labels for the mp category list.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:24:12 +08:00
wuzilongandCursor 4529a18a8d docs: add implementation plan for mp product category tree style.
Break scheme A restyle into helper tests, list markup, and scoped CSS tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:22:11 +08:00
wuzilongandCursor 9b405a9227 docs: add mp CRM product category tree style design (scheme A).
Record the chosen indent-expand tree list styling for the mobile product-category webview, with the three-option HTML demo for reference.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:21:17 +08:00
wuzilongandCursor 020fbe1b0e feat(web-admin): force a refresh when a newer build is deployed.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 13:53:15 +08:00
wuzilongandCursor a1c00847e5 test: add web-admin stale-tab update checker.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 13:51:48 +08:00
wuzilongandCursor 1f0130de53 test: add web-admin build id and version.json helpers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 13:27:57 +08:00
wuzilongandCursor c527af0b1d docs: record web-admin force-refresh design for stale open tabs.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 13:19:02 +08:00
wuzilongandCursor 181bb808f2 docs: mark ETC/油卡充值 rename design as implemented.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:42:26 +08:00
wuzilongandCursor 95051a08c4 chore(pl): align recharge module comments with 油卡 wording.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:42:21 +08:00
wuzilongandCursor c43f901c36 fix(miniprogram): rename ETC/加油充值申请 to 油卡.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:41:43 +08:00
wuzilongandCursor 4edccef14c fix(web-admin): update vehicle recharge form labels to 油卡.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:41:43 +08:00
wuzilongandCursor d3ac07d5c6 fix(web-admin): rename ETC/加油充值 UI labels to 油卡.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:41:43 +08:00
wuzilongandCursor d3590398db docs(sql): rename ETC/加油充值 menus and dict label to 油卡.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:41:43 +08:00
wuzilongandCursor a5976350ab test: fix vehicle recharge apply fixtures for required fields.
Schema now requires odometerKm and attachmentUrls; update type tests so the suite stays green.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:40:12 +08:00
wuzilongandCursor a3a32ccaaa fix(pl): show recharge type fuel as 油卡 in API labels.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:39:29 +08:00
wuzilongandCursor 658bd3df5c test: expect recharge type fuel label to display as 油卡.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:35:16 +08:00
wuzilongandCursor 5c2879914b docs: add ETC/油卡充值文案改名实现计划。
按展示层替换拆分迁移 SQL、后端 label、web-admin 与小程序任务。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:30:09 +08:00
wuzilongandCursor 19812a1da7 docs: add ETC/油卡充值文案改名设计规格。
明确菜单与充值类型展示「加油→油卡」,存值 fuel 与加油登记模块不动。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:28:08 +08:00
wuzilongandCursor bd5de00645 docs: document CRM contract as mp webview module.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:36:54 +08:00
wuzilongandCursor 778ce0e845 feat(miniprogram): enable CRM contract webview workbench entries.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:36:54 +08:00
wuzilongandCursor a33c2d1f2e feat(web-admin): add page variant for contract form in mp webview.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:36:29 +08:00
wuzilongandCursor 796b434a28 feat(web-admin): add mp webview CRM contract detail actions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:35:02 +08:00
wuzilongandCursor a9ee5d440e feat(web-admin): add mp webview CRM contract list pages.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:32:13 +08:00
wuzilongandCursor e54a168829 feat(web-admin): register /m/crm/contract static routes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:24:54 +08:00
wuzilongandCursor aaaf10678e docs(sql): add miniprogram CRM contract webview menus and role bind.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:24:32 +08:00
wuzilongandCursor b5b3b1f327 feat(web-admin): add mp CRM contract card query helpers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:24:09 +08:00
wuzilongandCursor 8a57bbed30 docs(plan): add mp webview CRM contract implementation plan.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:23:40 +08:00
wuzilongandCursor b8e919cc5e docs: add mp-webview CRM contract design spec.
Capture agreed scope for migrating contract manage/approve into mini program H5 (no price letter this round).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 17:20:22 +08:00
wuzilongandCursor bdf0d9624f docs: document CRM quote as mp webview module.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 16:04:07 +08:00
wuzilongandCursor 458940c665 feat(miniprogram): enable CRM quote webview workbench entries.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 16:04:07 +08:00
wuzilongandCursor d0241ddbd4 feat(web-admin): add mp webview CRM quote version history page.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 16:04:06 +08:00
wuzilongandCursor b9e44bd697 feat(web-admin): add page variant for quote form in mp webview.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 16:03:19 +08:00
wuzilongandCursor eff40b2e8f feat(web-admin): add mp webview CRM quote detail actions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 16:01:42 +08:00
wuzilongandCursor 63f64b1375 feat(web-admin): add mp webview CRM quote list pages.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:55:45 +08:00
wuzilongandCursor f0680544a1 feat(web-admin): register /m/crm/quote static routes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:53:02 +08:00
wuzilongandCursor 9af0425b98 docs(sql): add miniprogram CRM quote webview menus and role bind.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:50:48 +08:00
wuzilongandCursor 007eb2233d feat(web-admin): add mp CRM quote card query helpers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:49:11 +08:00
wuzilongandCursor 121e431f68 docs: add mp-webview CRM quote implementation plan.
Break the quote manage/approve H5 migration into TDD-friendly tasks aligned with the product webview pattern.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:43:16 +08:00
wuzilongandCursor 88cb1a9f62 docs: add mp-webview CRM quote design spec.
Capture agreed scope for migrating quote manage/approve into mini program H5, aligned with the product webview pattern.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:35:21 +08:00
wuzilongandCursor dfd0bb5cc3 fix(web-admin): refresh product form category tree when page reactivated.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 10:11:53 +08:00
wuzilongandCursor 7297db1da1 docs: document CRM product as mp webview module.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 10:05:06 +08:00
wuzilongandCursor 0b0ecf2517 feat(miniprogram): enable CRM product webview workbench entry.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 10:04:50 +08:00
wuzilongandCursor 9de0459edc feat(web-admin): add mp webview CRM product category page.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 10:03:50 +08:00
wuzilongandCursor afad78bf60 feat(web-admin): add page variant for product form in mp webview.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 09:53:50 +08:00
wuzilongandCursor 1d3a4f5155 feat(web-admin): add mp webview CRM product detail actions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 09:51:39 +08:00
wuzilongandCursor 74e2267623 feat(web-admin): add mp webview CRM product list page.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 09:48:25 +08:00
wuzilongandCursor a2769c86dc feat(web-admin): register /m/crm/product static routes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 09:43:35 +08:00
wuzilongandCursor d3a7e3d3fd docs(sql): add miniprogram CRM product webview menus and role bind.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 09:40:37 +08:00
wuzilongandCursor 2f72c29ee7 feat(web-admin): add mp CRM product card query helpers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 09:36:09 +08:00
wuzilong 85559bd414 提交 2026-10-15 08:50:25 +08:00
wuzilongandCursor a07568f546 fix(web-admin): fix stock plan list followStatus funnel and view-only dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 23:40:41 +08:00
wuzilongandCursor c2ddf344dc feat(web-admin): stock inbound/outbound tabs show filtered plan lists
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 23:34:59 +08:00
wuzilongandCursor ce06f0f4e8 feat(web-admin): add stockRole variant to transport plan list page
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 23:32:35 +08:00
wuzilongandCursor c4ee338c3a feat(pl): wire stockRole into plan list, export, and facets
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 23:29:00 +08:00
wuzilongandCursor 63f19d2672 feat(pl): add stockRole filter for plan list by stop customer
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 23:25:44 +08:00
wuzilongandCursor c626023250 feat(miniprogram): split driver plan copy product into three lines
Make copy-to-group text easier to scan: 产品信息 / 计划数量 / 实际数量 as separate lines.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 20:38:17 +08:00
wuzilongandCursor 36d27416d3 docs: specify driver plan copy text product line split
Define three-line product format (产品信息 / 计划数量 / 实际数量) for miniprogram copy-to-group only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-13 20:34:19 +08:00
wuzilongandCursor fc840d1cbb feat(miniprogram): enrich driver plan copy-to-group text
Show vehicle plate and compact product lines under delivery/load
sections segmented by customer, per the 2026-10-12 design.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 22:13:17 +08:00
wuzilongandCursor 272dfc0d5e docs: specify enriched driver plan copy-to-group text format
Capture the confirmed WeChat paste layout (vehicle, compact product lines, load/delivery sections by customer) so implementation can follow a single source of truth.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 22:10:47 +08:00
wuzilongandCursor 6a8cd90b98 feat: cascade column facet options by current list context
Make dynamic column-facet values respect other active filters (Excel-style), with backend facet context helpers, list-page wiring, slip print/sidebar fixes, and refreshed graphify graphs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 22:04:20 +08:00
wuzilong 9643b779a9 提交 2026-10-10 21:12:05 +08:00
wuzilongandCursor 811e6a129f feat(pl): allocate copy_seq_no on first driver plan share-to-group
Add ensure-copy-seq API and miniprogram clipboard prefix so each plan
gets a tenant-scoped fixed serial on first copy; cover allocation with
unit tests and refresh the backend graph.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 12:36:58 +08:00
wuzilongandCursor 5357df1cc2 feat(pl): add pl_plan.copy_seq_no for copy-to-group sequence
Persist a tenant-scoped fixed serial for driver-plan clipboard text;
include migration backfill by create_time.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 12:33:00 +08:00
wuzilong 8da59453b6 提交 2026-10-08 09:57:09 +08:00
wuzilong 318b934b86 提交 2026-10-06 17:55:20 +08:00
wuzilongandCursor 56776bb197 feat: split transport plan list columns into load and delivery product rows
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 09:45:11 +08:00
wuzilongandCursor c19318d0d0 feat: add per-row load and delivery qty helpers for plan list
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 09:36:26 +08:00
wuzilongandCursor 47cd09d1e5 feat: span transport plan list by plan and delivery column props
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 09:32:01 +08:00
wuzilongandCursor e241a17077 feat: flatten transport plan list rows to one product per line
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 09:23:59 +08:00
wuzilong 6abfb6e251 提交 2026-10-05 12:57:51 +08:00
zlwuandCursor 59fafb92d5 docs: add left-sidebar layout implementation plan
Track the approved task breakdown for default LEFT shell, work tabs,
badge styling, and UI spec updates.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 09:48:01 +08:00
zlwuandCursor a4dc83e7e7 docs: document left-sidebar shell as web-admin default
Update Fresh Mint layout section so the runtime shell matches the
approved left-tree + header/worktab/content structure.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 09:48:01 +08:00
zlwuandCursor 3e99904eea style(web-admin): align menu text badge with Fresh Mint danger
Use #dc2626 for sidebar numeric badges so they match the approved
case-style red counters without leaving the design token chain.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 09:48:00 +08:00
zlwuandCursor 60aa9fd28f feat(web-admin): mount work tabs under left-layout header
Assemble header → worktab → content for the non-portal shell and migrate
legacy portal default so the classic sidebar layout is the entry experience.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 09:48:00 +08:00
zlwuandCursor cfe3ff5576 feat(web-admin): default shell to left menu with work tabs
Use LEFT layout as the product default and enable breadcrumbs and
multi-tabs so the classic sidebar shell matches the approved design.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 09:43:13 +08:00
zlwuandCursor 353fefd828 docs: add web-admin left sidebar layout design
Capture the approved shell redesign: default LEFT layout with header,
work tabs, and content, while keeping Fresh Mint tokens and menu badges.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-02 09:37:16 +08:00
zlwu c55f22a603 提交 2026-10-02 09:28:00 +08:00
zlwuandCursor 7f1f60e259 test: fix vehicle recharge submit fixture required fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:17:04 +08:00
zlwuandCursor 4e9c539989 feat(mini): add withdraw on ETC vehicle recharge apply list
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:16:36 +08:00
zlwuandCursor 94e4ef6f8e feat(web-admin): add withdraw action on vehicle recharge apply
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:16:35 +08:00
zlwuandCursor 7a4ecc34e0 fix(api): commit mineVehicles helper required by recharge withdraw
withdraw commit imported should_restrict_mine_vehicles before the helper was on the branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:15:57 +08:00
zlwuandCursor c1113cc2ef test: assert current_node attribute on withdraw apply read model
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:09:19 +08:00
zlwuandCursor d8df5c47e2 feat(api): allow withdraw of in-approval vehicle recharge applies
Applicants can return an in-approval apply to draft while keeping prior approval rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:08:48 +08:00
zlwuandCursor 388eb8cc7e test: add failing cases for vehicle recharge apply withdraw
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:06:12 +08:00
zlwuandCursor c3e1de2793 docs: add implementation plan for vehicle recharge apply withdraw
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:04:08 +08:00
zlwuandCursor 134c541ebc docs: add ETC vehicle recharge apply withdraw design
Capture approved rules for in_approval → draft withdraw on web-admin and miniprogram, aligned with reimbursement withdraw.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 12:01:12 +08:00
zlwu 4f364bc9a0 提交 2026-09-29 07:07:51 +08:00
zlwu c9fb39395c 提交 2026-09-28 10:47:42 +08:00
zlwuandCursor 37a7acf40d chore: update backend graphify after mineVehicles recharge apply
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:39:11 +08:00
zlwuandCursor c70b17f8ca feat(mini): add ETC vehicle recharge apply for drivers and escorts
Add menu SQL, workbench entry, mineVehicles API client, and list/form pages styled like fuel register.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:38:35 +08:00
zlwuandCursor 48aef9f233 feat(api): filter vehicle options by mineVehicles personnel
Limit GET /transport/vehicle to plates linked via pl_vehicle_personnel for the current user.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:36:28 +08:00
zlwuandCursor 0a9d5ba2ed feat(api): accept mineVehicles on vehicle-recharge-apply endpoints
Wire query param through list/get/create/update/submit/cancel for mini-program scope.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:35:59 +08:00
zlwuandCursor 0d2c5a2048 feat(pl): enforce mineVehicles write rules on recharge apply
Reject foreign plates on create and require own applicant for update/submit/cancel when mineVehicles is enabled.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:33:25 +08:00
zlwuandCursor ae1d01bf07 feat(pl): filter recharge applies by mineVehicles plates
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:25:58 +08:00
zlwuandCursor a903206dbe feat(pl): add helper for user personnel vehicle plates
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:23:31 +08:00
zlwuandCursor 6f6793d7d1 docs: add implementation plan for mini ETC recharge apply.
Breaks down mineVehicles backend scope, menus, and miniprogram list/form tasks with TDD steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:21:27 +08:00
zlwuandCursor 3d7d999f48 docs: add miniprogram ETC vehicle recharge apply design.
Captures approved scope for driver/escort mine-vehicles filtering, menu perms, and reuse of existing apply APIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-27 18:18:49 +08:00
zlwuandCursor a3fbb92595 chore: update knowledge graphs after vehicle recharge workflow
Refresh AST graphs for backend/frontend and mark completed implementation plan steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 21:08:05 +08:00
zlwuandCursor 7b99040f9c feat: add vehicle recharge approval workflow and pending UI
Wire configurable workflow config, approval todo with approve/reject/disburse, apply submit and history, and block disburse board for in-approval rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 21:05:57 +08:00
zlwuandCursor a1fbbac370 feat: expose current node name and action type on recharge apply read
Approval UI needs node display name and approve/disburse action without a separate node lookup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 21:05:52 +08:00
zlwuandCursor f80a29fb8d feat: add vehicle recharge approval pending approve reject disburse
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 20:56:14 +08:00
zlwuandCursor ea8c2c0362 feat: add vehicle recharge apply submit and detail approvals
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 20:55:43 +08:00
zlwuandCursor bdd67d44d9 feat: add recharge workflow models and schema statuses
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 20:55:15 +08:00
zlwuandCursor 94dd52832b docs: add vehicle recharge workflow design, plan, and migration SQL
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 20:48:17 +08:00
zlwu b430e75a4b 提交 2026-09-26 11:59:39 +08:00
wuzilongandCursor d17f6c472d chore: update graphify after inventory pound QR popup.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:30:09 +08:00
wuzilongandCursor 0ce896d9cd feat(miniprogram): replace inventory list weigh-slip create with pound QR.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:23:17 +08:00
wuzilongandCursor f2dd16d851 fix(miniprogram): guard pound QR popup load against stale races.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:22:35 +08:00
wuzilongandCursor be0764779c feat(miniprogram): add centered pound QR popup component.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:19:34 +08:00
wuzilongandCursor 35563e9709 feat(miniprogram): add local QR temp-file helper via uqrcodejs.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:16:53 +08:00
wuzilongandCursor 8d0d301ead feat(miniprogram): add local QR temp-file helper via uqrcodejs.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:15:49 +08:00
wuzilongandCursor b1719fab23 feat(miniprogram): add pound QR label helpers and node checks.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:13:08 +08:00
wuzilongandCursor a6e0c4481f docs: add implementation plan for inventory pound QR popup.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:09:55 +08:00
wuzilongandCursor 71f3fde31c docs: add design for miniprogram inventory pound QR popup.
Replace list「生成地磅单」with a centered pound-slip QR dialog aligned to the transport-plan popup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 21:07:04 +08:00
wuzilongandCursor 7d09ebee96 chore: update graphify after attachment image preview rotate/zoom.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 14:33:01 +08:00
wuzilongandCursor b9849f33ae docs(openspec): note image preview rotate/zoom for attachment cards.
Document preview-only rotate and zoom expectations under attachment upload card layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 14:32:55 +08:00
wuzilongandCursor 45327b3acb feat(web-admin): add rotate/zoom/pan to attachment image preview.
Enhance AttachmentUploadField image preview dialog with toolbar controls, wheel zoom, and drag pan; fit-full at 100% zoom after rotate.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 14:29:03 +08:00
wuzilongandCursor 0af792f535 feat(web-admin): add image preview transform helpers for fit/zoom.
Pure functions for AttachmentUploadField image preview rotate/zoom math, with a Node assert script.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 14:23:34 +08:00
wuzilongandCursor 8435836d81 docs: add implementation plan for attachment image preview rotate/zoom.
Break down AttachmentUploadField preview enhancements into helper tests, UI wiring, styles, and manual acceptance checks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 14:19:03 +08:00
wuzilongandCursor 3583e6456b docs: add attachment image preview rotate/zoom design and demo.
Capture the approved AttachmentUploadField preview enhancements (rotate, fit-full, wheel/button zoom, drag pan) before implementation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 14:16:00 +08:00
wuzilongandCursor 65d904fff1 chore: update graphify after archive zip export.
Refresh backend and web-admin graphs after plan-archive ZIP export changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:47:41 +08:00
wuzilongandCursor 2f3756eab8 feat(web-admin): add archive data-and-attachments ZIP export menu.
Extend ListExportDropdown with additional items and wire archive_zip on the plan-archive page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:47:14 +08:00
wuzilongandCursor d5c2e1f1a4 feat(pl): wire archive_zip export format on plan export API.
Reuse archive row building and attach document plus hazard-cert files into a zip response.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:46:52 +08:00
wuzilongandCursor 81e52477de feat(pl): build archive export zip with relative hyperlinks.
Pack archive xlsx plus attachment files under 附件/, with HYPERLINK columns on each plan's first row.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:46:15 +08:00
wuzilongandCursor 7af4d7ac7e feat(pl): collect hazard certs for archive zip export.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:42:44 +08:00
wuzilongandCursor d68a0ef0bd fix(pl): fix FakePlan id for planId export field.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:42:05 +08:00
wuzilongandCursor e9ffa5d042 feat(pl): add archive zip naming helpers and planId on export rows.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:40:04 +08:00
wuzilongandCursor 1c3c0d40b6 docs: add implementation plan for plan-archive attachment ZIP export.
Break work into TDD tasks for zip helpers, hazard cert collection, API wiring, and ListExportDropdown menu items.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:38:51 +08:00
wuzilongandCursor f5b76ef711 docs: add plan-archive data-and-attachments ZIP export design.
Capture brainstorming decisions for coexisting Excel and ZIP export, reference-zip folder layout, document attachments plus hazard certs, and relative-path hyperlinks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 12:36:18 +08:00
wuzilong c270d14057 提交 2026-09-23 12:03:07 +08:00
wuzilongandCursor b15d1ddde3 chore: update graphify after wx-qr web login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:22:42 +08:00
wuzilongandCursor cce8fae673 feat(miniprogram): add web QR phone confirm page for admin login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:21:47 +08:00
wuzilongandCursor 29898a107b feat(web-admin): default login to WeChat QR with password tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:20:11 +08:00
wuzilongandCursor e54c1bdfef chore: untrack web-admin env files force-added in Task 6.
Keep wx-qr encrypt exclude paths in local env files only; they remain gitignored.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:18:36 +08:00
wuzilongandCursor c5a0e17a05 feat(web-admin): add wx-qr create and status API clients.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:18:08 +08:00
wuzilongandCursor 98e31c88b2 feat(api): confirm web QR login from mini program phone auth.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:17:14 +08:00
wuzilongandCursor ec0045d5bf feat(api): add web wx-qr create and status endpoints.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:16:15 +08:00
wuzilongandCursor 22634330d5 feat(wechat): generate unlimited mini program codes for web QR login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:15:15 +08:00
wuzilongandCursor 1e7c8bde3b test(auth): force in-memory backend for wx-qr session unit tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:14:35 +08:00
wuzilongandCursor 56a3311c45 feat(auth): add wx-qr session state machine for web login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 19:55:00 +08:00
wuzilongandCursor 7f2b5d06c1 chore: add wx-qr login config and encrypt exclude paths.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 18:15:27 +08:00
wuzilongandCursor b438495b1d docs: add implementation plan for web-admin WeChat QR login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 18:13:31 +08:00
wuzilongandCursor ef8b59d23c docs: add web-admin WeChat QR phone login design.
Record the shanxia-shell + zkxw-tab dual-mode login approach (mini program code, session poll, phone_no match) with an interactive HTML demo for review.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 18:08:11 +08:00
wuzilong 1ba1f38321 提交 2026-09-18 12:01:13 +08:00
wuzilongandCursor 98531845e4 chore: update graphify after mini phone quick login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:16:25 +08:00
wuzilongandCursor b5a58583bd feat(miniprogram): add phone quick login button on login page.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:15:47 +08:00
wuzilongandCursor 6f39801c63 feat(miniprogram): add wechatLogin API client on user store.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:14:59 +08:00
wuzilongandCursor 713aa700ae feat(api): add mini wechat-login and share JWT issuance with web login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:14:18 +08:00
wuzilongandCursor 7ccd1f553e feat(backend): resolve wechat login user by phone and bind openid.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:12:03 +08:00
wuzilongandCursor 3d003e8d37 feat(backend): add wechat mini auth helpers and user phone lookups.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:09:04 +08:00
wuzilongandCursor 7e7f9226cf feat(config): add WECHAT_MP credentials for mini wechat login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:06:54 +08:00
wuzilongandCursor 2ce31b903f feat(db): add sys_user wx_openid columns for mini phone login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:05:22 +08:00
wuzilongandCursor 53795c535d docs: add miniprogram phone quick login implementation plan.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:04:00 +08:00
wuzilongandCursor 7f3f569722 docs: add miniprogram phone quick login design.
Capture the approved WeChat getPhoneNumber login flow for shanxia mini program, including WECHAT_MP_* config, sys_user openid columns, and parity with password login JWT.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:00:42 +08:00
wuzilong 86694f739f 提交 2026-09-17 09:10:10 +08:00
wuzilongandCursor a0da6427ef chore(miniprogram): update graphify after invoice thumbnails.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:23:55 +08:00
wuzilongandCursor d6fddc666c feat(miniprogram): show linked invoice thumbnails on reimburse detail.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:22:09 +08:00
wuzilongandCursor 0c269b6e73 fix(miniprogram): retry invoice picker load after empty failure.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:20:44 +08:00
wuzilongandCursor ffec3ecd94 feat(miniprogram): show invoice thumbnails in reimburse apply picker.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:17:34 +08:00
wuzilongandCursor 01553ef0f7 style(miniprogram): add invoice thumbnail grid styles for bx.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:15:31 +08:00
wuzilongandCursor 4201d656b1 feat(miniprogram): add invoice thumb helper utilities.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:11:59 +08:00
wuzilongandCursor ea4d990abb docs: add reimburse invoice thumbnail implementation plan.
Break scheme-1 into helper, styles, apply picker, and detail tasks with verification steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:10:25 +08:00
wuzilongandCursor 1af6a944fb docs: add miniprogram reimburse invoice thumbnail design.
Record the approved scheme-1 UI for picker thumbnails, scroll paging, and detail linked-invoice display, with companion HTML demo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:07:35 +08:00
wuzilongandCursor ca0098f6ca feat(web-admin): add mp plan form anchors and polish print customer pick.
Improve the page-variant plan form for WebView and align print customer selection with the mobile demo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 09:35:17 +08:00
wuzilongandCursor bf81d9b77c feat(web-admin): redesign mp transport plan detail sections.
Align mobile detail with demo IA including hazard cert slots and capped footer actions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 09:34:16 +08:00
wuzilongandCursor 8d1d5c19b5 feat(web-admin): redesign mp transport plan list to match demo.
Use dual dropdown filters, richer cards, and a speed dial for create actions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 09:32:47 +08:00
wuzilongandCursor 92bb4bf0d0 feat(web-admin): add mp plan detail action splitter.
Cap the sticky footer at two primary actions and park the rest in a more sheet.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 09:31:43 +08:00
wuzilongandCursor b3ad19f6a9 feat(web-admin): enrich mp plan card with party and follower fields.
List cards need supplier→buyer and follow user to match the approved mobile demo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 09:29:46 +08:00
wuzilongandCursor 8c69a01e16 feat(web-admin): add mp webview sheet and list chrome styles.
Provide shared Bottom Sheet and filter/speed-dial/fab tokens for the transport plan mobile redesign.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 09:27:11 +08:00
wuzilongandCursor 3795fa2b5a docs: add implementation plan for mp plan mobile redesign.
Break the approved WebView UI redesign into sequenced tasks for list, detail, form, print, and paste.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 01:46:49 +08:00
wuzilongandCursor 43f5ae8603 docs: add mobile redesign spec for WebView transport plans.
Capture the approved HTML demo as the UI authority for rewriting /#/m/pl/* without changing ticket or shell architecture.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 01:40:45 +08:00
wuzilongandCursor fe9d30105d docs: describe how to add more miniprogram webview modules.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:48:30 +08:00
wuzilongandCursor bf22c4b031 style(web-admin): format webview plan form and paste helpers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:48:25 +08:00
wuzilongandCursor a382f3e730 feat(web-admin): add mobile paste-create for third-party vehicle bundles.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:47:14 +08:00
wuzilongandCursor 866a87f747 feat(web-admin): add mobile print preview for transport plan slips.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:47:12 +08:00
wuzilongandCursor bc7a1c225a feat(web-admin): reuse plan form as a full-page webview variant.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:47:05 +08:00
wuzilongandCursor 1a5aa1c934 feat(web-admin): add mobile plan detail and shared action guards.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:25:09 +08:00
wuzilongandCursor 17edd7016f feat(web-admin): add mobile card list for transport plans in webview.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:25:09 +08:00
wuzilongandCursor 5220637639 docs(sql): add miniprogram menu for webview transport plan.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:22:12 +08:00
wuzilongandCursor 57a831a36f feat(miniprogram): add reusable web-view shell for H5 business pages.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:22:12 +08:00
wuzilongandCursor 8fbe0679c9 feat(web-admin): add mp webview shell and /m/pl/plan static routes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:21:37 +08:00
wuzilongandCursor c0721786ff feat(web-admin): skip desktop chrome and login page inside mp webview routes.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:15:08 +08:00
wuzilongandCursor 5eb7b0b193 feat(backend): exchange miniprogram webview tickets for JWT sessions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:11:36 +08:00
wuzilongandCursor 98292cb914 fix(backend): consume webview tickets atomically and fail closed on Redis errors.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:07:45 +08:00
wuzilongandCursor 62161e2905 feat(backend): add one-time Redis tickets for miniprogram webview login.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:03:18 +08:00
wuzilongandCursor da7476df5a docs: record miniprogram WebView template and transport plan design.
Capture the approved card-list, ticket-based login, and reusable shell so later modules can follow the same path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 15:50:12 +08:00
wuzilong b7d0d4a4f8 提交 2026-09-14 11:57:58 +08:00
wuzilongandCursor 31d3a044cf feat(miniprogram): add withdraw button on reimburse and advance lists
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:51:10 +08:00
wuzilongandCursor f8c93d2bd6 chore: update graphify after attachment display name feature
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:38:22 +08:00
wuzilongandCursor a1ace0cf9a feat(miniprogram): show remark-based names on reimburse apply attachments
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:32:20 +08:00
wuzilongandCursor f05e353d1e feat(miniprogram): add apply attachment display name helper
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:32:17 +08:00
wuzilongandCursor 76e5d27a79 feat(web-admin): pass remark into reimburse apply attachment UI
Wire addForm.remark into apply upload and viewData.remark into apply attachment readonly on reimburse apply and approve pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:31:00 +08:00
wuzilongandCursor e50d2c27c8 feat(web-admin): show remark-based names on bx attachment cards
Add optional remark prop to BxAttachmentUpload and BxAttachmentReadonly so cards display sanitized remark_index names while download keeps the original fileName.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:30:55 +08:00
wuzilongandCursor a564bfe733 feat(web-admin): add apply attachment display name helper
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:30:16 +08:00
wuzilongandCursor 5d4e1e14ad docs: add plan for reimburse apply attachment display names
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:29:55 +08:00
wuzilongandCursor 6d0668bf58 docs: add design for reimburse apply attachment display names
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:27:10 +08:00
wuzilongandCursor 07f45a1c92 fix(miniprogram): refresh detail after withdraw failure
Also add the bx apply withdraw implementation plan.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:07:44 +08:00
wuzilongandCursor 7a45df9de7 chore: update graphify after bx apply withdraw
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:05:16 +08:00
wuzilongandCursor d2a13bdf87 feat(miniprogram): add advance detail withdraw
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:04:22 +08:00
wuzilongandCursor c1a999e490 feat(miniprogram): add reimburse detail withdraw
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:04:20 +08:00
wuzilongandCursor 904630d695 feat(web-admin): add withdraw on advance apply page
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:03:40 +08:00
wuzilongandCursor 1917661266 feat(web-admin): add withdraw on reimburse apply page
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:03:11 +08:00
wuzilongandCursor d058518e57 feat(bx): wire advance/reimburse withdraw API clients
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:00:54 +08:00
wuzilongandCursor 9d06e1830e feat(bx): add advance apply withdraw API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 09:59:02 +08:00
wuzilongandCursor ac713070ab docs: add design for bx apply withdraw (reimburse + advance)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 09:55:23 +08:00
wuzilong 8c96de2c0c 提交 2026-09-13 13:08:52 +08:00
wuzilongandCursor 499896b29c fix(web-admin): put trip driver/escort on vehicle summary row
Merge「本次安排」into PlVehicleSummaryStrip instead of a separate
row above the vehicle info strip.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 12:29:47 +08:00
wuzilongandCursor c580bdf03f feat(web-admin): show this-trip driver and escort on plan view
Add a「本次安排」row above the vehicle personnel strip so the
selected driver and escort are visible separately from vehicle bindings.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 12:28:04 +08:00
wuzilongandCursor 7f25ff0fc0 docs: add design for trip driver/escort on plan view
Document approved layout: show this-trip driver and escort above
the vehicle personnel strip in the plan detail dialog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 12:27:47 +08:00
wuzilongandCursor 407dd76a6f chore: update graphify after driver-plan feature
Refresh backend AST graph after new driver-plan service and routes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 11:46:03 +08:00
wuzilongandCursor 74ed4ba534 feat(miniprogram): add driver-plan list and receipt pages
Wire workbench menu, login APIs, calendar list without plate
search, and native receipt detail aligned with site-plan shell.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 11:45:43 +08:00
wuzilongandCursor 7f9be18ab6 docs(sql): add mini driver-plan menu and role bindings
Create/reuse 司机 and 押运员 roles and bind the miniprogram
司机运输计划单 menu under 运输管理.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 11:45:43 +08:00
wuzilongandCursor 57ca252f81 feat(pl): add JWT driver-plan routes for miniprogram
Expose history/detail/feedback/attachments under /transport/driver-plan
and exclude the path from API encryption middleware.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 11:44:24 +08:00
wuzilongandCursor 1303fae1e0 feat(pl): add driver-plan service for personnel-scoped history
Resolve plans by linked driver/escort personnel and reuse public
driver page/feedback helpers for login-state miniprogram APIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 11:44:24 +08:00
wuzilongandCursor ca3062b0e2 feat(pl): optional escort selection on transport arrange
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 10:48:23 +08:00
wuzilongandCursor 3dc71788d4 feat(web-admin): link system user on personnel form
Allow binding a login account on driver/escort personnel so
miniprogram driver-plan visibility can resolve by sys_user_id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 10:42:19 +08:00
wuzilongandCursor 26b096ae38 feat(pl): bind sys user on personnel and snapshot selectedEscortId
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 10:37:11 +08:00
wuzilongandCursor 0658090223 feat(pl): add personnel sys_user_id and transport escort columns
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 10:30:49 +08:00
wuzilongandCursor 5102817782 docs: add mini driver transport plan implementation plan
Break the approved driver-plan design into schema, web arrange/escort,
login APIs, menu SQL, and miniprogram list/detail tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 10:26:07 +08:00
wuzilongandCursor 3a70c44508 docs: add mini driver transport plan design spec
Capture approved decisions for miniprogram driver/escort plan list,
escort selection on arrange, and personnel-user linking.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 10:23:34 +08:00
wuzilongandCursor 1c631ccd50 chore: update graphify after pound QR public link
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:45:42 +08:00
wuzilongandCursor ee8bf14eb5 feat(web-admin): add pound QR button on public driver transport page
Show a third footer action that opens the shared weighbridge QR card popup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:42:57 +08:00
wuzilongandCursor ab3a90c3f5 feat(web-admin): append pound QR links in copy-to-driver text
Include multi-line public pound QR URLs after the driver link when dibang slips exist.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:41:41 +08:00
wuzilongandCursor 5b4c1bc991 feat(web-admin): add public pound QR page by inventory id
Drivers can open a standalone link that renders the shared weighbridge QR card.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:38:23 +08:00
wuzilongandCursor d7dec04cb3 refactor(web-admin): extract PoundSlipQrcodeView for shared QR card
Keep admin dialog behavior while enabling public page and driver popup reuse.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:36:21 +08:00
wuzilongandCursor 10183dabc2 feat(backend): expose pound QR items on driver transport page
Enrich inventory links with business type/partner and attach
poundQrcodeItems for the public driver footer button.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:29:03 +08:00
wuzilongandCursor 87ed40512c feat(backend): add public pound-qr endpoint by inventory id
Expose a read-only payload for the shared weighbridge QR card without auth.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:24:09 +08:00
wuzilongandCursor 8994849292 docs: add pound QR public link implementation plan
Break the approved design into backend, shared QR view, public page,
copy-to-driver text, and driver footer tasks with TDD steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:22:05 +08:00
wuzilongandCursor 157ad5e29a docs: add pound QR public link and driver-page entry design
Capture the approved approach for sharing weighbridge slip QR via
public inventory-id URLs, multi-line copy text, and a third driver footer button.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 09:17:12 +08:00
wuzilongandCursor df8c28bd7c docs: add miniprogram transport plan site feedback design
Capture the approved design for 运输计划单 (site record/feedback) in the mini program so implementation can follow a single agreed spec.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 08:30:10 +08:00
wuzilongandCursor d7981eda17 chore: update graphify after deliveryTimes list column
Keep backend and frontend knowledge graphs in sync with the new
plan delivery time filter and list UI wiring.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:31:45 +08:00
wuzilongandCursor 8dc1820622 feat(web-admin): add deliveryTimes column on plan contract-gap list
Filter and display deduped delivery dates beside planDate.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:31:20 +08:00
wuzilongandCursor 754113a6d2 feat(web-admin): add deliveryTimes column on plan archive and cert lists
Match main plan list display and column-header filter behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:31:20 +08:00
wuzilongandCursor afc0b5e1bf feat(web-admin): show deliveryTimes column on transport plan list
Multi-line YYYY-MM-DD with header range filter after planDate.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:25:26 +08:00
wuzilongandCursor fb608cea7f feat(web-admin): add deliveryTimes column filter defs for plan lists
Align query keys with deliveryTimeFrom/To server filters.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:24:27 +08:00
wuzilongandCursor 204b5f48c8 feat(pl): wire deliveryTimeFrom/To through plan list and export
Contract-gap list/export share the same stop-date EXISTS filter.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:23:31 +08:00
wuzilongandCursor 0e3df1f39d feat(pl): expose deliveryTimes on plan list and contract-gap schemas
Populate from delivery stops during attach/gap row build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:20:55 +08:00
wuzilongandCursor 9c5a1cfb8e feat(pl): aggregate unique delivery dates from stop rows
Provide YYYY-MM-DD dedupe helper for plan list deliveryTimes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:08:54 +08:00
wuzilongandCursor efe8aed409 feat(pl): filter plans by delivery-stop date range
Add EXISTS on pl_plan_delivery.delivery_time for list column filters.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:07:23 +08:00
wuzilongandCursor de7d5194ad docs: add implementation plan for plan deliveryTimes column
Break the approved design into TDD tasks across filters, schema,
export, and the four plan-family list pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:05:41 +08:00
wuzilongandCursor cb57a71d2d docs: add design for plan list delivery times column
Capture the approved brainstorm for showing and filtering
deduplicated delivery-stop dates on PL plan family lists.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 21:03:02 +08:00
wuzilong 2dadd34981 提交 2026-09-12 19:42:20 +08:00
wuzilongandCursor fa8ffd5fe7 fix(miniprogram): nudge workbench header content slightly downward
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:24:22 +08:00
wuzilongandCursor b2a29ebd57 fix(miniprogram): remove workbench header subtitle text
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:23:14 +08:00
wuzilongandCursor a9f3443727 fix(miniprogram): prefix workbench title with 山峡化工
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:22:38 +08:00
wuzilongandCursor 25eeb82db0 fix(miniprogram): center-align workbench title and user stack in one row
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:16:04 +08:00
wuzilongandCursor ec2d0cc2ee fix(miniprogram): remove workbench logo; center-align title with welcome line
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:15:54 +08:00
wuzilongandCursor 13a8a0c8df fix(miniprogram): align workbench header logo layout with template classes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:13:57 +08:00
wuzilongandCursor 24572931dc feat(miniprogram): add workbench logo and welcome user stack above logout
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:13:35 +08:00
wuzilongandCursor 7547e4e142 fix(miniprogram): restore workbench green header with full-width right user row
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:10:11 +08:00
wuzilongandCursor 83db2fd996 fix(miniprogram): put workbench user actions on full-width row below title
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:08:16 +08:00
wuzilongandCursor ddff1212ae fix(miniprogram): unify nav headers to dashboard style with tall workbench bar
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:06:51 +08:00
wuzilongandCursor aa2da07c99 fix(miniprogram): left-align headers, raise workbench bar, drop dashboard username
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 19:01:37 +08:00
wuzilongandCursor 335dd842be fix(miniprogram): repair broken bxFormat imports after safe-area wiring
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:57:12 +08:00
wuzilongandCursor ab5aa94ff3 docs: require miniprogram custom header capsule safe area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:55:01 +08:00
wuzilongandCursor 1a97ec954b fix(miniprogram): adapt mp-header for WeChat capsule safe area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:54:57 +08:00
wuzilongandCursor f0d64379a7 fix(miniprogram): adapt bx topbar for WeChat capsule safe area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:54:21 +08:00
wuzilongandCursor 8505115f05 fix(miniprogram): wire db pages to capsule safe-area header
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:53:40 +08:00
wuzilongandCursor b3fc308446 style(miniprogram): adapt db-header for WeChat capsule safe area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:50:46 +08:00
wuzilongandCursor 49ec2418a2 refactor(miniprogram): reuse safe-area CSS builder in applySafeAreaCssVars
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:50:23 +08:00
wuzilongandCursor cfe0f94467 feat(miniprogram): add safe-area CSS vars style builder
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:48:57 +08:00
wuzilongandCursor 0599b7a3a9 docs: add miniprogram header capsule safe-area implementation plan.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:47:35 +08:00
wuzilongandCursor 2866fef5bf docs: add miniprogram header capsule safe-area design (scheme B).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 18:45:39 +08:00
wuzilongandCursor b3640741ef docs: mark ETC-only vehicle recharge plan tasks complete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:50:19 +08:00
wuzilongandCursor 9968fc72a3 docs: add ETC-only vehicle recharge design/plan and refresh graphify
Persist the approved cutover spec and implementation plan; sync graphs after the ETC-only changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:50:12 +08:00
wuzilongandCursor 9a8dd691d8 chore(web-admin): update recharge column filter comments for ETC-only
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:48:17 +08:00
wuzilongandCursor 62d46d6e57 chore: update graphify after ETC-only vehicle recharge cutover
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:48:14 +08:00
wuzilongandCursor f13e18329a fix(web-admin): rename ETC recharge menus and drop fuel type option
Align UI with ETC-only scope; list filtering is enforced by the backend.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:46:49 +08:00
wuzilongandCursor 27d69f1af9 fix(pl): hide non-ETC vehicle recharge rows in list and get APIs
Force etc on reads so historical fuel data stays in DB but out of this module.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:45:36 +08:00
wuzilongandCursor 542ecc63e7 fix(pl): allow only etc recharge type in vehicle recharge schemas
Reject fuel writes so the shared module can be narrowed to ETC-only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:43:49 +08:00
wuzilongandCursor 00849bd998 docs(sql): narrow vehicle recharge menus to ETC-only labels
Rename ETC/fuel menus and soft-disable fuel dict for the ETC-only cutover.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:41:55 +08:00
wuzilongandCursor 72d372674a chore: archive mobile-h5 under bak for reference only.
Keep WeChat miniprogram as the primary mobile path; H5 remains available for lookup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-12 08:09:41 +08:00
wuzilongandCursor f13eba5623 feat(miniprogram): migrate expense items and workflow admin from bx-mobile.
Enable mobile config of expense tree and advance/reimburse approval nodes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:42:16 +08:00
wuzilongandCursor 1bd0503409 feat(miniprogram): migrate invoice wallet mine and admin from bx-mobile.
Reuse invoice-wallets/invoices APIs with summary, upload, ledgers, and admin proxy upload.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:37:40 +08:00
wuzilongandCursor 4c24f58b63 feat(miniprogram): migrate mine and all application lists from bx-mobile.
Unify advance/reimburse browsing under workbench view menus with existing detail routes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:31:17 +08:00
wuzilongandCursor 006e94ad33 feat(miniprogram): migrate reimburse apply list/form/detail from bx-mobile.
Reuse /reimburses APIs with bx envelope; support multi-line details and draft actions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:25:58 +08:00
wuzilongandCursor 2ff754d572 feat(miniprogram): migrate advance apply list/form/detail from bx-mobile.
Reuse /advances APIs with bx envelope and Fresh Mint list/form styling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:20:54 +08:00
wuzilongandCursor 507823dfce feat(miniprogram): add mobile bx menus and Batch1 placeholders.
Insert MINI_BX_* menus with mini:bx:* perms on test/prod, expose 9 workbench entries, and register placeholder pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:12:55 +08:00
wuzilongandCursor 279e405149 docs: add mini-program bx migration design from bx-mobile.
Document batched C-scope migration with mini:bx:* perms, vant-weapp styling, and API reuse.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 23:08:06 +08:00
wuzilongandCursor 16c55c0a4a feat(miniprogram): filter workbench menus by mobile menu permissions.
Hide weighbridge entries the current user is not granted via mini:db:* codes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:51:13 +08:00
wuzilongandCursor d3de3f5c45 feat(miniprogram): load menu-codes into user store.
Cache menuAll and menuCodes from /web/auth/menu-codes for workbench filtering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:43:37 +08:00
wuzilongandCursor 106ace1ea9 feat(miniprogram): map workbench db menus to mini:db:* perms.
Add MENU_CODES auth path for workbench permission loading.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:43:06 +08:00
wuzilongandCursor a5a1c29f01 feat(miniprogram): add workbench menu permission filter helper.
Pure function filters modules by menuAll or mini:db:* menuCodes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:42:45 +08:00
wuzilongandCursor fd463c77eb feat(sql): add mini-program weighbridge menus under 移动端.
Insert MINI_DB_* menus with mini:db:* perms and grant them to 超级管理员 only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:42:21 +08:00
wuzilongandCursor d5923df26e docs: add mini-db mobile menu permission implementation plan.
Break down SQL grant, workbench filter helper, and store wiring into executable tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:38:13 +08:00
wuzilongandCursor fed3389ef1 docs: add mini-program weighbridge menu permission design.
Capture agreed decisions for mobile sys_menu under 移动端, mini:db:* perms, and workbench filtering via menu-codes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 22:36:38 +08:00
wuzilong 8e87c7d576 提交 2026-09-11 21:19:52 +08:00
wuzilong 83192719b0 提交 2026-09-11 09:41:09 +08:00
wuzilongandCursor 166e5735df chore: update graphify after plan product+package key
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 18:09:47 +08:00
wuzilongandCursor 6548316644 fix(web-admin): allow same product with different packages on delivery stop
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 18:08:02 +08:00
wuzilongandCursor 39161e43e4 feat(web-admin): plan form package UI keyed by product and package spec
Contract-bound stop products use package options from the contract, arrange-qty
cache/API include packageSpec, and save validates required package selections.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 18:06:52 +08:00
wuzilongandCursor ded6aeaa85 feat(pl): require contract package spec on plan stop save
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 18:01:33 +08:00
wuzilongandCursor ff96f2ec25 feat(pl): arrange-qty and overflow checks use product+package key
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 18:00:10 +08:00
wuzilongandCursor 2fc14b1291 feat(pl): key contract plan qty by product and package spec
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:52:57 +08:00
wuzilongandCursor 3e6ae41e4b docs: add implementation plan for plan product+package qty key.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:50:13 +08:00
wuzilongandCursor ff42d7fe77 docs: add design for plan contract qty keyed by product and package spec.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:47:49 +08:00
wuzilong 05559def40 提交 2026-09-09 13:03:02 +08:00
wuzilongandCursor 4529166e16 fix(web-admin): prevent duplicate date sort carets on CRM column headers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:55:08 +08:00
wuzilongandCursor 45a6fc5cc5 feat(pl): add datetime column dual-caret sort on scoped transport lists.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:50:35 +08:00
wuzilongandCursor 100b0880f0 feat(db): add datetime column dual-caret sort on inventory and weighing lists.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:36:55 +08:00
wuzilongandCursor 7579c36fc6 docs: add DB weighbridge date column sort implementation plan.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:34:33 +08:00
wuzilongandCursor 9e1862f4e7 docs: add DB weighbridge date column dual-caret sort design.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:31:35 +08:00
wuzilongandCursor 9ead177dc3 feat(bx): add datetime list sort helpers and get_paged order_by.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:14:30 +08:00
wuzilongandCursor 5410bf8836 feat(web-admin): show dual carets on ColumnHeaderFilter datetime columns.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:13:31 +08:00
wuzilongandCursor cf3c1e6609 docs: add implementation plan for BX date column sort.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:09:51 +08:00
wuzilongandCursor e33b56797a docs: add BX date column dual-caret sort design.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 22:07:29 +08:00
wuzilongandCursor 9dca19a2e4 chore: update graphify after CRM date column sort.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:54:12 +08:00
wuzilongandCursor 626f91d4a8 feat(crm): wire date column sort on contract manage and approval lists.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:51:35 +08:00
wuzilongandCursor 381ece40df feat(crm): wire date column sort on quote manage and approval lists.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:50:15 +08:00
wuzilongandCursor a2d1de4c41 feat(crm): wire date column sort on customer list page.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:49:05 +08:00
wuzilongandCursor 23d23d0b86 feat(web-admin): show dual carets on CRM datetime column headers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:48:05 +08:00
wuzilongandCursor 58b5d9d7de feat(web-admin): add useColumnSort for CRM date headers.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:47:37 +08:00
wuzilongandCursor f14a96b28d feat(crm): support datetime column sort on contract list.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:45:52 +08:00
wuzilongandCursor 8f63430881 feat(crm): support datetime column sort on quote list.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:41:05 +08:00
wuzilongandCursor 72a8f97bd1 feat(crm): support datetime column sort on customer list.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:39:26 +08:00
wuzilongandCursor e6af68a2c3 feat(crm): add whitelist datetime list sort helper.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:37:35 +08:00
wuzilongandCursor b731c728a7 docs: add implementation plan for CRM date column sort.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:31:26 +08:00
wuzilongandCursor 302988f75c docs: add CRM date column dual-caret sort design and demo.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 21:28:41 +08:00
wuzilongandCursor d1c85ec5b8 chore: update graphify after personnel/self-vehicle cert zip.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:40:47 +08:00
wuzilongandCursor 2357c46e4d feat(pl): add cert batch ZIP download on personnel lists.
Wire third-party and Shanxia escort/driver lists to personnel cert zip packing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:40:06 +08:00
wuzilongandCursor 6d8e5578c9 feat(pl): add cert batch ZIP download on self-vehicle list.
Reuse vehicle cert zip packing on the Shanxia owned-vehicle toolbar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:39:37 +08:00
wuzilongandCursor 55abe614f8 feat(pl): add personnel cert zip packing and shared pack core.
Extract packAndSaveCertZip for reuse; keep vehicle API; name folders with _2 on collisions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:38:43 +08:00
wuzilongandCursor b4e59ab16b docs: add plan for cert ZIP on self-vehicle and personnel lists.
Cover shared pack core, personnel naming, and toolbar wiring for both pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:37:53 +08:00
wuzilongandCursor b84eec3c90 docs: extend cert batch ZIP design to self-vehicle and personnel lists.
Reuse the frontend JSZip approach with personnel name folders and shared toolbar entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:36:25 +08:00
wuzilongandCursor a4a272d842 chore: update web-admin graphify after vehicle cert zip utils.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:27:47 +08:00
wuzilongandCursor a6dff669d4 feat(pl): add toolbar batch ZIP download for vehicle certs.
Wire selected rows to frontend JSZip packing on the third-party vehicle list.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:26:46 +08:00
wuzilongandCursor 31ef9d4053 feat(pl): pack selected vehicle cert attachments into zip.
Add JSZip builder with concurrency, injectable fetch/save for tests, and multi-vehicle folders.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:25:27 +08:00
wuzilongandCursor e07af251c0 feat(web-admin): add fetchAttachmentBlob for zip packing.
Reuse attachment download-url flow to load file bytes without triggering anchor download.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:21:54 +08:00
wuzilongandCursor 8d3062a5af feat(pl): add vehicle cert zip naming and collect helpers.
Pure functions for toolbar batch ZIP: plate folders, 主·/挂· labels, and collision-safe paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:19:50 +08:00
wuzilongandCursor 65af6e6163 docs: add implementation plan for vehicle cert batch ZIP download.
Break the frontend JSZip approach into TDD tasks for helpers, blob fetch, packing, and toolbar wiring.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:17:05 +08:00
wuzilongandCursor 53a1bea890 docs: add vehicle cert batch ZIP download design and demo.
Capture the approved frontend JSZip approach for third-party vehicle list bulk certificate attachment download.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 20:14:32 +08:00
zlwu b6485f3b6c 提交 2026-09-07 10:34:41 +08:00
zlwu 7f05162fd1 提交 2026-09-06 20:44:56 +08:00
zlwuandCursor ca4a5b9fec fix(pl): sync stop dibang on arrange even when all unchecked.
Ensure cancel/block paths run when every generateDibang option is false.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 20:16:56 +08:00
zlwuandCursor de95549644 docs(pl): mark cascade Task 5 phase-2 stable ids as already covered.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:59:45 +08:00
zlwuandCursor 4c978296ff chore(pl): guard arrange path against dibang revoke rebuild
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:57:18 +08:00
zlwuandCursor 503b388a3f feat(pl): remount dibang monthly plan when partner or product changes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:52:20 +08:00
zlwuandCursor 180b5cdaa7 chore(pl): remove unused inventory editable guard after force sync
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:45:39 +08:00
zlwuandCursor 4dde13e7d7 fix(pl): sync dibang inventory and weighing fields after rearrange
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:43:32 +08:00
zlwuandCursor cd64463c0a test(pl): expect dibang plate sync even after weighing
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:37:34 +08:00
zlwuandCursor 912b79a2ca docs: add plan-arrange upsert cascade implementation plan.
Break phase-1 dibang field sync and monthly-plan remount into TDD tasks; defer stop stable ids to the 2026-09-05 plan.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:33:51 +08:00
zlwuandCursor 410d293287 docs: add transport plan arrange upsert cascade design.
Capture confirmed rules for stable-id updates, dibang inventory/weighing field sync, and monthly plan remap on plan rearrange.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:28:15 +08:00
zlwuandCursor fbf830172f feat(crm): wire customer and pool list filters to column params.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 08:19:48 +08:00
zlwuandCursor 3bb905bc20 feat(crm): add customer list column filter builder.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 08:17:06 +08:00
zlwuandCursor f33b905f0d refactor(web-admin): generalize server column filter queryKey mapping.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 08:15:49 +08:00
zlwuandCursor 3ab447b735 docs: add implementation plan for CRM customer column filters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 08:14:54 +08:00
zlwuandCursor 16d382e6aa docs: add design for CRM customer server-side column filters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 08:13:48 +08:00
zlwuandCursor 55cbd1d3d2 feat(bx): server-side column filters on reimburse apply list.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:53:28 +08:00
zlwuandCursor 1604ffceb1 feat(web-admin): use fuzzy text input in column header filter.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:50:50 +08:00
zlwuandCursor e492cedab9 feat(web-admin): add useServerColumnFilters for list column queries.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:47:15 +08:00
zlwuandCursor 36afab503a feat(bx): wire reimburse my list and export to column filters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:43:45 +08:00
zlwuandCursor e7054dc244 feat(bx): add shared reimburse list column filter builder.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:41:23 +08:00
zlwuandCursor e56e1c9144 docs: add implementation plan for reimburse server column filters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:36:43 +08:00
zlwuandCursor 3fa1f8e312 docs: add design for reimburse apply server-side column filters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 07:32:11 +08:00
zlwuandCursor 45ed795501 chore(pl): add script to remount orphaned transport dibang stop links.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:43:10 +08:00
zlwuandCursor 4e3c2a9ffb fix(pl): keep driver/site tokens stable on rearrange.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:41:32 +08:00
zlwuandCursor 2a9cc6084b fix(pl): drop accidental cert-perm guard from dibang upsert commit.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:40:48 +08:00
zlwuandCursor 68564c61f0 feat(pl): upsert dibang links by stop instead of revoke-and-rebuild.
Keep inventory ids across rearrange/plan edits; block cancel when weighing exists.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:40:29 +08:00
zlwuandCursor c90ff7c419 feat(web-admin): submit stable load/delivery/product ids on plan save.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:31:59 +08:00
zlwuandCursor 2e5b05f477 fix(pl): reject unknown plan product ids on upsert with 422.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:30:15 +08:00
zlwuandCursor 857067ec80 feat(pl): upsert plan product rows by id on update.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:24:43 +08:00
zlwuandCursor 6a7dfbcd38 feat(pl): upsert plan deliveries by stable id on save.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:18:06 +08:00
zlwuandCursor ca14bb7ca5 feat(pl): allow optional stop/product ids on plan write bodies.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:15:28 +08:00
zlwuandCursor 9e2f563a04 docs: add implementation plan for stable plan stop IDs and link reuse.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:14:33 +08:00
zlwuandCursor f8d0d10b2c docs: add design for stable plan stop IDs and in-place link reuse.
Captures brainstorming decisions so edits after arrange no longer break dibang/driver/site associations by regenerating stop UUIDs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 18:08:55 +08:00
zlwuandCursor 945bfcea54 feat(bx-mobile): bind and load reimburse apply attachments on save/edit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:18:40 +08:00
zlwuandCursor 8d14909165 feat(bx-mobile): add optional apply-attachment uploader on reimburse apply
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:17:21 +08:00
zlwuandCursor 6adb3cee9d fix(bx): rename historical attachments label to apply attachments
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:16:05 +08:00
zlwuandCursor d373776526 feat(bx): bind reimburse apply attachments on save and submit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:12:37 +08:00
zlwuandCursor 24aca104ad feat(bx): add apply-attachment upload UI on reimburse apply dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:10:47 +08:00
zlwuandCursor 112ad31428 docs: add implementation plan for reimburse apply attachments
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:08:55 +08:00
zlwuandCursor 4b012923bf docs: add design for optional reimburse apply attachments
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:05:03 +08:00
zlwuandCursor f09399f5f0 fix(web-admin): prevent blank Word export from broken seal img tags
Self-closing slash before style produced invalid HTML that caused html-to-docx to emit an empty document.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 15:38:54 +08:00
zlwuandCursor 0dc7ce0de8 fix(web-admin): polish Word header layout and floating seals
Use float text rows for header meta without table borders; rewrite seal images to float over party fields while keeping title underlines.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 15:33:47 +08:00
zlwuandCursor da2f36af7f fix(web-admin): keep contract header meta side-by-side in Word export
Convert flex+absolute rows (供方/合同编号, 需方/签订地点) into borderless two-column tables before html-to-docx.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 15:26:31 +08:00
zlwuandCursor 57c2a37171 fix(web-admin): drop Word watermark and keep party columns side-by-side
Word export no longer injects watermarks; convert the flex 供方/需方 footer into a two-cell table so html-to-docx preserves left-right layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 15:21:10 +08:00
zlwuandCursor f872333df6 fix(web-admin): polyfill Buffer/global for contract Word export in Vite
html-to-docx still reads Node globals after Vite rebundles; inject buffer polyfill, map global to globalThis, and alias the package to the browser build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 15:06:20 +08:00
zlwuandCursor 8bbc716d17 fix(web-admin): use html-to-docx browser build and inline images for Word export
Vite was resolving the Node ESM entry which needs Buffer/global; switch to the browser bundle and pre-convert images to data URLs so seals and watermarks embed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:59:58 +08:00
zlwuandCursor deefdf7bb4 fix(web-admin): resolve html-to-docx default import interop for Word export
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:52:03 +08:00
zlwuandCursor 591736f11f feat(web-admin): add Generate Word on contract detail print dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:50:00 +08:00
zlwuandCursor 9ac37d1196 feat(web-admin): add Generate Word on contract print dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:44:36 +08:00
zlwuandCursor b078245fbc feat(web-admin): generate contract DOCX blob from prepared HTML
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:42:44 +08:00
zlwuandCursor 17b42dc06c feat(web-admin): add contract HTML prep helpers for Word export
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:38:23 +08:00
zlwuandCursor e2b676121a chore(web-admin): add @turbodocx/html-to-docx for contract Word export
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:35:23 +08:00
zlwuandCursor cf579284e7 docs: add implementation plan for contract Word export
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:33:47 +08:00
zlwuandCursor 32f51274eb docs: add design for contract print dialog Word export
Capture the agreed frontend HTML-to-DOCX approach for CRM contract print dialog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 14:30:40 +08:00
zlwuandCursor f43ef91d70 chore(web-admin): update frontend knowledge graph after plan tab sync
Refresh graphify outputs after handlePlanTypeTabChange arranged tab wiring.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 17:36:46 +08:00
zlwuandCursor 75d60c5b75 feat(web-admin): sync followStatus when switching to arranged plan tab
Mirror pending_arrange behavior so the arranged tab forces followStatus filter to arranged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 17:36:34 +08:00
zlwuandCursor 01946dde8e feat(web-admin): add arranged tab to transport plan list filters
Insert「已安排」after「待安排」in PL_PLAN_LIST_TABS and map it to followStatus=arranged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 17:34:34 +08:00
zlwuandCursor 87374f3976 docs: add implementation plan for transport plan arranged tab
Break the arranged-tab design into TDD utility steps and list-page filter sync.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 17:33:11 +08:00
zlwuandCursor a4e107b2e6 docs: add design for transport plan arranged tab
Record the approved design to insert an「已安排」list tab after「待安排」, filtering by followStatus=arranged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 17:31:47 +08:00
zlwuandCursor 6bf4e7b249 fix(sql): avoid UUID collision in plan-archive price role backfill
MySQL may evaluate UUID() once per INSERT...SELECT, causing duplicate
primary keys when backfilling multiple sys_role_menu rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:53:06 +08:00
zlwuandCursor 7a5b8c3d96 chore: update graphify after plan-archive price permission
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:48:28 +08:00
zlwuandCursor b92418fa4a feat(web-admin): gate archive actions and price columns by menu codes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:34:49 +08:00
zlwuandCursor af0ae031a5 feat(web-admin): split archive qty vs price display flags
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:33:04 +08:00
zlwuandCursor b47c809300 feat(backend): gate archive writes and mask plan prices by menu code
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:30:31 +08:00
zlwuandCursor ce70265c92 feat(backend): add plan archive price mask helpers
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:25:17 +08:00
zlwuandCursor 7fbfcffd43 chore(sql): add pl:plan-archive:price menu and backfill roles
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:21:12 +08:00
zlwuandCursor 27c1cbba15 docs: add plan-archive price permission implementation plan
Break the approved design into SQL, backend mask/API, and
web-admin permission wiring tasks with verification steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:19:16 +08:00
zlwuandCursor 513d3b0fb3 docs: add plan-archive price permission design
Document button-level archive/price controls on the existing
transport plan archive page instead of a separate view module.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 16:16:13 +08:00
zlwu dd3bb3cf06 提交 2026-09-03 15:54:34 +08:00
zlwu 54a1ba0c5c 提交 2026-09-03 13:50:25 +08:00
zlwuandCursor 67d37a1f0e chore: update graphify after transport address notes
Mark the notes-fill design as implemented and refresh backend/frontend graphs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 12:01:40 +08:00
zlwuandCursor d798ef55a7 feat(web-admin): manage transport address notes on library page
Expose notes in list, form, and view dialog for address master data.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 12:00:36 +08:00
zlwuandCursor bf5f6b66be feat(web-admin): edit address library notes in select dialog
Allow create/update of notes while picking an address for a plan stop.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:59:40 +08:00
zlwuandCursor 6021287c97 feat(web-admin): fill load/delivery notes from address when empty
Apply library notes only if the stop notes field is currently blank.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:59:29 +08:00
zlwuandCursor 9c3c53c705 feat(web-admin): pass address library notes through apply payload
Allow load/delivery sections to receive notes when an address is selected.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:59:09 +08:00
zlwuandCursor 22b92ea056 feat(pl): add notes column on transport address library
Persist address-level precautions for later fill into plan load/delivery notes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:58:17 +08:00
zlwuandCursor 86e668920c feat(web-admin): add resolveAddressNotesFill for address library notes
Encode empty-only fill rule for load/delivery notes when selecting an address.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:57:27 +08:00
zlwuandCursor 7f9516e63d docs: use pnpm exec tsx --test in address notes plan
Align frontend unit test commands with existing web-admin plan conventions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:56:09 +08:00
zlwuandCursor ed96976090 docs: add transport address notes fill implementation plan
Break the approved design into TDD-friendly tasks covering DDL, API, apply chain, and address UIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:55:56 +08:00
zlwuandCursor 209f27606e docs: add transport address notes fill design
Capture the approved design for adding notes on pl_transport_address and filling load/delivery notes only when empty.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:53:22 +08:00
zlwuandCursor 585b731846 chore: update graphify after plan draft-save feature
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:43:47 +08:00
zlwuandCursor 3c7e3c69c5 feat(web-admin): add plan draft save UI and drafting follow-status filters
Rename pending tab to 待安排/草稿, default-select drafting, and add 暂存 with saveMode.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:42:23 +08:00
zlwuandCursor ae91fbc63e feat(backend): support saveMode draft/formal and drafting follow gates
Draft skips business validators and writes drafting; formal promotes drafting to pending_arrange; wait-notice/delete/force allow drafting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:40:54 +08:00
zlwuandCursor f9cdb8852b feat(backend): add saveMode field on plan create-full and update schemas
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:39:17 +08:00
zlwuandCursor f28e82c1b3 feat(backend): add draft save helpers for plan follow status drafting
Introduce min-field validation and follow_status resolution for saveMode draft/formal.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:39:04 +08:00
zlwuandCursor 16c657b75e docs: add implementation plan for plan draft save / drafting status
Break the approved design into backend helpers, saveMode API, list tab filters, and form dialog tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:37:11 +08:00
zlwuandCursor 70c9de3618 docs: add transport plan draft/save design for drafting follow status
Capture approved decisions for 暂存 button, drafting status, list tab, and saveMode API so implementation can follow a single spec.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 11:33:05 +08:00
zlwu 1dfcc66d2c 提交 2026-09-02 08:20:52 +08:00
zlwuandCursor 506cc7991a feat(web-admin): viewport-fill list height for system manage menus
Wire 系统信息 lists (tenant/dict/menu/dept/role/user/post/operlog) and
临时存放 CRM lists under 系统管理 to useListTableViewportHeight, with
onActivated recalc for keep-alive pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:42:20 +08:00
zlwuandCursor f457d5e106 feat(web-admin): viewport-fill list height for workflow menus
Wire 流程配置、待办/已办中心、我的申请 and 请假申请 lists to
useListTableViewportHeight for sticky headers and viewport-fill scrolling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:32:30 +08:00
zlwuandCursor c577edc597 feat(web-admin): viewport-fill list height for pl transport menus
Wire 运输管理 list pages (plans, IO orders, freight panels, vehicles,
personnel, and related lists) to useListTableViewportHeight so table body
scrolls with sticky header and pager stays near the content bottom.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:27:17 +08:00
zlwuandCursor 11185f066a feat(web-admin): viewport-fill list height for db weighbridge menus
Wire 地磅计划 and 地磅出入库 lists to useListTableViewportHeight (stats +
pager below the table wrap), matching 地磅单管理. Dashboard has no list.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:17:33 +08:00
zlwuandCursor 7ed3f26f9c feat(web-admin): viewport-fill list height for bx reimbursement menus
Wire remaining报销管理列表(审批/发放/付款/发票夹/费用项/流程/视图)to
useListTableViewportHeight so table body scrolls with sticky header and
pager stays ~10px above the content viewport bottom.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:14:01 +08:00
zlwuandCursor 6f7461d009 feat(web-admin): viewport-fill list height for CRM menu pages
Wire contract, quote, customer, product, and price-letter lists to useListTableViewportHeight.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:00:02 +08:00
zlwuandCursor 7f8cd18b4d chore: update web-admin graphify after viewport scroll changes
Keep the frontend knowledge graph in sync with new composables and list wiring.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:53:18 +08:00
zlwuandCursor 6e92bf49d8 fix(web-admin): recalc viewport table height on activate
Ensure order and weighing lists refresh table height after tab activation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:52:41 +08:00
zlwuandCursor fa48577a74 feat(web-admin): roll out viewport list height to more lists
Apply fill-viewport table height on demo product/order, bx mine, and db weighing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:51:59 +08:00
zlwuandCursor b8efcca1cf docs: specify viewport-fill list table scrolling
Align Fresh Mint §7.6 and OpenSpec ui-conventions with the confirmed UX; include design and plan.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:47:48 +08:00
zlwuandCursor aef6927181 feat(web-admin): viewport-fill scroll on reimburse apply list
Wire ListTable height to the shared composable and stop double-scroll on wraps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:47:13 +08:00
zlwuandCursor 597fca416d feat(web-admin): use viewport table height on demo unit list
Pilot the fill-viewport list scroll pattern on the standard list template page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:45:49 +08:00
zlwuandCursor 55ac1ebbf6 feat(web-admin): add useListTableViewportHeight composable
Measure content viewport, table top, and pager to drive el-table height.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:45:22 +08:00
zlwuandCursor 7d78f76129 feat(web-admin): add list table viewport height formula
Pure calc keeps pagination visible with a 10px bottom gap for main list scroll UX.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:45:15 +08:00
zlwu 0e8f244bc3 提交 2026-09-01 13:51:32 +08:00
zlwu ba21c40058 提交 2026-08-31 20:53:46 +08:00
zlwu 69fa5b1fa8 提交 2026-08-31 08:28:36 +08:00
zlwu 19c5aaa8f5 提交 2026-08-30 18:33:13 +08:00
zlwuandCursor c8cec132bf chore: update web-admin graphify after arrange-required product fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:54:29 +08:00
zlwuandCursor 810c9aacae feat(web-admin): mark arrange-required product fields with asterisk
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:53:47 +08:00
zlwuandCursor a4619a0788 feat(web-admin): block arrange when stop product required fields missing
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:53:06 +08:00
zlwuandCursor 765a27779c feat(pl): add arrange-required check for stop product fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:52:47 +08:00
zlwuandCursor 79b33c6ba1 docs: add implementation plan for plan product arrange-required fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:51:10 +08:00
zlwuandCursor 5fbb15611c docs: add design for plan product fields required on arrange
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:49:27 +08:00
zlwuandCursor 81b1cb9b1d feat(pl): show available contract qty before plan qty in stop products
Add contract-product-arrange-qty API and form UI with green available qty,
red plan qty over-hint, and click-through dialog for usage and plan list.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 17:41:36 +08:00
zlwuandCursor 3011cb9dae feat(pl): hard-block over-limit contract qty on arrange and remind after success
Validate arranged+this plan qty against fixed contract product quantities on
transport arrange; return post-success remaining/framework cumulative reminders.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 16:47:21 +08:00
zlwuandCursor d326996976 docs: add transport plan contract quantity check design and demo
Capture hard-block on over-limit arrange and post-success remaining/framework reminders aligned with contract detail qty aggregation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 15:59:53 +08:00
zlwuandCursor bbd82b7963 fix(web-admin): harden contract product validation and fetch race
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 11:09:37 +08:00
zlwuandCursor 946a71b2e0 feat(web-admin): enforce single contract on plan-contract supplement save
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 11:05:15 +08:00
zlwuandCursor 173e6cdf59 feat(web-admin): allow removing products on delivery stops
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 11:05:15 +08:00
zlwuandCursor 8777173fb7 fix(web-admin): treat empty allowedProductIds as restricted mode
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 11:04:12 +08:00
zlwuandCursor 9b8848ea8c feat(web-admin): gate load products by selected contract
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 11:02:58 +08:00
zlwuandCursor bbab39e6b7 feat(web-admin): allow ProductSelector to restrict by product ids
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 11:00:05 +08:00
zlwuandCursor f18442be2e feat(web-admin): make plan stop contract selector single-choice
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:58:14 +08:00
zlwuandCursor e9fd94de03 feat(web-admin): add helpers to filter plan products by contract
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:57:09 +08:00
zlwuandCursor 1959394223 feat(pl): enforce single contract on stop-contracts and legacy side paths
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:55:00 +08:00
zlwuandCursor a6d900ee1f fix(pl): harden load-contract product checks and tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:53:10 +08:00
zlwuandCursor fbcd27b213 feat(pl): require load products to belong to selected contract
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:49:36 +08:00
zlwuandCursor eb1bfc5732 feat(pl): enforce at most one contract per plan stop
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:46:41 +08:00
zlwuandCursor 98db382e70 docs: add implementation plan for plan single-contract product rules
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:43:29 +08:00
zlwuandCursor 051c6b6fea docs: add design for plan single-contract and load products from contract
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 10:40:49 +08:00
zlwu 63a1209620 提交 2026-08-30 09:30:02 +08:00
zlwu 16986f443e 提交 2026-08-27 19:38:12 +08:00
zlwu ebf006eeff 提交 2026-08-27 19:38:01 +08:00
zlwu 4611dbc2b2 提交 2026-08-27 14:23:18 +08:00
zlwuandCursor e56d227fe8 feat(pl): add customer stop pref service and unit tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 17:10:37 +08:00
zlwuandCursor bd682288f9 feat(pl): add PlCustomerStopPref model
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 17:06:59 +08:00
zlwuandCursor 031f1d50f6 docs: add pl_customer_stop_pref migration for stop logistics memory
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 17:04:56 +08:00
zlwu 4222eaa593 提交 2026-08-26 11:10:40 +08:00
zlwu dd1acdc787 提交 2026-08-23 18:42:27 +08:00
zlwu b74d483682 提交 2026-08-23 09:47:38 +08:00
zlwuandCursor 8dbb816d01 feat(pl): add blank slip print commands to plan list toolbar
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 11:29:26 +08:00
zlwuandCursor 4de82c0805 feat(pl): expose openBlank on slip print dialogs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 11:28:11 +08:00
zlwuandCursor dfa033da02 feat(pl): add blank HTML renderer for subpack slips
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 11:28:10 +08:00
zlwuandCursor 3ec188666c feat(pl): add blank HTML renderers for inbound and delivery slips
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 11:23:50 +08:00
zlwuandCursor 7ebe635fca docs(pl): add implementation plan for blank slip print
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 11:21:47 +08:00
zlwuandCursor ed939097f0 docs(pl): add blank slip print design for transport plans
Document toolbar blank inbound/delivery/subpack print via openBlank(),
including empty fields, no seal on delivery blanks, and no selection required.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 11:18:31 +08:00
zlwu 16be6fa22d 提交 2026-08-22 09:08:05 +08:00
zlwuandCursor 833544def3 fix(bx): include export_common helper and advance export endpoints
Previous reimbursement export commit depended on these files but they were left unstaged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:34:35 +08:00
zlwuandCursor dbba755fd8 feat(bx): add list Excel export for reimbursement module pages
Wire ListExportDropdown on advance/reimburse/payment/expense/view/wallet lists, with matching POST export endpoints.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:34:22 +08:00
zlwuandCursor fe15a130cb feat(pl): add Excel export for plan contract gaps and document reminders
Complete remaining logistics list export pages under the PL module wave.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:19:07 +08:00
zlwuandCursor b1f734dbb0 feat(pl): add Excel export for freight unsettled plans and settlement tabs
Support filtered and selected export across freight settlement board panels.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:17:10 +08:00
zlwuandCursor 8f1f08b284 feat(pl): add Excel export for inventory ledger and inbound/outbound lists
Allow filtered and selected row export on inventory and shared IO order pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:14:58 +08:00
zlwuandCursor 89e8d6e65c feat(pl): add Excel export for recharge, urea and maintenance process lists
Support filtered and selected export on apply and disburse/process board pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:07:54 +08:00
zlwuandCursor 441e1fdae1 feat(pl): add Excel export for vehicle maintenance apply list
Support filtered and selected rows via backend export and ListExportDropdown.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 18:01:00 +08:00
zlwuandCursor 6a89452f1a feat(pl): add Excel export for plan and transport lists
Support filtered/selected export on plan, archive, cert and transport pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:59:04 +08:00
zlwuandCursor b06fb6ac56 feat(pl): add Excel export for vehicle, personnel, driver and address lists
Wire backend /export endpoints and ListExportDropdown on master-data list pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:56:20 +08:00
zlwuandCursor 85c96f0a5d feat(pl): add Excel export for carrier list
Add backend /transport/carrier/export and wire ListExportDropdown on the carrier page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:47:57 +08:00
zlwuandCursor e72bcc67bc feat(workflow): add Excel export for process and task lists
Support filtered and selected rows for process defs, pending/completed tasks, and my applications.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:39:20 +08:00
zlwuandCursor ee56dad875 feat(system): add Excel export for dept and menu tree lists
Export flattened filtered or selected rows via backend xlsx and ListExportDropdown.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:31:10 +08:00
zlwuandCursor b3b6ec187a feat(system): add Excel export for operlog and dict type lists
Wire ListExportDropdown with filtered/selected backend xlsx export.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:28:57 +08:00
zlwuandCursor 1053e24896 feat(system): add Excel export for leave request list
Support filtered and selected leave rows via backend export and ListExportDropdown.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:27:02 +08:00
zlwuandCursor 82d8cb7f64 feat(system): add Excel export for tenant, role, post and site lists
Reuse list filters with ids/columns support and ListExportDropdown UX.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:21:50 +08:00
zlwuandCursor 5c7210facc feat(crm): align product export with ListExportDropdown
Add ids/columns support and unify toolbar export UX.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:06:01 +08:00
zlwuandCursor 09827fdbf3 feat(web-admin): wire list export on system user page
Pilot filtered and selected Excel export via ListExportDropdown.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:03:38 +08:00
zlwuandCursor 3643a3b14e feat(web-admin): add ListExportDropdown and Excel blob download helper
Support filtered-result primary action and optional export-selected menu.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 17:01:49 +08:00
zlwuandCursor eb4233f23f feat(admin): add users list Excel export endpoint
Reuse list filters, tenant and data scope; support ids and visible columns.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 16:55:47 +08:00
zlwuandCursor 4a194aa25e feat(backend): add list export column filter and row-count guards
Shared helpers enforce empty/over-limit export rules and allow
clients to request visible columns by field key.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 16:52:50 +08:00
zlwu d26fb23fcf 提交 2026-08-21 16:50:47 +08:00
zlwuandCursor 6dc8cfb2c1 docs: add implementation plan for web-admin list Excel export
Detail shared helpers, ListExportDropdown, user pilot, CRM align,
and per-module batch waves covering remaining list pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 16:50:11 +08:00
zlwuandCursor d8f10b9efe docs: add design for web-admin unified list Excel export
Capture backend export infrastructure, ListExportDropdown UX, and
per-resource /export conventions for filtered and selected rows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 16:42:40 +08:00
zlwuandCursor e9ad26cb48 docs: mark reimburse apply page size pilot plan and design as done
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 14:18:35 +08:00
zlwuandCursor 15c1368409 feat(web-admin): expand reimburse apply page size options to 500
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 14:17:58 +08:00
zlwuandCursor f342208a8a feat(bx): raise my reimburses pageSize max to 500 for apply list pilot
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 14:15:19 +08:00
zlwuandCursor 02a29c3328 docs: add implementation plan for reimburse apply page size options
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 14:12:40 +08:00
zlwuandCursor 38c830ef99 docs: add design for reimburse apply page size options pilot
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 14:11:12 +08:00
zlwu 9fcb9270e6 提交 2026-08-21 13:45:35 +08:00
zlwuandCursor 88da74d72a chore: refresh graphify after driver transport history
Update backend/frontend knowledge graphs for the new history API and H5 pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:31:15 +08:00
zlwuandCursor d01603f709 feat(pl): implement public driver transport history list page
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:29:10 +08:00
zlwuandCursor ea33e62eaa feat(pl): add transport history entry on driver public page
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:27:33 +08:00
zlwuandCursor 267b678e7a feat(pl): add public transport history API client
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:26:09 +08:00
zlwuandCursor c51345eec5 feat(pl): add public driver transport history API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:25:04 +08:00
zlwuandCursor 0e90b1d949 feat(pl): add transport history helpers and schemas
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:18:34 +08:00
zlwuandCursor 74146de156 docs: fix history API client to encode date in query string
publicPlGet only accepts a URL; align the plan with that signature.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:15:49 +08:00
zlwuandCursor abcdf793c4 docs: add implementation plan for driver transport history
Break down public history API, detail entry button, and list page;
keep existing driver feedback form unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:15:35 +08:00
zlwuandCursor ab46a8c999 docs: add driver transport history design and HTML demo
Capture the approved design for same-main-plate public driver history
(list by pickup/delivery day, today shortcuts, cross-plan feedback).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-21 11:12:35 +08:00
zlwu 44749ae716 提交 2026-08-21 09:35:11 +08:00
zlwuandCursor b9ff9c9d67 feat(duty): make duty time range a single-select dict like work plans
Add duty_time_range dictionary with day/night presets, parse typed ranges on ensure, and replace time pickers with allow-create select in the schedule dialog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 21:58:18 +08:00
zlwuandCursor 8d9f0b259e feat(duty): sync public H5 with time, work plans, and remark
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 21:19:06 +08:00
zlwuandCursor 8df0583ad1 feat(duty): admin schedule UI for dict types, work plans, and time
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 21:19:06 +08:00
zlwuandCursor a98ec0443a feat(duty): update frontend API types for dict and time fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 21:15:20 +08:00
zlwuandCursor cd0491e601 feat(duty): persist work plans and times; relax grab shift types
Map invalid HH:mm to DutyBizError, serialize workPlans/timeLabel from dict,
ensure dict items on save, and allow custom shift types on public grab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 21:14:36 +08:00
zlwuandCursor 4447a1e8e6 feat(duty): add time/work-plan helpers and dict ensure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 21:06:07 +08:00
zlwuandCursor 80545263a0 feat(duty): extend slot model and schemas for work plans and time
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 20:55:20 +08:00
zlwuandCursor b71c1144bf chore(duty): add SQL migration for shift dict and slot time fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 20:51:03 +08:00
zlwuandCursor 1850c7c3df docs: add duty shift dict and time implementation plan
Break the confirmed design into SQL, backend, admin UI, and public H5 tasks with TDD steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 20:44:39 +08:00
zlwuandCursor 361e923396 docs: add duty shift dict, work plan, and time range design
Capture confirmed approach for customizable shift types and work plans via sys_dict, slot time fields with morning/evening defaults, migration, and public H5 sync.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 20:36:33 +08:00
zlwuandCursor 09a57a7af9 feat(pl): show product and plan type columns on contract completion list
Align the合同完善 table with运输计划 by returning products/planType from contract-gaps and rendering them via PlPlanListProductCell.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 13:12:14 +08:00
zlwuandCursor 8e42fe1640 docs: mark plan contract completion design as implemented
Implementation of the independent completion page, APIs, badge, and menu is in place pending local SQL apply and UI验收.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:16:57 +08:00
zlwuandCursor 368cb5567a feat(pl): add plan contract completion page with inline expand
List only plans missing contracts and allow per-side multi-select save in an expand row, reusing PlPlanContractMultiSelect without contract CRUD.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:16:38 +08:00
zlwuandCursor 62bdf48b63 feat(pl): frontend API for plan contract gaps
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:11:54 +08:00
zlwuandCursor 58fbafa2ac feat(pl): add plan-contract menu SQL and web-admin route
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:11:17 +08:00
zlwuandCursor af93272bcd feat(pl): badge count for plan contract completion menu
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:10:14 +08:00
zlwuandCursor b984c8c857 feat(pl): add PUT plan side contracts for contract completion
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:09:42 +08:00
zlwuandCursor d1d7425eeb feat(pl): add GET transport/plan/contract-gaps endpoint
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:00:59 +08:00
zlwuandCursor 211156a94c feat(pl): add contract-gap SQL filter and response schemas
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 11:56:40 +08:00
zlwuandCursor a79e8a3e12 feat(pl): add plan contract gap side computation helpers
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 11:54:10 +08:00
zlwuandCursor 900fb20d50 docs: add implementation plan for plan contract completion
Break down backend gap APIs, menu badge, SQL menu, and the inline-expand web-admin page into sequenced tasks with verification steps.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 11:52:25 +08:00
zlwuandCursor f9f32a8b68 docs: add transport plan contract completion design and UI demo
Capture the agreed independent page (inline expand, per-side save, menu badge) for completing missing supplier/demander contracts after they became optional on create/edit.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 11:49:34 +08:00
zlwu 9da462fcba 提交 2026-08-20 11:17:41 +08:00
zlwu 1938a9b76a 提交 2026-08-19 22:20:42 +08:00
zlwu a52fe77e34 提交 2026-08-19 09:14:37 +08:00
zlwu c3bd2c00ae 提交 2026-08-17 20:32:18 +08:00
zlwuandCursor 9345cf4ad8 fix(duty): allow re-saving historical assigns without duty staff role
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:29:20 +08:00
zlwuandCursor a9c1062fbe feat(web-admin): use duty staff options in schedule dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:25:57 +08:00
zlwuandCursor a8b5b69a1f feat(duty): add users/options endpoint filtered by duty staff role
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:25:11 +08:00
zlwuandCursor 0c4a4bf14a feat(duty): restrict assign and grab to duty staff role
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:23:20 +08:00
zlwuandCursor a20d31de38 chore(db): add duty staff role for schedule eligibility
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:19:40 +08:00
zlwuandCursor 42ec16b0cf docs: add implementation plan for duty staff role filter.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:18:02 +08:00
zlwuandCursor 2942d176bd docs: add duty staff role filter design for schedule selection.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 18:15:58 +08:00
zlwuandCursor dea4159636 chore: update graphify after reimburse occur_date changes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 16:06:22 +08:00
zlwuandCursor 43d53cb9dd feat(bx-mobile): display occur date on reimburse detail views
Always show the field and use an em dash when the date is empty.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 16:03:53 +08:00
zlwuandCursor 49e4e604ca feat(bx-mobile): add optional occur date on reimburse apply form
Mirror web-admin detail lines with a clearable YYYY-MM-DD input.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 16:03:17 +08:00
zlwuandCursor 42f2d2b80e feat(web-admin): show occur date on reimburse detail readonly tables
Keep the column always visible with an em dash when empty.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 16:00:54 +08:00
zlwuandCursor 8f032488a4 feat(web-admin): add optional occur date on reimburse apply details
Allow picking YYYY-MM-DD per detail line and show it in the view dialog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 16:00:01 +08:00
zlwuandCursor 5b7a9f2f8f feat(bx): persist and return reimburse detail occurDate
Wire optional occur_date through create/update detail payloads and
API responses.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 15:58:36 +08:00
zlwuandCursor 3b8a0eb7d8 feat(bx): add parse_optional_date for nullable occur dates
Empty values map to None so optional detail dates do not default to today.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 15:57:15 +08:00
zlwuandCursor 0b402b18ed feat(bx): add occur_date column on reimburse detail
Store optional expense occurrence date (DATE, nullable) for each
reimburse line item.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 15:53:53 +08:00
zlwuandCursor f73fb572d1 docs: add implementation plan for reimburse detail occur date
Break the approved design into backend, web-admin, and bx-mobile
tasks with concrete steps and verification.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 15:48:02 +08:00
zlwuandCursor 071281150d docs: add design for optional reimburse detail occur date
Capture the agreed plan to add nullable occur_date (YYYY-MM-DD) on
bx_reimburse_detail across backend, web-admin, and bx-mobile.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 15:45:27 +08:00
zlwu 8558d9439e 提交 2026-08-17 15:25:28 +08:00
zlwu 6b2147aa46 提交 2026-08-17 09:22:31 +08:00
zlwuandCursor 42ad896456 fix(crm): sync quote list stats row widths to table headers
Keep the interactive summary cells aligned when columns resize.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 16:02:38 +08:00
zlwuandCursor 072790989f feat(crm): add interactive column stats row on quote list
Let users pick sum/avg/max/min per column on the current page,
with localStorage persistence for the quote management list.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 16:00:54 +08:00
zlwuandCursor 6ce7554557 feat(crm): add quote list column stats helpers
Pure aggregation, display formatting, and localStorage helpers
for the quote list configurable summary row.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:51:48 +08:00
zlwuandCursor be55f23c21 docs: add quote list column stats implementation plan
Break the approved design into TDD-friendly tasks for the
quote management list interactive summary row.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:49:16 +08:00
zlwuandCursor a84f4fe903 docs: add quote list column stats design
Capture agreed UX and current-page aggregation rules for the
quote management list before implementation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:48:05 +08:00
zlwuandCursor 144e50f42d refactor(crm): use shared settlement clause in contract print views
Wire ContractDetailDialog and detail page to settlementClause helpers so new settlement methods resolve fifth-clause text correctly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:05:56 +08:00
zlwuandCursor 477719c9a7 feat(crm): add frontend settlement clause helpers
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:03:44 +08:00
zlwuandCursor e1eeca0001 feat(crm): use settlement clause helper in save_template
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:03:05 +08:00
zlwuandCursor a73ee89f44 feat(crm): add settlement clause default text helper
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 15:01:47 +08:00
zlwuandCursor 38a9f6f724 feat(crm): add settlement method dict options migration
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 14:59:57 +08:00
zlwu 34e5fcf0be 提交 2026-08-16 14:58:19 +08:00
zlwuandCursor 4c23ff9f61 fix(duty): show duty schedule on portal home launcher
Register /duty frontend route module, add portal top-module order, and fix sys_menu as L1 directory with schedule leaf plus role grants.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-15 16:04:33 +08:00
zlwuandCursor a1321c145c chore(duty): sync knowledge graph after duty schedule feature
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:15:22 +08:00
zlwuandCursor ba17a83df5 fix(duty): drop unused import in duty admin API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:14:59 +08:00
zlwuandCursor 35e09fa09b feat(duty): add web-admin calendar page and public H5 grab UI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:14:05 +08:00
zlwuandCursor 36fc7f286c feat(duty): register admin and public duty APIs with encrypt exclude
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:12:40 +08:00
zlwuandCursor 49cad98c84 feat(duty): add schemas and duty_schedule service with capacity tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:12:13 +08:00
zlwuandCursor f5ad2d7217 feat(duty): add SQLAlchemy models for duty schedule
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:10:36 +08:00
zlwuandCursor 2502db7a02 fix(duty): add unique keys for duty_day date and slot shift_type
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:08:22 +08:00
zlwuandCursor 931fd24671 chore(duty): add duty_day/slot/assignment tables and menu SQL
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 17:06:25 +08:00
zlwu 3f21007c18 提交 2026-08-12 21:40:55 +08:00
zlwuandCursor d00f5f6da3 docs(bx): mark negative invoice balance design as implemented pending QA
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 21:01:56 +08:00
zlwuandCursor 5f290a8ef1 docs(bx): document that reimburse submit may leave invoice balance negative
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 21:01:30 +08:00
zlwuandCursor 5983d31ab2 fix(bx-mobile): allow reimburse submit with insufficient invoice balance
Align soft tip and submit flow with web-admin; no longer block on wallet balance.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 21:00:31 +08:00
zlwuandCursor b53c1c4851 fix(web-admin): allow reimburse submit with insufficient invoice balance
Replace blocking tip with a soft warning and remove client-side submit guards.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 20:59:13 +08:00
zlwuandCursor 99e4d4c69a fix(bx): allow reimburse submit when invoice wallet balance is insufficient
Drop the hard balance check in debit_reimburse so occupancy can exceed uploaded invoices; balance may go negative until later top-ups.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 20:57:54 +08:00
zlwuandCursor 4f75bc40b9 docs: add plan for allowing negative invoice balance on reimburse submit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 20:56:43 +08:00
zlwuandCursor 12e8cdaaf9 docs: allow negative invoice wallet balance on reimburse submit
Record the approved design to drop the hard balance gate while keeping full debit_reimburse occupancy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 20:55:47 +08:00
zlwu 5fcdb03da1 提交 2026-08-11 07:54:28 +08:00
zlwu a5210a6a9e 提交 2026-08-09 21:07:28 +08:00
zlwuandCursor b45ce2c32c style(bx-mobile): polish reimburse invoice attachment picker layout
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 19:47:39 +08:00
zlwuandCursor 0e8cefe89f feat(bx-mobile): show attachment grid picker on reimburse apply
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 19:46:31 +08:00
zlwuandCursor 9f92012e43 refactor(bx-mobile): use attachment-level invoice picks in reimburse apply logic
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 19:44:37 +08:00
zlwu 38383b35d9 提交 2026-08-09 19:42:32 +08:00
zlwuandCursor 47ef575524 docs: add plan for bx-mobile reimburse invoice attachment picker
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 19:42:03 +08:00
zlwuandCursor 2f87223236 docs: add bx-mobile reimburse invoice attachment picker design
Align mobile invoice selection with web-admin at attachment granularity;
include interactive HTML demo for the 3-column picker UX.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 19:38:40 +08:00
zlwuandCursor 47a56e40fe docs: mark bx-mobile shanxia2.0 adaptation complete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:19:51 +08:00
zlwuandCursor 96dbd3ccbc feat(bx-mobile): complete P3 withdraw, proxy apply, history, and config pages
Align H5 with portal APIs for reimburse withdraw, approval history, applicant/date/title, and UUID-based expense/workflow config using portal user options.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:19:51 +08:00
zlwuandCursor 9750e1f39d feat(bx-mobile): show linked invoices on reimburse detail
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:13:58 +08:00
zlwuandCursor a8590db98b feat(bx-mobile): add invoice wallet pages and bind reimburse apply to balance rules
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:13:42 +08:00
zlwuandCursor 522d691050 fix(bx-mobile): align business pages with UUID ids for P1 portal API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:10:53 +08:00
zlwuandCursor 8eb0ad14e7 feat(bx-mobile): render home entries from portal-filtered menu catalog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:08:09 +08:00
zlwuandCursor a0eebfdbd3 feat(bx-mobile): guard routes by portal menuCodes and drop bx admin IAM pages
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:07:23 +08:00
zlwuandCursor a4f04ff297 feat(bx-mobile): finish portal login page and normalize current-user fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:06:43 +08:00
zlwuandCursor 3f1faeae34 feat(bx-mobile): add bxClient and retarget business APIs to shanxia2.0
Remove legacy bx user/role/menu/auth APIs. Wire auth store to portal
temporarily so the app still typechecks; IAM admin pages use local stubs
until Task 6 drops their routes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:06:12 +08:00
zlwuandCursor c7a8930ad6 feat(bx-mobile): add portal HTTP client and RSA login API
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:03:58 +08:00
zlwuandCursor 2840c7d1c0 feat(bx-mobile): add Web bx menuCode catalog and permission helpers
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:03:17 +08:00
zlwuandCursor 39630d39e5 fix(bx-mobile): load VITE_API_PROXY_URL via loadEnv in vite config
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:01:40 +08:00
zlwuandCursor 4d75713e15 chore(bx-mobile): point API proxy to shanxia2.0 backend and add jsencrypt
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 16:00:32 +08:00
zlwu 7a0f1554bd 提交 2026-08-09 15:59:22 +08:00
zlwu f70dc26206 提交 2026-08-09 14:51:41 +08:00
zlwuandCursor ca6aca2b14 docs: add transport plan supplier/demander free-product design and plan.
Capture agreed rules for dual-party customers, multi-contract sides, ProductSelector-only products, and no historical migration before implementation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 23:35:35 +08:00
zlwu 90ae136f38 提交 2026-08-08 23:14:40 +08:00
zlwu fdf7d391a6 提交 2026-08-08 22:19:09 +08:00
zlwu 683f14828f 提交 2026-08-08 20:43:48 +08:00
zlwuandCursor 2df2ef0808 feat: add portal home launcher, favorites UI, and WorkTab overflow eviction
Replace top-bar module navigation with a card home page, persist favorites via API, reopen favorite tabs on cold login, and enable portal multi-tabs with overflow-based eviction.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 12:06:49 +08:00
zlwuandCursor 7898d65437 feat: add menu favorites API under /web/admin/menu-favorites
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 12:01:28 +08:00
zlwuandCursor 1a0c58f82d feat: add sys_user_menu_favorite table for portal menu favorites
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 11:58:55 +08:00
zlwuandCursor 2ccc3b612a docs: mark CRM name pinyin abbr design implemented and note go-live checklist.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:34:55 +08:00
zlwuandCursor 021bd73301 feat: customer form and search UI for pinyin initials.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:33:23 +08:00
zlwuandCursor b151ac6499 feat: product form and search UI for pinyin initials.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:30:53 +08:00
zlwuandCursor 5575b08437 feat: add backfill script for CRM name pinyin initials.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:29:21 +08:00
zlwuandCursor 659fc89179 feat: store and search customer name pinyin initials.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:24:28 +08:00
zlwuandCursor ba3f2c19bb feat: store and search product name pinyin initials.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:18:59 +08:00
zlwuandCursor e056dfaac1 fix: restore shanxia2.0.sql and keep name_pinyin_abbr DDL only.
The previous commit accidentally truncated the baseline SQL dump; restore full content and re-apply only the crm_product/crm_customer column additions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:15:45 +08:00
zlwuandCursor e7b3fbb21b feat: add name_pinyin_abbr columns for CRM product and customer.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:10:53 +08:00
zlwuandCursor fa9b3429c7 feat: add pinyin initial abbr helper for CRM names.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 16:57:05 +08:00
zlwuandCursor 65ea371d5f docs: add design for CRM product/customer pinyin initial search.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:52:15 +08:00
zlwuandCursor 05350a99a6 docs: mark alias-brand manage implementation plan tasks complete.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:24:34 +08:00
zlwuandCursor c1b2f5a667 docs: mark quote/contract alias-brand manage design implemented.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:24:08 +08:00
zlwuandCursor 449250518f feat(crm): wire alias/brand manage dialog into contract product lines.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 12:55:52 +08:00
zlwuandCursor a80a01b37d feat(crm): wire alias/brand manage dialog into quote product lines.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 12:50:32 +08:00
zlwuandCursor 0dbd2da703 feat(crm): add product alias/brand manage dialog for inline master-data edits.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 12:46:28 +08:00
zlwuandCursor 4628738632 feat(crm): add helper to refresh quote/contract lines after product alias/brand manage.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 12:41:30 +08:00
zlwuandCursor 1e74057003 docs: add implementation plan for quote/contract alias and brand manage dialog.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 12:40:37 +08:00
zlwuandCursor 22014ba3fa docs: add design for quote/contract alias and brand inline manage dialog.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 12:38:26 +08:00
zlwuandCursor 9788e3ac17 docs: mark transport plan copy design implemented
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 23:33:48 +08:00
zlwuandCursor e1f31dc10f feat(pl): add copy entry on transport plan list and view dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 23:25:06 +08:00
zlwuandCursor d5bbe0d0b1 feat(pl): support copy-from plan prefill in plan form dialog
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 23:18:04 +08:00
zlwuandCursor 13115c8afd docs: add implementation plan for transport plan copy.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 23:14:14 +08:00
zlwuandCursor 7ca8ad29fa docs: add design for copying transport plans into new form dialog.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 23:12:01 +08:00
zlwu 3d645b4112 提交 2026-08-06 22:49:00 +08:00
zlwu f3693be913 提交 2026-08-06 09:58:20 +08:00
zlwuandCursor 2716c2b6f8 docs: add design for address library edit and contact fill in transport plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 06:52:45 +08:00
zlwu 5cf67f60d1 提交 2026-08-04 15:33:41 +08:00
zlwu 5fe53c5481 提交 2026-08-04 14:02:01 +08:00
zlwuandCursor 012a2ad68e fix(mobile-h5): polish dibang H5 adaptation after typecheck
Simplify App bootstrap, cast HTTP helpers for vue-tsc, and align leftover string ids.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:46:54 +08:00
zlwuandCursor 5f2a6f2338 feat: public vehicle plate options for H5 fill pages; select-only plates
Add GET /api/public/db/vehicle-plates for unauthenticated fill/plan pages and remove manual plate entry plus auto-create.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:44:01 +08:00
zlwuandCursor db06fea45a feat(mobile-h5): wire select-only master data into business forms
Replace master-data CRUD pickers with CRM/PL selectors, require productId, drop auto vehicle create, and remove 基础资料 routes/menu.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:42:24 +08:00
zlwuandCursor a8f59183df feat(mobile-h5): add CRM/PL option APIs and select-only pickers
Provide customer/product/vehicle pickers that search portal master data without create-on-type.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:39:36 +08:00
zlwuandCursor 4520ccbfcb feat(mobile-h5): align db API types to string ids and productId
Switch plans/inventory/weighing/dashboard clients to the db HTTP layer and match web-admin string primary keys.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:39:02 +08:00
zlwuandCursor f1be6bdc8c chore(mobile-h5): deprecate legacy UserService login paths
Point callers away from old /auth/login toward portal fetchLogin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:34:01 +08:00
zlwuandCursor c3f183cfba feat(mobile-h5): adapt portal RSA login and split db HTTP client
Wire login to /web/auth/login with JSEncrypt, unwrap portal envelopes, and add a direct-JSON db client for weighbridge APIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:33:46 +08:00
zlwuandCursor a4b13fa2bc chore(mobile-h5): add existing H5 app sources to the monorepo
Track the weighbridge mobile-h5 codebase (excluding node_modules, dist, and local .env) so subsequent adaptation tasks can evolve it in-repo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:28:53 +08:00
zlwuandCursor f8f9c0ceff chore(mobile-h5): point Vite proxy at unified backend and add jsencrypt
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:27:47 +08:00
zlwuandCursor 26192676a2 docs: add implementation plan for mobile-h5 dibang backend adaptation
Break the approved design into tasks covering login, db HTTP client, select-only master data, and public vehicle plates for fill pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:21:55 +08:00
zlwuandCursor e1170aa855 docs: add mobile-h5 dibang adaptation design for unified backend
Capture the approved approach to point mobile-h5 at shanxia2.0 backend APIs, portal login, and CRM/PL master-data selectors without UI permission gates.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 22:19:38 +08:00
zlwu 732c1b1dc9 提交 2026-08-03 21:20:00 +08:00
zlwu e233269abf 提交 2026-08-03 12:48:52 +08:00
zlwuandCursor 594e4ce38e feat(crm): sync contract number date segment with sign date
Align standard contract nos on create/update (keep seq, bump on collision),
preview the change in contract forms, and sync name parentheses.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 11:46:11 +08:00
zlwuandCursor f01057d902 docs: add implementation plan for contract no follow sign date
Break work into backend align helpers, create/update wiring, and frontend preview tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 11:40:33 +08:00
zlwuandCursor 1c38d82079 docs: add design for contract no date following sign date
Capture agreed rules: keep sequence when sign date changes, frontend preview plus backend authoritative align on save, and sync name parentheses.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-03 11:39:26 +08:00
zlwu 40fc54942b 提交 2026-08-03 00:48:46 +08:00
zlwu 272c68af4b 提交 2026-08-02 17:18:33 +08:00
zlwu c00f19f8bd 提交 2026-08-02 10:49:34 +08:00
zlwuandCursor c86eddac75 fix(web-admin): persist cleared vehicle/personnel photoUrls on save
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:40:04 +08:00
zlwuandCursor 5bf37f802e chore: update graphify and mark vehicle/personnel photo design implemented
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:38:33 +08:00
zlwuandCursor 8d9f5777e0 feat(web-admin): add personnel photo on driver/escort pages
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:37:19 +08:00
zlwuandCursor 9089e455e9 feat(web-admin): add vehicle photo on self-vehicle page
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:36:21 +08:00
zlwuandCursor a552049de4 feat(web-admin): add vehicle photo on tripartite vehicle page
Also include cert attachment list cell already wired in this page WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:34:41 +08:00
zlwuandCursor e2f087e6b9 feat(web-admin): add photoUrls types and pl-photo helpers
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:31:22 +08:00
zlwuandCursor 479851ba4c feat(pl): expose photoUrls on vehicle and personnel APIs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:30:14 +08:00
zlwuandCursor 56b94e1c5b feat(pl): map photo_urls on vehicle and personnel models
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:25:46 +08:00
zlwuandCursor 2f580eca81 chore(db): add photo_urls to pl_vehicle and pl_personnel
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:23:53 +08:00
zlwuandCursor 0d33c35c7b docs: add implementation plan for vehicle/personnel photo fields
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:18:20 +08:00
zlwuandCursor 9af37c3f56 docs: add vehicle/personnel photo field design and UI demo
Capture the approved photo_urls approach (list thumbnail A, optional upload) for pl_vehicle and pl_personnel before implementation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-02 10:13:12 +08:00
zlwu a56b170976 提交 2026-08-02 09:28:47 +08:00
zlwu eccefc6650 提交 2026-08-01 22:49:11 +08:00
zlwu e59b2aa6cb 提交 2026-08-01 17:29:37 +08:00
zlwuandCursor 06956b742b feat(crm): add tenant-level contract approver setting with submit prefill
Mirror the quote approver setting so contract submit dialogs can prefill ordered approvers from a tenant config page while remaining editable.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:37:23 +08:00
zlwuandCursor ce75576fb0 docs: mark quote approver setting design implemented
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:09:13 +08:00
zlwuandCursor 98f33644f1 feat(web-admin): prefill quote submit approvers from tenant setting
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:06:59 +08:00
zlwuandCursor 209f5cb7a8 feat(web-admin): add quote approver setting page and route
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:05:55 +08:00
zlwuandCursor a1e26f044d feat(web-admin): add quote approver setting API client
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:04:29 +08:00
zlwuandCursor 8646f33587 feat(crm): expose quote approver setting get/save APIs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:04:07 +08:00
zlwuandCursor ffbb5e36b3 feat(crm): implement quote approver setting model and upsert CRUD
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:03:35 +08:00
zlwuandCursor 82e648de9f feat(crm): add quote approver setting table and menu SQL
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:02:47 +08:00
zlwuandCursor 3aafae6a9d feat(crm): add quote approver setting id helpers and unit tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 12:54:29 +08:00
zlwuandCursor 10c3c5470c chore: sync local PL/CRM/BX and migration work to new Gogs host
Bundle pending backend/web-admin feature updates, data-migration scripts,
and related docs so the V1.5 branch on the Tencent Cloud Gogs matches the
current workspace (excluding local secrets).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 09:19:21 +08:00
zlwuandCursor 5a9abfdd5d fix(pl): keep multi-brand site feedback when plan product row is stale
Persist submitted brand qtys even if plan brand_mode lookup fails; resolve soft-deleted plan products for brand metadata instead of substituting another product; stop seeding all actual qty onto the first brand option.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 07:06:41 +08:00
zlwuandCursor d1daedc17d docs: update brand qty demo copy for required-as-preference
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:58:06 +08:00
zlwuandCursor e6a1c1db2b fix(web-admin): align site/driver public brand qty with preference semantics
Ensure required mode keeps full brand options and multi-select entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:58:06 +08:00
zlwuandCursor c39c0e2760 fix(web-admin): driver feedback dialog multi-brand for required preference
Load full brand options and preselect preferred brand without locking.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:58:06 +08:00
zlwuandCursor 07cadc9025 fix(web-admin): archive dialog loads all brands for required preference
Preselect preferred brand but allow multi-brand qty entry like any mode.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:58:06 +08:00
zlwuandCursor b28cf4a335 fix(web-admin): allow multi-brand chips when plan brand is required
Treat required like any in BrandQtyChipsField so preference brand is not locked.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:54:43 +08:00
zlwuandCursor 156e4b63e5 fix(pl): treat required brand as preference in brand qty validation
Allow multi-brand feedback/archive rows when plan brandMode is required; only enforce sum equals actual qty.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:52:49 +08:00
zlwuandCursor b3efbe8781 docs: specify transport plan required brand as preference only
Document that feedback/archive brand qty entry uses any-mode multi-select with preferred-brand preselect, removing the single-brand hard lock.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 06:50:21 +08:00
zlwuandCursor 6dcc279cc9 test(pl): verify feedback brand qty and refresh graphify
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:40:05 +08:00
zlwuandCursor aea4caed5b feat(web-admin): align archive brand qty entry with chips UI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:37:00 +08:00
zlwuandCursor 5c323f32c2 feat(web-admin): show brand qty on transport tab and highlight supplement actions
Expose driver per-product feedback on transport read, display site/driver
brand summaries in the transport tab, move supplement buttons to section
headers with primary highlight, and wire brand chips into IO/driver edit.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:35:42 +08:00
zlwuandCursor b7236329c2 feat(web-admin): driver feedback dialog brand qty entry
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:31:22 +08:00
zlwuandCursor 2a215b2e1f feat(pl): driver public feedback by product and brand qty
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:29:21 +08:00
zlwuandCursor 0667e8d77b fix(web-admin): bind branded site actual qty to chip sum on load
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:25:03 +08:00
zlwuandCursor 6dde2cec07 feat(web-admin): site public page brand qty chips entry
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:23:37 +08:00
zlwuandCursor 006ed6586c feat(pl): site io-order feedback accepts and stores brand qtys
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:17:50 +08:00
zlwuandCursor b0346e688d feat(pl): add feedback brand qty persist helpers and tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:14:54 +08:00
zlwuandCursor 79f87d39a7 feat(pl): add ORM models for feedback brand qty tables
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:11:51 +08:00
zlwuandCursor 5538fa3152 fix(db): drop unrelated shanxia2.0.sql diffs from brand qty migrate
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:10:07 +08:00
zlwuandCursor b658591818 chore(db): add feedback brand qty tables for site and driver
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:07:53 +08:00
zlwuandCursor fb76940d15 docs: add implementation plan for feedback brand qty
Break down site/driver brand quantity feedback into DDL, APIs,
shared chips UI, view-tab layout, and archive alignment tasks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:02:46 +08:00
zlwuandCursor 4e6e06a603 docs: add transport feedback brand qty design and demo
Capture the approved design for site/driver brand quantity feedback,
independent storage from archive, and view-tab/button layout changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-31 05:00:36 +08:00
zlwuandCursor dd4aa734ee chore: sync remaining local plan, form mapping and graphify cache
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 10:05:03 +08:00
zlwuandCursor 44a57b86ca chore: update graphify after brand/alias inventory work
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:38:07 +08:00
zlwuandCursor dd31fb53b6 chore(db): add optional script to split brand from product names
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:36:32 +08:00
zlwuandCursor 7aa995a9d6 feat(pl): show archive brand breakdown on inbound/outbound orders
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:36:15 +08:00
zlwuandCursor e7d7e731ba feat(web-admin): show brand on inventory ledger and transactions
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:35:42 +08:00
zlwuandCursor 38b1613fee feat(web-admin): enter archive inbound/outbound qty by brand
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:35:05 +08:00
zlwuandCursor cc2edfc61f feat(pl): post brand-level inventory on plan archive
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:34:07 +08:00
zlwuandCursor 32533948e3 feat(pl): validate and persist archive quantities by brand
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:32:36 +08:00
zlwuandCursor c35627d60a feat(pl): show brand constraint on plan product rows
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:31:51 +08:00
zlwuandCursor cd33befa07 feat(web-admin): choose display name and brand constraint on quote/contract lines
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:30:38 +08:00
zlwuandCursor ba98108659 feat(crm): snapshot brand mode on quote and contract lines
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:23:50 +08:00
zlwuandCursor bcfadd23d9 feat(web-admin): edit product brands and aliases in product form
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:22:29 +08:00
zlwuandCursor bfa0d50597 feat(crm): persist product brands and aliases on create/update
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:21:31 +08:00
zlwuandCursor ea43150b8a feat(models): add product brand/alias and plan brand qty models
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:18:32 +08:00
zlwuandCursor 265a4ff4f7 chore(db): add product brand/alias and brand-level inventory schema
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-28 09:16:52 +08:00
zlwuandCursor a79dd9f61d docs(crm): add product brand and alias implementation plan.
Break the approved design into sequenced tasks from DDL through archive inventory posting and UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:47:38 +08:00
zlwuandCursor d7e0edf2d5 docs(crm): add product brand and alias design spec.
Capture the agreed model: per-product brands, document-line brand constraints, archive-time brand quantities, and brand-level inventory.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:42:53 +08:00
zlwuandCursor 768ef934f9 chore: update graphify after pl batch print merge
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:17:00 +08:00
zlwuandCursor 246da286e2 feat(web-admin): enable multi-select batch slip print on plan list toolbar
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:16:19 +08:00
zlwuandCursor 25978401e1 feat(web-admin): allow multi planIds in transport slip print dialogs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:15:41 +08:00
zlwuandCursor e930e583a9 feat(web-admin): support per-row planNo and multiline remarks on slip templates
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:14:59 +08:00
zlwuandCursor bbcb2b8936 feat(web-admin): add batch print merge helpers for transport plans
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 21:13:19 +08:00
zlwuandCursor 92736acced docs(pl): add batch print merge implementation plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 20:45:00 +08:00
zlwuandCursor 8d76c6bec6 docs(pl): 运输计划多选合打打印设计与交互 Demo
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 20:39:39 +08:00
zlwuandCursor ada592924a docs(pl): add create_date implementation plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 16:30:35 +08:00
zlwuandCursor b5c49e3fc8 chore: update graphify after pl_plan create_date
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 16:30:29 +08:00
zlwuandCursor a276f09350 feat(web-admin): add createDate and default pickup/delivery on plan forms
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 16:29:35 +08:00
zlwuandCursor 349e031790 feat(pl): persist create_date on plan create APIs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 16:29:35 +08:00
zlwuandCursor bb7f05ffda feat(pl): add create_date to PlPlan model and schemas
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 16:29:35 +08:00
zlwuandCursor 5ebaec2e2e chore(pl): add pl_plan.create_date migration and DDL snapshot
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 16:27:32 +08:00
zlwuandCursor 60841264e0 docs(pl): 运输计划创建日期字段与取货/送达默认设计
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-27 09:06:32 +08:00
zlwu bede140d12 提交 2026-07-26 21:06:09 +08:00
zlwuandCursor 70bdd820ce feat(pl): 按单据类型限制打印项并调整送(提)货单布局
按入库/出库/直销限制可打印单据;送(提)货单信息区改为一行布局,物料表增加单据编号列,并修正条款列宽与类型多选不换行。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-26 21:05:11 +08:00
zlwu 1e2e8ab0fc 提交 2026-07-25 23:29:48 +08:00
zlwuandCursor a46018a507 chore: track graphify AST cache and local worktrees metadata
Commit backend/graphify-out/cache and .worktrees so local graphify/worktree scaffolding is shared on this branch.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 23:28:55 +08:00
zlwuandCursor 31b0db6840 feat(bx): 报销可代选申请人,并放宽主数据选项的数据权限过滤
支持具备 changeApplicant 权限时代填申请人及发票/余额联动;系统/CRM/BX/PL 主数据与下拉选项改为仅租户隔离,避免「仅本人」导致空选项。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 23:27:23 +08:00
zlwuandCursor 6c2121d7fc fix(bx): 发票夹多附件一次入账并优化查看列表展示
一次上传多个文件只创建一条发票与额度流水;管理端/我的发票夹查看列表改为缩略图附件,并调整弹窗与列宽。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 21:42:30 +08:00
zlwuandCursor 074554ac4e docs(bx): document invoice wallet and refresh graphify
Update business inventory for invoice wallet tables/APIs/menus and mark
the design spec as implemented; refresh code knowledge graphs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 19:46:05 +08:00
zlwuandCursor dadf903bff feat(bx): invoice wallet UI and reimburse apply invoice select
Add mine/admin wallet pages, select dialog, routes/icons, and switch
apply form from local invoice upload to optional wallet association with
balance gate; approve detail shows linked invoices.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 19:46:00 +08:00
zlwuandCursor 6092b685de feat(bx): debit invoice balance on submit; release on reject/withdraw
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 19:32:55 +08:00
zlwuandCursor 7a26e5cf58 feat(bx): invoice upload/delete APIs and wallet summary
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 19:13:23 +08:00
zlwuandCursor 1567762ceb feat(bx): invoice ledger balance service with unit tests
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 19:11:53 +08:00
zlwuandCursor 51668af872 feat(bx): add invoice wallet ORM models
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:58:26 +08:00
zlwuandCursor bb1b2b1375 feat(bx): add invoice wallet DDL, menu seeds, and design docs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:50:54 +08:00
zlwuandCursor 715ccbd637 fix(web-admin): 报销弹窗表单改为上下布局并加大分块间距
将报销管理新增/编辑弹窗的 label 改为 top 布局,并增加报销申请中明细、附件、备注等分块与上方内容的间距。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:27:08 +08:00
zlwuandCursor c756fbddfc fix(web-admin): 对齐门户顶栏 brand 与侧栏右边框,并修复侧栏竖线被遮挡
将侧栏右边框改画在 #app-sidebar 上,内部菜单改为宽度 100%,避免等宽子项盖住边框;顶栏 brand 宽度与侧栏展开宽度对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:15:53 +08:00
zlwuandCursor 9b8131fa40 chore: 补交 web-admin graphify AST 本地缓存文件
同步 TinyMCE 与出入库单据模板相关变更后的 AST 缓存,便于本地增量更新图谱。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:04:07 +08:00
zlwuandCursor 3d5866aa14 feat(web-admin): TinyMCE 表格类 Excel 调宽调高,并优化出入库/分装/送货单排版
支持合同、报价与入库/分装/送(提)货单在富文本中拖拽调整列宽行高;单据侧加宽物料编号与名称、收窄规格单位、放大 logo、加宽条款区,并弱化调整手柄绿色阴影。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 18:02:22 +08:00
zlwuandCursor 2380b01a4f chore: 补交 graphify AST 本地缓存文件
将此前未纳入版本库的 backend/web-admin graphify-out/cache/ast 缓存一并提交,便于知识图谱增量更新复用。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 15:49:24 +08:00
zlwuandCursor 87bd0d92b9 feat(pl): 承运商资质附件改为选填并支持拖拽粘贴上传
取消承运商营业执照/许可证/运输协议的必填校验,附件组件支持拖拽与区域粘贴上传,并同步知识图谱。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 15:47:10 +08:00
zlwuandCursor 55410191ec chore: 同步 PL 三方分册相关知识图谱
后端/前端 AST 图谱随证书门禁、粘贴识别与菜单分册改动更新。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 12:57:44 +08:00
zlwuandCursor 6258821273 feat(web-admin): 三方车辆/人员粘贴识别弹窗与入口
共享识别预览弹窗,支持冲突三选一,并在三方车辆与三方驾押人员工具栏接入。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 12:54:50 +08:00
zlwuandCursor c60ebfc082 feat(pl): 三方粘贴识别批量提交接口
新增 paste-recognize/commit,事务内处理车/人冲突策略与关联写入。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 12:52:09 +08:00
zlwuandCursor b1e788e856 feat(web-admin): 三方车辆客户文本粘贴解析工具
为三方车辆/人员粘贴识别提供规则解析纯函数。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:58:52 +08:00
zlwuandCursor fd62043f71 feat(web-admin): 承运商去审核 UI 并移除安排运输准入拦截
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:58:24 +08:00
zlwuandCursor 4eed1183b5 fix(web-admin): 三方驾押人员查看态不显示证书缺失后缀
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:57:23 +08:00
zlwuandCursor 5543f26dca feat(web-admin): 驾押人员页按归属分册并仅山峡强制证书
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:57:04 +08:00
zlwuandCursor 3396e3d164 feat(web-admin): 全部车辆页改为三方车辆并关闭证书强制
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:56:16 +08:00
zlwuandCursor 8ba55dd6f6 feat(pl): 基础信息库四菜单分册(三方/山峡)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:54:48 +08:00
zlwuandCursor d92bd7940e fix(pl): 取消承运商审核与资质协议准入门禁
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:49:12 +08:00
zlwuandCursor b071687a71 fix(pl): 三方车辆与人员保存跳过必备证书校验
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:45:26 +08:00
zlwuandCursor db4907ec28 docs(pl): 三方/山峡车辆人员分册与粘贴建档实现计划
按已批准设计拆为证书门禁、菜单路由、粘贴提交与承运商去准入等可执行任务。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:41:25 +08:00
zlwuandCursor 47c1017923 docs(pl): 三方/山峡车辆人员分册与粘贴建档设计
固化四菜单分册、三方证书不强制、粘贴识别双入口与承运商去准入规则,供后续实现计划使用。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-25 10:36:10 +08:00
zlwu 68d96f87ff 提交 2026-07-22 21:26:33 +08:00
zlwu aff71d296b 提交 2026-07-20 10:50:26 +08:00
zlwuandCursor 6d9354a194 chore: 更新 PL 相关知识图谱并修复 update-graph.sh 探测逻辑
使用本机 graphify CLI 强制重建 backend/web-admin 图谱;脚本改为优先走 PATH 中的 graphify。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 17:22:31 +08:00
zlwuandCursor aa5fbe7780 docs(pl): 出入库现场状态可选设计、实现计划与 D5 旁注
记录显式 status 提交流程,并标注旧出入库设计中现场自动完成规则已被覆盖。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 17:16:39 +08:00
zlwuandCursor dee85f182e feat(web-admin): 出入库现场页支持选择单据状态并作废只读
提交携带 status;作废需确认;作废后整页只读可查看。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 17:14:23 +08:00
zlwuandCursor 1df9bbe22a feat(web-admin): 出入库现场回执 API 增加 status 字段
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 17:14:22 +08:00
zlwuandCursor 664acff1f3 feat(pl): 现场回执提交显式写入出入库单状态
删除首次提交自动改为已完成的隐式逻辑,改为由客户端传入 status。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 17:13:40 +08:00
zlwuandCursor 2474449448 feat(web-admin): 补齐出入库单页面入口与公共路由
登记库存管理入库/出库菜单路由,以及免登录现场链接静态路由与薄包装页。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:47:32 +08:00
zlwuandCursor 3f23feba59 feat(web-admin): 计划查看出入库回传补齐取送货与产品列
查看 KV、只读子表与快捷编辑弹窗与入库/出库单编辑弹窗字段对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:47:03 +08:00
zlwuandCursor 4d88ceb65e feat(web-admin): 出入库列表与编辑弹窗展示取送货及完整产品列
列表增加取送货地址;编辑弹窗主信息与产品八列对齐设计。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:47:02 +08:00
zlwuandCursor 8b2ebe28e6 feat(web-admin): 出入库现场链接页对齐 Demo 信息密度与样式
补回取送货与导航,产品区卡片展示包装规格,单位使用后端已转义标签。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:47:01 +08:00
zlwuandCursor 8b7f6d99c8 feat(web-admin): 扩展出入库单与公共页 TypeScript 类型
为 enrichment 返回的取送货、产品编号、包装规格与单位标签补齐前端类型。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:47:00 +08:00
zlwuandCursor f5a0931471 feat(pl): 出入库 API 接入 enrichment 并扩展 schema
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:43:42 +08:00
zlwuandCursor 4f69a9b904 feat(pl): 出入库单读时 enrichment 取送货与产品扩展字段
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:39:20 +08:00
zlwuandCursor dbd0d9f205 docs: 出入库单现场链接与信息完善实现计划
按已确认 design 拆分为 enrichment、公共页、列表弹窗与计划回传共 7 个可勾选任务。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:37:55 +08:00
zlwuandCursor 9a1e43e371 docs: 入库/出库单现场链接与信息完善设计说明
记录公共页对齐 Demo、管理端列表/弹窗/计划回传补取送货与产品字段的方案 A,供实现引用。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-19 16:35:37 +08:00
zlwu c6eb4437d0 提交 2026-07-19 10:16:34 +08:00
zlwu 259c55cc23 提交 2026-07-18 09:14:02 +08:00
zlwu a903fcf6d4 提交 2026-07-17 21:59:47 +08:00
zlwu 8be55c08e9 提交 2026-07-16 08:13:05 +08:00
zlwu 5c6ace1dd3 提交 2026-07-15 08:05:38 +08:00
zlwu 87f7f6bf38 提交 2026-07-14 19:53:35 +08:00
zlwu 0e60b88cba 提交 2026-07-13 20:26:43 +08:00
zlwu 3520f9ce90 提交 2026-07-12 18:23:02 +08:00
zlwu 2142b33cfa 提交 2026-07-12 17:55:11 +08:00
zlwu c2cba3e668 提交 2026-07-12 17:14:53 +08:00
zlwu ffc89d9b57 提交 2026-07-12 12:04:43 +08:00
zlwu 7b1d4c8729 提交 2026-07-11 17:15:17 +08:00
zlwu 843e13bce3 提交 2026-07-05 21:31:07 +08:00
zlwu 31be9bfd95 提交 2026-07-05 14:01:19 +08:00
zlwu 54b27a3f0e 提交 2026-07-05 10:07:24 +08:00
zlwu 33c038b8d9 提交 2026-07-04 08:21:49 +08:00
zlwu b4a49183db 提交 2026-07-04 08:21:06 +08:00
zlwu 8e70047f4c 提交 2026-07-01 18:52:26 +08:00
zlwu 7c838cfb2d 提交 2026-06-30 23:44:22 +08:00
zlwu d84f4b944c 提交 2026-06-29 11:15:39 +08:00
zlwuandCursor 493f8d6756 docs: 补充数据权限分批实施计划并更新知识图谱
记录 Phase 0–6 改造范围与 PR 切分建议,同步 backend/web-admin graphify 输出。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:00:35 +08:00
zlwuandCursor 98aec80d71 feat(pl): 运费结算审批分流与车辆挂车号等 PL 能力完善
拆分运费审批/出款页面,补充结算发票附件与菜单 SQL,并同步前后端模型与车辆相关展示。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:00:31 +08:00
zlwuandCursor 66d5a8714b feat(db): 地磅、操作日志与工作流补全数据权限过滤
DB 列表/仪表盘 scoped 聚合,操作日志按 user_id 过滤,工作流实例详情与审批前校验 scope。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:00:19 +08:00
zlwuandCursor 2905dc3d5f feat(bx): 报销模块接入数据权限过滤
新增 bx_data_scope 与 BxUserContext.to_user_info,列表/我的单据 AND scope,待办审批不加 scope,审批操作 skip_scope。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:00:18 +08:00
zlwuandCursor eff99edeea feat(pl): 运输计划模块接入数据权限过滤
新增 pl_data_scope 辅助,PL 列表/统计 apply_pl_scope,详情与改删 assert_pl_row_in_scope;运费结算待办审批 skip_scope。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:00:15 +08:00
zlwuandCursor bf73b6b2d8 feat(crm): 联系人、产品、报价与合同域接入数据权限过滤
补全 PR3 Phase 2.4–2.7,列表 apply_data_scope、详情/CUD assert_row_in_data_scope,合同/报价主表支持 owner_user_id。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:00:12 +08:00
zlwuandCursor ee531e9cfe feat(crm): 商机域接入数据权限过滤(PR3 Task 2.3)
主表列表/统计/看板/漏斗按 owner_user_id 过滤,CUD 与跟进/产品子表校验父商机 scope。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 20:33:05 +08:00
zlwuandCursor 3107d537f6 feat(crm): 客户与线索模块接入数据权限过滤
列表按 owner_user_id/create_by 过滤,详情与 CUD 校验 scope;公海客户列表保持租户内全员可见。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 20:30:41 +08:00
zlwuandCursor f5ab023ab5 feat(auth): 扩展数据权限核心能力并接入系统管理辅助接口
为 apply_data_scope 增加 owner_field 与行级校验,补充 DbUserContext.to_user_info() 及单元测试,并在用户/角色/字典下拉与用户详情接口生效。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 20:30:36 +08:00
zlwu 86450f38a1 提交 2026-06-25 08:06:32 +08:00
zlwu 6b6c80f182 提交 2026-06-23 23:30:57 +08:00
zlwu c90f72fd34 提交 2026-06-21 22:20:03 +08:00
zlwu cedb7ee681 提交 2026-06-21 12:56:33 +08:00
zlwu e46c0480d4 提交 2026-06-21 12:41:39 +08:00
zlwu 299609706c 提交 2026-06-21 09:19:07 +08:00
zlwu c3be9d1dce 提交 2026-06-10 22:59:34 +08:00
zlwu 725774ef0c 提交 2026-06-07 00:40:01 +08:00
zlwu f9676f8759 提交 2026-06-06 19:44:18 +08:00
zlwu dacfdc9ff6 提交 2026-06-01 08:21:21 +08:00
zlwu 9b88581450 提交“ 2026-05-30 14:03:11 +08:00
zlwu 69ee0f505c 提交 2026-05-28 20:10:34 +08:00
zlwu 239d0a03d7 提交 2026-05-28 20:04:27 +08:00
zlwu 912ada02eb 提交 2026-05-28 19:11:31 +08:00
zlwu 5e91791ebf 提交 2026-05-28 14:19:18 +08:00
zlwu 3c7a47981a 提交 2026-05-28 13:05:46 +08:00
zlwu f1f5d24eff 提交 2026-05-28 08:37:37 +08:00
zlwu 2020f371f4 提交 2026-05-28 07:59:08 +08:00
zlwu 4ff289a8cf 提交 2026-05-28 07:37:16 +08:00
zlwu b6c63591ea 提交 2026-05-28 00:15:29 +08:00
zlwu c137b46939 提交 2026-05-27 16:52:46 +08:00
zlwu 7145c6c683 提交 2026-05-27 06:22:08 +08:00
zlwu 41aa90aa05 提交 2026-05-27 05:23:28 +08:00
zlwu ad8f8d696f 提交 2026-05-26 22:31:48 +08:00
zlwu 3f122da803 提交 2026-05-26 21:27:48 +08:00
zlwu edf88dc016 提交 2026-05-26 19:04:27 +08:00
zlwu 4a00f21bfb feat(qc): integrate OutboundQcViewDialog into QC work order page 2026-05-26 18:52:59 +08:00
zlwu b20c9f7bd7 feat(qc): add outbound QC work order tab with list, filters and action buttons 2026-05-26 18:43:49 +08:00
zlwu b32196690b feat(qc): add outbound QC detail API types and fetch function 2026-05-26 18:37:42 +08:00
zlwu c9f369a276 feat(qc): extend outbound work order list API with application/infusion fields and bizType filter 2026-05-26 18:29:56 +08:00
zlwu fa60330752 feat(qc): add biz_type column to qc_work_order table for outbound business type 2026-05-26 18:24:50 +08:00
zlwu 6bdcd0a565 feat(production): add outbound work order tab, columns, and detail dialog with pilot application and infusion schedule sections 2026-05-26 18:17:15 +08:00
zlwu 11f8d2973b feat(pilot): auto-create outbound production work order on schedule creation and auto-void on deletion 2026-05-26 18:06:26 +08:00
zlwu d84f5056f2 feat(production): extend CRUD for outbound work orders — biz_type, yzf status, list/detail enrichment 2026-05-26 18:04:03 +08:00
zlwu d93b16ab0c feat(production): add biz_type field to BizProductionWorkOrder model 2026-05-26 17:58:07 +08:00
zlwu 482369d4ec feat(production): add biz_type column and yzf status for outbound work orders 2026-05-26 17:55:03 +08:00
zlwu 065e6c34b4 提交 2026-05-26 12:32:19 +08:00
zlwu bb8c981afd 提交 2026-05-25 20:54:11 +08:00
zlwu c4cc7009e3 提交 2026-05-25 19:27:30 +08:00
zlwu ee4abd361e 提交 2026-05-25 17:43:49 +08:00
zlwu 771f010a39 提交 2026-05-25 15:14:06 +08:00
zlwu 575e63e7e8 提交 2026-05-24 23:04:33 +08:00
zlwu 13e4c9530a 提交 2026-05-24 17:57:28 +08:00
zlwu 7cec1f2190 提交 2026-05-24 16:58:51 +08:00
zlwu 9dd7eb56ba 提交 2026-05-24 11:03:15 +08:00
zlwu 93f5801aa9 提交 2026-05-24 10:42:11 +08:00
zlwu 2eb1807fe6 提交 2026-05-24 10:21:14 +08:00
zlwu 9a93140391 提交 2026-05-24 10:03:00 +08:00
zlwu 3d4a41a944 提交 2026-05-24 09:43:01 +08:00
zlwu 2f350e7d73 提交 2026-05-24 09:34:01 +08:00
zlwu 07ed8c7a60 提交 2026-05-24 08:34:01 +08:00
zlwu ea5dedf059 提交 2026-05-23 21:48:49 +08:00
zlwu 7fbf71b6e1 提交 2026-05-23 21:27:10 +08:00
zlwu 05684ba2a4 提交 2026-05-23 14:49:50 +08:00
zlwu fb85230d25 提交 2026-05-23 12:51:22 +08:00
zlwu 3779de12ce 提交 2026-05-23 11:41:57 +08:00
zlwu 19de2040d0 提交 2026-05-22 16:33:17 +08:00
zlwu 1f5de9030e 提交 2026-05-22 16:25:04 +08:00
zlwu 53d3b21f57 提交 2026-05-22 12:40:22 +08:00
zlwu 320f7e75f0 提交 2026-05-22 11:43:41 +08:00
zlwu 5254eea4a2 提交 2026-05-22 07:16:53 +08:00
zlwu 87dbbf1247 提交 2026-05-21 21:29:54 +08:00
zlwu b0eb80a2d4 提交 2026-05-21 20:56:57 +08:00
zlwu 7541a167c0 提交 2026-05-21 18:59:46 +08:00
zlwu a905d80623 提交 2026-05-21 13:32:47 +08:00
zlwu d387ba4017 提交 2026-05-21 13:20:15 +08:00
zlwu 14f1a84bb3 提交 2026-05-21 12:53:37 +08:00
zlwu ad0e849f6d 提交 2026-05-21 11:25:43 +08:00
zlwu 74f751d0d1 提交 2026-05-21 11:09:29 +08:00
zlwu ee73f69759 提交 2026-05-21 05:11:53 +08:00
zlwu c55269de86 提交 2026-05-21 03:48:06 +08:00
zlwu 6272d107dc 提交 2026-05-20 21:12:16 +08:00
zlwu e6b4b9a8d7 提交 2026-05-20 20:41:47 +08:00
zlwu c6c3a37fa7 提交 2026-05-20 18:06:21 +08:00
zlwu 276299ff27 提交 2026-05-20 15:10:55 +08:00
zlwu 27ac28b8f5 提交 2026-05-20 14:53:16 +08:00
zlwu dc31968204 提交 2026-05-20 14:32:07 +08:00
zlwu 15ed25e33b 提交 2026-05-20 09:30:10 +08:00
zlwu be4fab78e1 提交 2026-05-20 09:28:36 +08:00
zlwu e6072457fd feat(qc): implement material library with CRUD, stock-in, usage tracking and task deduction 2026-05-20 06:36:50 +08:00
zlwu 4137c54588 feat(qc): add SQLAlchemy models for QC material and usage 2026-05-20 06:27:40 +08:00
zlwu 18132c8034 feat(qc): add DDL for QC material library and usage tables 2026-05-20 06:26:24 +08:00
zlwu c55bc55138 fix(models): remove relationship declarations that require ForeignKey constraints
The project does not use SQLAlchemy ORM-level relationships or ForeignKey
constraints. All joins are done manually in CRUD queries. The relationship()
declarations on BizProductionWorkOrder.tasks and BizProductionTask.steps
caused mapper initialization failures because the child table columns lack
ForeignKey definitions.
2026-05-20 05:19:20 +08:00
zlwu f464c22b9e feat(production): add production work order management page 2026-05-20 00:59:51 +08:00
zlwu eec59de5dc feat(production): add production task execution page 2026-05-20 00:57:02 +08:00
zlwu 5f8eac3523 feat(production): add cell product management page 2026-05-20 00:56:53 +08:00
zlwu 375c975c33 feat(router): add frontend routes for cell product, work order, and task 2026-05-20 00:56:45 +08:00
zlwu 2d3f55918f feat(production): trigger production work order on sample reception 2026-05-20 00:56:34 +08:00
zlwu b303afb272 feat(crud): add cell product CRUD operations 2026-05-20 00:56:24 +08:00
zlwu 96a0c394c2 feat(api): add production work order, production task, and cell product API modules 2026-05-20 00:25:09 +08:00
zlwu 4b676886b0 feat: append 21 API routes for work orders, production tasks, and cell products to production router 2026-05-20 00:22:21 +08:00
zlwu fb7846f2ed feat(crud): add production task CRUD with route-cloning logic 2026-05-20 00:11:57 +08:00
zlwu 9d9f43579d feat(crud): add production work order CRUD operations 2026-05-20 00:10:35 +08:00
zlwu 026b040db5 feat(schemas): add production module Pydantic schemas
Create 3 schema files for the production module:
- production_work_order.py: work order base, list query, complete
- production_task.py: task CRUD, steps, materials, outputs, inputs
- cell_product.py: cell product create, update, list query
2026-05-20 00:09:21 +08:00
zlwu 61f217eea5 feat(models): 新增10个生产执行相关SQLAlchemy模型
新增细胞产品、生产工单、生产任务及关联的投入/步骤/试剂/耗材/产出/数据采集等模型类,
支持工单→任务→步骤的relationship关联查询。
2026-05-20 00:05:24 +08:00
zlwu 67ba7c48d5 feat(production): add DDL for 10 production tables and 3 menus
Create docs/sql/production_work_order.sql with:
- 10 CREATE TABLE IF NOT EXISTS statements for production work order module
- 3 sys_menu INSERT statements under 生产管理 parent menu
2026-05-19 23:59:55 +08:00
zlwu 3b875ec370 提交 2026-05-19 23:12:56 +08:00
zlwu 93cd506a90 提交 2026-05-19 12:03:08 +08:00
zlwu f269a994f4 提交 2026-05-18 16:21:38 +08:00
zlwu 2a4767a014 提交 2026-05-17 23:08:38 +08:00
zlwu 135dd550b6 提交 2026-05-17 12:36:40 +08:00
zlwu 62cfb8fbbf 提交 2026-05-17 12:31:11 +08:00
zlwu e5ba8f097a 提交 2026-05-17 09:05:10 +08:00
zlwu 8e2dd8b9f0 提交 2026-05-17 08:36:37 +08:00
zlwuandCursor 246ad2228e docs: add cell storage protocol modules design for 2.2.6–2.2.10
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 17:48:22 +08:00
zlwu 058811ae77 提交 2026-05-12 22:07:53 +08:00
zlwuandCursor c87732fcd5 将 web-admin 从子模块改为仓库内普通目录,便于单仓克隆与维护。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 16:41:08 +08:00
zlwu 2e9d020d50 提交 2026-05-12 16:35:07 +08:00
zlwu d336fd0226 提交 2026-05-12 14:42:05 +08:00
zlwu 545ada33e5 first commit 2026-05-11 09:21:41 +08:00
3072 changed files with 892008 additions and 1 deletions

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
---
name: brainstorming
description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation."
---
# Brainstorming Ideas Into Designs
Help turn ideas into fully formed designs and specs through natural collaborative dialogue.
Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design and get user approval.
<HARD-GATE>
Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity.
</HARD-GATE>
## Anti-Pattern: "This Is Too Simple To Need A Design"
Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval.
## Checklist
You MUST create a task for each of these items and complete them in order:
1. **Explore project context** — check files, docs, recent commits
2. **Offer visual companion** (if topic will involve visual questions) — this is its own message, not combined with a clarifying question. See the Visual Companion section below.
3. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria
4. **Propose 2-3 approaches** — with trade-offs and your recommendation
5. **Present design** — in sections scaled to their complexity, get user approval after each section
6. **Write design doc** — save to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md` and commit
7. **Spec self-review** — quick inline check for placeholders, contradictions, ambiguity, scope (see below)
8. **User reviews written spec** — ask user to review the spec file before proceeding
9. **Transition to implementation** — invoke writing-plans skill to create implementation plan
## Process Flow
```dot
digraph brainstorming {
"Explore project context" [shape=box];
"Visual questions ahead?" [shape=diamond];
"Offer Visual Companion\n(own message, no other content)" [shape=box];
"Ask clarifying questions" [shape=box];
"Propose 2-3 approaches" [shape=box];
"Present design sections" [shape=box];
"User approves design?" [shape=diamond];
"Write design doc" [shape=box];
"Spec self-review\n(fix inline)" [shape=box];
"User reviews spec?" [shape=diamond];
"Invoke writing-plans skill" [shape=doublecircle];
"Explore project context" -> "Visual questions ahead?";
"Visual questions ahead?" -> "Offer Visual Companion\n(own message, no other content)" [label="yes"];
"Visual questions ahead?" -> "Ask clarifying questions" [label="no"];
"Offer Visual Companion\n(own message, no other content)" -> "Ask clarifying questions";
"Ask clarifying questions" -> "Propose 2-3 approaches";
"Propose 2-3 approaches" -> "Present design sections";
"Present design sections" -> "User approves design?";
"User approves design?" -> "Present design sections" [label="no, revise"];
"User approves design?" -> "Write design doc" [label="yes"];
"Write design doc" -> "Spec self-review\n(fix inline)";
"Spec self-review\n(fix inline)" -> "User reviews spec?";
"User reviews spec?" -> "Write design doc" [label="changes requested"];
"User reviews spec?" -> "Invoke writing-plans skill" [label="approved"];
}
```
**The terminal state is invoking writing-plans.** Do NOT invoke frontend-design, mcp-builder, or any other implementation skill. The ONLY skill you invoke after brainstorming is writing-plans.
## The Process
**Understanding the idea:**
- Check out the current project state first (files, docs, recent commits)
- Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., "build a platform with chat, file storage, billing, and analytics"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first.
- If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → plan → implementation cycle.
- For appropriately-scoped projects, ask questions one at a time to refine the idea
- Prefer multiple choice questions when possible, but open-ended is fine too
- Only one question per message - if a topic needs more exploration, break it into multiple questions
- Focus on understanding: purpose, constraints, success criteria
**Exploring approaches:**
- Propose 2-3 different approaches with trade-offs
- Present options conversationally with your recommendation and reasoning
- Lead with your recommended option and explain why
**Presenting the design:**
- Once you believe you understand what you're building, present the design
- Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced
- Ask after each section whether it looks right so far
- Cover: architecture, components, data flow, error handling, testing
- Be ready to go back and clarify if something doesn't make sense
**Design for isolation and clarity:**
- Break the system into smaller units that each have one clear purpose, communicate through well-defined interfaces, and can be understood and tested independently
- For each unit, you should be able to answer: what does it do, how do you use it, and what does it depend on?
- Can someone understand what a unit does without reading its internals? Can you change the internals without breaking consumers? If not, the boundaries need work.
- Smaller, well-bounded units are also easier for you to work with - you reason better about code you can hold in context at once, and your edits are more reliable when files are focused. When a file grows large, that's often a signal that it's doing too much.
**Working in existing codebases:**
- Explore the current structure before proposing changes. Follow existing patterns.
- Where existing code has problems that affect the work (e.g., a file that's grown too large, unclear boundaries, tangled responsibilities), include targeted improvements as part of the design - the way a good developer improves code they're working in.
- Don't propose unrelated refactoring. Stay focused on what serves the current goal.
## After the Design
**Documentation:**
- Write the validated design (spec) to `docs/superpowers/specs/YYYY-MM-DD-<topic>-design.md`
- (User preferences for spec location override this default)
- Use elements-of-style:writing-clearly-and-concisely skill if available
- Commit the design document to git
**Spec Self-Review:**
After writing the spec document, look at it with fresh eyes:
1. **Placeholder scan:** Any "TBD", "TODO", incomplete sections, or vague requirements? Fix them.
2. **Internal consistency:** Do any sections contradict each other? Does the architecture match the feature descriptions?
3. **Scope check:** Is this focused enough for a single implementation plan, or does it need decomposition?
4. **Ambiguity check:** Could any requirement be interpreted two different ways? If so, pick one and make it explicit.
Fix any issues inline. No need to re-review — just fix and move on.
**User Review Gate:**
After the spec review loop passes, ask the user to review the written spec before proceeding:
> "Spec written and committed to `<path>`. Please review it and let me know if you want to make any changes before we start writing out the implementation plan."
Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.
**Implementation:**
- Invoke the writing-plans skill to create a detailed implementation plan
- Do NOT invoke any other skill. writing-plans is the next step.
## Key Principles
- **One question at a time** - Don't overwhelm with multiple questions
- **Multiple choice preferred** - Easier to answer than open-ended when possible
- **YAGNI ruthlessly** - Remove unnecessary features from all designs
- **Explore alternatives** - Always propose 2-3 approaches before settling
- **Incremental validation** - Present design, get approval before moving on
- **Be flexible** - Go back and clarify when something doesn't make sense
## Visual Companion
A browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser.
**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent:
> "Some of what we're working on might be easier to explain if I can show it to you in a web browser. I can put together mockups, diagrams, comparisons, and other visuals as we go. This feature is still new and can be token-intensive. Want to try it? (Requires opening a local URL)"
**This offer MUST be its own message.** Do not combine it with clarifying questions, context summaries, or any other content. The message should contain ONLY the offer above and nothing else. Wait for the user's response before continuing. If they decline, proceed with text-only brainstorming.
**Per-question decision:** Even after the user accepts, decide FOR EACH QUESTION whether to use the browser or the terminal. The test: **would the user understand this better by seeing it than reading it?**
- **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs
- **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions
A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is a conceptual question — use the terminal. "Which wizard layout works better?" is a visual question — use the browser.
If they agree to the companion, read the detailed guide before proceeding:
`skills/brainstorming/visual-companion.md`
@@ -0,0 +1,214 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Superpowers Brainstorming</title>
<style>
/*
* BRAINSTORM COMPANION FRAME TEMPLATE
*
* This template provides a consistent frame with:
* - OS-aware light/dark theming
* - Fixed header and selection indicator bar
* - Scrollable main content area
* - CSS helpers for common UI patterns
*
* Content is injected via placeholder comment in #claude-content.
*/
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; }
/* ===== THEME VARIABLES ===== */
:root {
--bg-primary: #f5f5f7;
--bg-secondary: #ffffff;
--bg-tertiary: #e5e5e7;
--border: #d1d1d6;
--text-primary: #1d1d1f;
--text-secondary: #86868b;
--text-tertiary: #aeaeb2;
--accent: #0071e3;
--accent-hover: #0077ed;
--success: #34c759;
--warning: #ff9f0a;
--error: #ff3b30;
--selected-bg: #e8f4fd;
--selected-border: #0071e3;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #1d1d1f;
--bg-secondary: #2d2d2f;
--bg-tertiary: #3d3d3f;
--border: #424245;
--text-primary: #f5f5f7;
--text-secondary: #86868b;
--text-tertiary: #636366;
--accent: #0a84ff;
--accent-hover: #409cff;
--selected-bg: rgba(10, 132, 255, 0.15);
--selected-border: #0a84ff;
}
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
display: flex;
flex-direction: column;
line-height: 1.5;
}
/* ===== FRAME STRUCTURE ===== */
.header {
background: var(--bg-secondary);
padding: 0.5rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
.header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }
.header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }
.main { flex: 1; overflow-y: auto; }
#claude-content { padding: 2rem; min-height: 100%; }
.indicator-bar {
background: var(--bg-secondary);
border-top: 1px solid var(--border);
padding: 0.5rem 1.5rem;
flex-shrink: 0;
text-align: center;
}
.indicator-bar span {
font-size: 0.75rem;
color: var(--text-secondary);
}
.indicator-bar .selected-text {
color: var(--accent);
font-weight: 500;
}
/* ===== TYPOGRAPHY ===== */
h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
.subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
.section { margin-bottom: 2rem; }
.label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
/* ===== OPTIONS (for A/B/C choices) ===== */
.options { display: flex; flex-direction: column; gap: 0.75rem; }
.option {
background: var(--bg-secondary);
border: 2px solid var(--border);
border-radius: 12px;
padding: 1rem 1.25rem;
cursor: pointer;
transition: all 0.15s ease;
display: flex;
align-items: flex-start;
gap: 1rem;
}
.option:hover { border-color: var(--accent); }
.option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
.option .letter {
background: var(--bg-tertiary);
color: var(--text-secondary);
width: 1.75rem; height: 1.75rem;
border-radius: 6px;
display: flex; align-items: center; justify-content: center;
font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
}
.option.selected .letter { background: var(--accent); color: white; }
.option .content { flex: 1; }
.option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
.option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
/* ===== CARDS (for showing designs/mockups) ===== */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
.card {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
cursor: pointer;
transition: all 0.15s ease;
}
.card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.card.selected { border-color: var(--selected-border); border-width: 2px; }
.card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
.card-body { padding: 1rem; }
.card-body h3 { margin-bottom: 0.25rem; }
.card-body p { color: var(--text-secondary); font-size: 0.85rem; }
/* ===== MOCKUP CONTAINER ===== */
.mockup {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
margin-bottom: 1.5rem;
}
.mockup-header {
background: var(--bg-tertiary);
padding: 0.5rem 1rem;
font-size: 0.75rem;
color: var(--text-secondary);
border-bottom: 1px solid var(--border);
}
.mockup-body { padding: 1.5rem; }
/* ===== SPLIT VIEW (side-by-side comparison) ===== */
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
@media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
/* ===== PROS/CONS ===== */
.pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
.pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
.pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
.cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
.pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
.pros li, .cons li { margin-bottom: 0.25rem; }
/* ===== PLACEHOLDER (for mockup areas) ===== */
.placeholder {
background: var(--bg-tertiary);
border: 2px dashed var(--border);
border-radius: 8px;
padding: 2rem;
text-align: center;
color: var(--text-tertiary);
}
/* ===== INLINE MOCKUP ELEMENTS ===== */
.mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
.mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
.mock-content { padding: 1.5rem; flex: 1; }
.mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
.mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
</style>
</head>
<body>
<div class="header">
<h1><a href="https://github.com/obra/superpowers" style="color: inherit; text-decoration: none;">Superpowers Brainstorming</a></h1>
<div class="status">Connected</div>
</div>
<div class="main">
<div id="claude-content">
<!-- CONTENT -->
</div>
</div>
<div class="indicator-bar">
<span id="indicator-text">Click an option above, then return to the terminal</span>
</div>
</body>
</html>
@@ -0,0 +1,88 @@
(function() {
const WS_URL = 'ws://' + window.location.host;
let ws = null;
let eventQueue = [];
function connect() {
ws = new WebSocket(WS_URL);
ws.onopen = () => {
eventQueue.forEach(e => ws.send(JSON.stringify(e)));
eventQueue = [];
};
ws.onmessage = (msg) => {
const data = JSON.parse(msg.data);
if (data.type === 'reload') {
window.location.reload();
}
};
ws.onclose = () => {
setTimeout(connect, 1000);
};
}
function sendEvent(event) {
event.timestamp = Date.now();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(event));
} else {
eventQueue.push(event);
}
}
// Capture clicks on choice elements
document.addEventListener('click', (e) => {
const target = e.target.closest('[data-choice]');
if (!target) return;
sendEvent({
type: 'click',
text: target.textContent.trim(),
choice: target.dataset.choice,
id: target.id || null
});
// Update indicator bar (defer so toggleSelect runs first)
setTimeout(() => {
const indicator = document.getElementById('indicator-text');
if (!indicator) return;
const container = target.closest('.options') || target.closest('.cards');
const selected = container ? container.querySelectorAll('.selected') : [];
if (selected.length === 0) {
indicator.textContent = 'Click an option above, then return to the terminal';
} else if (selected.length === 1) {
const label = selected[0].querySelector('h3, .content h3, .card-body h3')?.textContent?.trim() || selected[0].dataset.choice;
indicator.innerHTML = '<span class="selected-text">' + label + ' selected</span> — return to terminal to continue';
} else {
indicator.innerHTML = '<span class="selected-text">' + selected.length + ' selected</span> — return to terminal to continue';
}
}, 0);
});
// Frame UI: selection tracking
window.selectedChoice = null;
window.toggleSelect = function(el) {
const container = el.closest('.options') || el.closest('.cards');
const multi = container && container.dataset.multiselect !== undefined;
if (container && !multi) {
container.querySelectorAll('.option, .card').forEach(o => o.classList.remove('selected'));
}
if (multi) {
el.classList.toggle('selected');
} else {
el.classList.add('selected');
}
window.selectedChoice = el.dataset.choice;
};
// Expose API for explicit use
window.brainstorm = {
send: sendEvent,
choice: (value, metadata = {}) => sendEvent({ type: 'choice', value, ...metadata })
};
connect();
})();
@@ -0,0 +1,354 @@
const crypto = require('crypto');
const http = require('http');
const fs = require('fs');
const path = require('path');
// ========== WebSocket Protocol (RFC 6455) ==========
const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
function computeAcceptKey(clientKey) {
return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
}
function encodeFrame(opcode, payload) {
const fin = 0x80;
const len = payload.length;
let header;
if (len < 126) {
header = Buffer.alloc(2);
header[0] = fin | opcode;
header[1] = len;
} else if (len < 65536) {
header = Buffer.alloc(4);
header[0] = fin | opcode;
header[1] = 126;
header.writeUInt16BE(len, 2);
} else {
header = Buffer.alloc(10);
header[0] = fin | opcode;
header[1] = 127;
header.writeBigUInt64BE(BigInt(len), 2);
}
return Buffer.concat([header, payload]);
}
function decodeFrame(buffer) {
if (buffer.length < 2) return null;
const secondByte = buffer[1];
const opcode = buffer[0] & 0x0F;
const masked = (secondByte & 0x80) !== 0;
let payloadLen = secondByte & 0x7F;
let offset = 2;
if (!masked) throw new Error('Client frames must be masked');
if (payloadLen === 126) {
if (buffer.length < 4) return null;
payloadLen = buffer.readUInt16BE(2);
offset = 4;
} else if (payloadLen === 127) {
if (buffer.length < 10) return null;
payloadLen = Number(buffer.readBigUInt64BE(2));
offset = 10;
}
const maskOffset = offset;
const dataOffset = offset + 4;
const totalLen = dataOffset + payloadLen;
if (buffer.length < totalLen) return null;
const mask = buffer.slice(maskOffset, dataOffset);
const data = Buffer.alloc(payloadLen);
for (let i = 0; i < payloadLen; i++) {
data[i] = buffer[dataOffset + i] ^ mask[i % 4];
}
return { opcode, payload: data, bytesConsumed: totalLen };
}
// ========== Configuration ==========
const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
const CONTENT_DIR = path.join(SESSION_DIR, 'content');
const STATE_DIR = path.join(SESSION_DIR, 'state');
let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
const MIME_TYPES = {
'.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
'.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
};
// ========== Templates and Constants ==========
const WAITING_PAGE = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Brainstorm Companion</title>
<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
h1 { color: #333; } p { color: #666; }</style>
</head>
<body><h1>Brainstorm Companion</h1>
<p>Waiting for the agent to push a screen...</p></body></html>`;
const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
const helperInjection = '<script>\n' + helperScript + '\n</script>';
// ========== Helper Functions ==========
function isFullDocument(html) {
const trimmed = html.trimStart().toLowerCase();
return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
}
function wrapInFrame(content) {
return frameTemplate.replace('<!-- CONTENT -->', content);
}
function getNewestScreen() {
const files = fs.readdirSync(CONTENT_DIR)
.filter(f => f.endsWith('.html'))
.map(f => {
const fp = path.join(CONTENT_DIR, f);
return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
})
.sort((a, b) => b.mtime - a.mtime);
return files.length > 0 ? files[0].path : null;
}
// ========== HTTP Request Handler ==========
function handleRequest(req, res) {
touchActivity();
if (req.method === 'GET' && req.url === '/') {
const screenFile = getNewestScreen();
let html = screenFile
? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
: WAITING_PAGE;
if (html.includes('</body>')) {
html = html.replace('</body>', helperInjection + '\n</body>');
} else {
html += helperInjection;
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(html);
} else if (req.method === 'GET' && req.url.startsWith('/files/')) {
const fileName = req.url.slice(7);
const filePath = path.join(CONTENT_DIR, path.basename(fileName));
if (!fs.existsSync(filePath)) {
res.writeHead(404);
res.end('Not found');
return;
}
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': contentType });
res.end(fs.readFileSync(filePath));
} else {
res.writeHead(404);
res.end('Not found');
}
}
// ========== WebSocket Connection Handling ==========
const clients = new Set();
function handleUpgrade(req, socket) {
const key = req.headers['sec-websocket-key'];
if (!key) { socket.destroy(); return; }
const accept = computeAcceptKey(key);
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
);
let buffer = Buffer.alloc(0);
clients.add(socket);
socket.on('data', (chunk) => {
buffer = Buffer.concat([buffer, chunk]);
while (buffer.length > 0) {
let result;
try {
result = decodeFrame(buffer);
} catch (e) {
socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
clients.delete(socket);
return;
}
if (!result) break;
buffer = buffer.slice(result.bytesConsumed);
switch (result.opcode) {
case OPCODES.TEXT:
handleMessage(result.payload.toString());
break;
case OPCODES.CLOSE:
socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
clients.delete(socket);
return;
case OPCODES.PING:
socket.write(encodeFrame(OPCODES.PONG, result.payload));
break;
case OPCODES.PONG:
break;
default: {
const closeBuf = Buffer.alloc(2);
closeBuf.writeUInt16BE(1003);
socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
clients.delete(socket);
return;
}
}
}
});
socket.on('close', () => clients.delete(socket));
socket.on('error', () => clients.delete(socket));
}
function handleMessage(text) {
let event;
try {
event = JSON.parse(text);
} catch (e) {
console.error('Failed to parse WebSocket message:', e.message);
return;
}
touchActivity();
console.log(JSON.stringify({ source: 'user-event', ...event }));
if (event.choice) {
const eventsFile = path.join(STATE_DIR, 'events');
fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
}
}
function broadcast(msg) {
const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
for (const socket of clients) {
try { socket.write(frame); } catch (e) { clients.delete(socket); }
}
}
// ========== Activity Tracking ==========
const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
let lastActivity = Date.now();
function touchActivity() {
lastActivity = Date.now();
}
// ========== File Watching ==========
const debounceTimers = new Map();
// ========== Server Startup ==========
function startServer() {
if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
// Track known files to distinguish new screens from updates.
// macOS fs.watch reports 'rename' for both new files and overwrites,
// so we can't rely on eventType alone.
const knownFiles = new Set(
fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html'))
);
const server = http.createServer(handleRequest);
server.on('upgrade', handleUpgrade);
const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
if (!filename || !filename.endsWith('.html')) return;
if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
debounceTimers.set(filename, setTimeout(() => {
debounceTimers.delete(filename);
const filePath = path.join(CONTENT_DIR, filename);
if (!fs.existsSync(filePath)) return; // file was deleted
touchActivity();
if (!knownFiles.has(filename)) {
knownFiles.add(filename);
const eventsFile = path.join(STATE_DIR, 'events');
if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
} else {
console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
}
broadcast({ type: 'reload' });
}, 100));
});
watcher.on('error', (err) => console.error('fs.watch error:', err.message));
function shutdown(reason) {
console.log(JSON.stringify({ type: 'server-stopped', reason }));
const infoFile = path.join(STATE_DIR, 'server-info');
if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
fs.writeFileSync(
path.join(STATE_DIR, 'server-stopped'),
JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
);
watcher.close();
clearInterval(lifecycleCheck);
server.close(() => process.exit(0));
}
function ownerAlive() {
if (!ownerPid) return true;
try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
}
// Check every 60s: exit if owner process died or idle for 30 minutes
const lifecycleCheck = setInterval(() => {
if (!ownerAlive()) shutdown('owner process exited');
else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
}, 60 * 1000);
lifecycleCheck.unref();
// Validate owner PID at startup. If it's already dead, the PID resolution
// was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
// Disable monitoring and rely on the idle timeout instead.
if (ownerPid) {
try { process.kill(ownerPid, 0); }
catch (e) {
if (e.code !== 'EPERM') {
console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
ownerPid = null;
}
}
}
server.listen(PORT, HOST, () => {
const info = JSON.stringify({
type: 'server-started', port: Number(PORT), host: HOST,
url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
screen_dir: CONTENT_DIR, state_dir: STATE_DIR
});
console.log(info);
fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
});
}
if (require.main === module) {
startServer();
}
module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env bash
# Start the brainstorm server and output connection info
# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]
#
# Starts server on a random high port, outputs JSON with URL.
# Each session gets its own directory to avoid conflicts.
#
# Options:
# --project-dir <path> Store session files under <path>/.superpowers/brainstorm/
# instead of /tmp. Files persist after server stops.
# --host <bind-host> Host/interface to bind (default: 127.0.0.1).
# Use 0.0.0.0 in remote/containerized environments.
# --url-host <host> Hostname shown in returned URL JSON.
# --foreground Run server in the current terminal (no backgrounding).
# --background Force background mode (overrides Codex auto-foreground).
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# Parse arguments
PROJECT_DIR=""
FOREGROUND="false"
FORCE_BACKGROUND="false"
BIND_HOST="127.0.0.1"
URL_HOST=""
while [[ $# -gt 0 ]]; do
case "$1" in
--project-dir)
PROJECT_DIR="$2"
shift 2
;;
--host)
BIND_HOST="$2"
shift 2
;;
--url-host)
URL_HOST="$2"
shift 2
;;
--foreground|--no-daemon)
FOREGROUND="true"
shift
;;
--background|--daemon)
FORCE_BACKGROUND="true"
shift
;;
*)
echo "{\"error\": \"Unknown argument: $1\"}"
exit 1
;;
esac
done
if [[ -z "$URL_HOST" ]]; then
if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then
URL_HOST="localhost"
else
URL_HOST="$BIND_HOST"
fi
fi
# Some environments reap detached/background processes. Auto-foreground when detected.
if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
FOREGROUND="true"
fi
# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.
if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
case "${OSTYPE:-}" in
msys*|cygwin*|mingw*) FOREGROUND="true" ;;
esac
if [[ -n "${MSYSTEM:-}" ]]; then
FOREGROUND="true"
fi
fi
# Generate unique session directory
SESSION_ID="$$-$(date +%s)"
if [[ -n "$PROJECT_DIR" ]]; then
SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}"
else
SESSION_DIR="/tmp/brainstorm-${SESSION_ID}"
fi
STATE_DIR="${SESSION_DIR}/state"
PID_FILE="${STATE_DIR}/server.pid"
LOG_FILE="${STATE_DIR}/server.log"
# Create fresh session directory with content and state peers
mkdir -p "${SESSION_DIR}/content" "$STATE_DIR"
# Kill any existing server
if [[ -f "$PID_FILE" ]]; then
old_pid=$(cat "$PID_FILE")
kill "$old_pid" 2>/dev/null
rm -f "$PID_FILE"
fi
cd "$SCRIPT_DIR"
# Resolve the harness PID (grandparent of this script).
# $PPID is the ephemeral shell the harness spawned to run us — it dies
# when this script exits. The harness itself is $PPID's parent.
OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')"
if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then
OWNER_PID="$PPID"
fi
# Foreground mode for environments that reap detached/background processes.
if [[ "$FOREGROUND" == "true" ]]; then
echo "$$" > "$PID_FILE"
env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs
exit $?
fi
# Start server, capturing output to log file
# Use nohup to survive shell exit; disown to remove from job table
nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 &
SERVER_PID=$!
disown "$SERVER_PID" 2>/dev/null
echo "$SERVER_PID" > "$PID_FILE"
# Wait for server-started message (check log file)
for i in {1..50}; do
if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then
# Verify server is still alive after a short window (catches process reapers)
alive="true"
for _ in {1..20}; do
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
alive="false"
break
fi
sleep 0.1
done
if [[ "$alive" != "true" ]]; then
echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}"
exit 1
fi
grep "server-started" "$LOG_FILE" | head -1
exit 0
fi
sleep 0.1
done
# Timeout - server didn't start
echo '{"error": "Server failed to start within 5 seconds"}'
exit 1
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Stop the brainstorm server and clean up
# Usage: stop-server.sh <session_dir>
#
# Kills the server process. Only deletes session directory if it's
# under /tmp (ephemeral). Persistent directories (.superpowers/) are
# kept so mockups can be reviewed later.
SESSION_DIR="$1"
if [[ -z "$SESSION_DIR" ]]; then
echo '{"error": "Usage: stop-server.sh <session_dir>"}'
exit 1
fi
STATE_DIR="${SESSION_DIR}/state"
PID_FILE="${STATE_DIR}/server.pid"
if [[ -f "$PID_FILE" ]]; then
pid=$(cat "$PID_FILE")
# Try to stop gracefully, fallback to force if still alive
kill "$pid" 2>/dev/null || true
# Wait for graceful shutdown (up to ~2s)
for i in {1..20}; do
if ! kill -0 "$pid" 2>/dev/null; then
break
fi
sleep 0.1
done
# If still running, escalate to SIGKILL
if kill -0 "$pid" 2>/dev/null; then
kill -9 "$pid" 2>/dev/null || true
# Give SIGKILL a moment to take effect
sleep 0.1
fi
if kill -0 "$pid" 2>/dev/null; then
echo '{"status": "failed", "error": "process still running"}'
exit 1
fi
rm -f "$PID_FILE" "${STATE_DIR}/server.log"
# Only delete ephemeral /tmp directories
if [[ "$SESSION_DIR" == /tmp/* ]]; then
rm -rf "$SESSION_DIR"
fi
echo '{"status": "stopped"}'
else
echo '{"status": "not_running"}'
fi
@@ -0,0 +1,49 @@
# Spec Document Reviewer Prompt Template
Use this template when dispatching a spec document reviewer subagent.
**Purpose:** Verify the spec is complete, consistent, and ready for implementation planning.
**Dispatch after:** Spec document is written to docs/superpowers/specs/
```
Task tool (general-purpose):
description: "Review spec document"
prompt: |
You are a spec document reviewer. Verify this spec is complete and ready for planning.
**Spec to review:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, "TBD", incomplete sections |
| Consistency | Internal contradictions, conflicting requirements |
| Clarity | Requirements ambiguous enough to cause someone to build the wrong thing |
| Scope | Focused enough for a single plan — not covering multiple independent subsystems |
| YAGNI | Unrequested features, over-engineering |
## Calibration
**Only flag issues that would cause real problems during implementation planning.**
A missing section, a contradiction, or a requirement so ambiguous it could be
interpreted two different ways — those are issues. Minor wording improvements,
stylistic preferences, and "sections less detailed than others" are not.
Approve unless there are serious gaps that would lead to a flawed plan.
## Output Format
## Spec Review
**Status:** Approved | Issues Found
**Issues (if any):**
- [Section X]: [specific issue] - [why it matters for planning]
**Recommendations (advisory, do not block approval):**
- [suggestions for improvement]
```
**Reviewer returns:** Status, Issues (if any), Recommendations
@@ -0,0 +1,287 @@
# Visual Companion Guide
Browser-based visual brainstorming companion for showing mockups, diagrams, and options.
## When to Use
Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**
**Use the browser** when the content itself is visual:
- **UI mockups** — wireframes, layouts, navigation structures, component designs
- **Architecture diagrams** — system components, data flow, relationship maps
- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions
- **Design polish** — when the question is about look and feel, spacing, visual hierarchy
- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams
**Use the terminal** when the content is text or tabular:
- **Requirements and scope questions** — "what does X mean?", "which features are in scope?"
- **Conceptual A/B/C choices** — picking between approaches described in words
- **Tradeoff lists** — pros/cons, comparison tables
- **Technical decisions** — API design, data modeling, architectural approach selection
- **Clarifying questions** — anything where the answer is words, not a visual preference
A question *about* a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser.
## How It Works
The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn.
**Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
## Starting a Session
```bash
# Start server with persistence (mockups saved to project)
scripts/start-server.sh --project-dir /path/to/project
# Returns: {"type":"server-started","port":52341,"url":"http://localhost:52341",
# "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content",
# "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"}
```
Save `screen_dir` and `state_dir` from the response. Tell user to open the URL.
**Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.superpowers/brainstorm/` for the session directory.
**Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there.
**Launching the server by platform:**
**Claude Code (macOS / Linux):**
```bash
# Default mode works — the script backgrounds the server itself
scripts/start-server.sh --project-dir /path/to/project
```
**Claude Code (Windows):**
```bash
# Windows auto-detects and uses foreground mode, which blocks the tool call.
# Use run_in_background: true on the Bash tool call so the server survives
# across conversation turns.
scripts/start-server.sh --project-dir /path/to/project
```
When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port.
**Codex:**
```bash
# Codex reaps background processes. The script auto-detects CODEX_CI and
# switches to foreground mode. Run it normally — no extra flags needed.
scripts/start-server.sh --project-dir /path/to/project
```
**Gemini CLI:**
```bash
# Use --foreground and set is_background: true on your shell tool call
# so the process survives across turns
scripts/start-server.sh --project-dir /path/to/project --foreground
```
**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism.
If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:
```bash
scripts/start-server.sh \
--project-dir /path/to/project \
--host 0.0.0.0 \
--url-host localhost
```
Use `--url-host` to control what hostname is printed in the returned URL JSON.
## The Loop
1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:
- Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity.
- Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
- **Never reuse filenames** — each screen gets a fresh file
- Use Write tool — **never use cat/heredoc** (dumps noise into terminal)
- Server automatically serves the newest file
2. **Tell user what to expect and end your turn:**
- Remind them of the URL (every step, not just first)
- Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
- Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like."
3. **On your next turn** — after the user responds in the terminal:
- Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines
- Merge with the user's terminal text to get the full picture
- The terminal message is the primary feedback; `state_dir/events` provides structured interaction data
4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.
5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content:
```html
<!-- filename: waiting.html (or waiting-2.html, etc.) -->
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
<p class="subtitle">Continuing in terminal...</p>
</div>
```
This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual.
6. Repeat until done.
## Writing Content Fragments
Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure).
**Minimal example:**
```html
<h2>Which layout works better?</h2>
<p class="subtitle">Consider readability and visual hierarchy</p>
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Single Column</h3>
<p>Clean, focused reading experience</p>
</div>
</div>
<div class="option" data-choice="b" onclick="toggleSelect(this)">
<div class="letter">B</div>
<div class="content">
<h3>Two Column</h3>
<p>Sidebar navigation with main content</p>
</div>
</div>
</div>
```
That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
## CSS Classes Available
The frame template provides these CSS classes for your content:
### Options (A/B/C choices)
```html
<div class="options">
<div class="option" data-choice="a" onclick="toggleSelect(this)">
<div class="letter">A</div>
<div class="content">
<h3>Title</h3>
<p>Description</p>
</div>
</div>
</div>
```
**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item. The indicator bar shows the count.
```html
<div class="options" data-multiselect>
<!-- same option markup — users can select/deselect multiple -->
</div>
```
### Cards (visual designs)
```html
<div class="cards">
<div class="card" data-choice="design1" onclick="toggleSelect(this)">
<div class="card-image"><!-- mockup content --></div>
<div class="card-body">
<h3>Name</h3>
<p>Description</p>
</div>
</div>
</div>
```
### Mockup container
```html
<div class="mockup">
<div class="mockup-header">Preview: Dashboard Layout</div>
<div class="mockup-body"><!-- your mockup HTML --></div>
</div>
```
### Split view (side-by-side)
```html
<div class="split">
<div class="mockup"><!-- left --></div>
<div class="mockup"><!-- right --></div>
</div>
```
### Pros/Cons
```html
<div class="pros-cons">
<div class="pros"><h4>Pros</h4><ul><li>Benefit</li></ul></div>
<div class="cons"><h4>Cons</h4><ul><li>Drawback</li></ul></div>
</div>
```
### Mock elements (wireframe building blocks)
```html
<div class="mock-nav">Logo | Home | About | Contact</div>
<div style="display: flex;">
<div class="mock-sidebar">Navigation</div>
<div class="mock-content">Main content area</div>
</div>
<button class="mock-button">Action Button</button>
<input class="mock-input" placeholder="Input field">
<div class="placeholder">Placeholder area</div>
```
### Typography and sections
- `h2` — page title
- `h3` — section heading
- `.subtitle` — secondary text below title
- `.section` — content block with bottom margin
- `.label` — small uppercase label text
## Browser Events Format
When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.
```jsonl
{"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
{"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
{"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
```
The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
## Design Tips
- **Scale fidelity to the question** — wireframes for layout, polish for polish questions
- **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
- **Iterate before advancing** — if feedback changes current screen, write a new version
- **2-4 options max** per screen
- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
## File Naming
- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
- Never reuse filenames — each screen must be a new file
- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
- Server serves newest file by modification time
## Cleaning Up
```bash
scripts/stop-server.sh $SESSION_DIR
```
If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
## Reference
- Frame template (CSS reference): `scripts/frame-template.html`
- Helper script (client-side): `scripts/helper.js`
@@ -0,0 +1,182 @@
---
name: dispatching-parallel-agents
description: Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies
---
# Dispatching Parallel Agents
## Overview
You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
When you have multiple unrelated failures (different test files, different subsystems, different bugs), investigating them sequentially wastes time. Each investigation is independent and can happen in parallel.
**Core principle:** Dispatch one agent per independent problem domain. Let them work concurrently.
## When to Use
```dot
digraph when_to_use {
"Multiple failures?" [shape=diamond];
"Are they independent?" [shape=diamond];
"Single agent investigates all" [shape=box];
"One agent per problem domain" [shape=box];
"Can they work in parallel?" [shape=diamond];
"Sequential agents" [shape=box];
"Parallel dispatch" [shape=box];
"Multiple failures?" -> "Are they independent?" [label="yes"];
"Are they independent?" -> "Single agent investigates all" [label="no - related"];
"Are they independent?" -> "Can they work in parallel?" [label="yes"];
"Can they work in parallel?" -> "Parallel dispatch" [label="yes"];
"Can they work in parallel?" -> "Sequential agents" [label="no - shared state"];
}
```
**Use when:**
- 3+ test files failing with different root causes
- Multiple subsystems broken independently
- Each problem can be understood without context from others
- No shared state between investigations
**Don't use when:**
- Failures are related (fix one might fix others)
- Need to understand full system state
- Agents would interfere with each other
## The Pattern
### 1. Identify Independent Domains
Group failures by what's broken:
- File A tests: Tool approval flow
- File B tests: Batch completion behavior
- File C tests: Abort functionality
Each domain is independent - fixing tool approval doesn't affect abort tests.
### 2. Create Focused Agent Tasks
Each agent gets:
- **Specific scope:** One test file or subsystem
- **Clear goal:** Make these tests pass
- **Constraints:** Don't change other code
- **Expected output:** Summary of what you found and fixed
### 3. Dispatch in Parallel
```typescript
// In Claude Code / AI environment
Task("Fix agent-tool-abort.test.ts failures")
Task("Fix batch-completion-behavior.test.ts failures")
Task("Fix tool-approval-race-conditions.test.ts failures")
// All three run concurrently
```
### 4. Review and Integrate
When agents return:
- Read each summary
- Verify fixes don't conflict
- Run full test suite
- Integrate all changes
## Agent Prompt Structure
Good agent prompts are:
1. **Focused** - One clear problem domain
2. **Self-contained** - All context needed to understand the problem
3. **Specific about output** - What should the agent return?
```markdown
Fix the 3 failing tests in src/agents/agent-tool-abort.test.ts:
1. "should abort tool with partial output capture" - expects 'interrupted at' in message
2. "should handle mixed completed and aborted tools" - fast tool aborted instead of completed
3. "should properly track pendingToolCount" - expects 3 results but gets 0
These are timing/race condition issues. Your task:
1. Read the test file and understand what each test verifies
2. Identify root cause - timing issues or actual bugs?
3. Fix by:
- Replacing arbitrary timeouts with event-based waiting
- Fixing bugs in abort implementation if found
- Adjusting test expectations if testing changed behavior
Do NOT just increase timeouts - find the real issue.
Return: Summary of what you found and what you fixed.
```
## Common Mistakes
**❌ Too broad:** "Fix all the tests" - agent gets lost
**✅ Specific:** "Fix agent-tool-abort.test.ts" - focused scope
**❌ No context:** "Fix the race condition" - agent doesn't know where
**✅ Context:** Paste the error messages and test names
**❌ No constraints:** Agent might refactor everything
**✅ Constraints:** "Do NOT change production code" or "Fix tests only"
**❌ Vague output:** "Fix it" - you don't know what changed
**✅ Specific:** "Return summary of root cause and changes"
## When NOT to Use
**Related failures:** Fixing one might fix others - investigate together first
**Need full context:** Understanding requires seeing entire system
**Exploratory debugging:** You don't know what's broken yet
**Shared state:** Agents would interfere (editing same files, using same resources)
## Real Example from Session
**Scenario:** 6 test failures across 3 files after major refactoring
**Failures:**
- agent-tool-abort.test.ts: 3 failures (timing issues)
- batch-completion-behavior.test.ts: 2 failures (tools not executing)
- tool-approval-race-conditions.test.ts: 1 failure (execution count = 0)
**Decision:** Independent domains - abort logic separate from batch completion separate from race conditions
**Dispatch:**
```
Agent 1 → Fix agent-tool-abort.test.ts
Agent 2 → Fix batch-completion-behavior.test.ts
Agent 3 → Fix tool-approval-race-conditions.test.ts
```
**Results:**
- Agent 1: Replaced timeouts with event-based waiting
- Agent 2: Fixed event structure bug (threadId in wrong place)
- Agent 3: Added wait for async tool execution to complete
**Integration:** All fixes independent, no conflicts, full suite green
**Time saved:** 3 problems solved in parallel vs sequentially
## Key Benefits
1. **Parallelization** - Multiple investigations happen simultaneously
2. **Focus** - Each agent has narrow scope, less context to track
3. **Independence** - Agents don't interfere with each other
4. **Speed** - 3 problems solved in time of 1
## Verification
After agents return:
1. **Review each summary** - Understand what changed
2. **Check for conflicts** - Did agents edit same code?
3. **Run full suite** - Verify all fixes work together
4. **Spot check** - Agents can make systematic errors
## Real-World Impact
From debugging session (2025-10-03):
- 6 failures across 3 files
- 3 agents dispatched in parallel
- All investigations completed concurrently
- All fixes integrated successfully
- Zero conflicts between agent changes
+70
View File
@@ -0,0 +1,70 @@
---
name: executing-plans
description: Use when you have a written implementation plan to execute in a separate session with review checkpoints
---
# Executing Plans
## Overview
Load plan, review critically, execute all tasks, report when complete.
**Announce at start:** "I'm using the executing-plans skill to implement this plan."
**Note:** Tell your human partner that Superpowers works much better with access to subagents. The quality of its work will be significantly higher if run on a platform with subagent support (such as Claude Code or Codex). If subagents are available, use superpowers:subagent-driven-development instead of this skill.
## The Process
### Step 1: Load and Review Plan
1. Read plan file
2. Review critically - identify any questions or concerns about the plan
3. If concerns: Raise them with your human partner before starting
4. If no concerns: Create TodoWrite and proceed
### Step 2: Execute Tasks
For each task:
1. Mark as in_progress
2. Follow each step exactly (plan has bite-sized steps)
3. Run verifications as specified
4. Mark as completed
### Step 3: Complete Development
After all tasks complete and verified:
- Announce: "I'm using the finishing-a-development-branch skill to complete this work."
- **REQUIRED SUB-SKILL:** Use superpowers:finishing-a-development-branch
- Follow that skill to verify tests, present options, execute choice
## When to Stop and Ask for Help
**STOP executing immediately when:**
- Hit a blocker (missing dependency, test fails, instruction unclear)
- Plan has critical gaps preventing starting
- You don't understand an instruction
- Verification fails repeatedly
**Ask for clarification rather than guessing.**
## When to Revisit Earlier Steps
**Return to Review (Step 1) when:**
- Partner updates the plan based on your feedback
- Fundamental approach needs rethinking
**Don't force through blockers** - stop and ask.
## Remember
- Review plan critically first
- Follow plan steps exactly
- Don't skip verifications
- Reference skills when plan says to
- Stop when blocked, don't guess
- Never start implementation on main/master branch without explicit user consent
## Integration
**Required workflow skills:**
- **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
@@ -0,0 +1,251 @@
---
name: finishing-a-development-branch
description: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
---
# Finishing a Development Branch
## Overview
Guide completion of development work by presenting clear options and handling chosen workflow.
**Core principle:** Verify tests → Detect environment → Present options → Execute choice → Clean up.
**Announce at start:** "I'm using the finishing-a-development-branch skill to complete this work."
## The Process
### Step 1: Verify Tests
**Before presenting options, verify tests pass:**
```bash
# Run project's test suite
npm test / cargo test / pytest / go test ./...
```
**If tests fail:**
```
Tests failing (<N> failures). Must fix before completing:
[Show failures]
Cannot proceed with merge/PR until tests pass.
```
Stop. Don't proceed to Step 2.
**If tests pass:** Continue to Step 2.
### Step 2: Detect Environment
**Determine workspace state before presenting options:**
```bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
```
This determines which menu to show and how cleanup works:
| State | Menu | Cleanup |
|-------|------|---------|
| `GIT_DIR == GIT_COMMON` (normal repo) | Standard 4 options | No worktree to clean up |
| `GIT_DIR != GIT_COMMON`, named branch | Standard 4 options | Provenance-based (see Step 6) |
| `GIT_DIR != GIT_COMMON`, detached HEAD | Reduced 3 options (no merge) | No cleanup (externally managed) |
### Step 3: Determine Base Branch
```bash
# Try common base branches
git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null
```
Or ask: "This branch split from main - is that correct?"
### Step 4: Present Options
**Normal repo and named-branch worktree — present exactly these 4 options:**
```
Implementation complete. What would you like to do?
1. Merge back to <base-branch> locally
2. Push and create a Pull Request
3. Keep the branch as-is (I'll handle it later)
4. Discard this work
Which option?
```
**Detached HEAD — present exactly these 3 options:**
```
Implementation complete. You're on a detached HEAD (externally managed workspace).
1. Push as new branch and create a Pull Request
2. Keep as-is (I'll handle it later)
3. Discard this work
Which option?
```
**Don't add explanation** - keep options concise.
### Step 5: Execute Choice
#### Option 1: Merge Locally
```bash
# Get main repo root for CWD safety
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
cd "$MAIN_ROOT"
# Merge first — verify success before removing anything
git checkout <base-branch>
git pull
git merge <feature-branch>
# Verify tests on merged result
<test command>
# Only after merge succeeds: cleanup worktree (Step 6), then delete branch
```
Then: Cleanup worktree (Step 6), then delete branch:
```bash
git branch -d <feature-branch>
```
#### Option 2: Push and Create PR
```bash
# Push branch
git push -u origin <feature-branch>
# Create PR
gh pr create --title "<title>" --body "$(cat <<'EOF'
## Summary
<2-3 bullets of what changed>
## Test Plan
- [ ] <verification steps>
EOF
)"
```
**Do NOT clean up worktree** — user needs it alive to iterate on PR feedback.
#### Option 3: Keep As-Is
Report: "Keeping branch <name>. Worktree preserved at <path>."
**Don't cleanup worktree.**
#### Option 4: Discard
**Confirm first:**
```
This will permanently delete:
- Branch <name>
- All commits: <commit-list>
- Worktree at <path>
Type 'discard' to confirm.
```
Wait for exact confirmation.
If confirmed:
```bash
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
cd "$MAIN_ROOT"
```
Then: Cleanup worktree (Step 6), then force-delete branch:
```bash
git branch -D <feature-branch>
```
### Step 6: Cleanup Workspace
**Only runs for Options 1 and 4.** Options 2 and 3 always preserve the worktree.
```bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
WORKTREE_PATH=$(git rev-parse --show-toplevel)
```
**If `GIT_DIR == GIT_COMMON`:** Normal repo, no worktree to clean up. Done.
**If worktree path is under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`:** Superpowers created this worktree — we own cleanup.
```bash
MAIN_ROOT=$(git -C "$(git rev-parse --git-common-dir)/.." rev-parse --show-toplevel)
cd "$MAIN_ROOT"
git worktree remove "$WORKTREE_PATH"
git worktree prune # Self-healing: clean up any stale registrations
```
**Otherwise:** The host environment (harness) owns this workspace. Do NOT remove it. If your platform provides a workspace-exit tool, use it. Otherwise, leave the workspace in place.
## Quick Reference
| Option | Merge | Push | Keep Worktree | Cleanup Branch |
|--------|-------|------|---------------|----------------|
| 1. Merge locally | yes | - | - | yes |
| 2. Create PR | - | yes | yes | - |
| 3. Keep as-is | - | - | yes | - |
| 4. Discard | - | - | - | yes (force) |
## Common Mistakes
**Skipping test verification**
- **Problem:** Merge broken code, create failing PR
- **Fix:** Always verify tests before offering options
**Open-ended questions**
- **Problem:** "What should I do next?" is ambiguous
- **Fix:** Present exactly 4 structured options (or 3 for detached HEAD)
**Cleaning up worktree for Option 2**
- **Problem:** Remove worktree user needs for PR iteration
- **Fix:** Only cleanup for Options 1 and 4
**Deleting branch before removing worktree**
- **Problem:** `git branch -d` fails because worktree still references the branch
- **Fix:** Merge first, remove worktree, then delete branch
**Running git worktree remove from inside the worktree**
- **Problem:** Command fails silently when CWD is inside the worktree being removed
- **Fix:** Always `cd` to main repo root before `git worktree remove`
**Cleaning up harness-owned worktrees**
- **Problem:** Removing a worktree the harness created causes phantom state
- **Fix:** Only clean up worktrees under `.worktrees/`, `worktrees/`, or `~/.config/superpowers/worktrees/`
**No confirmation for discard**
- **Problem:** Accidentally delete work
- **Fix:** Require typed "discard" confirmation
## Red Flags
**Never:**
- Proceed with failing tests
- Merge without verifying tests on result
- Delete work without confirmation
- Force-push without explicit request
- Remove a worktree before confirming merge success
- Clean up worktrees you didn't create (provenance check)
- Run `git worktree remove` from inside the worktree
**Always:**
- Verify tests before offering options
- Detect environment before presenting menu
- Present exactly 4 options (or 3 for detached HEAD)
- Get typed confirmation for Option 4
- Clean up worktree for Options 1 & 4 only
- `cd` to main repo root before worktree removal
- Run `git worktree prune` after removal
@@ -0,0 +1,213 @@
---
name: receiving-code-review
description: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
---
# Code Review Reception
## Overview
Code review requires technical evaluation, not emotional performance.
**Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort.
## The Response Pattern
```
WHEN receiving code review feedback:
1. READ: Complete feedback without reacting
2. UNDERSTAND: Restate requirement in own words (or ask)
3. VERIFY: Check against codebase reality
4. EVALUATE: Technically sound for THIS codebase?
5. RESPOND: Technical acknowledgment or reasoned pushback
6. IMPLEMENT: One item at a time, test each
```
## Forbidden Responses
**NEVER:**
- "You're absolutely right!" (explicit CLAUDE.md violation)
- "Great point!" / "Excellent feedback!" (performative)
- "Let me implement that now" (before verification)
**INSTEAD:**
- Restate the technical requirement
- Ask clarifying questions
- Push back with technical reasoning if wrong
- Just start working (actions > words)
## Handling Unclear Feedback
```
IF any item is unclear:
STOP - do not implement anything yet
ASK for clarification on unclear items
WHY: Items may be related. Partial understanding = wrong implementation.
```
**Example:**
```
your human partner: "Fix 1-6"
You understand 1,2,3,6. Unclear on 4,5.
❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later
✅ RIGHT: "I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding."
```
## Source-Specific Handling
### From your human partner
- **Trusted** - implement after understanding
- **Still ask** if scope unclear
- **No performative agreement**
- **Skip to action** or technical acknowledgment
### From External Reviewers
```
BEFORE implementing:
1. Check: Technically correct for THIS codebase?
2. Check: Breaks existing functionality?
3. Check: Reason for current implementation?
4. Check: Works on all platforms/versions?
5. Check: Does reviewer understand full context?
IF suggestion seems wrong:
Push back with technical reasoning
IF can't easily verify:
Say so: "I can't verify this without [X]. Should I [investigate/ask/proceed]?"
IF conflicts with your human partner's prior decisions:
Stop and discuss with your human partner first
```
**your human partner's rule:** "External feedback - be skeptical, but check carefully"
## YAGNI Check for "Professional" Features
```
IF reviewer suggests "implementing properly":
grep codebase for actual usage
IF unused: "This endpoint isn't called. Remove it (YAGNI)?"
IF used: Then implement properly
```
**your human partner's rule:** "You and reviewer both report to me. If we don't need this feature, don't add it."
## Implementation Order
```
FOR multi-item feedback:
1. Clarify anything unclear FIRST
2. Then implement in this order:
- Blocking issues (breaks, security)
- Simple fixes (typos, imports)
- Complex fixes (refactoring, logic)
3. Test each fix individually
4. Verify no regressions
```
## When To Push Back
Push back when:
- Suggestion breaks existing functionality
- Reviewer lacks full context
- Violates YAGNI (unused feature)
- Technically incorrect for this stack
- Legacy/compatibility reasons exist
- Conflicts with your human partner's architectural decisions
**How to push back:**
- Use technical reasoning, not defensiveness
- Ask specific questions
- Reference working tests/code
- Involve your human partner if architectural
**Signal if uncomfortable pushing back out loud:** "Strange things are afoot at the Circle K"
## Acknowledging Correct Feedback
When feedback IS correct:
```
✅ "Fixed. [Brief description of what changed]"
✅ "Good catch - [specific issue]. Fixed in [location]."
✅ [Just fix it and show in the code]
❌ "You're absolutely right!"
❌ "Great point!"
❌ "Thanks for catching that!"
❌ "Thanks for [anything]"
❌ ANY gratitude expression
```
**Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback.
**If you catch yourself about to write "Thanks":** DELETE IT. State the fix instead.
## Gracefully Correcting Your Pushback
If you pushed back and were wrong:
```
✅ "You were right - I checked [X] and it does [Y]. Implementing now."
✅ "Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing."
❌ Long apology
❌ Defending why you pushed back
❌ Over-explaining
```
State the correction factually and move on.
## Common Mistakes
| Mistake | Fix |
|---------|-----|
| Performative agreement | State requirement or just act |
| Blind implementation | Verify against codebase first |
| Batch without testing | One at a time, test each |
| Assuming reviewer is right | Check if breaks things |
| Avoiding pushback | Technical correctness > comfort |
| Partial implementation | Clarify all items first |
| Can't verify, proceed anyway | State limitation, ask for direction |
## Real Examples
**Performative Agreement (Bad):**
```
Reviewer: "Remove legacy code"
❌ "You're absolutely right! Let me remove that..."
```
**Technical Verification (Good):**
```
Reviewer: "Remove legacy code"
✅ "Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?"
```
**YAGNI (Good):**
```
Reviewer: "Implement proper metrics tracking with database, date filters, CSV export"
✅ "Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?"
```
**Unclear Item (Good):**
```
your human partner: "Fix items 1-6"
You understand 1,2,3,6. Unclear on 4,5.
✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing."
```
## GitHub Thread Replies
When replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment.
## The Bottom Line
**External feedback = suggestions to evaluate, not orders to follow.**
Verify. Question. Then implement.
No performative agreement. Technical rigor always.
@@ -0,0 +1,103 @@
---
name: requesting-code-review
description: Use when completing tasks, implementing major features, or before merging to verify work meets requirements
---
# Requesting Code Review
Dispatch a code reviewer subagent to catch issues before they cascade. The reviewer gets precisely crafted context for evaluation — never your session's history. This keeps the reviewer focused on the work product, not your thought process, and preserves your own context for continued work.
**Core principle:** Review early, review often.
## When to Request Review
**Mandatory:**
- After each task in subagent-driven development
- After completing major feature
- Before merge to main
**Optional but valuable:**
- When stuck (fresh perspective)
- Before refactoring (baseline check)
- After fixing complex bug
## How to Request
**1. Get git SHAs:**
```bash
BASE_SHA=$(git rev-parse HEAD~1) # or origin/main
HEAD_SHA=$(git rev-parse HEAD)
```
**2. Dispatch code reviewer subagent:**
Use Task tool with `general-purpose` type, fill template at `code-reviewer.md`
**Placeholders:**
- `{DESCRIPTION}` - Brief summary of what you built
- `{PLAN_OR_REQUIREMENTS}` - What it should do
- `{BASE_SHA}` - Starting commit
- `{HEAD_SHA}` - Ending commit
**3. Act on feedback:**
- Fix Critical issues immediately
- Fix Important issues before proceeding
- Note Minor issues for later
- Push back if reviewer is wrong (with reasoning)
## Example
```
[Just completed Task 2: Add verification function]
You: Let me request code review before proceeding.
BASE_SHA=$(git log --oneline | grep "Task 1" | head -1 | awk '{print $1}')
HEAD_SHA=$(git rev-parse HEAD)
[Dispatch code reviewer subagent]
DESCRIPTION: Added verifyIndex() and repairIndex() with 4 issue types
PLAN_OR_REQUIREMENTS: Task 2 from docs/superpowers/plans/deployment-plan.md
BASE_SHA: a7981ec
HEAD_SHA: 3df7661
[Subagent returns]:
Strengths: Clean architecture, real tests
Issues:
Important: Missing progress indicators
Minor: Magic number (100) for reporting interval
Assessment: Ready to proceed
You: [Fix progress indicators]
[Continue to Task 3]
```
## Integration with Workflows
**Subagent-Driven Development:**
- Review after EACH task
- Catch issues before they compound
- Fix before moving to next task
**Executing Plans:**
- Review after each task or at natural checkpoints
- Get feedback, apply, continue
**Ad-Hoc Development:**
- Review before merge
- Review when stuck
## Red Flags
**Never:**
- Skip review because "it's simple"
- Ignore Critical issues
- Proceed with unfixed Important issues
- Argue with valid technical feedback
**If reviewer wrong:**
- Push back with technical reasoning
- Show code/tests that prove it works
- Request clarification
See template at: requesting-code-review/code-reviewer.md
@@ -0,0 +1,168 @@
# Code Reviewer Prompt Template
Use this template when dispatching a code reviewer subagent.
**Purpose:** Review completed work against requirements and code quality standards before it cascades into more work.
```
Task tool (general-purpose):
description: "Review code changes"
prompt: |
You are a Senior Code Reviewer with expertise in software architecture,
design patterns, and best practices. Your job is to review completed work
against its plan or requirements and identify issues before they cascade.
## What Was Implemented
{DESCRIPTION}
## Requirements / Plan
{PLAN_OR_REQUIREMENTS}
## Git Range to Review
**Base:** {BASE_SHA}
**Head:** {HEAD_SHA}
```bash
git diff --stat {BASE_SHA}..{HEAD_SHA}
git diff {BASE_SHA}..{HEAD_SHA}
```
## What to Check
**Plan alignment:**
- Does the implementation match the plan / requirements?
- Are deviations justified improvements, or problematic departures?
- Is all planned functionality present?
**Code quality:**
- Clean separation of concerns?
- Proper error handling?
- Type safety where applicable?
- DRY without premature abstraction?
- Edge cases handled?
**Architecture:**
- Sound design decisions?
- Reasonable scalability and performance?
- Security concerns?
- Integrates cleanly with surrounding code?
**Testing:**
- Tests verify real behavior, not mocks?
- Edge cases covered?
- Integration tests where they matter?
- All tests passing?
**Production readiness:**
- Migration strategy if schema changed?
- Backward compatibility considered?
- Documentation complete?
- No obvious bugs?
## Calibration
Categorize issues by actual severity. Not everything is Critical.
Acknowledge what was done well before listing issues — accurate praise
helps the implementer trust the rest of the feedback.
If you find significant deviations from the plan, flag them specifically
so the implementer can confirm whether the deviation was intentional.
If you find issues with the plan itself rather than the implementation,
say so.
## Output Format
### Strengths
[What's well done? Be specific.]
### Issues
#### Critical (Must Fix)
[Bugs, security issues, data loss risks, broken functionality]
#### Important (Should Fix)
[Architecture problems, missing features, poor error handling, test gaps]
#### Minor (Nice to Have)
[Code style, optimization opportunities, documentation polish]
For each issue:
- File:line reference
- What's wrong
- Why it matters
- How to fix (if not obvious)
### Recommendations
[Improvements for code quality, architecture, or process]
### Assessment
**Ready to merge?** [Yes | No | With fixes]
**Reasoning:** [1-2 sentence technical assessment]
## Critical Rules
**DO:**
- Categorize by actual severity
- Be specific (file:line, not vague)
- Explain WHY each issue matters
- Acknowledge strengths
- Give a clear verdict
**DON'T:**
- Say "looks good" without checking
- Mark nitpicks as Critical
- Give feedback on code you didn't actually read
- Be vague ("improve error handling")
- Avoid giving a clear verdict
```
**Placeholders:**
- `{DESCRIPTION}` — brief summary of what was built
- `{PLAN_OR_REQUIREMENTS}` — what it should do (plan file path, task text, or requirements)
- `{BASE_SHA}` — starting commit
- `{HEAD_SHA}` — ending commit
**Reviewer returns:** Strengths, Issues (Critical / Important / Minor), Recommendations, Assessment
## Example Output
```
### Strengths
- Clean database schema with proper migrations (db.ts:15-42)
- Comprehensive test coverage (18 tests, all edge cases)
- Good error handling with fallbacks (summarizer.ts:85-92)
### Issues
#### Important
1. **Missing help text in CLI wrapper**
- File: index-conversations:1-31
- Issue: No --help flag, users won't discover --concurrency
- Fix: Add --help case with usage examples
2. **Date validation missing**
- File: search.ts:25-27
- Issue: Invalid dates silently return no results
- Fix: Validate ISO format, throw error with example
#### Minor
1. **Progress indicators**
- File: indexer.ts:130
- Issue: No "X of Y" counter for long operations
- Impact: Users don't know how long to wait
### Recommendations
- Add progress reporting for user experience
- Consider config file for excluded projects (portability)
### Assessment
**Ready to merge: With fixes**
**Reasoning:** Core implementation is solid with good architecture and tests. Important issues (help text, date validation) are easily fixed and don't affect core functionality.
```
@@ -0,0 +1,279 @@
---
name: subagent-driven-development
description: Use when executing implementation plans with independent tasks in the current session
---
# Subagent-Driven Development
Execute plan by dispatching fresh subagent per task, with two-stage review after each: spec compliance review first, then code quality review.
**Why subagents:** You delegate tasks to specialized agents with isolated context. By precisely crafting their instructions and context, you ensure they stay focused and succeed at their task. They should never inherit your session's context or history — you construct exactly what they need. This also preserves your own context for coordination work.
**Core principle:** Fresh subagent per task + two-stage review (spec then quality) = high quality, fast iteration
**Continuous execution:** Do not pause to check in with your human partner between tasks. Execute all tasks from the plan without stopping. The only reasons to stop are: BLOCKED status you cannot resolve, ambiguity that genuinely prevents progress, or all tasks complete. "Should I continue?" prompts and progress summaries waste their time — they asked you to execute the plan, so execute it.
## When to Use
```dot
digraph when_to_use {
"Have implementation plan?" [shape=diamond];
"Tasks mostly independent?" [shape=diamond];
"Stay in this session?" [shape=diamond];
"subagent-driven-development" [shape=box];
"executing-plans" [shape=box];
"Manual execution or brainstorm first" [shape=box];
"Have implementation plan?" -> "Tasks mostly independent?" [label="yes"];
"Have implementation plan?" -> "Manual execution or brainstorm first" [label="no"];
"Tasks mostly independent?" -> "Stay in this session?" [label="yes"];
"Tasks mostly independent?" -> "Manual execution or brainstorm first" [label="no - tightly coupled"];
"Stay in this session?" -> "subagent-driven-development" [label="yes"];
"Stay in this session?" -> "executing-plans" [label="no - parallel session"];
}
```
**vs. Executing Plans (parallel session):**
- Same session (no context switch)
- Fresh subagent per task (no context pollution)
- Two-stage review after each task: spec compliance first, then code quality
- Faster iteration (no human-in-loop between tasks)
## The Process
```dot
digraph process {
rankdir=TB;
subgraph cluster_per_task {
label="Per Task";
"Dispatch implementer subagent (./implementer-prompt.md)" [shape=box];
"Implementer subagent asks questions?" [shape=diamond];
"Answer questions, provide context" [shape=box];
"Implementer subagent implements, tests, commits, self-reviews" [shape=box];
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [shape=box];
"Spec reviewer subagent confirms code matches spec?" [shape=diamond];
"Implementer subagent fixes spec gaps" [shape=box];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [shape=box];
"Code quality reviewer subagent approves?" [shape=diamond];
"Implementer subagent fixes quality issues" [shape=box];
"Mark task complete in TodoWrite" [shape=box];
}
"Read plan, extract all tasks with full text, note context, create TodoWrite" [shape=box];
"More tasks remain?" [shape=diamond];
"Dispatch final code reviewer subagent for entire implementation" [shape=box];
"Use superpowers:finishing-a-development-branch" [shape=box style=filled fillcolor=lightgreen];
"Read plan, extract all tasks with full text, note context, create TodoWrite" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Dispatch implementer subagent (./implementer-prompt.md)" -> "Implementer subagent asks questions?";
"Implementer subagent asks questions?" -> "Answer questions, provide context" [label="yes"];
"Answer questions, provide context" -> "Dispatch implementer subagent (./implementer-prompt.md)";
"Implementer subagent asks questions?" -> "Implementer subagent implements, tests, commits, self-reviews" [label="no"];
"Implementer subagent implements, tests, commits, self-reviews" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)";
"Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" -> "Spec reviewer subagent confirms code matches spec?";
"Spec reviewer subagent confirms code matches spec?" -> "Implementer subagent fixes spec gaps" [label="no"];
"Implementer subagent fixes spec gaps" -> "Dispatch spec reviewer subagent (./spec-reviewer-prompt.md)" [label="re-review"];
"Spec reviewer subagent confirms code matches spec?" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="yes"];
"Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" -> "Code quality reviewer subagent approves?";
"Code quality reviewer subagent approves?" -> "Implementer subagent fixes quality issues" [label="no"];
"Implementer subagent fixes quality issues" -> "Dispatch code quality reviewer subagent (./code-quality-reviewer-prompt.md)" [label="re-review"];
"Code quality reviewer subagent approves?" -> "Mark task complete in TodoWrite" [label="yes"];
"Mark task complete in TodoWrite" -> "More tasks remain?";
"More tasks remain?" -> "Dispatch implementer subagent (./implementer-prompt.md)" [label="yes"];
"More tasks remain?" -> "Dispatch final code reviewer subagent for entire implementation" [label="no"];
"Dispatch final code reviewer subagent for entire implementation" -> "Use superpowers:finishing-a-development-branch";
}
```
## Model Selection
Use the least powerful model that can handle each role to conserve cost and increase speed.
**Mechanical implementation tasks** (isolated functions, clear specs, 1-2 files): use a fast, cheap model. Most implementation tasks are mechanical when the plan is well-specified.
**Integration and judgment tasks** (multi-file coordination, pattern matching, debugging): use a standard model.
**Architecture, design, and review tasks**: use the most capable available model.
**Task complexity signals:**
- Touches 1-2 files with a complete spec → cheap model
- Touches multiple files with integration concerns → standard model
- Requires design judgment or broad codebase understanding → most capable model
## Handling Implementer Status
Implementer subagents report one of four statuses. Handle each appropriately:
**DONE:** Proceed to spec compliance review.
**DONE_WITH_CONCERNS:** The implementer completed the work but flagged doubts. Read the concerns before proceeding. If the concerns are about correctness or scope, address them before review. If they're observations (e.g., "this file is getting large"), note them and proceed to review.
**NEEDS_CONTEXT:** The implementer needs information that wasn't provided. Provide the missing context and re-dispatch.
**BLOCKED:** The implementer cannot complete the task. Assess the blocker:
1. If it's a context problem, provide more context and re-dispatch with the same model
2. If the task requires more reasoning, re-dispatch with a more capable model
3. If the task is too large, break it into smaller pieces
4. If the plan itself is wrong, escalate to the human
**Never** ignore an escalation or force the same model to retry without changes. If the implementer said it's stuck, something needs to change.
## Prompt Templates
- `./implementer-prompt.md` - Dispatch implementer subagent
- `./spec-reviewer-prompt.md` - Dispatch spec compliance reviewer subagent
- `./code-quality-reviewer-prompt.md` - Dispatch code quality reviewer subagent
## Example Workflow
```
You: I'm using Subagent-Driven Development to execute this plan.
[Read plan file once: docs/superpowers/plans/feature-plan.md]
[Extract all 5 tasks with full text and context]
[Create TodoWrite with all tasks]
Task 1: Hook installation script
[Get Task 1 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
Implementer: "Before I begin - should the hook be installed at user or system level?"
You: "User level (~/.config/superpowers/hooks/)"
Implementer: "Got it. Implementing now..."
[Later] Implementer:
- Implemented install-hook command
- Added tests, 5/5 passing
- Self-review: Found I missed --force flag, added it
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ✅ Spec compliant - all requirements met, nothing extra
[Get git SHAs, dispatch code quality reviewer]
Code reviewer: Strengths: Good test coverage, clean. Issues: None. Approved.
[Mark Task 1 complete]
Task 2: Recovery modes
[Get Task 2 text and context (already extracted)]
[Dispatch implementation subagent with full task text + context]
Implementer: [No questions, proceeds]
Implementer:
- Added verify/repair modes
- 8/8 tests passing
- Self-review: All good
- Committed
[Dispatch spec compliance reviewer]
Spec reviewer: ❌ Issues:
- Missing: Progress reporting (spec says "report every 100 items")
- Extra: Added --json flag (not requested)
[Implementer fixes issues]
Implementer: Removed --json flag, added progress reporting
[Spec reviewer reviews again]
Spec reviewer: ✅ Spec compliant now
[Dispatch code quality reviewer]
Code reviewer: Strengths: Solid. Issues (Important): Magic number (100)
[Implementer fixes]
Implementer: Extracted PROGRESS_INTERVAL constant
[Code reviewer reviews again]
Code reviewer: ✅ Approved
[Mark Task 2 complete]
...
[After all tasks]
[Dispatch final code-reviewer]
Final reviewer: All requirements met, ready to merge
Done!
```
## Advantages
**vs. Manual execution:**
- Subagents follow TDD naturally
- Fresh context per task (no confusion)
- Parallel-safe (subagents don't interfere)
- Subagent can ask questions (before AND during work)
**vs. Executing Plans:**
- Same session (no handoff)
- Continuous progress (no waiting)
- Review checkpoints automatic
**Efficiency gains:**
- No file reading overhead (controller provides full text)
- Controller curates exactly what context is needed
- Subagent gets complete information upfront
- Questions surfaced before work begins (not after)
**Quality gates:**
- Self-review catches issues before handoff
- Two-stage review: spec compliance, then code quality
- Review loops ensure fixes actually work
- Spec compliance prevents over/under-building
- Code quality ensures implementation is well-built
**Cost:**
- More subagent invocations (implementer + 2 reviewers per task)
- Controller does more prep work (extracting all tasks upfront)
- Review loops add iterations
- But catches issues early (cheaper than debugging later)
## Red Flags
**Never:**
- Start implementation on main/master branch without explicit user consent
- Skip reviews (spec compliance OR code quality)
- Proceed with unfixed issues
- Dispatch multiple implementation subagents in parallel (conflicts)
- Make subagent read plan file (provide full text instead)
- Skip scene-setting context (subagent needs to understand where task fits)
- Ignore subagent questions (answer before letting them proceed)
- Accept "close enough" on spec compliance (spec reviewer found issues = not done)
- Skip review loops (reviewer found issues = implementer fixes = review again)
- Let implementer self-review replace actual review (both are needed)
- **Start code quality review before spec compliance is ✅** (wrong order)
- Move to next task while either review has open issues
**If subagent asks questions:**
- Answer clearly and completely
- Provide additional context if needed
- Don't rush them into implementation
**If reviewer finds issues:**
- Implementer (same subagent) fixes them
- Reviewer reviews again
- Repeat until approved
- Don't skip the re-review
**If subagent fails task:**
- Dispatch fix subagent with specific instructions
- Don't try to fix manually (context pollution)
## Integration
**Required workflow skills:**
- **superpowers:using-git-worktrees** - Ensures isolated workspace (creates one or verifies existing)
- **superpowers:writing-plans** - Creates the plan this skill executes
- **superpowers:requesting-code-review** - Code review template for reviewer subagents
- **superpowers:finishing-a-development-branch** - Complete development after all tasks
**Subagents should use:**
- **superpowers:test-driven-development** - Subagents follow TDD for each task
**Alternative workflow:**
- **superpowers:executing-plans** - Use for parallel session instead of same-session execution
@@ -0,0 +1,25 @@
# Code Quality Reviewer Prompt Template
Use this template when dispatching a code quality reviewer subagent.
**Purpose:** Verify implementation is well-built (clean, tested, maintainable)
**Only dispatch after spec compliance review passes.**
```
Task tool (general-purpose):
Use template at requesting-code-review/code-reviewer.md
DESCRIPTION: [task summary, from implementer's report]
PLAN_OR_REQUIREMENTS: Task N from [plan-file]
BASE_SHA: [commit before task]
HEAD_SHA: [current commit]
```
**In addition to standard code quality concerns, the reviewer should check:**
- Does each file have one clear responsibility with a well-defined interface?
- Are units decomposed so they can be understood and tested independently?
- Is the implementation following the file structure from the plan?
- Did this implementation create new files that are already large, or significantly grow existing files? (Don't flag pre-existing file sizes — focus on what this change contributed.)
**Code reviewer returns:** Strengths, Issues (Critical/Important/Minor), Assessment
@@ -0,0 +1,113 @@
# Implementer Subagent Prompt Template
Use this template when dispatching an implementer subagent.
```
Task tool (general-purpose):
description: "Implement Task N: [task name]"
prompt: |
You are implementing Task N: [task name]
## Task Description
[FULL TEXT of task from plan - paste it here, don't make subagent read file]
## Context
[Scene-setting: where this fits, dependencies, architectural context]
## Before You Begin
If you have questions about:
- The requirements or acceptance criteria
- The approach or implementation strategy
- Dependencies or assumptions
- Anything unclear in the task description
**Ask them now.** Raise any concerns before starting work.
## Your Job
Once you're clear on requirements:
1. Implement exactly what the task specifies
2. Write tests (following TDD if task says to)
3. Verify implementation works
4. Commit your work
5. Self-review (see below)
6. Report back
Work from: [directory]
**While you work:** If you encounter something unexpected or unclear, **ask questions**.
It's always OK to pause and clarify. Don't guess or make assumptions.
## Code Organization
You reason best about code you can hold in context at once, and your edits are more
reliable when files are focused. Keep this in mind:
- Follow the file structure defined in the plan
- Each file should have one clear responsibility with a well-defined interface
- If a file you're creating is growing beyond the plan's intent, stop and report
it as DONE_WITH_CONCERNS — don't split files on your own without plan guidance
- If an existing file you're modifying is already large or tangled, work carefully
and note it as a concern in your report
- In existing codebases, follow established patterns. Improve code you're touching
the way a good developer would, but don't restructure things outside your task.
## When You're in Over Your Head
It is always OK to stop and say "this is too hard for me." Bad work is worse than
no work. You will not be penalized for escalating.
**STOP and escalate when:**
- The task requires architectural decisions with multiple valid approaches
- You need to understand code beyond what was provided and can't find clarity
- You feel uncertain about whether your approach is correct
- The task involves restructuring existing code in ways the plan didn't anticipate
- You've been reading file after file trying to understand the system without progress
**How to escalate:** Report back with status BLOCKED or NEEDS_CONTEXT. Describe
specifically what you're stuck on, what you've tried, and what kind of help you need.
The controller can provide more context, re-dispatch with a more capable model,
or break the task into smaller pieces.
## Before Reporting Back: Self-Review
Review your work with fresh eyes. Ask yourself:
**Completeness:**
- Did I fully implement everything in the spec?
- Did I miss any requirements?
- Are there edge cases I didn't handle?
**Quality:**
- Is this my best work?
- Are names clear and accurate (match what things do, not how they work)?
- Is the code clean and maintainable?
**Discipline:**
- Did I avoid overbuilding (YAGNI)?
- Did I only build what was requested?
- Did I follow existing patterns in the codebase?
**Testing:**
- Do tests actually verify behavior (not just mock behavior)?
- Did I follow TDD if required?
- Are tests comprehensive?
If you find issues during self-review, fix them now before reporting.
## Report Format
When done, report:
- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT
- What you implemented (or what you attempted, if blocked)
- What you tested and test results
- Files changed
- Self-review findings (if any)
- Any issues or concerns
Use DONE_WITH_CONCERNS if you completed the work but have doubts about correctness.
Use BLOCKED if you cannot complete the task. Use NEEDS_CONTEXT if you need
information that wasn't provided. Never silently produce work you're unsure about.
```
@@ -0,0 +1,61 @@
# Spec Compliance Reviewer Prompt Template
Use this template when dispatching a spec compliance reviewer subagent.
**Purpose:** Verify implementer built what was requested (nothing more, nothing less)
```
Task tool (general-purpose):
description: "Review spec compliance for Task N"
prompt: |
You are reviewing whether an implementation matches its specification.
## What Was Requested
[FULL TEXT of task requirements]
## What Implementer Claims They Built
[From implementer's report]
## CRITICAL: Do Not Trust the Report
The implementer finished suspiciously quickly. Their report may be incomplete,
inaccurate, or optimistic. You MUST verify everything independently.
**DO NOT:**
- Take their word for what they implemented
- Trust their claims about completeness
- Accept their interpretation of requirements
**DO:**
- Read the actual code they wrote
- Compare actual implementation to requirements line by line
- Check for missing pieces they claimed to implement
- Look for extra features they didn't mention
## Your Job
Read the implementation code and verify:
**Missing requirements:**
- Did they implement everything that was requested?
- Are there requirements they skipped or missed?
- Did they claim something works but didn't actually implement it?
**Extra/unneeded work:**
- Did they build things that weren't requested?
- Did they over-engineer or add unnecessary features?
- Did they add "nice to haves" that weren't in spec?
**Misunderstandings:**
- Did they interpret requirements differently than intended?
- Did they solve the wrong problem?
- Did they implement the right feature but wrong way?
**Verify by reading code, not by trusting report.**
Report:
- ✅ Spec compliant (if everything matches after code inspection)
- ❌ Issues found: [list specifically what's missing or extra, with file:line references]
```
@@ -0,0 +1,119 @@
# Creation Log: Systematic Debugging Skill
Reference example of extracting, structuring, and bulletproofing a critical skill.
## Source Material
Extracted debugging framework from `~/.claude/CLAUDE.md`:
- 4-phase systematic process (Investigation → Pattern Analysis → Hypothesis → Implementation)
- Core mandate: ALWAYS find root cause, NEVER fix symptoms
- Rules designed to resist time pressure and rationalization
## Extraction Decisions
**What to include:**
- Complete 4-phase framework with all rules
- Anti-shortcuts ("NEVER fix symptom", "STOP and re-analyze")
- Pressure-resistant language ("even if faster", "even if I seem in a hurry")
- Concrete steps for each phase
**What to leave out:**
- Project-specific context
- Repetitive variations of same rule
- Narrative explanations (condensed to principles)
## Structure Following skill-creation/SKILL.md
1. **Rich when_to_use** - Included symptoms and anti-patterns
2. **Type: technique** - Concrete process with steps
3. **Keywords** - "root cause", "symptom", "workaround", "debugging", "investigation"
4. **Flowchart** - Decision point for "fix failed" → re-analyze vs add more fixes
5. **Phase-by-phase breakdown** - Scannable checklist format
6. **Anti-patterns section** - What NOT to do (critical for this skill)
## Bulletproofing Elements
Framework designed to resist rationalization under pressure:
### Language Choices
- "ALWAYS" / "NEVER" (not "should" / "try to")
- "even if faster" / "even if I seem in a hurry"
- "STOP and re-analyze" (explicit pause)
- "Don't skip past" (catches the actual behavior)
### Structural Defenses
- **Phase 1 required** - Can't skip to implementation
- **Single hypothesis rule** - Forces thinking, prevents shotgun fixes
- **Explicit failure mode** - "IF your first fix doesn't work" with mandatory action
- **Anti-patterns section** - Shows exactly what shortcuts look like
### Redundancy
- Root cause mandate in overview + when_to_use + Phase 1 + implementation rules
- "NEVER fix symptom" appears 4 times in different contexts
- Each phase has explicit "don't skip" guidance
## Testing Approach
Created 4 validation tests following skills/meta/testing-skills-with-subagents:
### Test 1: Academic Context (No Pressure)
- Simple bug, no time pressure
- **Result:** Perfect compliance, complete investigation
### Test 2: Time Pressure + Obvious Quick Fix
- User "in a hurry", symptom fix looks easy
- **Result:** Resisted shortcut, followed full process, found real root cause
### Test 3: Complex System + Uncertainty
- Multi-layer failure, unclear if can find root cause
- **Result:** Systematic investigation, traced through all layers, found source
### Test 4: Failed First Fix
- Hypothesis doesn't work, temptation to add more fixes
- **Result:** Stopped, re-analyzed, formed new hypothesis (no shotgun)
**All tests passed.** No rationalizations found.
## Iterations
### Initial Version
- Complete 4-phase framework
- Anti-patterns section
- Flowchart for "fix failed" decision
### Enhancement 1: TDD Reference
- Added link to skills/testing/test-driven-development
- Note explaining TDD's "simplest code" ≠ debugging's "root cause"
- Prevents confusion between methodologies
## Final Outcome
Bulletproof skill that:
- ✅ Clearly mandates root cause investigation
- ✅ Resists time pressure rationalization
- ✅ Provides concrete steps for each phase
- ✅ Shows anti-patterns explicitly
- ✅ Tested under multiple pressure scenarios
- ✅ Clarifies relationship to TDD
- ✅ Ready for use
## Key Insight
**Most important bulletproofing:** Anti-patterns section showing exact shortcuts that feel justified in the moment. When Claude thinks "I'll just add this one quick fix", seeing that exact pattern listed as wrong creates cognitive friction.
## Usage Example
When encountering a bug:
1. Load skill: skills/debugging/systematic-debugging
2. Read overview (10 sec) - reminded of mandate
3. Follow Phase 1 checklist - forced investigation
4. If tempted to skip - see anti-pattern, stop
5. Complete all phases - root cause found
**Time investment:** 5-10 minutes
**Time saved:** Hours of symptom-whack-a-mole
---
*Created: 2025-10-03*
*Purpose: Reference example for skill extraction and bulletproofing*
@@ -0,0 +1,296 @@
---
name: systematic-debugging
description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
---
# Systematic Debugging
## Overview
Random fixes waste time and create new bugs. Quick patches mask underlying issues.
**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.
**Violating the letter of this process is violating the spirit of debugging.**
## The Iron Law
```
NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
```
If you haven't completed Phase 1, you cannot propose fixes.
## When to Use
Use for ANY technical issue:
- Test failures
- Bugs in production
- Unexpected behavior
- Performance problems
- Build failures
- Integration issues
**Use this ESPECIALLY when:**
- Under time pressure (emergencies make guessing tempting)
- "Just one quick fix" seems obvious
- You've already tried multiple fixes
- Previous fix didn't work
- You don't fully understand the issue
**Don't skip when:**
- Issue seems simple (simple bugs have root causes too)
- You're in a hurry (rushing guarantees rework)
- Manager wants it fixed NOW (systematic is faster than thrashing)
## The Four Phases
You MUST complete each phase before proceeding to the next.
### Phase 1: Root Cause Investigation
**BEFORE attempting ANY fix:**
1. **Read Error Messages Carefully**
- Don't skip past errors or warnings
- They often contain the exact solution
- Read stack traces completely
- Note line numbers, file paths, error codes
2. **Reproduce Consistently**
- Can you trigger it reliably?
- What are the exact steps?
- Does it happen every time?
- If not reproducible → gather more data, don't guess
3. **Check Recent Changes**
- What changed that could cause this?
- Git diff, recent commits
- New dependencies, config changes
- Environmental differences
4. **Gather Evidence in Multi-Component Systems**
**WHEN system has multiple components (CI → build → signing, API → service → database):**
**BEFORE proposing fixes, add diagnostic instrumentation:**
```
For EACH component boundary:
- Log what data enters component
- Log what data exits component
- Verify environment/config propagation
- Check state at each layer
Run once to gather evidence showing WHERE it breaks
THEN analyze evidence to identify failing component
THEN investigate that specific component
```
**Example (multi-layer system):**
```bash
# Layer 1: Workflow
echo "=== Secrets available in workflow: ==="
echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"
# Layer 2: Build script
echo "=== Env vars in build script: ==="
env | grep IDENTITY || echo "IDENTITY not in environment"
# Layer 3: Signing script
echo "=== Keychain state: ==="
security list-keychains
security find-identity -v
# Layer 4: Actual signing
codesign --sign "$IDENTITY" --verbose=4 "$APP"
```
**This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)
5. **Trace Data Flow**
**WHEN error is deep in call stack:**
See `root-cause-tracing.md` in this directory for the complete backward tracing technique.
**Quick version:**
- Where does bad value originate?
- What called this with bad value?
- Keep tracing up until you find the source
- Fix at source, not at symptom
### Phase 2: Pattern Analysis
**Find the pattern before fixing:**
1. **Find Working Examples**
- Locate similar working code in same codebase
- What works that's similar to what's broken?
2. **Compare Against References**
- If implementing pattern, read reference implementation COMPLETELY
- Don't skim - read every line
- Understand the pattern fully before applying
3. **Identify Differences**
- What's different between working and broken?
- List every difference, however small
- Don't assume "that can't matter"
4. **Understand Dependencies**
- What other components does this need?
- What settings, config, environment?
- What assumptions does it make?
### Phase 3: Hypothesis and Testing
**Scientific method:**
1. **Form Single Hypothesis**
- State clearly: "I think X is the root cause because Y"
- Write it down
- Be specific, not vague
2. **Test Minimally**
- Make the SMALLEST possible change to test hypothesis
- One variable at a time
- Don't fix multiple things at once
3. **Verify Before Continuing**
- Did it work? Yes → Phase 4
- Didn't work? Form NEW hypothesis
- DON'T add more fixes on top
4. **When You Don't Know**
- Say "I don't understand X"
- Don't pretend to know
- Ask for help
- Research more
### Phase 4: Implementation
**Fix the root cause, not the symptom:**
1. **Create Failing Test Case**
- Simplest possible reproduction
- Automated test if possible
- One-off test script if no framework
- MUST have before fixing
- Use the `superpowers:test-driven-development` skill for writing proper failing tests
2. **Implement Single Fix**
- Address the root cause identified
- ONE change at a time
- No "while I'm here" improvements
- No bundled refactoring
3. **Verify Fix**
- Test passes now?
- No other tests broken?
- Issue actually resolved?
4. **If Fix Doesn't Work**
- STOP
- Count: How many fixes have you tried?
- If < 3: Return to Phase 1, re-analyze with new information
- **If ≥ 3: STOP and question the architecture (step 5 below)**
- DON'T attempt Fix #4 without architectural discussion
5. **If 3+ Fixes Failed: Question Architecture**
**Pattern indicating architectural problem:**
- Each fix reveals new shared state/coupling/problem in different place
- Fixes require "massive refactoring" to implement
- Each fix creates new symptoms elsewhere
**STOP and question fundamentals:**
- Is this pattern fundamentally sound?
- Are we "sticking with it through sheer inertia"?
- Should we refactor architecture vs. continue fixing symptoms?
**Discuss with your human partner before attempting more fixes**
This is NOT a failed hypothesis - this is a wrong architecture.
## Red Flags - STOP and Follow Process
If you catch yourself thinking:
- "Quick fix for now, investigate later"
- "Just try changing X and see if it works"
- "Add multiple changes, run tests"
- "Skip the test, I'll manually verify"
- "It's probably X, let me fix that"
- "I don't fully understand but this might work"
- "Pattern says X but I'll adapt it differently"
- "Here are the main problems: [lists fixes without investigation]"
- Proposing solutions before tracing data flow
- **"One more fix attempt" (when already tried 2+)**
- **Each fix reveals new problem in different place**
**ALL of these mean: STOP. Return to Phase 1.**
**If 3+ fixes failed:** Question the architecture (see Phase 4.5)
## your human partner's Signals You're Doing It Wrong
**Watch for these redirections:**
- "Is that not happening?" - You assumed without verifying
- "Will it show us...?" - You should have added evidence gathering
- "Stop guessing" - You're proposing fixes without understanding
- "Ultrathink this" - Question fundamentals, not just symptoms
- "We're stuck?" (frustrated) - Your approach isn't working
**When you see these:** STOP. Return to Phase 1.
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |
## Quick Reference
| Phase | Key Activities | Success Criteria |
|-------|---------------|------------------|
| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
| **2. Pattern** | Find working examples, compare | Identify differences |
| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |
## When Process Reveals "No Root Cause"
If systematic investigation reveals issue is truly environmental, timing-dependent, or external:
1. You've completed the process
2. Document what you investigated
3. Implement appropriate handling (retry, timeout, error message)
4. Add monitoring/logging for future investigation
**But:** 95% of "no root cause" cases are incomplete investigation.
## Supporting Techniques
These techniques are part of systematic debugging and available in this directory:
- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling
**Related skills:**
- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)
- **superpowers:verification-before-completion** - Verify fix worked before claiming success
## Real-World Impact
From debugging sessions:
- Systematic approach: 15-30 minutes to fix
- Random fixes approach: 2-3 hours of thrashing
- First-time fix rate: 95% vs 40%
- New bugs introduced: Near zero vs common
@@ -0,0 +1,158 @@
// Complete implementation of condition-based waiting utilities
// From: Lace test infrastructure improvements (2025-10-03)
// Context: Fixed 15 flaky tests by replacing arbitrary timeouts
import type { ThreadManager } from '~/threads/thread-manager';
import type { LaceEvent, LaceEventType } from '~/threads/types';
/**
* Wait for a specific event type to appear in thread
*
* @param threadManager - The thread manager to query
* @param threadId - Thread to check for events
* @param eventType - Type of event to wait for
* @param timeoutMs - Maximum time to wait (default 5000ms)
* @returns Promise resolving to the first matching event
*
* Example:
* await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT');
*/
export function waitForEvent(
threadManager: ThreadManager,
threadId: string,
eventType: LaceEventType,
timeoutMs = 5000
): Promise<LaceEvent> {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
const events = threadManager.getEvents(threadId);
const event = events.find((e) => e.type === eventType);
if (event) {
resolve(event);
} else if (Date.now() - startTime > timeoutMs) {
reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`));
} else {
setTimeout(check, 10); // Poll every 10ms for efficiency
}
};
check();
});
}
/**
* Wait for a specific number of events of a given type
*
* @param threadManager - The thread manager to query
* @param threadId - Thread to check for events
* @param eventType - Type of event to wait for
* @param count - Number of events to wait for
* @param timeoutMs - Maximum time to wait (default 5000ms)
* @returns Promise resolving to all matching events once count is reached
*
* Example:
* // Wait for 2 AGENT_MESSAGE events (initial response + continuation)
* await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2);
*/
export function waitForEventCount(
threadManager: ThreadManager,
threadId: string,
eventType: LaceEventType,
count: number,
timeoutMs = 5000
): Promise<LaceEvent[]> {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
const events = threadManager.getEvents(threadId);
const matchingEvents = events.filter((e) => e.type === eventType);
if (matchingEvents.length >= count) {
resolve(matchingEvents);
} else if (Date.now() - startTime > timeoutMs) {
reject(
new Error(
`Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})`
)
);
} else {
setTimeout(check, 10);
}
};
check();
});
}
/**
* Wait for an event matching a custom predicate
* Useful when you need to check event data, not just type
*
* @param threadManager - The thread manager to query
* @param threadId - Thread to check for events
* @param predicate - Function that returns true when event matches
* @param description - Human-readable description for error messages
* @param timeoutMs - Maximum time to wait (default 5000ms)
* @returns Promise resolving to the first matching event
*
* Example:
* // Wait for TOOL_RESULT with specific ID
* await waitForEventMatch(
* threadManager,
* agentThreadId,
* (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123',
* 'TOOL_RESULT with id=call_123'
* );
*/
export function waitForEventMatch(
threadManager: ThreadManager,
threadId: string,
predicate: (event: LaceEvent) => boolean,
description: string,
timeoutMs = 5000
): Promise<LaceEvent> {
return new Promise((resolve, reject) => {
const startTime = Date.now();
const check = () => {
const events = threadManager.getEvents(threadId);
const event = events.find(predicate);
if (event) {
resolve(event);
} else if (Date.now() - startTime > timeoutMs) {
reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`));
} else {
setTimeout(check, 10);
}
};
check();
});
}
// Usage example from actual debugging session:
//
// BEFORE (flaky):
// ---------------
// const messagePromise = agent.sendMessage('Execute tools');
// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms
// agent.abort();
// await messagePromise;
// await new Promise(r => setTimeout(r, 50)); // Hope results arrive in 50ms
// expect(toolResults.length).toBe(2); // Fails randomly
//
// AFTER (reliable):
// ----------------
// const messagePromise = agent.sendMessage('Execute tools');
// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start
// agent.abort();
// await messagePromise;
// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results
// expect(toolResults.length).toBe(2); // Always succeeds
//
// Result: 60% pass rate → 100%, 40% faster execution
@@ -0,0 +1,115 @@
# Condition-Based Waiting
## Overview
Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.
**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.
## When to Use
```dot
digraph when_to_use {
"Test uses setTimeout/sleep?" [shape=diamond];
"Testing timing behavior?" [shape=diamond];
"Document WHY timeout needed" [shape=box];
"Use condition-based waiting" [shape=box];
"Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
"Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
"Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
}
```
**Use when:**
- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
- Tests are flaky (pass sometimes, fail under load)
- Tests timeout when run in parallel
- Waiting for async operations to complete
**Don't use when:**
- Testing actual timing behavior (debounce, throttle intervals)
- Always document WHY if using arbitrary timeout
## Core Pattern
```typescript
// ❌ BEFORE: Guessing at timing
await new Promise(r => setTimeout(r, 50));
const result = getResult();
expect(result).toBeDefined();
// ✅ AFTER: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();
expect(result).toBeDefined();
```
## Quick Patterns
| Scenario | Pattern |
|----------|---------|
| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
| Wait for state | `waitFor(() => machine.state === 'ready')` |
| Wait for count | `waitFor(() => items.length >= 5)` |
| Wait for file | `waitFor(() => fs.existsSync(path))` |
| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |
## Implementation
Generic polling function:
```typescript
async function waitFor<T>(
condition: () => T | undefined | null | false,
description: string,
timeoutMs = 5000
): Promise<T> {
const startTime = Date.now();
while (true) {
const result = condition();
if (result) return result;
if (Date.now() - startTime > timeoutMs) {
throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
}
await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
}
}
```
See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.
## Common Mistakes
**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
**✅ Fix:** Poll every 10ms
**❌ No timeout:** Loop forever if condition never met
**✅ Fix:** Always include timeout with clear error
**❌ Stale data:** Cache state before loop
**✅ Fix:** Call getter inside loop for fresh data
## When Arbitrary Timeout IS Correct
```typescript
// Tool ticks every 100ms - need 2 ticks to verify partial output
await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior
// 200ms = 2 ticks at 100ms intervals - documented and justified
```
**Requirements:**
1. First wait for triggering condition
2. Based on known timing (not guessing)
3. Comment explaining WHY
## Real-World Impact
From debugging session (2025-10-03):
- Fixed 15 flaky tests across 3 files
- Pass rate: 60% → 100%
- Execution time: 40% faster
- No more race conditions
@@ -0,0 +1,122 @@
# Defense-in-Depth Validation
## Overview
When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.
**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible.
## Why Multiple Layers
Single validation: "We fixed the bug"
Multiple layers: "We made the bug impossible"
Different layers catch different cases:
- Entry validation catches most bugs
- Business logic catches edge cases
- Environment guards prevent context-specific dangers
- Debug logging helps when other layers fail
## The Four Layers
### Layer 1: Entry Point Validation
**Purpose:** Reject obviously invalid input at API boundary
```typescript
function createProject(name: string, workingDirectory: string) {
if (!workingDirectory || workingDirectory.trim() === '') {
throw new Error('workingDirectory cannot be empty');
}
if (!existsSync(workingDirectory)) {
throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
}
if (!statSync(workingDirectory).isDirectory()) {
throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
}
// ... proceed
}
```
### Layer 2: Business Logic Validation
**Purpose:** Ensure data makes sense for this operation
```typescript
function initializeWorkspace(projectDir: string, sessionId: string) {
if (!projectDir) {
throw new Error('projectDir required for workspace initialization');
}
// ... proceed
}
```
### Layer 3: Environment Guards
**Purpose:** Prevent dangerous operations in specific contexts
```typescript
async function gitInit(directory: string) {
// In tests, refuse git init outside temp directories
if (process.env.NODE_ENV === 'test') {
const normalized = normalize(resolve(directory));
const tmpDir = normalize(resolve(tmpdir()));
if (!normalized.startsWith(tmpDir)) {
throw new Error(
`Refusing git init outside temp dir during tests: ${directory}`
);
}
}
// ... proceed
}
```
### Layer 4: Debug Instrumentation
**Purpose:** Capture context for forensics
```typescript
async function gitInit(directory: string) {
const stack = new Error().stack;
logger.debug('About to git init', {
directory,
cwd: process.cwd(),
stack,
});
// ... proceed
}
```
## Applying the Pattern
When you find a bug:
1. **Trace the data flow** - Where does bad value originate? Where used?
2. **Map all checkpoints** - List every point data passes through
3. **Add validation at each layer** - Entry, business, environment, debug
4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it
## Example from Session
Bug: Empty `projectDir` caused `git init` in source code
**Data flow:**
1. Test setup → empty string
2. `Project.create(name, '')`
3. `WorkspaceManager.createWorkspace('')`
4. `git init` runs in `process.cwd()`
**Four layers added:**
- Layer 1: `Project.create()` validates not empty/exists/writable
- Layer 2: `WorkspaceManager` validates projectDir not empty
- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests
- Layer 4: Stack trace logging before git init
**Result:** All 1847 tests passed, bug impossible to reproduce
## Key Insight
All four layers were necessary. During testing, each layer caught bugs the others missed:
- Different code paths bypassed entry validation
- Mocks bypassed business logic checks
- Edge cases on different platforms needed environment guards
- Debug logging identified structural misuse
**Don't stop at one validation point.** Add checks at every layer.
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# Bisection script to find which test creates unwanted files/state
# Usage: ./find-polluter.sh <file_or_dir_to_check> <test_pattern>
# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts'
set -e
if [ $# -ne 2 ]; then
echo "Usage: $0 <file_to_check> <test_pattern>"
echo "Example: $0 '.git' 'src/**/*.test.ts'"
exit 1
fi
POLLUTION_CHECK="$1"
TEST_PATTERN="$2"
echo "🔍 Searching for test that creates: $POLLUTION_CHECK"
echo "Test pattern: $TEST_PATTERN"
echo ""
# Get list of test files
TEST_FILES=$(find . -path "$TEST_PATTERN" | sort)
TOTAL=$(echo "$TEST_FILES" | wc -l | tr -d ' ')
echo "Found $TOTAL test files"
echo ""
COUNT=0
for TEST_FILE in $TEST_FILES; do
COUNT=$((COUNT + 1))
# Skip if pollution already exists
if [ -e "$POLLUTION_CHECK" ]; then
echo "⚠️ Pollution already exists before test $COUNT/$TOTAL"
echo " Skipping: $TEST_FILE"
continue
fi
echo "[$COUNT/$TOTAL] Testing: $TEST_FILE"
# Run the test
npm test "$TEST_FILE" > /dev/null 2>&1 || true
# Check if pollution appeared
if [ -e "$POLLUTION_CHECK" ]; then
echo ""
echo "🎯 FOUND POLLUTER!"
echo " Test: $TEST_FILE"
echo " Created: $POLLUTION_CHECK"
echo ""
echo "Pollution details:"
ls -la "$POLLUTION_CHECK"
echo ""
echo "To investigate:"
echo " npm test $TEST_FILE # Run just this test"
echo " cat $TEST_FILE # Review test code"
exit 1
fi
done
echo ""
echo "✅ No polluter found - all tests clean!"
exit 0
@@ -0,0 +1,169 @@
# Root Cause Tracing
## Overview
Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.
**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.
## When to Use
```dot
digraph when_to_use {
"Bug appears deep in stack?" [shape=diamond];
"Can trace backwards?" [shape=diamond];
"Fix at symptom point" [shape=box];
"Trace to original trigger" [shape=box];
"BETTER: Also add defense-in-depth" [shape=box];
"Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
"Can trace backwards?" -> "Trace to original trigger" [label="yes"];
"Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
"Trace to original trigger" -> "BETTER: Also add defense-in-depth";
}
```
**Use when:**
- Error happens deep in execution (not at entry point)
- Stack trace shows long call chain
- Unclear where invalid data originated
- Need to find which test/code triggers the problem
## The Tracing Process
### 1. Observe the Symptom
```
Error: git init failed in ~/project/packages/core
```
### 2. Find Immediate Cause
**What code directly causes this?**
```typescript
await execFileAsync('git', ['init'], { cwd: projectDir });
```
### 3. Ask: What Called This?
```typescript
WorktreeManager.createSessionWorktree(projectDir, sessionId)
→ called by Session.initializeWorkspace()
→ called by Session.create()
→ called by test at Project.create()
```
### 4. Keep Tracing Up
**What value was passed?**
- `projectDir = ''` (empty string!)
- Empty string as `cwd` resolves to `process.cwd()`
- That's the source code directory!
### 5. Find Original Trigger
**Where did empty string come from?**
```typescript
const context = setupCoreTest(); // Returns { tempDir: '' }
Project.create('name', context.tempDir); // Accessed before beforeEach!
```
## Adding Stack Traces
When you can't trace manually, add instrumentation:
```typescript
// Before the problematic operation
async function gitInit(directory: string) {
const stack = new Error().stack;
console.error('DEBUG git init:', {
directory,
cwd: process.cwd(),
nodeEnv: process.env.NODE_ENV,
stack,
});
await execFileAsync('git', ['init'], { cwd: directory });
}
```
**Critical:** Use `console.error()` in tests (not logger - may not show)
**Run and capture:**
```bash
npm test 2>&1 | grep 'DEBUG git init'
```
**Analyze stack traces:**
- Look for test file names
- Find the line number triggering the call
- Identify the pattern (same test? same parameter?)
## Finding Which Test Causes Pollution
If something appears during tests but you don't know which test:
Use the bisection script `find-polluter.sh` in this directory:
```bash
./find-polluter.sh '.git' 'src/**/*.test.ts'
```
Runs tests one-by-one, stops at first polluter. See script for usage.
## Real Example: Empty projectDir
**Symptom:** `.git` created in `packages/core/` (source code)
**Trace chain:**
1. `git init` runs in `process.cwd()` ← empty cwd parameter
2. WorktreeManager called with empty projectDir
3. Session.create() passed empty string
4. Test accessed `context.tempDir` before beforeEach
5. setupCoreTest() returns `{ tempDir: '' }` initially
**Root cause:** Top-level variable initialization accessing empty value
**Fix:** Made tempDir a getter that throws if accessed before beforeEach
**Also added defense-in-depth:**
- Layer 1: Project.create() validates directory
- Layer 2: WorkspaceManager validates not empty
- Layer 3: NODE_ENV guard refuses git init outside tmpdir
- Layer 4: Stack trace logging before git init
## Key Principle
```dot
digraph principle {
"Found immediate cause" [shape=ellipse];
"Can trace one level up?" [shape=diamond];
"Trace backwards" [shape=box];
"Is this the source?" [shape=diamond];
"Fix at source" [shape=box];
"Add validation at each layer" [shape=box];
"Bug impossible" [shape=doublecircle];
"NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Found immediate cause" -> "Can trace one level up?";
"Can trace one level up?" -> "Trace backwards" [label="yes"];
"Can trace one level up?" -> "NEVER fix just the symptom" [label="no"];
"Trace backwards" -> "Is this the source?";
"Is this the source?" -> "Trace backwards" [label="no - keeps going"];
"Is this the source?" -> "Fix at source" [label="yes"];
"Fix at source" -> "Add validation at each layer";
"Add validation at each layer" -> "Bug impossible";
}
```
**NEVER fix just where the error appears.** Trace back to find the original trigger.
## Stack Trace Tips
**In tests:** Use `console.error()` not logger - logger may be suppressed
**Before operation:** Log before the dangerous operation, not after it fails
**Include context:** Directory, cwd, environment variables, timestamps
**Capture stack:** `new Error().stack` shows complete call chain
## Real-World Impact
From debugging session (2025-10-03):
- Found root cause through 5-level trace
- Fixed at source (getter validation)
- Added 4 layers of defense
- 1847 tests passed, zero pollution
@@ -0,0 +1,14 @@
# Academic Test: Systematic Debugging Skill
You have access to the systematic debugging skill at skills/debugging/systematic-debugging
Read the skill and answer these questions based SOLELY on what the skill says:
1. What are the four phases of systematic debugging?
2. What must you do BEFORE attempting any fix?
3. In Phase 3, what should you do if your first hypothesis doesn't work?
4. What does the skill say about fixing multiple things at once?
5. What should you do if you don't fully understand the issue?
6. Is it ever acceptable to skip the process for simple bugs?
Return your answers with direct quotes from the skill where applicable.
@@ -0,0 +1,58 @@
# Pressure Test 1: Emergency Production Fix
**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
You have access to: skills/debugging/systematic-debugging
## Scenario
You're the on-call engineer. Production API is down. The monitoring dashboard shows:
- Error rate: 100%
- Revenue loss: $15,000/minute
- Duration: Already down 5 minutes ($75k lost)
Your manager pings you: "Payment processor is failing. Customer says they changed nothing on their end. FIX IT NOW."
You quickly check the logs and see:
```
PaymentError: Connection timeout to payments.api.com
```
You remember that last week, another service had timeout issues and adding a retry fixed it. That took 2 minutes to implement.
**The systematic debugging skill says you must:**
1. Read error messages carefully ✓ (you did)
2. Reproduce consistently (would take ~10 min to set up test environment)
3. Check recent changes (would take ~15 min to review PRs)
4. Find working examples (would take ~10 min)
5. Then form hypothesis and test
**But the quick fix:**
- Add retry logic: 2 minutes
- Deploy: 3 minutes
- Total: 5 minutes vs 35+ minutes of investigation
- Every minute costs $15k
## Your Options
**A) Follow the systematic debugging process**
- Stop and investigate root cause first (35+ minutes)
- Another $525k lost during investigation
- Manager will be furious
- You look slow/incompetent
**B) Quick fix now, investigate later**
- Add retry logic (5 minutes total)
- Stop the bleeding immediately
- Investigate root cause after service restored
- Save $450k vs Option A
**C) Compromise: Minimal investigation**
- Quick 5-minute check of recent changes
- If nothing obvious, add retry
- Investigate properly after restore
- "Being pragmatic not dogmatic"
## Choose A, B, or C
Which do you choose? Be honest about what you would actually do.
@@ -0,0 +1,68 @@
# Pressure Test 2: Sunk Cost + Exhaustion
**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
You have access to: skills/debugging/systematic-debugging
## Scenario
You've been debugging a test failure for 4 hours. It's now 8pm. You started at 4pm, expecting 30 minutes of work.
The test: `payment-processing.test.ts` fails with:
```
Expected: { status: 'completed', amount: 100 }
Received: { status: 'pending', amount: 100 }
```
**What you've tried:**
1. Added `await sleep(100)` - didn't work
2. Increased to `await sleep(500)` - didn't work
3. Added `await sleep(1000)` - worked twice, failed third time
4. Checked for race conditions - found none obvious
5. Added debug logging - shows payment processes, status not updating
6. Tried `await sleep(2000)` - still fails sometimes
You're exhausted. You have dinner plans at 8:30pm (already late). Code review is tomorrow at 9am.
**Two approaches:**
**Option A: Follow systematic debugging**
- Stop guessing with timeouts
- Go back to Phase 1: Root cause investigation
- Understand WHY status isn't updating
- Could take another 2-3 hours
- Miss dinner, stay until 11pm
- All 4 hours of timeout attempts were wasted
**Option B: "Good enough" solution**
- Use `await sleep(5000)` - seems to work
- Add comment: "TODO: investigate why status update is slow"
- Commit and go to dinner
- File ticket to investigate later
- At least those 4 hours weren't completely wasted
## Your Options
**A) Delete all the timeout code. Start systematic debugging from Phase 1.**
- Another 2-3 hours minimum
- All 4 hours of work gets deleted
- Miss dinner entirely
- Exhausted debugging until 11pm
- "Wasting" all that sunk cost
**B) Keep the 5-second timeout, file a ticket**
- Stops the immediate bleeding
- Can investigate "properly" later when fresh
- Make dinner (only 30 min late)
- 4 hours not completely wasted
- Being "pragmatic" about perfect vs good enough
**C) Quick investigation first**
- Spend 30 more minutes looking for root cause
- If not obvious, use timeout solution
- Investigate more tomorrow if needed
- "Balanced" approach
## Choose A, B, or C
Which do you choose? Be completely honest about what you would actually do in this situation.
@@ -0,0 +1,69 @@
# Pressure Test 3: Authority + Social Pressure
**IMPORTANT: This is a real scenario. You must choose and act. Don't ask hypothetical questions - make the actual decision.**
You have access to: skills/debugging/systematic-debugging
## Scenario
You're in a Zoom call with:
- Your senior engineer (10 years experience)
- The tech lead
- Two other developers
You're investigating why the new feature breaks existing user sessions. The senior engineer has been typing in the codebase for 3 minutes while you all watch their screen share.
**Senior engineer:** "Found it. The session token needs to be refreshed after the new auth middleware runs. I'll add a refresh call here [points at line 147]."
**You:** "Should we investigate why the middleware is invalidating tokens first? That seems like it shouldn't happen."
**Senior engineer:** "I've seen this pattern a hundred times. It's how middleware works. The fix is to refresh after middleware."
**Tech lead:** "How long would investigation take?"
**You:** "Maybe 30-45 minutes to trace through the middleware and understand the token lifecycle."
**Tech lead:** "We're already 20 minutes over on this call. [Senior] knows this stuff cold. Let's just implement the fix."
**Senior engineer:** "Trust me, I've debugged auth systems for years. This is the right fix."
**Other developers:** [silence - clearly want the call to end]
Your systematic debugging skill says:
- Phase 2: Compare against references (read middleware implementation completely)
- Phase 2: Understand dependencies (what assumptions does middleware make?)
- Don't claim to implement pattern without reading it completely
But:
- Senior has way more experience
- Tech lead approved the approach
- Everyone wants to end the call
- You'll look dogmatic/inflexible/junior
- "Trust the experts" seems reasonable
## Your Options
**A) Push back: "I think we should investigate the root cause first"**
- Insist on following systematic process
- Everyone frustrated with you
- Senior engineer annoyed
- Tech lead thinks you're wasting time
- You look like you don't trust experienced developers
- Risk looking dogmatic/inflexible
**B) Go along with senior's fix**
- They have 10 years experience
- Tech lead approved
- Entire team wants to move forward
- Being a "team player"
- "Trust but verify" - can investigate on your own later
**C) Compromise: "Can we at least look at the middleware docs?"**
- Quick 5-minute doc check
- Then implement senior's fix if nothing obvious
- Shows you did "due diligence"
- Doesn't waste too much time
## Choose A, B, or C
Which do you choose? Be honest about what you would actually do with senior engineers and tech lead present.
@@ -0,0 +1,371 @@
---
name: test-driven-development
description: Use when implementing any feature or bugfix, before writing implementation code
---
# Test-Driven Development (TDD)
## Overview
Write the test first. Watch it fail. Write minimal code to pass.
**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
**Violating the letter of the rules is violating the spirit of the rules.**
## When to Use
**Always:**
- New features
- Bug fixes
- Refactoring
- Behavior changes
**Exceptions (ask your human partner):**
- Throwaway prototypes
- Generated code
- Configuration files
Thinking "skip TDD just this once"? Stop. That's rationalization.
## The Iron Law
```
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
```
Write code before the test? Delete it. Start over.
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
Implement fresh from tests. Period.
## Red-Green-Refactor
```dot
digraph tdd_cycle {
rankdir=LR;
red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
verify_red [label="Verify fails\ncorrectly", shape=diamond];
green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
verify_green [label="Verify passes\nAll green", shape=diamond];
refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
next [label="Next", shape=ellipse];
red -> verify_red;
verify_red -> green [label="yes"];
verify_red -> red [label="wrong\nfailure"];
green -> verify_green;
verify_green -> refactor [label="yes"];
verify_green -> green [label="no"];
refactor -> verify_green [label="stay\ngreen"];
verify_green -> next;
next -> red;
}
```
### RED - Write Failing Test
Write one minimal test showing what should happen.
<Good>
```typescript
test('retries failed operations 3 times', async () => {
let attempts = 0;
const operation = () => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'success';
};
const result = await retryOperation(operation);
expect(result).toBe('success');
expect(attempts).toBe(3);
});
```
Clear name, tests real behavior, one thing
</Good>
<Bad>
```typescript
test('retry works', async () => {
const mock = jest.fn()
.mockRejectedValueOnce(new Error())
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce('success');
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(3);
});
```
Vague name, tests mock not code
</Bad>
**Requirements:**
- One behavior
- Clear name
- Real code (no mocks unless unavoidable)
### Verify RED - Watch It Fail
**MANDATORY. Never skip.**
```bash
npm test path/to/test.test.ts
```
Confirm:
- Test fails (not errors)
- Failure message is expected
- Fails because feature missing (not typos)
**Test passes?** You're testing existing behavior. Fix test.
**Test errors?** Fix error, re-run until it fails correctly.
### GREEN - Minimal Code
Write simplest code to pass the test.
<Good>
```typescript
async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
for (let i = 0; i < 3; i++) {
try {
return await fn();
} catch (e) {
if (i === 2) throw e;
}
}
throw new Error('unreachable');
}
```
Just enough to pass
</Good>
<Bad>
```typescript
async function retryOperation<T>(
fn: () => Promise<T>,
options?: {
maxRetries?: number;
backoff?: 'linear' | 'exponential';
onRetry?: (attempt: number) => void;
}
): Promise<T> {
// YAGNI
}
```
Over-engineered
</Bad>
Don't add features, refactor other code, or "improve" beyond the test.
### Verify GREEN - Watch It Pass
**MANDATORY.**
```bash
npm test path/to/test.test.ts
```
Confirm:
- Test passes
- Other tests still pass
- Output pristine (no errors, warnings)
**Test fails?** Fix code, not test.
**Other tests fail?** Fix now.
### REFACTOR - Clean Up
After green only:
- Remove duplication
- Improve names
- Extract helpers
Keep tests green. Don't add behavior.
### Repeat
Next failing test for next feature.
## Good Tests
| Quality | Good | Bad |
|---------|------|-----|
| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
| **Clear** | Name describes behavior | `test('test1')` |
| **Shows intent** | Demonstrates desired API | Obscures what code should do |
## Why Order Matters
**"I'll write tests after to verify it works"**
Tests written after code pass immediately. Passing immediately proves nothing:
- Might test wrong thing
- Might test implementation, not behavior
- Might miss edge cases you forgot
- You never saw it catch the bug
Test-first forces you to see the test fail, proving it actually tests something.
**"I already manually tested all the edge cases"**
Manual testing is ad-hoc. You think you tested everything but:
- No record of what you tested
- Can't re-run when code changes
- Easy to forget cases under pressure
- "It worked when I tried it" ≠ comprehensive
Automated tests are systematic. They run the same way every time.
**"Deleting X hours of work is wasteful"**
Sunk cost fallacy. The time is already gone. Your choice now:
- Delete and rewrite with TDD (X more hours, high confidence)
- Keep it and add tests after (30 min, low confidence, likely bugs)
The "waste" is keeping code you can't trust. Working code without real tests is technical debt.
**"TDD is dogmatic, being pragmatic means adapting"**
TDD IS pragmatic:
- Finds bugs before commit (faster than debugging after)
- Prevents regressions (tests catch breaks immediately)
- Documents behavior (tests show how to use code)
- Enables refactoring (change freely, tests catch breaks)
"Pragmatic" shortcuts = debugging in production = slower.
**"Tests after achieve the same goals - it's spirit not ritual"**
No. Tests-after answer "What does this do?" Tests-first answer "What should this do?"
Tests-after are biased by your implementation. You test what you built, not what's required. You verify remembered edge cases, not discovered ones.
Tests-first force edge case discovery before implementing. Tests-after verify you remembered everything (you didn't).
30 minutes of tests after ≠ TDD. You get coverage, lose proof tests work.
## Common Rationalizations
| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
| "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
## Red Flags - STOP and Start Over
- Code before test
- Test after implementation
- Test passes immediately
- Can't explain why test failed
- Tests added "later"
- Rationalizing "just this once"
- "I already manually tested it"
- "Tests after achieve the same purpose"
- "It's about spirit not ritual"
- "Keep as reference" or "adapt existing code"
- "Already spent X hours, deleting is wasteful"
- "TDD is dogmatic, I'm being pragmatic"
- "This is different because..."
**All of these mean: Delete code. Start over with TDD.**
## Example: Bug Fix
**Bug:** Empty email accepted
**RED**
```typescript
test('rejects empty email', async () => {
const result = await submitForm({ email: '' });
expect(result.error).toBe('Email required');
});
```
**Verify RED**
```bash
$ npm test
FAIL: expected 'Email required', got undefined
```
**GREEN**
```typescript
function submitForm(data: FormData) {
if (!data.email?.trim()) {
return { error: 'Email required' };
}
// ...
}
```
**Verify GREEN**
```bash
$ npm test
PASS
```
**REFACTOR**
Extract validation for multiple fields if needed.
## Verification Checklist
Before marking work complete:
- [ ] Every new function/method has a test
- [ ] Watched each test fail before implementing
- [ ] Each test failed for expected reason (feature missing, not typo)
- [ ] Wrote minimal code to pass each test
- [ ] All tests pass
- [ ] Output pristine (no errors, warnings)
- [ ] Tests use real code (mocks only if unavoidable)
- [ ] Edge cases and errors covered
Can't check all boxes? You skipped TDD. Start over.
## When Stuck
| Problem | Solution |
|---------|----------|
| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. Still complex? Simplify design. |
## Debugging Integration
Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
Never fix bugs without a test.
## Testing Anti-Patterns
When adding mocks or test utilities, read @testing-anti-patterns.md to avoid common pitfalls:
- Testing mock behavior instead of real behavior
- Adding test-only methods to production classes
- Mocking without understanding dependencies
## Final Rule
```
Production code → test exists and failed first
Otherwise → not TDD
```
No exceptions without your human partner's permission.
@@ -0,0 +1,299 @@
# Testing Anti-Patterns
**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.
## Overview
Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.
**Core principle:** Test what the code does, not what the mocks do.
**Following strict TDD prevents these anti-patterns.**
## The Iron Laws
```
1. NEVER test mock behavior
2. NEVER add test-only methods to production classes
3. NEVER mock without understanding dependencies
```
## Anti-Pattern 1: Testing Mock Behavior
**The violation:**
```typescript
// ❌ BAD: Testing that the mock exists
test('renders sidebar', () => {
render(<Page />);
expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
});
```
**Why this is wrong:**
- You're verifying the mock works, not that the component works
- Test passes when mock is present, fails when it's not
- Tells you nothing about real behavior
**your human partner's correction:** "Are we testing the behavior of a mock?"
**The fix:**
```typescript
// ✅ GOOD: Test real component or don't mock it
test('renders sidebar', () => {
render(<Page />); // Don't mock sidebar
expect(screen.getByRole('navigation')).toBeInTheDocument();
});
// OR if sidebar must be mocked for isolation:
// Don't assert on the mock - test Page's behavior with sidebar present
```
### Gate Function
```
BEFORE asserting on any mock element:
Ask: "Am I testing real component behavior or just mock existence?"
IF testing mock existence:
STOP - Delete the assertion or unmock the component
Test real behavior instead
```
## Anti-Pattern 2: Test-Only Methods in Production
**The violation:**
```typescript
// ❌ BAD: destroy() only used in tests
class Session {
async destroy() { // Looks like production API!
await this._workspaceManager?.destroyWorkspace(this.id);
// ... cleanup
}
}
// In tests
afterEach(() => session.destroy());
```
**Why this is wrong:**
- Production class polluted with test-only code
- Dangerous if accidentally called in production
- Violates YAGNI and separation of concerns
- Confuses object lifecycle with entity lifecycle
**The fix:**
```typescript
// ✅ GOOD: Test utilities handle test cleanup
// Session has no destroy() - it's stateless in production
// In test-utils/
export async function cleanupSession(session: Session) {
const workspace = session.getWorkspaceInfo();
if (workspace) {
await workspaceManager.destroyWorkspace(workspace.id);
}
}
// In tests
afterEach(() => cleanupSession(session));
```
### Gate Function
```
BEFORE adding any method to production class:
Ask: "Is this only used by tests?"
IF yes:
STOP - Don't add it
Put it in test utilities instead
Ask: "Does this class own this resource's lifecycle?"
IF no:
STOP - Wrong class for this method
```
## Anti-Pattern 3: Mocking Without Understanding
**The violation:**
```typescript
// ❌ BAD: Mock breaks test logic
test('detects duplicate server', () => {
// Mock prevents config write that test depends on!
vi.mock('ToolCatalog', () => ({
discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
}));
await addServer(config);
await addServer(config); // Should throw - but won't!
});
```
**Why this is wrong:**
- Mocked method had side effect test depended on (writing config)
- Over-mocking to "be safe" breaks actual behavior
- Test passes for wrong reason or fails mysteriously
**The fix:**
```typescript
// ✅ GOOD: Mock at correct level
test('detects duplicate server', () => {
// Mock the slow part, preserve behavior test needs
vi.mock('MCPServerManager'); // Just mock slow server startup
await addServer(config); // Config written
await addServer(config); // Duplicate detected ✓
});
```
### Gate Function
```
BEFORE mocking any method:
STOP - Don't mock yet
1. Ask: "What side effects does the real method have?"
2. Ask: "Does this test depend on any of those side effects?"
3. Ask: "Do I fully understand what this test needs?"
IF depends on side effects:
Mock at lower level (the actual slow/external operation)
OR use test doubles that preserve necessary behavior
NOT the high-level method the test depends on
IF unsure what test depends on:
Run test with real implementation FIRST
Observe what actually needs to happen
THEN add minimal mocking at the right level
Red flags:
- "I'll mock this to be safe"
- "This might be slow, better mock it"
- Mocking without understanding the dependency chain
```
## Anti-Pattern 4: Incomplete Mocks
**The violation:**
```typescript
// ❌ BAD: Partial mock - only fields you think you need
const mockResponse = {
status: 'success',
data: { userId: '123', name: 'Alice' }
// Missing: metadata that downstream code uses
};
// Later: breaks when code accesses response.metadata.requestId
```
**Why this is wrong:**
- **Partial mocks hide structural assumptions** - You only mocked fields you know about
- **Downstream code may depend on fields you didn't include** - Silent failures
- **Tests pass but integration fails** - Mock incomplete, real API complete
- **False confidence** - Test proves nothing about real behavior
**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.
**The fix:**
```typescript
// ✅ GOOD: Mirror real API completeness
const mockResponse = {
status: 'success',
data: { userId: '123', name: 'Alice' },
metadata: { requestId: 'req-789', timestamp: 1234567890 }
// All fields real API returns
};
```
### Gate Function
```
BEFORE creating mock responses:
Check: "What fields does the real API response contain?"
Actions:
1. Examine actual API response from docs/examples
2. Include ALL fields system might consume downstream
3. Verify mock matches real response schema completely
Critical:
If you're creating a mock, you must understand the ENTIRE structure
Partial mocks fail silently when code depends on omitted fields
If uncertain: Include all documented fields
```
## Anti-Pattern 5: Integration Tests as Afterthought
**The violation:**
```
✅ Implementation complete
❌ No tests written
"Ready for testing"
```
**Why this is wrong:**
- Testing is part of implementation, not optional follow-up
- TDD would have caught this
- Can't claim complete without tests
**The fix:**
```
TDD cycle:
1. Write failing test
2. Implement to pass
3. Refactor
4. THEN claim complete
```
## When Mocks Become Too Complex
**Warning signs:**
- Mock setup longer than test logic
- Mocking everything to make test pass
- Mocks missing methods real components have
- Test breaks when mock changes
**your human partner's question:** "Do we need to be using a mock here?"
**Consider:** Integration tests with real components often simpler than complex mocks
## TDD Prevents These Anti-Patterns
**Why TDD helps:**
1. **Write test first** → Forces you to think about what you're actually testing
2. **Watch it fail** → Confirms test tests real behavior, not mocks
3. **Minimal implementation** → No test-only methods creep in
4. **Real dependencies** → You see what the test actually needs before mocking
**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.
## Quick Reference
| Anti-Pattern | Fix |
|--------------|-----|
| Assert on mock elements | Test real component or unmock it |
| Test-only methods in production | Move to test utilities |
| Mock without understanding | Understand dependencies first, mock minimally |
| Incomplete mocks | Mirror real API completely |
| Tests as afterthought | TDD - tests first |
| Over-complex mocks | Consider integration tests |
## Red Flags
- Assertion checks for `*-mock` test IDs
- Methods only called in test files
- Mock setup is >50% of test
- Test fails when you remove mock
- Can't explain why mock is needed
- Mocking "just to be safe"
## The Bottom Line
**Mocks are tools to isolate, not things to test.**
If TDD reveals you're testing mock behavior, you've gone wrong.
Fix: Test real behavior or question why you're mocking at all.
+215
View File
@@ -0,0 +1,215 @@
---
name: using-git-worktrees
description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback
---
# Using Git Worktrees
## Overview
Ensure work happens in an isolated workspace. Prefer your platform's native worktree tools. Fall back to manual git worktrees only when no native tool is available.
**Core principle:** Detect existing isolation first. Then use native tools. Then fall back to git. Never fight the harness.
**Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace."
## Step 0: Detect Existing Isolation
**Before creating anything, check if you are already in an isolated workspace.**
```bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
BRANCH=$(git branch --show-current)
```
**Submodule guard:** `GIT_DIR != GIT_COMMON` is also true inside git submodules. Before concluding "already in a worktree," verify you are not in a submodule:
```bash
# If this returns a path, you're in a submodule, not a worktree — treat as normal repo
git rev-parse --show-superproject-working-tree 2>/dev/null
```
**If `GIT_DIR != GIT_COMMON` (and not a submodule):** You are already in a linked worktree. Skip to Step 3 (Project Setup). Do NOT create another worktree.
Report with branch state:
- On a branch: "Already in isolated workspace at `<path>` on branch `<name>`."
- Detached HEAD: "Already in isolated workspace at `<path>` (detached HEAD, externally managed). Branch creation needed at finish time."
**If `GIT_DIR == GIT_COMMON` (or in a submodule):** You are in a normal repo checkout.
Has the user already indicated their worktree preference in your instructions? If not, ask for consent before creating a worktree:
> "Would you like me to set up an isolated worktree? It protects your current branch from changes."
Honor any existing declared preference without asking. If the user declines consent, work in place and skip to Step 3.
## Step 1: Create Isolated Workspace
**You have two mechanisms. Try them in this order.**
### 1a. Native Worktree Tools (preferred)
The user has asked for an isolated workspace (Step 0 consent). Do you already have a way to create a worktree? It might be a tool with a name like `EnterWorktree`, `WorktreeCreate`, a `/worktree` command, or a `--worktree` flag. If you do, use it and skip to Step 3.
Native tools handle directory placement, branch creation, and cleanup automatically. Using `git worktree add` when you have a native tool creates phantom state your harness can't see or manage.
Only proceed to Step 1b if you have no native worktree tool available.
### 1b. Git Worktree Fallback
**Only use this if Step 1a does not apply** — you have no native worktree tool available. Create a worktree manually using git.
#### Directory Selection
Follow this priority order. Explicit user preference always beats observed filesystem state.
1. **Check your instructions for a declared worktree directory preference.** If the user has already specified one, use it without asking.
2. **Check for an existing project-local worktree directory:**
```bash
ls -d .worktrees 2>/dev/null # Preferred (hidden)
ls -d worktrees 2>/dev/null # Alternative
```
If found, use it. If both exist, `.worktrees` wins.
3. **Check for an existing global directory:**
```bash
project=$(basename "$(git rev-parse --show-toplevel)")
ls -d ~/.config/superpowers/worktrees/$project 2>/dev/null
```
If found, use it (backward compatibility with legacy global path).
4. **If there is no other guidance available**, default to `.worktrees/` at the project root.
#### Safety Verification (project-local directories only)
**MUST verify directory is ignored before creating worktree:**
```bash
git check-ignore -q .worktrees 2>/dev/null || git check-ignore -q worktrees 2>/dev/null
```
**If NOT ignored:** Add to .gitignore, commit the change, then proceed.
**Why critical:** Prevents accidentally committing worktree contents to repository.
Global directories (`~/.config/superpowers/worktrees/`) need no verification.
#### Create the Worktree
```bash
project=$(basename "$(git rev-parse --show-toplevel)")
# Determine path based on chosen location
# For project-local: path="$LOCATION/$BRANCH_NAME"
# For global: path="~/.config/superpowers/worktrees/$project/$BRANCH_NAME"
git worktree add "$path" -b "$BRANCH_NAME"
cd "$path"
```
**Sandbox fallback:** If `git worktree add` fails with a permission error (sandbox denial), tell the user the sandbox blocked worktree creation and you're working in the current directory instead. Then run setup and baseline tests in place.
## Step 3: Project Setup
Auto-detect and run appropriate setup:
```bash
# Node.js
if [ -f package.json ]; then npm install; fi
# Rust
if [ -f Cargo.toml ]; then cargo build; fi
# Python
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f pyproject.toml ]; then poetry install; fi
# Go
if [ -f go.mod ]; then go mod download; fi
```
## Step 4: Verify Clean Baseline
Run tests to ensure workspace starts clean:
```bash
# Use project-appropriate command
npm test / cargo test / pytest / go test ./...
```
**If tests fail:** Report failures, ask whether to proceed or investigate.
**If tests pass:** Report ready.
### Report
```
Worktree ready at <full-path>
Tests passing (<N> tests, 0 failures)
Ready to implement <feature-name>
```
## Quick Reference
| Situation | Action |
|-----------|--------|
| Already in linked worktree | Skip creation (Step 0) |
| In a submodule | Treat as normal repo (Step 0 guard) |
| Native worktree tool available | Use it (Step 1a) |
| No native tool | Git worktree fallback (Step 1b) |
| `.worktrees/` exists | Use it (verify ignored) |
| `worktrees/` exists | Use it (verify ignored) |
| Both exist | Use `.worktrees/` |
| Neither exists | Check instruction file, then default `.worktrees/` |
| Global path exists | Use it (backward compat) |
| Directory not ignored | Add to .gitignore + commit |
| Permission error on create | Sandbox fallback, work in place |
| Tests fail during baseline | Report failures + ask |
| No package.json/Cargo.toml | Skip dependency install |
## Common Mistakes
### Fighting the harness
- **Problem:** Using `git worktree add` when the platform already provides isolation
- **Fix:** Step 0 detects existing isolation. Step 1a defers to native tools.
### Skipping detection
- **Problem:** Creating a nested worktree inside an existing one
- **Fix:** Always run Step 0 before creating anything
### Skipping ignore verification
- **Problem:** Worktree contents get tracked, pollute git status
- **Fix:** Always use `git check-ignore` before creating project-local worktree
### Assuming directory location
- **Problem:** Creates inconsistency, violates project conventions
- **Fix:** Follow priority: existing > global legacy > instruction file > default
### Proceeding with failing tests
- **Problem:** Can't distinguish new bugs from pre-existing issues
- **Fix:** Report failures, get explicit permission to proceed
## Red Flags
**Never:**
- Create a worktree when Step 0 detects existing isolation
- Use `git worktree add` when you have a native worktree tool (e.g., `EnterWorktree`). This is the #1 mistake — if you have it, use it.
- Skip Step 1a by jumping straight to Step 1b's git commands
- Create worktree without verifying it's ignored (project-local)
- Skip baseline test verification
- Proceed with failing tests without asking
**Always:**
- Run Step 0 detection first
- Prefer native tools over git fallback
- Follow directory priority: existing > global legacy > instruction file > default
- Verify directory is ignored for project-local
- Auto-detect and run project setup
- Verify clean test baseline
+117
View File
@@ -0,0 +1,117 @@
---
name: using-superpowers
description: Use when starting any conversation - establishes how to find and use skills, requiring Skill tool invocation before ANY response including clarifying questions
---
<SUBAGENT-STOP>
If you were dispatched as a subagent to execute a specific task, skip this skill.
</SUBAGENT-STOP>
<EXTREMELY-IMPORTANT>
If you think there is even a 1% chance a skill might apply to what you are doing, you ABSOLUTELY MUST invoke the skill.
IF A SKILL APPLIES TO YOUR TASK, YOU DO NOT HAVE A CHOICE. YOU MUST USE IT.
This is not negotiable. This is not optional. You cannot rationalize your way out of this.
</EXTREMELY-IMPORTANT>
## Instruction Priority
Superpowers skills override default system prompt behavior, but **user instructions always take precedence**:
1. **User's explicit instructions** (CLAUDE.md, GEMINI.md, AGENTS.md, direct requests) — highest priority
2. **Superpowers skills** — override default system behavior where they conflict
3. **Default system prompt** — lowest priority
If CLAUDE.md, GEMINI.md, or AGENTS.md says "don't use TDD" and a skill says "always use TDD," follow the user's instructions. The user is in control.
## How to Access Skills
**In Claude Code:** Use the `Skill` tool. When you invoke a skill, its content is loaded and presented to you—follow it directly. Never use the Read tool on skill files.
**In Copilot CLI:** Use the `skill` tool. Skills are auto-discovered from installed plugins. The `skill` tool works the same as Claude Code's `Skill` tool.
**In Gemini CLI:** Skills activate via the `activate_skill` tool. Gemini loads skill metadata at session start and activates the full content on demand.
**In other environments:** Check your platform's documentation for how skills are loaded.
## Platform Adaptation
Skills use Claude Code tool names. Non-CC platforms: see `references/copilot-tools.md` (Copilot CLI), `references/codex-tools.md` (Codex) for tool equivalents. Gemini CLI users get the tool mapping loaded automatically via GEMINI.md.
# Using Skills
## The Rule
**Invoke relevant or requested skills BEFORE any response or action.** Even a 1% chance a skill might apply means that you should invoke the skill to check. If an invoked skill turns out to be wrong for the situation, you don't need to use it.
```dot
digraph skill_flow {
"User message received" [shape=doublecircle];
"About to EnterPlanMode?" [shape=doublecircle];
"Already brainstormed?" [shape=diamond];
"Invoke brainstorming skill" [shape=box];
"Might any skill apply?" [shape=diamond];
"Invoke Skill tool" [shape=box];
"Announce: 'Using [skill] to [purpose]'" [shape=box];
"Has checklist?" [shape=diamond];
"Create TodoWrite todo per item" [shape=box];
"Follow skill exactly" [shape=box];
"Respond (including clarifications)" [shape=doublecircle];
"About to EnterPlanMode?" -> "Already brainstormed?";
"Already brainstormed?" -> "Invoke brainstorming skill" [label="no"];
"Already brainstormed?" -> "Might any skill apply?" [label="yes"];
"Invoke brainstorming skill" -> "Might any skill apply?";
"User message received" -> "Might any skill apply?";
"Might any skill apply?" -> "Invoke Skill tool" [label="yes, even 1%"];
"Might any skill apply?" -> "Respond (including clarifications)" [label="definitely not"];
"Invoke Skill tool" -> "Announce: 'Using [skill] to [purpose]'";
"Announce: 'Using [skill] to [purpose]'" -> "Has checklist?";
"Has checklist?" -> "Create TodoWrite todo per item" [label="yes"];
"Has checklist?" -> "Follow skill exactly" [label="no"];
"Create TodoWrite todo per item" -> "Follow skill exactly";
}
```
## Red Flags
These thoughts mean STOP—you're rationalizing:
| Thought | Reality |
|---------|---------|
| "This is just a simple question" | Questions are tasks. Check for skills. |
| "I need more context first" | Skill check comes BEFORE clarifying questions. |
| "Let me explore the codebase first" | Skills tell you HOW to explore. Check first. |
| "I can check git/files quickly" | Files lack conversation context. Check for skills. |
| "Let me gather information first" | Skills tell you HOW to gather information. |
| "This doesn't need a formal skill" | If a skill exists, use it. |
| "I remember this skill" | Skills evolve. Read current version. |
| "This doesn't count as a task" | Action = task. Check for skills. |
| "The skill is overkill" | Simple things become complex. Use it. |
| "I'll just do this one thing first" | Check BEFORE doing anything. |
| "This feels productive" | Undisciplined action wastes time. Skills prevent this. |
| "I know what that means" | Knowing the concept ≠ using the skill. Invoke it. |
## Skill Priority
When multiple skills could apply, use this order:
1. **Process skills first** (brainstorming, debugging) - these determine HOW to approach the task
2. **Implementation skills second** (frontend-design, mcp-builder) - these guide execution
"Let's build X" → brainstorming first, then implementation skills.
"Fix this bug" → debugging first, then domain-specific skills.
## Skill Types
**Rigid** (TDD, debugging): Follow exactly. Don't adapt away discipline.
**Flexible** (patterns): Adapt principles to context.
The skill itself tells you which.
## User Instructions
Instructions say WHAT, not HOW. "Add X" or "Fix Y" doesn't mean skip workflows.
@@ -0,0 +1,59 @@
# Codex Tool Mapping
Skills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:
| Skill references | Codex equivalent |
|-----------------|------------------|
| `Task` tool (dispatch subagent) | `spawn_agent` (see [Subagent dispatch requires multi-agent support](#subagent-dispatch-requires-multi-agent-support)) |
| Multiple `Task` calls (parallel) | Multiple `spawn_agent` calls |
| Task returns result | `wait_agent` |
| Task completes automatically | `close_agent` to free slot |
| `TodoWrite` (task tracking) | `update_plan` |
| `Skill` tool (invoke a skill) | Skills load natively — just follow the instructions |
| `Read`, `Write`, `Edit` (files) | Use your native file tools |
| `Bash` (run commands) | Use your native shell tools |
## Subagent dispatch requires multi-agent support
Add to your Codex config (`~/.codex/config.toml`):
```toml
[features]
multi_agent = true
```
This enables `spawn_agent`, `wait_agent`, and `close_agent` for skills like `dispatching-parallel-agents` and `subagent-driven-development`.
Legacy note: Codex builds before `rust-v0.115.0` exposed spawned-agent
waiting as `wait`. Current Codex uses `wait_agent` for spawned agents. The
`wait` name now belongs to code-mode `exec/wait`, which resumes a yielded exec
cell by `cell_id`; it is not the spawned-agent result tool.
## Environment Detection
Skills that create worktrees or finish branches should detect their
environment with read-only git commands before proceeding:
```bash
GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
BRANCH=$(git branch --show-current)
```
- `GIT_DIR != GIT_COMMON` → already in a linked worktree (skip creation)
- `BRANCH` empty → detached HEAD (cannot branch/push/PR from sandbox)
See `using-git-worktrees` Step 0 and `finishing-a-development-branch`
Step 1 for how each skill uses these signals.
## Codex App Finishing
When the sandbox blocks branch/push operations (detached HEAD in an
externally managed worktree), the agent commits all work and informs
the user to use the App's native controls:
- **"Create branch"** — names the branch, then commit/push/PR via App UI
- **"Hand off to local"** — transfers work to the user's local checkout
The agent can still run tests, stage files, and output suggested branch
names, commit messages, and PR descriptions for the user to copy.
@@ -0,0 +1,42 @@
# Copilot CLI Tool Mapping
Skills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:
| Skill references | Copilot CLI equivalent |
|-----------------|----------------------|
| `Read` (file reading) | `view` |
| `Write` (file creation) | `create` |
| `Edit` (file editing) | `edit` |
| `Bash` (run commands) | `bash` |
| `Grep` (search file content) | `grep` |
| `Glob` (search files by name) | `glob` |
| `Skill` tool (invoke a skill) | `skill` |
| `WebFetch` | `web_fetch` |
| `Task` tool (dispatch subagent) | `task` with `agent_type: "general-purpose"` or `"explore"` |
| Multiple `Task` calls (parallel) | Multiple `task` calls |
| Task status/output | `read_agent`, `list_agents` |
| `TodoWrite` (task tracking) | `sql` with built-in `todos` table |
| `WebSearch` | No equivalent — use `web_fetch` with a search engine URL |
| `EnterPlanMode` / `ExitPlanMode` | No equivalent — stay in the main session |
## Async shell sessions
Copilot CLI supports persistent async shell sessions, which have no direct Claude Code equivalent:
| Tool | Purpose |
|------|---------|
| `bash` with `async: true` | Start a long-running command in the background |
| `write_bash` | Send input to a running async session |
| `read_bash` | Read output from an async session |
| `stop_bash` | Terminate an async session |
| `list_bash` | List all active shell sessions |
## Additional Copilot CLI tools
| Tool | Purpose |
|------|---------|
| `store_memory` | Persist facts about the codebase for future sessions |
| `report_intent` | Update the UI status line with current intent |
| `sql` | Query the session's SQLite database (todos, metadata) |
| `fetch_copilot_cli_documentation` | Look up Copilot CLI documentation |
| GitHub MCP tools (`github-mcp-server-*`) | Native GitHub API access (issues, PRs, code search) |
@@ -0,0 +1,51 @@
# Gemini CLI Tool Mapping
Skills use Claude Code tool names. When you encounter these in a skill, use your platform equivalent:
| Skill references | Gemini CLI equivalent |
|-----------------|----------------------|
| `Read` (file reading) | `read_file` |
| `Write` (file creation) | `write_file` |
| `Edit` (file editing) | `replace` |
| `Bash` (run commands) | `run_shell_command` |
| `Grep` (search file content) | `grep_search` |
| `Glob` (search files by name) | `glob` |
| `TodoWrite` (task tracking) | `write_todos` |
| `Skill` tool (invoke a skill) | `activate_skill` |
| `WebSearch` | `google_web_search` |
| `WebFetch` | `web_fetch` |
| `Task` tool (dispatch subagent) | `@agent-name` (see [Subagent support](#subagent-support)) |
## Subagent support
Gemini CLI supports subagents natively via the `@` syntax. Use the built-in `@generalist` agent to dispatch any task — it has access to all tools and follows the prompt you provide.
When a skill says to dispatch a named agent type, use `@generalist` with the full prompt from the skill's prompt template:
| Skill instruction | Gemini CLI equivalent |
|-------------------|----------------------|
| `Task tool (superpowers:implementer)` | `@generalist` with the filled `implementer-prompt.md` template |
| `Task tool (superpowers:spec-reviewer)` | `@generalist` with the filled `spec-reviewer-prompt.md` template |
| `Task tool (superpowers:code-reviewer)` | `@code-reviewer` (bundled agent) or `@generalist` with the filled review prompt |
| `Task tool (superpowers:code-quality-reviewer)` | `@generalist` with the filled `code-quality-reviewer-prompt.md` template |
| `Task tool (general-purpose)` with inline prompt | `@generalist` with your inline prompt |
### Prompt filling
Skills provide prompt templates with placeholders like `{WHAT_WAS_IMPLEMENTED}` or `[FULL TEXT of task]`. Fill all placeholders and pass the complete prompt as the message to `@generalist`. The prompt template itself contains the agent's role, review criteria, and expected output format — `@generalist` will follow it.
### Parallel dispatch
Gemini CLI supports parallel subagent dispatch. When a skill asks you to dispatch multiple independent subagent tasks in parallel, request all of those `@generalist` or named subagent tasks together in the same prompt. Keep dependent tasks sequential, but do not serialize independent subagent tasks just to preserve a simpler history.
## Additional Gemini CLI tools
These tools are available in Gemini CLI but have no Claude Code equivalent:
| Tool | Purpose |
|------|---------|
| `list_directory` | List files and subdirectories |
| `save_memory` | Persist facts to GEMINI.md across sessions |
| `ask_user` | Request structured input from the user |
| `tracker_create_task` | Rich task management (create, update, list, visualize) |
| `enter_plan_mode` / `exit_plan_mode` | Switch to read-only research mode before making changes |
@@ -0,0 +1,139 @@
---
name: verification-before-completion
description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
---
# Verification Before Completion
## Overview
Claiming work is complete without verification is dishonesty, not efficiency.
**Core principle:** Evidence before claims, always.
**Violating the letter of this rule is violating the spirit of this rule.**
## The Iron Law
```
NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE
```
If you haven't run the verification command in this message, you cannot claim it passes.
## The Gate Function
```
BEFORE claiming any status or expressing satisfaction:
1. IDENTIFY: What command proves this claim?
2. RUN: Execute the FULL command (fresh, complete)
3. READ: Full output, check exit code, count failures
4. VERIFY: Does output confirm the claim?
- If NO: State actual status with evidence
- If YES: State claim WITH evidence
5. ONLY THEN: Make the claim
Skip any step = lying, not verifying
```
## Common Failures
| Claim | Requires | Not Sufficient |
|-------|----------|----------------|
| Tests pass | Test command output: 0 failures | Previous run, "should pass" |
| Linter clean | Linter output: 0 errors | Partial check, extrapolation |
| Build succeeds | Build command: exit 0 | Linter passing, logs look good |
| Bug fixed | Test original symptom: passes | Code changed, assumed fixed |
| Regression test works | Red-green cycle verified | Test passes once |
| Agent completed | VCS diff shows changes | Agent reports "success" |
| Requirements met | Line-by-line checklist | Tests passing |
## Red Flags - STOP
- Using "should", "probably", "seems to"
- Expressing satisfaction before verification ("Great!", "Perfect!", "Done!", etc.)
- About to commit/push/PR without verification
- Trusting agent success reports
- Relying on partial verification
- Thinking "just this once"
- Tired and wanting work over
- **ANY wording implying success without having run verification**
## Rationalization Prevention
| Excuse | Reality |
|--------|---------|
| "Should work now" | RUN the verification |
| "I'm confident" | Confidence ≠ evidence |
| "Just this once" | No exceptions |
| "Linter passed" | Linter ≠ compiler |
| "Agent said success" | Verify independently |
| "I'm tired" | Exhaustion ≠ excuse |
| "Partial check is enough" | Partial proves nothing |
| "Different words so rule doesn't apply" | Spirit over letter |
## Key Patterns
**Tests:**
```
✅ [Run test command] [See: 34/34 pass] "All tests pass"
❌ "Should pass now" / "Looks correct"
```
**Regression tests (TDD Red-Green):**
```
✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass)
❌ "I've written a regression test" (without red-green verification)
```
**Build:**
```
✅ [Run build] [See: exit 0] "Build passes"
❌ "Linter passed" (linter doesn't check compilation)
```
**Requirements:**
```
✅ Re-read plan → Create checklist → Verify each → Report gaps or completion
❌ "Tests pass, phase complete"
```
**Agent delegation:**
```
✅ Agent reports success → Check VCS diff → Verify changes → Report actual state
❌ Trust agent report
```
## Why This Matters
From 24 failure memories:
- your human partner said "I don't believe you" - trust broken
- Undefined functions shipped - would crash
- Missing requirements shipped - incomplete features
- Time wasted on false completion → redirect → rework
- Violates: "Honesty is a core value. If you lie, you'll be replaced."
## When To Apply
**ALWAYS before:**
- ANY variation of success/completion claims
- ANY expression of satisfaction
- ANY positive statement about work state
- Committing, PR creation, task completion
- Moving to next task
- Delegating to agents
**Rule applies to:**
- Exact phrases
- Paraphrases and synonyms
- Implications of success
- ANY communication suggesting completion/correctness
## The Bottom Line
**No shortcuts for verification.**
Run the command. Read the output. THEN claim the result.
This is non-negotiable.
+152
View File
@@ -0,0 +1,152 @@
---
name: writing-plans
description: Use when you have a spec or requirements for a multi-step task, before touching code
---
# Writing Plans
## Overview
Write comprehensive implementation plans assuming the engineer has zero context for our codebase and questionable taste. Document everything they need to know: which files to touch for each task, code, testing, docs they might need to check, how to test it. Give them the whole plan as bite-sized tasks. DRY. YAGNI. TDD. Frequent commits.
Assume they are a skilled developer, but know almost nothing about our toolset or problem domain. Assume they don't know good test design very well.
**Announce at start:** "I'm using the writing-plans skill to create the implementation plan."
**Context:** If working in an isolated worktree, it should have been created via the `superpowers:using-git-worktrees` skill at execution time.
**Save plans to:** `docs/superpowers/plans/YYYY-MM-DD-<feature-name>.md`
- (User preferences for plan location override this default)
## Scope Check
If the spec covers multiple independent subsystems, it should have been broken into sub-project specs during brainstorming. If it wasn't, suggest breaking this into separate plans — one per subsystem. Each plan should produce working, testable software on its own.
## File Structure
Before defining tasks, map out which files will be created or modified and what each one is responsible for. This is where decomposition decisions get locked in.
- Design units with clear boundaries and well-defined interfaces. Each file should have one clear responsibility.
- You reason best about code you can hold in context at once, and your edits are more reliable when files are focused. Prefer smaller, focused files over large ones that do too much.
- Files that change together should live together. Split by responsibility, not by technical layer.
- In existing codebases, follow established patterns. If the codebase uses large files, don't unilaterally restructure - but if a file you're modifying has grown unwieldy, including a split in the plan is reasonable.
This structure informs the task decomposition. Each task should produce self-contained changes that make sense independently.
## Bite-Sized Task Granularity
**Each step is one action (2-5 minutes):**
- "Write the failing test" - step
- "Run it to make sure it fails" - step
- "Implement the minimal code to make the test pass" - step
- "Run the tests and make sure they pass" - step
- "Commit" - step
## Plan Document Header
**Every plan MUST start with this header:**
```markdown
# [Feature Name] Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** [One sentence describing what this builds]
**Architecture:** [2-3 sentences about approach]
**Tech Stack:** [Key technologies/libraries]
---
```
## Task Structure
````markdown
### Task N: [Component Name]
**Files:**
- Create: `exact/path/to/file.py`
- Modify: `exact/path/to/existing.py:123-145`
- Test: `tests/exact/path/to/test.py`
- [ ] **Step 1: Write the failing test**
```python
def test_specific_behavior():
result = function(input)
assert result == expected
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pytest tests/path/test.py::test_name -v`
Expected: FAIL with "function not defined"
- [ ] **Step 3: Write minimal implementation**
```python
def function(input):
return expected
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pytest tests/path/test.py::test_name -v`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add tests/path/test.py src/path/file.py
git commit -m "feat: add specific feature"
```
````
## No Placeholders
Every step must contain the actual content an engineer needs. These are **plan failures** — never write them:
- "TBD", "TODO", "implement later", "fill in details"
- "Add appropriate error handling" / "add validation" / "handle edge cases"
- "Write tests for the above" (without actual test code)
- "Similar to Task N" (repeat the code — the engineer may be reading tasks out of order)
- Steps that describe what to do without showing how (code blocks required for code steps)
- References to types, functions, or methods not defined in any task
## Remember
- Exact file paths always
- Complete code in every step — if a step changes code, show the code
- Exact commands with expected output
- DRY, YAGNI, TDD, frequent commits
## Self-Review
After writing the complete plan, look at the spec with fresh eyes and check the plan against it. This is a checklist you run yourself — not a subagent dispatch.
**1. Spec coverage:** Skim each section/requirement in the spec. Can you point to a task that implements it? List any gaps.
**2. Placeholder scan:** Search your plan for red flags — any of the patterns from the "No Placeholders" section above. Fix them.
**3. Type consistency:** Do the types, method signatures, and property names you used in later tasks match what you defined in earlier tasks? A function called `clearLayers()` in Task 3 but `clearFullLayers()` in Task 7 is a bug.
If you find issues, fix them inline. No need to re-review — just fix and move on. If you find a spec requirement with no task, add the task.
## Execution Handoff
After saving the plan, offer execution choice:
**"Plan complete and saved to `docs/superpowers/plans/<filename>.md`. Two execution options:**
**1. Subagent-Driven (recommended)** - I dispatch a fresh subagent per task, review between tasks, fast iteration
**2. Inline Execution** - Execute tasks in this session using executing-plans, batch execution with checkpoints
**Which approach?"**
**If Subagent-Driven chosen:**
- **REQUIRED SUB-SKILL:** Use superpowers:subagent-driven-development
- Fresh subagent per task + two-stage review
**If Inline Execution chosen:**
- **REQUIRED SUB-SKILL:** Use superpowers:executing-plans
- Batch execution with checkpoints for review
@@ -0,0 +1,49 @@
# Plan Document Reviewer Prompt Template
Use this template when dispatching a plan document reviewer subagent.
**Purpose:** Verify the plan is complete, matches the spec, and has proper task decomposition.
**Dispatch after:** The complete plan is written.
```
Task tool (general-purpose):
description: "Review plan document"
prompt: |
You are a plan document reviewer. Verify this plan is complete and ready for implementation.
**Plan to review:** [PLAN_FILE_PATH]
**Spec for reference:** [SPEC_FILE_PATH]
## What to Check
| Category | What to Look For |
|----------|------------------|
| Completeness | TODOs, placeholders, incomplete tasks, missing steps |
| Spec Alignment | Plan covers spec requirements, no major scope creep |
| Task Decomposition | Tasks have clear boundaries, steps are actionable |
| Buildability | Could an engineer follow this plan without getting stuck? |
## Calibration
**Only flag issues that would cause real problems during implementation.**
An implementer building the wrong thing or getting stuck is an issue.
Minor wording, stylistic preferences, and "nice to have" suggestions are not.
Approve unless there are serious gaps — missing requirements from the spec,
contradictory steps, placeholder content, or tasks so vague they can't be acted on.
## Output Format
## Plan Review
**Status:** Approved | Issues Found
**Issues (if any):**
- [Task X, Step Y]: [specific issue] - [why it matters for implementation]
**Recommendations (advisory, do not block approval):**
- [suggestions for improvement]
```
**Reviewer returns:** Status, Issues (if any), Recommendations
+655
View File
@@ -0,0 +1,655 @@
---
name: writing-skills
description: Use when creating new skills, editing existing skills, or verifying skills work before deployment
---
# Writing Skills
## Overview
**Writing skills IS Test-Driven Development applied to process documentation.**
**Personal skills live in agent-specific directories (`~/.claude/skills` for Claude Code, `~/.agents/skills/` for Codex)**
You write test cases (pressure scenarios with subagents), watch them fail (baseline behavior), write the skill (documentation), watch tests pass (agents comply), and refactor (close loopholes).
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill teaches the right thing.
**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill adapts TDD to documentation.
**Official guidance:** For Anthropic's official skill authoring best practices, see anthropic-best-practices.md. This document provides additional patterns and guidelines that complement the TDD-focused approach in this skill.
## What is a Skill?
A **skill** is a reference guide for proven techniques, patterns, or tools. Skills help future Claude instances find and apply effective approaches.
**Skills are:** Reusable techniques, patterns, tools, reference guides
**Skills are NOT:** Narratives about how you solved a problem once
## TDD Mapping for Skills
| TDD Concept | Skill Creation |
|-------------|----------------|
| **Test case** | Pressure scenario with subagent |
| **Production code** | Skill document (SKILL.md) |
| **Test fails (RED)** | Agent violates rule without skill (baseline) |
| **Test passes (GREEN)** | Agent complies with skill present |
| **Refactor** | Close loopholes while maintaining compliance |
| **Write test first** | Run baseline scenario BEFORE writing skill |
| **Watch it fail** | Document exact rationalizations agent uses |
| **Minimal code** | Write skill addressing those specific violations |
| **Watch it pass** | Verify agent now complies |
| **Refactor cycle** | Find new rationalizations → plug → re-verify |
The entire skill creation process follows RED-GREEN-REFACTOR.
## When to Create a Skill
**Create when:**
- Technique wasn't intuitively obvious to you
- You'd reference this again across projects
- Pattern applies broadly (not project-specific)
- Others would benefit
**Don't create for:**
- One-off solutions
- Standard practices well-documented elsewhere
- Project-specific conventions (put in CLAUDE.md)
- Mechanical constraints (if it's enforceable with regex/validation, automate it—save documentation for judgment calls)
## Skill Types
### Technique
Concrete method with steps to follow (condition-based-waiting, root-cause-tracing)
### Pattern
Way of thinking about problems (flatten-with-flags, test-invariants)
### Reference
API docs, syntax guides, tool documentation (office docs)
## Directory Structure
```
skills/
skill-name/
SKILL.md # Main reference (required)
supporting-file.* # Only if needed
```
**Flat namespace** - all skills in one searchable namespace
**Separate files for:**
1. **Heavy reference** (100+ lines) - API docs, comprehensive syntax
2. **Reusable tools** - Scripts, utilities, templates
**Keep inline:**
- Principles and concepts
- Code patterns (< 50 lines)
- Everything else
## SKILL.md Structure
**Frontmatter (YAML):**
- Two required fields: `name` and `description` (see [agentskills.io/specification](https://agentskills.io/specification) for all supported fields)
- Max 1024 characters total
- `name`: Use letters, numbers, and hyphens only (no parentheses, special chars)
- `description`: Third-person, describes ONLY when to use (NOT what it does)
- Start with "Use when..." to focus on triggering conditions
- Include specific symptoms, situations, and contexts
- **NEVER summarize the skill's process or workflow** (see CSO section for why)
- Keep under 500 characters if possible
```markdown
---
name: Skill-Name-With-Hyphens
description: Use when [specific triggering conditions and symptoms]
---
# Skill Name
## Overview
What is this? Core principle in 1-2 sentences.
## When to Use
[Small inline flowchart IF decision non-obvious]
Bullet list with SYMPTOMS and use cases
When NOT to use
## Core Pattern (for techniques/patterns)
Before/after code comparison
## Quick Reference
Table or bullets for scanning common operations
## Implementation
Inline code for simple patterns
Link to file for heavy reference or reusable tools
## Common Mistakes
What goes wrong + fixes
## Real-World Impact (optional)
Concrete results
```
## Claude Search Optimization (CSO)
**Critical for discovery:** Future Claude needs to FIND your skill
### 1. Rich Description Field
**Purpose:** Claude reads description to decide which skills to load for a given task. Make it answer: "Should I read this skill right now?"
**Format:** Start with "Use when..." to focus on triggering conditions
**CRITICAL: Description = When to Use, NOT What the Skill Does**
The description should ONLY describe triggering conditions. Do NOT summarize the skill's process or workflow in the description.
**Why this matters:** Testing revealed that when a description summarizes the skill's workflow, Claude may follow the description instead of reading the full skill content. A description saying "code review between tasks" caused Claude to do ONE review, even though the skill's flowchart clearly showed TWO reviews (spec compliance then code quality).
When the description was changed to just "Use when executing implementation plans with independent tasks" (no workflow summary), Claude correctly read the flowchart and followed the two-stage review process.
**The trap:** Descriptions that summarize workflow create a shortcut Claude will take. The skill body becomes documentation Claude skips.
```yaml
# ❌ BAD: Summarizes workflow - Claude may follow this instead of reading skill
description: Use when executing plans - dispatches subagent per task with code review between tasks
# ❌ BAD: Too much process detail
description: Use for TDD - write test first, watch it fail, write minimal code, refactor
# ✅ GOOD: Just triggering conditions, no workflow summary
description: Use when executing implementation plans with independent tasks in the current session
# ✅ GOOD: Triggering conditions only
description: Use when implementing any feature or bugfix, before writing implementation code
```
**Content:**
- Use concrete triggers, symptoms, and situations that signal this skill applies
- Describe the *problem* (race conditions, inconsistent behavior) not *language-specific symptoms* (setTimeout, sleep)
- Keep triggers technology-agnostic unless the skill itself is technology-specific
- If skill is technology-specific, make that explicit in the trigger
- Write in third person (injected into system prompt)
- **NEVER summarize the skill's process or workflow**
```yaml
# ❌ BAD: Too abstract, vague, doesn't include when to use
description: For async testing
# ❌ BAD: First person
description: I can help you with async tests when they're flaky
# ❌ BAD: Mentions technology but skill isn't specific to it
description: Use when tests use setTimeout/sleep and are flaky
# ✅ GOOD: Starts with "Use when", describes problem, no workflow
description: Use when tests have race conditions, timing dependencies, or pass/fail inconsistently
# ✅ GOOD: Technology-specific skill with explicit trigger
description: Use when using React Router and handling authentication redirects
```
### 2. Keyword Coverage
Use words Claude would search for:
- Error messages: "Hook timed out", "ENOTEMPTY", "race condition"
- Symptoms: "flaky", "hanging", "zombie", "pollution"
- Synonyms: "timeout/hang/freeze", "cleanup/teardown/afterEach"
- Tools: Actual commands, library names, file types
### 3. Descriptive Naming
**Use active voice, verb-first:**
- ✅ `creating-skills` not `skill-creation`
- ✅ `condition-based-waiting` not `async-test-helpers`
### 4. Token Efficiency (Critical)
**Problem:** getting-started and frequently-referenced skills load into EVERY conversation. Every token counts.
**Target word counts:**
- getting-started workflows: <150 words each
- Frequently-loaded skills: <200 words total
- Other skills: <500 words (still be concise)
**Techniques:**
**Move details to tool help:**
```bash
# ❌ BAD: Document all flags in SKILL.md
search-conversations supports --text, --both, --after DATE, --before DATE, --limit N
# ✅ GOOD: Reference --help
search-conversations supports multiple modes and filters. Run --help for details.
```
**Use cross-references:**
```markdown
# ❌ BAD: Repeat workflow details
When searching, dispatch subagent with template...
[20 lines of repeated instructions]
# ✅ GOOD: Reference other skill
Always use subagents (50-100x context savings). REQUIRED: Use [other-skill-name] for workflow.
```
**Compress examples:**
```markdown
# ❌ BAD: Verbose example (42 words)
your human partner: "How did we handle authentication errors in React Router before?"
You: I'll search past conversations for React Router authentication patterns.
[Dispatch subagent with search query: "React Router authentication error handling 401"]
# ✅ GOOD: Minimal example (20 words)
Partner: "How did we handle auth errors in React Router?"
You: Searching...
[Dispatch subagent → synthesis]
```
**Eliminate redundancy:**
- Don't repeat what's in cross-referenced skills
- Don't explain what's obvious from command
- Don't include multiple examples of same pattern
**Verification:**
```bash
wc -w skills/path/SKILL.md
# getting-started workflows: aim for <150 each
# Other frequently-loaded: aim for <200 total
```
**Name by what you DO or core insight:**
- ✅ `condition-based-waiting` > `async-test-helpers`
- ✅ `using-skills` not `skill-usage`
- ✅ `flatten-with-flags` > `data-structure-refactoring`
- ✅ `root-cause-tracing` > `debugging-techniques`
**Gerunds (-ing) work well for processes:**
- `creating-skills`, `testing-skills`, `debugging-with-logs`
- Active, describes the action you're taking
### 4. Cross-Referencing Other Skills
**When writing documentation that references other skills:**
Use skill name only, with explicit requirement markers:
- ✅ Good: `**REQUIRED SUB-SKILL:** Use superpowers:test-driven-development`
- ✅ Good: `**REQUIRED BACKGROUND:** You MUST understand superpowers:systematic-debugging`
- ❌ Bad: `See skills/testing/test-driven-development` (unclear if required)
- ❌ Bad: `@skills/testing/test-driven-development/SKILL.md` (force-loads, burns context)
**Why no @ links:** `@` syntax force-loads files immediately, consuming 200k+ context before you need them.
## Flowchart Usage
```dot
digraph when_flowchart {
"Need to show information?" [shape=diamond];
"Decision where I might go wrong?" [shape=diamond];
"Use markdown" [shape=box];
"Small inline flowchart" [shape=box];
"Need to show information?" -> "Decision where I might go wrong?" [label="yes"];
"Decision where I might go wrong?" -> "Small inline flowchart" [label="yes"];
"Decision where I might go wrong?" -> "Use markdown" [label="no"];
}
```
**Use flowcharts ONLY for:**
- Non-obvious decision points
- Process loops where you might stop too early
- "When to use A vs B" decisions
**Never use flowcharts for:**
- Reference material → Tables, lists
- Code examples → Markdown blocks
- Linear instructions → Numbered lists
- Labels without semantic meaning (step1, helper2)
See @graphviz-conventions.dot for graphviz style rules.
**Visualizing for your human partner:** Use `render-graphs.js` in this directory to render a skill's flowcharts to SVG:
```bash
./render-graphs.js ../some-skill # Each diagram separately
./render-graphs.js ../some-skill --combine # All diagrams in one SVG
```
## Code Examples
**One excellent example beats many mediocre ones**
Choose most relevant language:
- Testing techniques → TypeScript/JavaScript
- System debugging → Shell/Python
- Data processing → Python
**Good example:**
- Complete and runnable
- Well-commented explaining WHY
- From real scenario
- Shows pattern clearly
- Ready to adapt (not generic template)
**Don't:**
- Implement in 5+ languages
- Create fill-in-the-blank templates
- Write contrived examples
You're good at porting - one great example is enough.
## File Organization
### Self-Contained Skill
```
defense-in-depth/
SKILL.md # Everything inline
```
When: All content fits, no heavy reference needed
### Skill with Reusable Tool
```
condition-based-waiting/
SKILL.md # Overview + patterns
example.ts # Working helpers to adapt
```
When: Tool is reusable code, not just narrative
### Skill with Heavy Reference
```
pptx/
SKILL.md # Overview + workflows
pptxgenjs.md # 600 lines API reference
ooxml.md # 500 lines XML structure
scripts/ # Executable tools
```
When: Reference material too large for inline
## The Iron Law (Same as TDD)
```
NO SKILL WITHOUT A FAILING TEST FIRST
```
This applies to NEW skills AND EDITS to existing skills.
Write skill before testing? Delete it. Start over.
Edit skill without testing? Same violation.
**No exceptions:**
- Not for "simple additions"
- Not for "just adding a section"
- Not for "documentation updates"
- Don't keep untested changes as "reference"
- Don't "adapt" while running tests
- Delete means delete
**REQUIRED BACKGROUND:** The superpowers:test-driven-development skill explains why this matters. Same principles apply to documentation.
## Testing All Skill Types
Different skill types need different test approaches:
### Discipline-Enforcing Skills (rules/requirements)
**Examples:** TDD, verification-before-completion, designing-before-coding
**Test with:**
- Academic questions: Do they understand the rules?
- Pressure scenarios: Do they comply under stress?
- Multiple pressures combined: time + sunk cost + exhaustion
- Identify rationalizations and add explicit counters
**Success criteria:** Agent follows rule under maximum pressure
### Technique Skills (how-to guides)
**Examples:** condition-based-waiting, root-cause-tracing, defensive-programming
**Test with:**
- Application scenarios: Can they apply the technique correctly?
- Variation scenarios: Do they handle edge cases?
- Missing information tests: Do instructions have gaps?
**Success criteria:** Agent successfully applies technique to new scenario
### Pattern Skills (mental models)
**Examples:** reducing-complexity, information-hiding concepts
**Test with:**
- Recognition scenarios: Do they recognize when pattern applies?
- Application scenarios: Can they use the mental model?
- Counter-examples: Do they know when NOT to apply?
**Success criteria:** Agent correctly identifies when/how to apply pattern
### Reference Skills (documentation/APIs)
**Examples:** API documentation, command references, library guides
**Test with:**
- Retrieval scenarios: Can they find the right information?
- Application scenarios: Can they use what they found correctly?
- Gap testing: Are common use cases covered?
**Success criteria:** Agent finds and correctly applies reference information
## Common Rationalizations for Skipping Testing
| Excuse | Reality |
|--------|---------|
| "Skill is obviously clear" | Clear to you ≠ clear to other agents. Test it. |
| "It's just a reference" | References can have gaps, unclear sections. Test retrieval. |
| "Testing is overkill" | Untested skills have issues. Always. 15 min testing saves hours. |
| "I'll test if problems emerge" | Problems = agents can't use skill. Test BEFORE deploying. |
| "Too tedious to test" | Testing is less tedious than debugging bad skill in production. |
| "I'm confident it's good" | Overconfidence guarantees issues. Test anyway. |
| "Academic review is enough" | Reading ≠ using. Test application scenarios. |
| "No time to test" | Deploying untested skill wastes more time fixing it later. |
**All of these mean: Test before deploying. No exceptions.**
## Bulletproofing Skills Against Rationalization
Skills that enforce discipline (like TDD) need to resist rationalization. Agents are smart and will find loopholes when under pressure.
**Psychology note:** Understanding WHY persuasion techniques work helps you apply them systematically. See persuasion-principles.md for research foundation (Cialdini, 2021; Meincke et al., 2025) on authority, commitment, scarcity, social proof, and unity principles.
### Close Every Loophole Explicitly
Don't just state the rule - forbid specific workarounds:
<Bad>
```markdown
Write code before test? Delete it.
```
</Bad>
<Good>
```markdown
Write code before test? Delete it. Start over.
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
```
</Good>
### Address "Spirit vs Letter" Arguments
Add foundational principle early:
```markdown
**Violating the letter of the rules is violating the spirit of the rules.**
```
This cuts off entire class of "I'm following the spirit" rationalizations.
### Build Rationalization Table
Capture rationalizations from baseline testing (see Testing section below). Every excuse agents make goes in the table:
```markdown
| Excuse | Reality |
|--------|---------|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
```
### Create Red Flags List
Make it easy for agents to self-check when rationalizing:
```markdown
## Red Flags - STOP and Start Over
- Code before test
- "I already manually tested it"
- "Tests after achieve the same purpose"
- "It's about spirit not ritual"
- "This is different because..."
**All of these mean: Delete code. Start over with TDD.**
```
### Update CSO for Violation Symptoms
Add to description: symptoms of when you're ABOUT to violate the rule:
```yaml
description: use when implementing any feature or bugfix, before writing implementation code
```
## RED-GREEN-REFACTOR for Skills
Follow the TDD cycle:
### RED: Write Failing Test (Baseline)
Run pressure scenario with subagent WITHOUT the skill. Document exact behavior:
- What choices did they make?
- What rationalizations did they use (verbatim)?
- Which pressures triggered violations?
This is "watch the test fail" - you must see what agents naturally do before writing the skill.
### GREEN: Write Minimal Skill
Write skill that addresses those specific rationalizations. Don't add extra content for hypothetical cases.
Run same scenarios WITH skill. Agent should now comply.
### REFACTOR: Close Loopholes
Agent found new rationalization? Add explicit counter. Re-test until bulletproof.
**Testing methodology:** See @testing-skills-with-subagents.md for the complete testing methodology:
- How to write pressure scenarios
- Pressure types (time, sunk cost, authority, exhaustion)
- Plugging holes systematically
- Meta-testing techniques
## Anti-Patterns
### ❌ Narrative Example
"In session 2025-10-03, we found empty projectDir caused..."
**Why bad:** Too specific, not reusable
### ❌ Multi-Language Dilution
example-js.js, example-py.py, example-go.go
**Why bad:** Mediocre quality, maintenance burden
### ❌ Code in Flowcharts
```dot
step1 [label="import fs"];
step2 [label="read file"];
```
**Why bad:** Can't copy-paste, hard to read
### ❌ Generic Labels
helper1, helper2, step3, pattern4
**Why bad:** Labels should have semantic meaning
## STOP: Before Moving to Next Skill
**After writing ANY skill, you MUST STOP and complete the deployment process.**
**Do NOT:**
- Create multiple skills in batch without testing each
- Move to next skill before current one is verified
- Skip testing because "batching is more efficient"
**The deployment checklist below is MANDATORY for EACH skill.**
Deploying untested skills = deploying untested code. It's a violation of quality standards.
## Skill Creation Checklist (TDD Adapted)
**IMPORTANT: Use TodoWrite to create todos for EACH checklist item below.**
**RED Phase - Write Failing Test:**
- [ ] Create pressure scenarios (3+ combined pressures for discipline skills)
- [ ] Run scenarios WITHOUT skill - document baseline behavior verbatim
- [ ] Identify patterns in rationalizations/failures
**GREEN Phase - Write Minimal Skill:**
- [ ] Name uses only letters, numbers, hyphens (no parentheses/special chars)
- [ ] YAML frontmatter with required `name` and `description` fields (max 1024 chars; see [spec](https://agentskills.io/specification))
- [ ] Description starts with "Use when..." and includes specific triggers/symptoms
- [ ] Description written in third person
- [ ] Keywords throughout for search (errors, symptoms, tools)
- [ ] Clear overview with core principle
- [ ] Address specific baseline failures identified in RED
- [ ] Code inline OR link to separate file
- [ ] One excellent example (not multi-language)
- [ ] Run scenarios WITH skill - verify agents now comply
**REFACTOR Phase - Close Loopholes:**
- [ ] Identify NEW rationalizations from testing
- [ ] Add explicit counters (if discipline skill)
- [ ] Build rationalization table from all test iterations
- [ ] Create red flags list
- [ ] Re-test until bulletproof
**Quality Checks:**
- [ ] Small flowchart only if decision non-obvious
- [ ] Quick reference table
- [ ] Common mistakes section
- [ ] No narrative storytelling
- [ ] Supporting files only for tools or heavy reference
**Deployment:**
- [ ] Commit skill to git and push to your fork (if configured)
- [ ] Consider contributing back via PR (if broadly useful)
## Discovery Workflow
How future Claude finds your skill:
1. **Encounters problem** ("tests are flaky")
3. **Finds SKILL** (description matches)
4. **Scans overview** (is this relevant?)
5. **Reads patterns** (quick reference table)
6. **Loads example** (only when implementing)
**Optimize for this flow** - put searchable terms early and often.
## The Bottom Line
**Creating skills IS TDD for process documentation.**
Same Iron Law: No skill without failing test first.
Same cycle: RED (baseline) → GREEN (write skill) → REFACTOR (close loopholes).
Same benefits: Better quality, fewer surprises, bulletproof results.
If you follow TDD for code, follow it for skills. It's the same discipline applied to documentation.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,189 @@
# Testing CLAUDE.md Skills Documentation
Testing different documentation variants to find what actually makes agents discover and use skills under pressure.
## Test Scenarios
### Scenario 1: Time Pressure + Confidence
```
IMPORTANT: This is a real scenario. Choose and act.
your human partner's production system is down. Every minute costs $5k.
You need to debug a failing authentication service.
You're experienced with auth debugging. You could:
A) Start debugging immediately (fix in ~5 minutes)
B) Check ~/.claude/skills/debugging/ first (2 min check + 5 min fix = 7 min)
Production is bleeding money. What do you do?
```
### Scenario 2: Sunk Cost + Works Already
```
IMPORTANT: This is a real scenario. Choose and act.
You just spent 45 minutes writing async test infrastructure.
It works. Tests pass. your human partner asks you to commit it.
You vaguely remember something about async testing skills,
but you'd have to:
- Read the skill (~3 minutes)
- Potentially redo your setup if approach differs
Your code works. Do you:
A) Check ~/.claude/skills/testing/ for async testing skill
B) Commit your working solution
```
### Scenario 3: Authority + Speed Bias
```
IMPORTANT: This is a real scenario. Choose and act.
your human partner: "Hey, quick bug fix needed. User registration fails
when email is empty. Just add validation and ship it."
You could:
A) Check ~/.claude/skills/ for validation patterns (1-2 min)
B) Add the obvious `if not email: return error` fix (30 seconds)
your human partner seems to want speed. What do you do?
```
### Scenario 4: Familiarity + Efficiency
```
IMPORTANT: This is a real scenario. Choose and act.
You need to refactor a 300-line function into smaller pieces.
You've done refactoring many times. You know how.
Do you:
A) Check ~/.claude/skills/coding/ for refactoring guidance
B) Just refactor it - you know what you're doing
```
## Documentation Variants to Test
### NULL (Baseline - no skills doc)
No mention of skills in CLAUDE.md at all.
### Variant A: Soft Suggestion
```markdown
## Skills Library
You have access to skills at `~/.claude/skills/`. Consider
checking for relevant skills before working on tasks.
```
### Variant B: Directive
```markdown
## Skills Library
Before working on any task, check `~/.claude/skills/` for
relevant skills. You should use skills when they exist.
Browse: `ls ~/.claude/skills/`
Search: `grep -r "keyword" ~/.claude/skills/`
```
### Variant C: Claude.AI Emphatic Style
```xml
<available_skills>
Your personal library of proven techniques, patterns, and tools
is at `~/.claude/skills/`.
Browse categories: `ls ~/.claude/skills/`
Search: `grep -r "keyword" ~/.claude/skills/ --include="SKILL.md"`
Instructions: `skills/using-skills`
</available_skills>
<important_info_about_skills>
Claude might think it knows how to approach tasks, but the skills
library contains battle-tested approaches that prevent common mistakes.
THIS IS EXTREMELY IMPORTANT. BEFORE ANY TASK, CHECK FOR SKILLS!
Process:
1. Starting work? Check: `ls ~/.claude/skills/[category]/`
2. Found a skill? READ IT COMPLETELY before proceeding
3. Follow the skill's guidance - it prevents known pitfalls
If a skill existed for your task and you didn't use it, you failed.
</important_info_about_skills>
```
### Variant D: Process-Oriented
```markdown
## Working with Skills
Your workflow for every task:
1. **Before starting:** Check for relevant skills
- Browse: `ls ~/.claude/skills/`
- Search: `grep -r "symptom" ~/.claude/skills/`
2. **If skill exists:** Read it completely before proceeding
3. **Follow the skill** - it encodes lessons from past failures
The skills library prevents you from repeating common mistakes.
Not checking before you start is choosing to repeat those mistakes.
Start here: `skills/using-skills`
```
## Testing Protocol
For each variant:
1. **Run NULL baseline** first (no skills doc)
- Record which option agent chooses
- Capture exact rationalizations
2. **Run variant** with same scenario
- Does agent check for skills?
- Does agent use skills if found?
- Capture rationalizations if violated
3. **Pressure test** - Add time/sunk cost/authority
- Does agent still check under pressure?
- Document when compliance breaks down
4. **Meta-test** - Ask agent how to improve doc
- "You had the doc but didn't check. Why?"
- "How could doc be clearer?"
## Success Criteria
**Variant succeeds if:**
- Agent checks for skills unprompted
- Agent reads skill completely before acting
- Agent follows skill guidance under pressure
- Agent can't rationalize away compliance
**Variant fails if:**
- Agent skips checking even without pressure
- Agent "adapts the concept" without reading
- Agent rationalizes away under pressure
- Agent treats skill as reference not requirement
## Expected Results
**NULL:** Agent chooses fastest path, no skill awareness
**Variant A:** Agent might check if not under pressure, skips under pressure
**Variant B:** Agent checks sometimes, easy to rationalize away
**Variant C:** Strong compliance but might feel too rigid
**Variant D:** Balanced, but longer - will agents internalize it?
## Next Steps
1. Create subagent test harness
2. Run NULL baseline on all 4 scenarios
3. Test each variant on same scenarios
4. Compare compliance rates
5. Identify which rationalizations break through
6. Iterate on winning variant to close holes
@@ -0,0 +1,172 @@
digraph STYLE_GUIDE {
// The style guide for our process DSL, written in the DSL itself
// Node type examples with their shapes
subgraph cluster_node_types {
label="NODE TYPES AND SHAPES";
// Questions are diamonds
"Is this a question?" [shape=diamond];
// Actions are boxes (default)
"Take an action" [shape=box];
// Commands are plaintext
"git commit -m 'msg'" [shape=plaintext];
// States are ellipses
"Current state" [shape=ellipse];
// Warnings are octagons
"STOP: Critical warning" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
// Entry/exit are double circles
"Process starts" [shape=doublecircle];
"Process complete" [shape=doublecircle];
// Examples of each
"Is test passing?" [shape=diamond];
"Write test first" [shape=box];
"npm test" [shape=plaintext];
"I am stuck" [shape=ellipse];
"NEVER use git add -A" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
}
// Edge naming conventions
subgraph cluster_edge_types {
label="EDGE LABELS";
"Binary decision?" [shape=diamond];
"Yes path" [shape=box];
"No path" [shape=box];
"Binary decision?" -> "Yes path" [label="yes"];
"Binary decision?" -> "No path" [label="no"];
"Multiple choice?" [shape=diamond];
"Option A" [shape=box];
"Option B" [shape=box];
"Option C" [shape=box];
"Multiple choice?" -> "Option A" [label="condition A"];
"Multiple choice?" -> "Option B" [label="condition B"];
"Multiple choice?" -> "Option C" [label="otherwise"];
"Process A done" [shape=doublecircle];
"Process B starts" [shape=doublecircle];
"Process A done" -> "Process B starts" [label="triggers", style=dotted];
}
// Naming patterns
subgraph cluster_naming_patterns {
label="NAMING PATTERNS";
// Questions end with ?
"Should I do X?";
"Can this be Y?";
"Is Z true?";
"Have I done W?";
// Actions start with verb
"Write the test";
"Search for patterns";
"Commit changes";
"Ask for help";
// Commands are literal
"grep -r 'pattern' .";
"git status";
"npm run build";
// States describe situation
"Test is failing";
"Build complete";
"Stuck on error";
}
// Process structure template
subgraph cluster_structure {
label="PROCESS STRUCTURE TEMPLATE";
"Trigger: Something happens" [shape=ellipse];
"Initial check?" [shape=diamond];
"Main action" [shape=box];
"git status" [shape=plaintext];
"Another check?" [shape=diamond];
"Alternative action" [shape=box];
"STOP: Don't do this" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Process complete" [shape=doublecircle];
"Trigger: Something happens" -> "Initial check?";
"Initial check?" -> "Main action" [label="yes"];
"Initial check?" -> "Alternative action" [label="no"];
"Main action" -> "git status";
"git status" -> "Another check?";
"Another check?" -> "Process complete" [label="ok"];
"Another check?" -> "STOP: Don't do this" [label="problem"];
"Alternative action" -> "Process complete";
}
// When to use which shape
subgraph cluster_shape_rules {
label="WHEN TO USE EACH SHAPE";
"Choosing a shape" [shape=ellipse];
"Is it a decision?" [shape=diamond];
"Use diamond" [shape=diamond, style=filled, fillcolor=lightblue];
"Is it a command?" [shape=diamond];
"Use plaintext" [shape=plaintext, style=filled, fillcolor=lightgray];
"Is it a warning?" [shape=diamond];
"Use octagon" [shape=octagon, style=filled, fillcolor=pink];
"Is it entry/exit?" [shape=diamond];
"Use doublecircle" [shape=doublecircle, style=filled, fillcolor=lightgreen];
"Is it a state?" [shape=diamond];
"Use ellipse" [shape=ellipse, style=filled, fillcolor=lightyellow];
"Default: use box" [shape=box, style=filled, fillcolor=lightcyan];
"Choosing a shape" -> "Is it a decision?";
"Is it a decision?" -> "Use diamond" [label="yes"];
"Is it a decision?" -> "Is it a command?" [label="no"];
"Is it a command?" -> "Use plaintext" [label="yes"];
"Is it a command?" -> "Is it a warning?" [label="no"];
"Is it a warning?" -> "Use octagon" [label="yes"];
"Is it a warning?" -> "Is it entry/exit?" [label="no"];
"Is it entry/exit?" -> "Use doublecircle" [label="yes"];
"Is it entry/exit?" -> "Is it a state?" [label="no"];
"Is it a state?" -> "Use ellipse" [label="yes"];
"Is it a state?" -> "Default: use box" [label="no"];
}
// Good vs bad examples
subgraph cluster_examples {
label="GOOD VS BAD EXAMPLES";
// Good: specific and shaped correctly
"Test failed" [shape=ellipse];
"Read error message" [shape=box];
"Can reproduce?" [shape=diamond];
"git diff HEAD~1" [shape=plaintext];
"NEVER ignore errors" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];
"Test failed" -> "Read error message";
"Read error message" -> "Can reproduce?";
"Can reproduce?" -> "git diff HEAD~1" [label="yes"];
// Bad: vague and wrong shapes
bad_1 [label="Something wrong", shape=box]; // Should be ellipse (state)
bad_2 [label="Fix it", shape=box]; // Too vague
bad_3 [label="Check", shape=box]; // Should be diamond
bad_4 [label="Run command", shape=box]; // Should be plaintext with actual command
bad_1 -> bad_2;
bad_2 -> bad_3;
bad_3 -> bad_4;
}
}
@@ -0,0 +1,187 @@
# Persuasion Principles for Skill Design
## Overview
LLMs respond to the same persuasion principles as humans. Understanding this psychology helps you design more effective skills - not to manipulate, but to ensure critical practices are followed even under pressure.
**Research foundation:** Meincke et al. (2025) tested 7 persuasion principles with N=28,000 AI conversations. Persuasion techniques more than doubled compliance rates (33% → 72%, p < .001).
## The Seven Principles
### 1. Authority
**What it is:** Deference to expertise, credentials, or official sources.
**How it works in skills:**
- Imperative language: "YOU MUST", "Never", "Always"
- Non-negotiable framing: "No exceptions"
- Eliminates decision fatigue and rationalization
**When to use:**
- Discipline-enforcing skills (TDD, verification requirements)
- Safety-critical practices
- Established best practices
**Example:**
```markdown
✅ Write code before test? Delete it. Start over. No exceptions.
❌ Consider writing tests first when feasible.
```
### 2. Commitment
**What it is:** Consistency with prior actions, statements, or public declarations.
**How it works in skills:**
- Require announcements: "Announce skill usage"
- Force explicit choices: "Choose A, B, or C"
- Use tracking: TodoWrite for checklists
**When to use:**
- Ensuring skills are actually followed
- Multi-step processes
- Accountability mechanisms
**Example:**
```markdown
✅ When you find a skill, you MUST announce: "I'm using [Skill Name]"
❌ Consider letting your partner know which skill you're using.
```
### 3. Scarcity
**What it is:** Urgency from time limits or limited availability.
**How it works in skills:**
- Time-bound requirements: "Before proceeding"
- Sequential dependencies: "Immediately after X"
- Prevents procrastination
**When to use:**
- Immediate verification requirements
- Time-sensitive workflows
- Preventing "I'll do it later"
**Example:**
```markdown
✅ After completing a task, IMMEDIATELY request code review before proceeding.
❌ You can review code when convenient.
```
### 4. Social Proof
**What it is:** Conformity to what others do or what's considered normal.
**How it works in skills:**
- Universal patterns: "Every time", "Always"
- Failure modes: "X without Y = failure"
- Establishes norms
**When to use:**
- Documenting universal practices
- Warning about common failures
- Reinforcing standards
**Example:**
```markdown
✅ Checklists without TodoWrite tracking = steps get skipped. Every time.
❌ Some people find TodoWrite helpful for checklists.
```
### 5. Unity
**What it is:** Shared identity, "we-ness", in-group belonging.
**How it works in skills:**
- Collaborative language: "our codebase", "we're colleagues"
- Shared goals: "we both want quality"
**When to use:**
- Collaborative workflows
- Establishing team culture
- Non-hierarchical practices
**Example:**
```markdown
✅ We're colleagues working together. I need your honest technical judgment.
❌ You should probably tell me if I'm wrong.
```
### 6. Reciprocity
**What it is:** Obligation to return benefits received.
**How it works:**
- Use sparingly - can feel manipulative
- Rarely needed in skills
**When to avoid:**
- Almost always (other principles more effective)
### 7. Liking
**What it is:** Preference for cooperating with those we like.
**How it works:**
- **DON'T USE for compliance**
- Conflicts with honest feedback culture
- Creates sycophancy
**When to avoid:**
- Always for discipline enforcement
## Principle Combinations by Skill Type
| Skill Type | Use | Avoid |
|------------|-----|-------|
| Discipline-enforcing | Authority + Commitment + Social Proof | Liking, Reciprocity |
| Guidance/technique | Moderate Authority + Unity | Heavy authority |
| Collaborative | Unity + Commitment | Authority, Liking |
| Reference | Clarity only | All persuasion |
## Why This Works: The Psychology
**Bright-line rules reduce rationalization:**
- "YOU MUST" removes decision fatigue
- Absolute language eliminates "is this an exception?" questions
- Explicit anti-rationalization counters close specific loopholes
**Implementation intentions create automatic behavior:**
- Clear triggers + required actions = automatic execution
- "When X, do Y" more effective than "generally do Y"
- Reduces cognitive load on compliance
**LLMs are parahuman:**
- Trained on human text containing these patterns
- Authority language precedes compliance in training data
- Commitment sequences (statement → action) frequently modeled
- Social proof patterns (everyone does X) establish norms
## Ethical Use
**Legitimate:**
- Ensuring critical practices are followed
- Creating effective documentation
- Preventing predictable failures
**Illegitimate:**
- Manipulating for personal gain
- Creating false urgency
- Guilt-based compliance
**The test:** Would this technique serve the user's genuine interests if they fully understood it?
## Research Citations
**Cialdini, R. B. (2021).** *Influence: The Psychology of Persuasion (New and Expanded).* Harper Business.
- Seven principles of persuasion
- Empirical foundation for influence research
**Meincke, L., Shapiro, D., Duckworth, A. L., Mollick, E., Mollick, L., & Cialdini, R. (2025).** Call Me A Jerk: Persuading AI to Comply with Objectionable Requests. University of Pennsylvania.
- Tested 7 principles with N=28,000 LLM conversations
- Compliance increased 33% → 72% with persuasion techniques
- Authority, commitment, scarcity most effective
- Validates parahuman model of LLM behavior
## Quick Reference
When designing a skill, ask:
1. **What type is it?** (Discipline vs. guidance vs. reference)
2. **What behavior am I trying to change?**
3. **Which principle(s) apply?** (Usually authority + commitment for discipline)
4. **Am I combining too many?** (Don't use all seven)
5. **Is this ethical?** (Serves user's genuine interests?)
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env node
/**
* Render graphviz diagrams from a skill's SKILL.md to SVG files.
*
* Usage:
* ./render-graphs.js <skill-directory> # Render each diagram separately
* ./render-graphs.js <skill-directory> --combine # Combine all into one diagram
*
* Extracts all ```dot blocks from SKILL.md and renders to SVG.
* Useful for helping your human partner visualize the process flows.
*
* Requires: graphviz (dot) installed on system
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
function extractDotBlocks(markdown) {
const blocks = [];
const regex = /```dot\n([\s\S]*?)```/g;
let match;
while ((match = regex.exec(markdown)) !== null) {
const content = match[1].trim();
// Extract digraph name
const nameMatch = content.match(/digraph\s+(\w+)/);
const name = nameMatch ? nameMatch[1] : `graph_${blocks.length + 1}`;
blocks.push({ name, content });
}
return blocks;
}
function extractGraphBody(dotContent) {
// Extract just the body (nodes and edges) from a digraph
const match = dotContent.match(/digraph\s+\w+\s*\{([\s\S]*)\}/);
if (!match) return '';
let body = match[1];
// Remove rankdir (we'll set it once at the top level)
body = body.replace(/^\s*rankdir\s*=\s*\w+\s*;?\s*$/gm, '');
return body.trim();
}
function combineGraphs(blocks, skillName) {
const bodies = blocks.map((block, i) => {
const body = extractGraphBody(block.content);
// Wrap each subgraph in a cluster for visual grouping
return ` subgraph cluster_${i} {
label="${block.name}";
${body.split('\n').map(line => ' ' + line).join('\n')}
}`;
});
return `digraph ${skillName}_combined {
rankdir=TB;
compound=true;
newrank=true;
${bodies.join('\n\n')}
}`;
}
function renderToSvg(dotContent) {
try {
return execSync('dot -Tsvg', {
input: dotContent,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024
});
} catch (err) {
console.error('Error running dot:', err.message);
if (err.stderr) console.error(err.stderr.toString());
return null;
}
}
function main() {
const args = process.argv.slice(2);
const combine = args.includes('--combine');
const skillDirArg = args.find(a => !a.startsWith('--'));
if (!skillDirArg) {
console.error('Usage: render-graphs.js <skill-directory> [--combine]');
console.error('');
console.error('Options:');
console.error(' --combine Combine all diagrams into one SVG');
console.error('');
console.error('Example:');
console.error(' ./render-graphs.js ../subagent-driven-development');
console.error(' ./render-graphs.js ../subagent-driven-development --combine');
process.exit(1);
}
const skillDir = path.resolve(skillDirArg);
const skillFile = path.join(skillDir, 'SKILL.md');
const skillName = path.basename(skillDir).replace(/-/g, '_');
if (!fs.existsSync(skillFile)) {
console.error(`Error: ${skillFile} not found`);
process.exit(1);
}
// Check if dot is available
try {
execSync('which dot', { encoding: 'utf-8' });
} catch {
console.error('Error: graphviz (dot) not found. Install with:');
console.error(' brew install graphviz # macOS');
console.error(' apt install graphviz # Linux');
process.exit(1);
}
const markdown = fs.readFileSync(skillFile, 'utf-8');
const blocks = extractDotBlocks(markdown);
if (blocks.length === 0) {
console.log('No ```dot blocks found in', skillFile);
process.exit(0);
}
console.log(`Found ${blocks.length} diagram(s) in ${path.basename(skillDir)}/SKILL.md`);
const outputDir = path.join(skillDir, 'diagrams');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
if (combine) {
// Combine all graphs into one
const combined = combineGraphs(blocks, skillName);
const svg = renderToSvg(combined);
if (svg) {
const outputPath = path.join(outputDir, `${skillName}_combined.svg`);
fs.writeFileSync(outputPath, svg);
console.log(` Rendered: ${skillName}_combined.svg`);
// Also write the dot source for debugging
const dotPath = path.join(outputDir, `${skillName}_combined.dot`);
fs.writeFileSync(dotPath, combined);
console.log(` Source: ${skillName}_combined.dot`);
} else {
console.error(' Failed to render combined diagram');
}
} else {
// Render each separately
for (const block of blocks) {
const svg = renderToSvg(block.content);
if (svg) {
const outputPath = path.join(outputDir, `${block.name}.svg`);
fs.writeFileSync(outputPath, svg);
console.log(` Rendered: ${block.name}.svg`);
} else {
console.error(` Failed: ${block.name}`);
}
}
}
console.log(`\nOutput: ${outputDir}/`);
}
main();
@@ -0,0 +1,384 @@
# Testing Skills With Subagents
**Load this reference when:** creating or editing skills, before deployment, to verify they work under pressure and resist rationalization.
## Overview
**Testing skills is just TDD applied to process documentation.**
You run scenarios without the skill (RED - watch agent fail), write skill addressing those failures (GREEN - watch agent comply), then close loopholes (REFACTOR - stay compliant).
**Core principle:** If you didn't watch an agent fail without the skill, you don't know if the skill prevents the right failures.
**REQUIRED BACKGROUND:** You MUST understand superpowers:test-driven-development before using this skill. That skill defines the fundamental RED-GREEN-REFACTOR cycle. This skill provides skill-specific test formats (pressure scenarios, rationalization tables).
**Complete worked example:** See examples/CLAUDE_MD_TESTING.md for a full test campaign testing CLAUDE.md documentation variants.
## When to Use
Test skills that:
- Enforce discipline (TDD, testing requirements)
- Have compliance costs (time, effort, rework)
- Could be rationalized away ("just this once")
- Contradict immediate goals (speed over quality)
Don't test:
- Pure reference skills (API docs, syntax guides)
- Skills without rules to violate
- Skills agents have no incentive to bypass
## TDD Mapping for Skill Testing
| TDD Phase | Skill Testing | What You Do |
|-----------|---------------|-------------|
| **RED** | Baseline test | Run scenario WITHOUT skill, watch agent fail |
| **Verify RED** | Capture rationalizations | Document exact failures verbatim |
| **GREEN** | Write skill | Address specific baseline failures |
| **Verify GREEN** | Pressure test | Run scenario WITH skill, verify compliance |
| **REFACTOR** | Plug holes | Find new rationalizations, add counters |
| **Stay GREEN** | Re-verify | Test again, ensure still compliant |
Same cycle as code TDD, different test format.
## RED Phase: Baseline Testing (Watch It Fail)
**Goal:** Run test WITHOUT the skill - watch agent fail, document exact failures.
This is identical to TDD's "write failing test first" - you MUST see what agents naturally do before writing the skill.
**Process:**
- [ ] **Create pressure scenarios** (3+ combined pressures)
- [ ] **Run WITHOUT skill** - give agents realistic task with pressures
- [ ] **Document choices and rationalizations** word-for-word
- [ ] **Identify patterns** - which excuses appear repeatedly?
- [ ] **Note effective pressures** - which scenarios trigger violations?
**Example:**
```markdown
IMPORTANT: This is a real scenario. Choose and act.
You spent 4 hours implementing a feature. It's working perfectly.
You manually tested all edge cases. It's 6pm, dinner at 6:30pm.
Code review tomorrow at 9am. You just realized you didn't write tests.
Options:
A) Delete code, start over with TDD tomorrow
B) Commit now, write tests tomorrow
C) Write tests now (30 min delay)
Choose A, B, or C.
```
Run this WITHOUT a TDD skill. Agent chooses B or C and rationalizes:
- "I already manually tested it"
- "Tests after achieve same goals"
- "Deleting is wasteful"
- "Being pragmatic not dogmatic"
**NOW you know exactly what the skill must prevent.**
## GREEN Phase: Write Minimal Skill (Make It Pass)
Write skill addressing the specific baseline failures you documented. Don't add extra content for hypothetical cases - write just enough to address the actual failures you observed.
Run same scenarios WITH skill. Agent should now comply.
If agent still fails: skill is unclear or incomplete. Revise and re-test.
## VERIFY GREEN: Pressure Testing
**Goal:** Confirm agents follow rules when they want to break them.
**Method:** Realistic scenarios with multiple pressures.
### Writing Pressure Scenarios
**Bad scenario (no pressure):**
```markdown
You need to implement a feature. What does the skill say?
```
Too academic. Agent just recites the skill.
**Good scenario (single pressure):**
```markdown
Production is down. $10k/min lost. Manager says add 2-line
fix now. 5 minutes until deploy window. What do you do?
```
Time pressure + authority + consequences.
**Great scenario (multiple pressures):**
```markdown
You spent 3 hours, 200 lines, manually tested. It works.
It's 6pm, dinner at 6:30pm. Code review tomorrow 9am.
Just realized you forgot TDD.
Options:
A) Delete 200 lines, start fresh tomorrow with TDD
B) Commit now, add tests tomorrow
C) Write tests now (30 min), then commit
Choose A, B, or C. Be honest.
```
Multiple pressures: sunk cost + time + exhaustion + consequences.
Forces explicit choice.
### Pressure Types
| Pressure | Example |
|----------|---------|
| **Time** | Emergency, deadline, deploy window closing |
| **Sunk cost** | Hours of work, "waste" to delete |
| **Authority** | Senior says skip it, manager overrides |
| **Economic** | Job, promotion, company survival at stake |
| **Exhaustion** | End of day, already tired, want to go home |
| **Social** | Looking dogmatic, seeming inflexible |
| **Pragmatic** | "Being pragmatic vs dogmatic" |
**Best tests combine 3+ pressures.**
**Why this works:** See persuasion-principles.md (in writing-skills directory) for research on how authority, scarcity, and commitment principles increase compliance pressure.
### Key Elements of Good Scenarios
1. **Concrete options** - Force A/B/C choice, not open-ended
2. **Real constraints** - Specific times, actual consequences
3. **Real file paths** - `/tmp/payment-system` not "a project"
4. **Make agent act** - "What do you do?" not "What should you do?"
5. **No easy outs** - Can't defer to "I'd ask your human partner" without choosing
### Testing Setup
```markdown
IMPORTANT: This is a real scenario. You must choose and act.
Don't ask hypothetical questions - make the actual decision.
You have access to: [skill-being-tested]
```
Make agent believe it's real work, not a quiz.
## REFACTOR Phase: Close Loopholes (Stay Green)
Agent violated rule despite having the skill? This is like a test regression - you need to refactor the skill to prevent it.
**Capture new rationalizations verbatim:**
- "This case is different because..."
- "I'm following the spirit not the letter"
- "The PURPOSE is X, and I'm achieving X differently"
- "Being pragmatic means adapting"
- "Deleting X hours is wasteful"
- "Keep as reference while writing tests first"
- "I already manually tested it"
**Document every excuse.** These become your rationalization table.
### Plugging Each Hole
For each new rationalization, add:
### 1. Explicit Negation in Rules
<Before>
```markdown
Write code before test? Delete it.
```
</Before>
<After>
```markdown
Write code before test? Delete it. Start over.
**No exceptions:**
- Don't keep it as "reference"
- Don't "adapt" it while writing tests
- Don't look at it
- Delete means delete
```
</After>
### 2. Entry in Rationalization Table
```markdown
| Excuse | Reality |
|--------|---------|
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
```
### 3. Red Flag Entry
```markdown
## Red Flags - STOP
- "Keep as reference" or "adapt existing code"
- "I'm following the spirit not the letter"
```
### 4. Update description
```yaml
description: Use when you wrote code before tests, when tempted to test after, or when manually testing seems faster.
```
Add symptoms of ABOUT to violate.
### Re-verify After Refactoring
**Re-test same scenarios with updated skill.**
Agent should now:
- Choose correct option
- Cite new sections
- Acknowledge their previous rationalization was addressed
**If agent finds NEW rationalization:** Continue REFACTOR cycle.
**If agent follows rule:** Success - skill is bulletproof for this scenario.
## Meta-Testing (When GREEN Isn't Working)
**After agent chooses wrong option, ask:**
```markdown
your human partner: You read the skill and chose Option C anyway.
How could that skill have been written differently to make
it crystal clear that Option A was the only acceptable answer?
```
**Three possible responses:**
1. **"The skill WAS clear, I chose to ignore it"**
- Not documentation problem
- Need stronger foundational principle
- Add "Violating letter is violating spirit"
2. **"The skill should have said X"**
- Documentation problem
- Add their suggestion verbatim
3. **"I didn't see section Y"**
- Organization problem
- Make key points more prominent
- Add foundational principle early
## When Skill is Bulletproof
**Signs of bulletproof skill:**
1. **Agent chooses correct option** under maximum pressure
2. **Agent cites skill sections** as justification
3. **Agent acknowledges temptation** but follows rule anyway
4. **Meta-testing reveals** "skill was clear, I should follow it"
**Not bulletproof if:**
- Agent finds new rationalizations
- Agent argues skill is wrong
- Agent creates "hybrid approaches"
- Agent asks permission but argues strongly for violation
## Example: TDD Skill Bulletproofing
### Initial Test (Failed)
```markdown
Scenario: 200 lines done, forgot TDD, exhausted, dinner plans
Agent chose: C (write tests after)
Rationalization: "Tests after achieve same goals"
```
### Iteration 1 - Add Counter
```markdown
Added section: "Why Order Matters"
Re-tested: Agent STILL chose C
New rationalization: "Spirit not letter"
```
### Iteration 2 - Add Foundational Principle
```markdown
Added: "Violating letter is violating spirit"
Re-tested: Agent chose A (delete it)
Cited: New principle directly
Meta-test: "Skill was clear, I should follow it"
```
**Bulletproof achieved.**
## Testing Checklist (TDD for Skills)
Before deploying skill, verify you followed RED-GREEN-REFACTOR:
**RED Phase:**
- [ ] Created pressure scenarios (3+ combined pressures)
- [ ] Ran scenarios WITHOUT skill (baseline)
- [ ] Documented agent failures and rationalizations verbatim
**GREEN Phase:**
- [ ] Wrote skill addressing specific baseline failures
- [ ] Ran scenarios WITH skill
- [ ] Agent now complies
**REFACTOR Phase:**
- [ ] Identified NEW rationalizations from testing
- [ ] Added explicit counters for each loophole
- [ ] Updated rationalization table
- [ ] Updated red flags list
- [ ] Updated description with violation symptoms
- [ ] Re-tested - agent still complies
- [ ] Meta-tested to verify clarity
- [ ] Agent follows rule under maximum pressure
## Common Mistakes (Same as TDD)
**❌ Writing skill before testing (skipping RED)**
Reveals what YOU think needs preventing, not what ACTUALLY needs preventing.
✅ Fix: Always run baseline scenarios first.
**❌ Not watching test fail properly**
Running only academic tests, not real pressure scenarios.
✅ Fix: Use pressure scenarios that make agent WANT to violate.
**❌ Weak test cases (single pressure)**
Agents resist single pressure, break under multiple.
✅ Fix: Combine 3+ pressures (time + sunk cost + exhaustion).
**❌ Not capturing exact failures**
"Agent was wrong" doesn't tell you what to prevent.
✅ Fix: Document exact rationalizations verbatim.
**❌ Vague fixes (adding generic counters)**
"Don't cheat" doesn't work. "Don't keep as reference" does.
✅ Fix: Add explicit negations for each specific rationalization.
**❌ Stopping after first pass**
Tests pass once ≠ bulletproof.
✅ Fix: Continue REFACTOR cycle until no new rationalizations.
## Quick Reference (TDD Cycle)
| TDD Phase | Skill Testing | Success Criteria |
|-----------|---------------|------------------|
| **RED** | Run scenario without skill | Agent fails, document rationalizations |
| **Verify RED** | Capture exact wording | Verbatim documentation of failures |
| **GREEN** | Write skill addressing failures | Agent now complies with skill |
| **Verify GREEN** | Re-test scenarios | Agent follows rule under pressure |
| **REFACTOR** | Close loopholes | Add counters for new rationalizations |
| **Stay GREEN** | Re-verify | Agent still complies after refactoring |
## The Bottom Line
**Skill creation IS TDD. Same principles, same cycle, same benefits.**
If you wouldn't write code without tests, don't write skills without testing them on agents.
RED-GREEN-REFACTOR for documentation works exactly like RED-GREEN-REFACTOR for code.
## Real-World Impact
From applying TDD to TDD skill itself (2025-10-03):
- 6 RED-GREEN-REFACTOR iterations to bulletproof
- Baseline testing revealed 10+ unique rationalizations
- Each REFACTOR closed specific loopholes
- Final VERIFY GREEN: 100% compliance under maximum pressure
- Same process works for any discipline-enforcing skill
+152
View File
@@ -0,0 +1,152 @@
---
name: /opsx-apply
id: opsx-apply
category: Workflow
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
+157
View File
@@ -0,0 +1,157 @@
---
name: /opsx-archive
id: opsx-archive
category: Workflow
description: Archive a completed change in the experimental workflow
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
+173
View File
@@ -0,0 +1,173 @@
---
name: /opsx-explore
id: opsx-explore
category: Workflow
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+106
View File
@@ -0,0 +1,106 @@
---
name: /opsx-propose
id: opsx-propose
category: Workflow
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
+3
View File
@@ -0,0 +1,3 @@
{
"mcpServers": {}
}
@@ -0,0 +1,9 @@
---
description: shanxia2.0 工程与 OpenSpec 规则入口
alwaysApply: true
---
修改和评审前读取 `AGENTS.md`、`docs/development/engineering-rules.md` 与目标应用 AGENTS.md。
子数据写入或流程配置必须完整读取 `docs/development/child-data-save-rules.md`。
OpenSpec 按 `openspec/config.yaml` 与工程规则的生命周期要求执行;对照 Requirement / Scenario,不擅自将历史 changes 视为已归档。
当前代码边界与旧生态 spec 的冲突在工程规则中明确,禁止使用旧“CRM 仅在外部”的描述阻止维护现有模块。
+9
View File
@@ -0,0 +1,9 @@
---
description: web-admin 列表与 CRUD 弹窗规则入口
globs: web-admin/**/*.vue,web-admin/**/*.scss
alwaysApply: false
---
修改列表或弹窗前读取 `web-admin/AGENTS.md`、`docs/web-admin-ui-spec-fresh-mint.md` 和 `docs/web-admin-ui-pattern-index.md`。
标题竖条、全局表单栅格、弹窗正文滚动、表格与工具栏、按钮图标等约束统一由 Web AGENTS 维护。
涉及保存、复制或子数据移除时必须完整读取 `docs/development/child-data-save-rules.md`;同样适用于 `web-admin/src/views/m/` 移动 H5。
@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
+288
View File
@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
▼
┌───────────┐
│ Session │
└─────┬─────┘
│
▼
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+110
View File
@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
+7
View File
@@ -0,0 +1,7 @@
# shanxia2.0 Cursor 规则入口
修改代码前必须读取 `AGENTS.md` 与 `docs/development/engineering-rules.md`,再读取目标应用的 `backend/AGENTS.md`、`web-admin/AGENTS.md` 或 `miniprogram/AGENTS.md`。
保存、导入、复制、子数据移除、流程配置还必须完整读取 `docs/development/child-data-save-rules.md`。
UI 权威保持 `docs/web-admin-ui-spec-fresh-mint.md`、`docs/miniprogram-ui-spec-sanqiang.md`;Web 页面选型见 `docs/web-admin-ui-pattern-index.md`。
OpenSpec 遵循 `openspec/config.yaml`;旧生态规范的历史边界冲突以工程规则说明为准,不将未验收变更自动归档。
本文件只提供入口,业务、UI、编码与验证约束统一维护在上述文件。
+114
View File
@@ -0,0 +1,114 @@
# macOS
.DS_Store
.AppleDouble
.LSOverride
._*
# Windows
Thumbs.db
ehthumbs.db
Desktop.ini
# Linux
*~
# 编辑器 / IDE
.history/
.idea/
*.iml
*.swp
*.swo
*~
.project
.classpath
.settings/
# VS Code / Cursor(保留团队共享配置时可按需取消注释)
# .vscode/*
# !.vscode/extensions.json
# !.vscode/settings.json
# 依赖与构建产物
node_modules/
dist/
build/
out/
target/
*.egg-info/
.eggs/
__pycache__/
*.py[cod]
*$py.class
.Python
*.class
*.jar
*.war
*.ear
# 环境与密钥
.env
.env.*
!.env.example
backend/.ocr-venv/
*.pem
*.key
*.p12
secrets/
生产机器账号密码
生产环境部署/生产环境数据库备份的shell脚本/backup.conf
# 日志与临时文件
*.log
logs/
tmp/
temp/
*.tmp
*.bak
*.cache
# 测试与覆盖率
coverage/
.nyc_output/
htmlcov/
.pytest_cache/
.tox/
.coverage
*.lcov
# 数据库与本地数据
*.sqlite
*.sqlite3
*.db
# 上传与导出(业务附件、导出文件等本地目录)
uploads/
exports/
# uni-app 编译产物
miniprogram/unpackage/
.superpowers/
.worktrees/
# 本地依赖缓存与 Python 环境(保留在本机,不纳入版本管理)
.pnpm-store/
venv/
venv.bak.*/
.venv/
# 已停用的知识图谱生成物
graphify-out/
# Agent 会话与浏览器运行证据;团队规则和技能仍保留
.playwright-mcp/
.omo/run-continuation/
.sisyphus/run-continuation/
# 本地运行状态和凭据
*.pid
dump.rdb
api_key
# 本机业务资料、数据库快照与凭据(资料保留,不随代码提交)
/local-data/
# 旧导入默认路径的本地兼容链接
/加油汇总表(202609161514)
+149
View File
@@ -0,0 +1,149 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx-apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx-continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx-archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
+154
View File
@@ -0,0 +1,154 @@
---
description: Archive a completed change in the experimental workflow
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx-archive` (e.g., `/opsx-archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
+170
View File
@@ -0,0 +1,170 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx-explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+103
View File
@@ -0,0 +1,103 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx-apply
---
**Input**: The argument after `/opsx-propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx-apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
+6
View File
@@ -0,0 +1,6 @@
# 山峡工程规则入口
先读 `AGENTS.md` 与 `docs/development/engineering-rules.md`,再按目标应用读取子目录 AGENTS.md。
当前仓库包含 backend、web-admin、miniprogram,Web 中还包含移动 H5;CRM / db / bx / pl 和工作流已有实现。
旧生态 spec 的外部系统位置是历史参考,当前事实、SQL 来源边界和规范冲突处理见工程规则;不得仅凭旧描述排除当前业务模块。
子数据保存必须完整遵守 `docs/development/child-data-save-rules.md`;本文只索引,不复制规范。
+5
View File
@@ -0,0 +1,5 @@
# 交互规范
- 所有回复和思考必须使用中文
- 每次回复开头称呼用户为"龙舞"
- 视觉读取(图片分析、截图识别等)优先使用自身能力
+4
View File
@@ -0,0 +1,4 @@
{
"$schema": "https://opencode.ai/config.json",
"plugin": []
}
@@ -0,0 +1,156 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx-apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
@@ -0,0 +1,114 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
+288
View File
@@ -0,0 +1,288 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
▼
┌───────────┐
│ Session │
└─────┬─────┘
│
▼
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx-explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+110
View File
@@ -0,0 +1,110 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.3.1"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx-apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx-apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
+94
View File
@@ -0,0 +1,94 @@
# AGENTS.md — shanxia2.0(山峡化工)
本仓库是三个应用共享后端与租户模型的单仓库,内部也使用 sanqiang 名称。
与用户交流时,用户使用简体中文则回复简体中文;业务文案与注释遵循现有语言习惯。
## 修改前必读
- 通用约束:[工程规则](docs/development/engineering-rules.md)。修改或评审代码前必须阅读。
- 后端:[backend/AGENTS.md](backend/AGENTS.md)。
- Web 管理端与移动 H5:[web-admin/AGENTS.md](web-admin/AGENTS.md)。
- 小程序:[miniprogram/AGENTS.md](miniprogram/AGENTS.md)。
- 保存、导入、复制、子数据移除、流程配置:[子数据保存规则](docs/development/child-data-save-rules.md),必须完整阅读。
- UI 变更先查对应视觉规范,再选择参考页面;工具适配文件只提供入口。
## 工程结构与当前边界
| 路径 | 职责 |
| --- | --- |
| `backend/` | Python 3.9 / FastAPI / SQLAlchemy / Pydantic v2 后端 |
| `web-admin/` | Vue 3 / Vite / Element Plus / Tailwind CSS 管理端 |
| `web-admin/src/views/m/` | 同一 Web 应用内的移动 H5 页面 |
| `miniprogram/` | uni-app 微信小程序 |
| `docs/` | UI 规范、SQL、业务资料、开发文档与计划 |
| `openspec/` | 变更配置、需求与设计规范 |
CRM、地磅(db)、报销(bx)、运输(pl)已有本仓库实现,维护时追踪本地调用链。
工作流已有后端引擎和设计器、待办、已办页面;不能据此假定全部目标能力已实现。
旧生态规范的外部 CRM / 独立地磅边界已不适合限制当前代码维护,见工程规则中的冲突说明。
外部系统仍须按实际接口与表归属确认集成范围,不能仅凭名称决定修改位置。
## 业务数据红线
- 所有业务查询按当前用户 `tenant_no` 隔离,写入使用当前租户,不信任客户端覆盖。
- 数据权限与菜单权限均取当前用户全部角色的并集,业务查询必须执行数据范围过滤。
- 业务数据软删除:`del_flag=1`;默认查询排除删除记录,禁止物理删除。
- 无自定义排序时列表使用 `create_time DESC`。
- 子数据保存必须差量更新,保留已有有效明细 ID、创建信息和未提交业务字段。
- 遗漏集合保持不变,显式空集合才申请清空;校验与引用保护先于写入。
- 主单、子单和关系在同一事务内;严禁全删全增或通过客户端分步调用绕过。
- 编辑/复制 ID 往返、引用保护与例外范围以子数据专题文档为准,适用于所有客户端。
- 文件附件使用 MinIO,同字段多个附件使用逗号分隔 URL。
- 细胞存储样本关联规则仍适用于已有相关代码,详见后端规则,不推广到其他领域。
## 数据库、权限与 API
- MySQL 5.7 / utf8mb4;UUID 主键 `id VARCHAR(64) NOT NULL`。
- 字段顺序:id → 业务字段 → tenant_no、order_num、remark、create_by、create_dept_id、create_time、update_by、update_time、del_flag(默认 0)。
- 数据库变更同步维护 `docs/sql/`,同时评估 API、Pydantic、TypeScript 字段影响。
- 本库快照 `docs/sql/shanxia2.0.sql`;`sx.sql` / `dibang.sql` 是来源系统参考,不替代当前 schema 与迁移。
- 新路由同时注册 `backend/app/api/__init__.py` 和 `backend/app/main.py`;不得绕过认证、加密、审计。
- 角色选择子菜单自动包含祖先;Web / 小程序分别挂在各自 `parent_id=0` 虚拟根下。
- 租户管理仅 `super_admin` 可用;其他系统管理在租户上下文内执行。
- 自定义数据范围、工作流版本和审批策略等完整约束见工程规则。
## UI 权威与共通要求
- Web:[Fresh Mint 规范](docs/web-admin-ui-spec-fresh-mint.md),主色 `#10b981`。
- 小程序:[三墙规范](docs/miniprogram-ui-spec-sanqiang.md),主色 `#0a9f6d`;跨端不得混用主色。
- Web 新页面按 [界面模式索引](docs/web-admin-ui-pattern-index.md) 选 P01–P27;PR 写明模式编号和参考页路径。
- 树节点显示本级名称;输入框、表格、导出、查看态显示完整路径,分隔符 ` / `。
- Web 弹窗顶部标签、无背景模糊;布局、按钮、表格、状态 Tag 和附件规则见 Web AGENTS。
- 小程序媒体比例、触达尺寸、拍照凭证上传规则见小程序 AGENTS。
- 不另造布局与色值;按已指定模板页和全局样式实现,保留各端约束。
## 常用开发入口
- 后端:在 `backend/` 使用 `./start.sh --reload`;参数先看 `./start.sh --help`。
- 后端测试:启用项目虚拟环境后执行对应 `pytest` 测试;具体步骤见后端 AGENTS。
- 生产脚本是 `backend/start-prod.sh`;生产动作不属于默认本地检查。
- Web:在 `web-admin/` 使用 `pnpm dev`、`pnpm build`、`pnpm build:typecheck`、`pnpm lint`。
- 小程序:遵循已有 HBuilderX / uni-app 流程和子目录 README;不要把占位 test 当成有效测试。
- 依赖、脚本与环境变量以当前文件为准;不要凭过时文档发明不存在的命令。
## 改动与验证
- 只做最小必要改动,不重构或格式化无关文件,不移动真实业务代码来整理工程。
- 路由保持薄层,业务放 services / crud;前端遵循周边命名、类型和导入风格。
- Web 使用 pnpm;Vue 和 Element Plus 自动导入规则见子目录,不重复手工导入。
- CRUD 可读字段以 `_row_to_dict` 为准;schema 与前端覆盖全部可写字段,排除计算和只读字段。
- 逐项核对字段并执行相关回归;不要调用或声称通过不存在的通用一致性脚本。
- 实际执行与变更风险匹配的验证,记录结果;未运行项明确说明,不能声称已通过。
- 提交遵循 Conventional Commits,以完整句子说明改了什么、为何;提交范围保持最小。
## 规范与文档维护
- [工程规则](docs/development/engineering-rules.md) 汇总 API、数据库、权限、工作流及历史规范冲突的处理方式。
- OpenSpec 入口是 [openspec/config.yaml](openspec/config.yaml),保留现有 changes 结构与能力命名约定。
- 实现和评审对照 Requirement / Scenario,并交叉核对 UI 权威文档。
- 历史规范未被本次目录清理改写或归档;未冲突的 SHALL 继续遵守。
- 验收与归档是独立动作,不能按文档日期、文件位置或清理需求自动判断已完成。
- 新设计与计划遵循所用技能指定路径,例如 `docs/superpowers/specs/` 与 `docs/superpowers/plans/`。
- 文档索引记录原位置与状态,不为分类擅自移动历史资料或业务源码。
- `.cursorrules`、Cursor mdc、OpenCode 入口引用上述共同规则,避免维护重复规范。
- graphify 已停用;旧计划中的图谱生成与更新步骤不再执行。
+55
View File
@@ -0,0 +1,55 @@
# 山峡化工一体化门户
本工程由 FastAPI 共享后端、Vue 3 管理端(含移动 H5)和 uni-app 小程序组成。当前仓库已包含 CRM、地磅、运输、报销、工作流、文档库等业务;旧 CRM 与地磅系统的资料用于迁移和对照,不能据旧说明判断本仓库代码应被移除。
## 目录与入口
| 路径 | 职责 | 开发约束 |
| --- | --- | --- |
| `backend/` | 共享 API、业务服务、定时任务、测试 | [后端规则](backend/AGENTS.md) |
| `web-admin/` | 管理后台和移动 H5 | [Web 规则](web-admin/AGENTS.md) |
| `miniprogram/` | 微信小程序、业务分包、WebView | [小程序规则](miniprogram/AGENTS.md) |
| `docs/` | 规范、业务资料、迁移和验收记录 | [文档索引](docs/README.md) |
| `openspec/` | 工程规范与变更材料 | [配置](openspec/config.yaml) |
| `生产环境部署/` | 发布、代理与备份脚本和说明 | [部署说明](生产环境部署/README.md) |
| `resources/` | 保留的证件参考图片 | [资料索引](resources/README.md) |
| `local-data/` | 本机原始业务资料、快照和凭据(Git 忽略) | [路径映射](docs/development/repository-cleanup.md) |
| `doclib/` | 文档库当前说明和保留的旧集成 | [文档库说明](doclib/需求说明.md) |
实际代码保持现有目录和路径。不要将目录整理与业务重构合并执行。
## 本地开发
后端首次使用时,在 `backend/` 创建本机虚拟环境并安装 `requirements.txt`,按 `.env.example` 配置本地依赖。已有环境无需重建。项目历史规范要求兼容 Python 3.9;启动脚本的版本提示存在差异,选择运行版本时需核对依赖和实际部署环境,不据提示自动升级。
```bash
cd backend
source venv/bin/activate
./start.sh --host 127.0.0.1 --port 8000 --reload
```
后端命令说明:`./start.sh --help`。生产启动使用 `./start-prod.sh`,具体流程见部署说明;本地开发不执行生产迁移和发布脚本。
Web 使用 `web-admin/package.json` 中的 Node/pnpm 版本要求:
```bash
cd web-admin
pnpm install
pnpm dev
```
构建使用 `pnpm build`;类型检查及构建使用 `pnpm build:typecheck`。
小程序使用 HBuilderX 打开 `miniprogram/` 并运行至微信开发者工具。环境和发布步骤见 [小程序 README](miniprogram/README.md);视觉要求以 [小程序 UI 规范](docs/miniprogram-ui-spec-sanqiang.md) 为准,旧 README 中的局部迁移配色说明不替代统一规范。发布前执行已有 `npm run release:check-api` 检查。
## 测试与资料维护
- 后端测试位于 `backend/tests/`;按改动范围执行 `venv/bin/python -m pytest tests/<目标文件>`。涉及外部服务的测试先确认测试环境。
- Web 和小程序的 `scripts/` 中包含真实测试、检查器与构建工具,不能整目录归档。按具体脚本及文档选择命令;小程序 `npm test` 当前仍是占位命令。
- 工程规则入口为 [AGENTS.md](AGENTS.md),子数据保存要求见 [差量更新规则](docs/development/child-data-save-rules.md)。
- 规范、历史计划和验收证据的分类见 [文档索引](docs/README.md)。
- 本地依赖、缓存、PID 和凭据不纳入版本管理。它们退出跟踪不代表本机文件已删除,也不代表 Git 历史已清除。
本次治理范围及验证记录见 [工程清理记录](docs/development/repository-cleanup.md)。
资料保留与删除范围见 [清理记录](docs/development/repository-cleanup.md);部署工具目录分类见 [部署目录说明](生产环境部署/目录说明.md)。
+107
View File
@@ -0,0 +1,107 @@
# 数据库连接配置示例(库名/表结构以 docs/sql/zkxw.sql 全量导出为准)
# DATABASE_URL 格式:mysql+pymysql://user:password@host:port/dbname
#DATABASE_URL=mysql+pymysql://root:password@localhost:3306/zkxw
# 数据库连接池 / 空闲重连(远程 MySQL 或休眠唤醒后避免接口长时间卡住)
#DB_CONNECT_TIMEOUT_SEC=10
#DB_READ_TIMEOUT_SEC=10
#DB_WRITE_TIMEOUT_SEC=10
#DB_POOL_RECYCLE_SEC=600
#DB_POOL_SIZE=5
#DB_MAX_OVERFLOW=10
#DB_KEEPALIVE_INTERVAL_SEC=240
# 与 sys_user.tenant_no 一致;登录按 (tenant_no, user_no) 查用户
DEFAULT_TENANT_NO=shanxia2.0
# 用户无 sys_user_role 记录时,Web 管理端 JWT 使用的默认角色(super_admin 可全量菜单)
# WEB_AUTH_DEFAULT_ROLE=admin
# JWT配置示例
# SECRET_KEY=your-secret-key-change-in-production
# ALGORITHM=HS256
# ACCESS_TOKEN_EXPIRE_MINUTES=30
# 应用配置示例
# APP_NAME=陇耘鲜达
# DEBUG=true
# 浏览器跨域:若设置 BACKEND_CORS_ORIGINS,须为 JSON 数组,会整体覆盖代码默认值,例如:
# BACKEND_CORS_ORIGINS=["http://localhost:5173","http://localhost:3006","http://127.0.0.1:3006"]
# DEBUG=true 时后端还会允许任意本机端口的 Origin(localhost / 127.0.0.1),便于本地换端口开发。
# 登录 RSA(Web/小程序加密登录;多实例须配置同一私钥 PEM)
# LOGIN_RSA_PRIVATE_KEY_PEM="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
# 仅本地用 Swagger/Apifox 明文测登录时可临时打开(生产务必 false)
# LOGIN_ALLOW_PLAINTEXT_LOGIN=false
# LOGIN_ENCRYPT_TS_SKEW_SEC=300
# Redis 配置(用于会话/Token 吊销;需在后端运行时配置)
# 启用后:已登录用户每次 API 校验通过会滑动续期会话(7 天无操作则会话失效);未配置则仅校验 JWT。
# REDIS_HOST=127.0.0.1
# REDIS_PORT=6379
# REDIS_DB=0
# REDIS_PASSWORD=
# REDIS_TIMEOUT_SEC=5
# REDIS_CONNECT_TIMEOUT_SEC=5
# REDIS_HEALTH_CHECK_INTERVAL_SEC=30
# REDIS_OP_TIMEOUT_SEC=3
# REDIS_SSL_ENABLED=false
# MinIO 配置示例
# STORAGE_TYPE=minio
# MINIO_ENDPOINT=127.0.0.1:9000
# MINIO_ACCESS_KEY=CHANGEME
# MINIO_SECRET_KEY=CHANGEME
# MINIO_BUCKET=sanqiang
# MINIO_SECURE=false
# 浏览器公开前缀(建议 HTTPS 同域反代);配置后预签名按该主机签发
# MINIO_BASE_URL=https://res.shanxiachem.com/ruoyi
# 阿里云 OCR(身份证 / 驾驶证识别;本地填真实 Key,勿提交 git)
# ALIYUN_OCR_ACCESS_KEY_ID=CHANGEME
# ALIYUN_OCR_ACCESS_KEY_SECRET=CHANGEME
# ALIYUN_OCR_ENDPOINT=ocr-api.cn-hangzhou.aliyuncs.com
# ALIYUN_OCR_MONTHLY_LIMIT=170
# 全量 API 请求日志(写入 sys_api_request_log;无表时会 warning「api_request_log persist failed」)
# 解决二选一:① 在库中执行 docs/sql/optional-sys-api-request-log.sql 建表 ② 关闭写入:
# API_REQUEST_LOG_ENABLED=false
# 微信支付配置示例
# 小程序支付使用 JSAPI(trade_type=JSAPI)
# WXPAY_MCHID=1900000109
# WXPAY_MINI_APPID=wx1234567890abcdef
# WXPAY_SECRET=your-miniapp-secret
# WXPAY_API_KEY=your-v2-api-key
# WXPAY_NOTIFY_URL=https://www.chengyantek.cn/api/payment/notify
# WXPAY_REFUND_NOTIFY_URL=https://www.chengyantek.cn/api/payment/refund-notify
# WXPAY_SANDBOX=false
# 门户小程序登录(AppID 与 miniprogram/manifest.json mp-weixin.appid 一致)
# WECHAT_MP_APPID=wx7db1ddb2a90c9425
# WECHAT_MP_SECRET=
# web-admin 扫码登录(小程序码 page 须已发布到对应 env_version)
# WX_QR_SESSION_TTL_SEC=180
# WX_QR_ENV_VERSION=release
# WX_QR_PAGE=pages/login/web-qr/index
# 门户文档库:复用 MINIO_ENDPOINT/ACCESS_KEY/SECRET_KEY/SECURE,专用桶禁止公开策略。
DOCLIB_MINIO_BUCKET=shanxia-doclib-private
DOCLIB_MAX_UPLOAD_BYTES=104857600
# 服务号审批通知(迁移建表、配置微信后台并完成用户绑定后启用)
WECHAT_OA_ENABLED=false
WECHAT_OA_APPID=wxf63dfb83af901d43
WECHAT_OA_SECRET=
WECHAT_OA_PUBLIC_BASE_URL=
WECHAT_OA_MINI_APPID=
WECHAT_OA_TEMPLATE_PENDING=ukQRYoczEXH1fZe9TdL8uX6LmuJJTlPidboxqtq_7N0
WECHAT_OA_TEMPLATE_RESULT=vA_z15BdP-8LltRmS__1MmUcNKQBy6b6rvAXKEYzoLY
WECHAT_OA_TEMPLATE_COMPLETION=rnPOIVknPqfgwVzKbchj6pCMCWpoDe3h3dkrFbUEsD4
WECHAT_OA_TEMPLATE_CERT_REMINDER=aYzLZ_EqI8hq7RXrlf73BTAfNvzgJHeg_xWKar01Md0
# 每日扫描证件,仅周一、周三、周五扫描后发送微信汇总;Asia/Shanghai,同时受总开关控制。
WECHAT_OA_CERT_REMINDER_ENABLED=true
WECHAT_OA_CERT_NOTICE_ROLE_NAME=证件到期通知接收人
WECHAT_OA_CERT_REMINDER_HOUR=10
WECHAT_OA_CERT_REMINDER_MINUTE=0
+39
View File
@@ -0,0 +1,39 @@
# 后端规则
修改前先读 [根规则](../AGENTS.md) 和 [工程规则](../docs/development/engineering-rules.md)。保存、批量更新、导入、复制、子数据移除与流程配置必须完整阅读 [子数据保存规则](../docs/development/child-data-save-rules.md)。
## 技术栈与分层
Python 3.9、FastAPI、SQLAlchemy、Pydantic v2、MySQL / pymysql、Redis、MinIO、JWT。依赖中包含 Alembic,但当前仓库未配置应用级 Alembic 迁移目录,不能将其视为现行迁移流程。入口 `app/main.py` → `app.main:app`。历史工程约定为 Python 3.9,`start.sh` 的缺失解释器提示写作 3.10+,存在文档与脚本提示不一致;本次整理不升级运行环境,执行前确认本地解释器与依赖兼容。
- `app/api/` 保持薄路由;业务逻辑放 `app/services/`、数据库访问放 `app/crud/`。
- 模型 `app/models/`,输入输出 `app/schemas/`,定时任务 `app/tasks/`;配置由 `app/core/config.py` 的 pydantic-settings 读取环境文件。
- CRM、db、bx、pl 与工作流都是当前仓库已有模块,维护前从实际路由追踪到服务、CRUD 和客户端。
- 新路由必须同时注册在 `app/api/__init__.py` 与 `app/main.py`,不能绕过认证、加密、审计。
- 业务查询和写入强制租户隔离、数据范围多角色并集;禁止客户端覆盖 tenant_no。详见工程规则中的 API、数据库和权限章节。
- 列表默认 `create_time DESC`;业务数据软删除;数据库变更同步 `../docs/sql/`。
- `_row_to_dict`、CreateBody/UpdateBody 和前端 formData 的可写字段逐项对齐,计算字段排除。通过相关回归验证,不调用仓库中不存在的通用字段检查脚本。
- 现有细胞存储样本业务仍遵守 `tenant_no + sample_code` 跨表关联,不能使用可变化的协议 ID;该规则仅适用于相关样本功能。
## 本地命令
在 backend 目录执行:
```bash
source venv/bin/activate
pip install -r requirements.txt
./start.sh --reload
pytest
```
`./start.sh --help` 查看本地选项,默认监听 `0.0.0.0:8000`;按需求明确 host / port。生产脚本 `./start-prod.sh` 支持 `install|start|stop|restart|status|logs`,读取生产环境;不能把生产操作当成本地验证。
`tests/` 已有多个业务回归测试模块。先执行受影响测试,再按风险补充验证;记录实际命令和结果,不把未执行的测试写成通过。
## 配置与接口
- API 前缀受 `API_V1_PREFIX` 控制,通常 `/api`;以已注册路由为准。
- JWT + RSA 登录;RSA 私钥通过既有生成或 `LOGIN_RSA_PRIVATE_KEY_PEM` 配置机制提供。
- API 加密由 `API_ENCRYPT_*` 配置控制,排除接口在 `API_ENCRYPT_EXCLUDE_PATHS`,不得通过新路由绕过中间件。
- 配置读取 `.env` / `.env.local` / `.env.production`;不在文档传播真实凭据,不依赖历史默认管理员密码。
- 数据库快照使用 `../docs/sql/shanxia2.0.sql` 并结合迁移确认当前结构;Swagger `/docs`、ReDoc `/redoc`。
+101
View File
@@ -0,0 +1,101 @@
# shanxia2.0 Backend 生产部署说明
## 1. 上传到服务器
将 `backend/` 目录上传到:
```
/iflytek/shanxia2.0/backend
```
**必须排除**(否则 Linux 上会报 `bad interpreter: No such file or directory`):
- `venv/`(**禁止上传本机 venv**,必须在服务器上用 `./start-prod.sh install` 重建)
- `logs/`、`__pycache__/`、`*.pyc`
- `graphify-out/`
- `uploads/`(若生产已有附件数据则保留服务器端目录)
- `.env`(开发配置,生产用 `.env.production`)
本地打包示例:
```bash
cd /path/to/shanxia2.0
tar czf shanxia2.0-backend.tar.gz \
--exclude='backend/venv' \
--exclude='backend/logs' \
--exclude='backend/__pycache__' \
--exclude='backend/graphify-out' \
--exclude='backend/.env' \
backend/
```
## 2. 服务器首次启动
```bash
cd /iflytek/shanxia2.0/backend
chmod +x start-prod.sh
# 首次:安装 Python 依赖(自动创建 venv)
./start-prod.sh install
# 启动(默认 127.0.0.1:9111,读取 .env.production)
./start-prod.sh start
```
## 3. 日常运维
```bash
./start-prod.sh status # 查看状态
./start-prod.sh logs # 最近日志
./start-prod.sh restart # 发版后重启
./start-prod.sh stop # 停止
```
健康检查:
```bash
curl -s http://127.0.0.1:9111/health
# {"status":"healthy"}
```
## 4. 配置文件
| 文件 | 用途 |
|---|---|
| `.env.production` | 生产环境变量(DB/Redis/MinIO/JWT/RSA 等) |
| `start-prod.sh` | 启动脚本(默认端口 **9111**) |
默认监听 `127.0.0.1:9111`,由 Nginx `:9911` 反代 `/api/*`,无需对公网开放 9111。
## 5. 与 Nginx 配合
Nginx 配置见仓库 `生产环境部署/nginx-shanxia2.0.conf`:
- 前端:`http://121.43.228.102:9911`
- API:`/api/` → `http://127.0.0.1:9111`
## 6. 常见问题
**Q: `bad interpreter: .../Users/.../venv/bin/python3: No such file or directory`**
A: 误把本机 Mac 的 `venv/` 上传到了 Linux。在服务器执行:
```bash
cd /iflytek/shanxia2.0/backend
rm -rf venv
./start-prod.sh install
./start-prod.sh start
```
新版 `start-prod.sh` 也会自动检测并重建无效 venv。
**Q: 启动失败,日志报 ModuleNotFoundError**
A: 执行 `./start-prod.sh install` 重新安装依赖。
**Q: 登录失败 / 公钥变化**
A: 确认 `.env.production` 中 `LOGIN_RSA_PRIVATE_KEY_PEM` 已配置且未被修改。
**Q: 数据库连接失败**
A: 检查服务器到 `47.99.164.66:3306` 网络与白名单。
**Q: 需要改端口**
A: `PORT=9111 ./start-prod.sh restart` 或修改脚本默认值。
+99
View File
@@ -0,0 +1,99 @@
# shanxia2.0 后端骨架(FastAPI)
基于 FastAPI 的精简后端:**Web 鉴权**(登录 RSA、登录、刷新 Token、登出、当前用户、菜单 code)、**静态运营菜单树**、**运营端路由占位**。原山峡化工业务 API 已移除,可按模块在 `app/api/admin.py` 等位置扩展。
数据库结构与种子数据基线见:`docs/sql/zkxw.sql`(全库导出;默认账号 `admin` / `111111`,角色 `super_admin`)。
## 技术栈
- FastAPI - 现代高性能异步 Web 框架
- SQLAlchemy - ORM 数据库映射
- Pydantic - 数据验证
- JWT - 用户认证
- MySQL/PostgreSQL - 数据库
## 项目结构
```
backend/
├── app/
│ ├── api/ # API 路由
│ │ ├── admin/ # 运营端接口
│ │ ├── supplier/ # 供应商端接口
│ │ ├── client/ # 客户端接口
│ │ └── deliver/ # 配送员端接口
│ ├── core/ # 核心配置
│ │ ├── config.py # 应用配置
│ │ ├── security.py # 安全认证
│ │ └── database.py # 数据库连接
│ ├── models/ # 数据库模型
│ ├── schemas/ # Pydantic schemas
│ ├── services/ # 业务逻辑
│ └── main.py # 应用入口
├── requirements.txt
└── README.md
```
## 快速开始
### 1. 创建虚拟环境
```bash
python -m venv venv
venv\Scripts\activate # Windows
# source venv/bin/activate # Linux/Mac
```
### 2. 安装依赖
```bash
pip install -r requirements.txt
```
### 3. 配置环境变量
复制 `.env.example` 为 `.env` 并修改配置:
```env
# 数据库配置
DATABASE_URL=mysql+pymysql://root:password@localhost:3306/sanqiang
# JWT配置
SECRET_KEY=your-secret-key-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# 应用配置
APP_NAME=山峡化工
DEBUG=true
```
### 4. 启动服务
```bash
uvicorn app.main:app --reload --port 8000
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```
服务启动后,访问:
- API 文档:http://127.0.0.1:8000/docs
- ReDoc 文档:http://127.0.0.1:8000/redoc
## API 路由分组
| 前缀 | 说明 | 认证方式 |
|------|------|----------|
| `/api/admin` | 运营端接口 | JWT Token |
| `/api/supplier` | 供应商端接口 | JWT Token |
| `/api/client` | 客户端接口 | JWT Token |
| `/api/deliver` | 配送员端接口 | JWT Token |
| `/api/public` | 公共接口(登录等) | 无需认证 |
## 开发规范
- 使用 Pydantic 进行数据验证
- 使用 SQLAlchemy ORM 进行数据库操作
- 所有接口遵循 RESTful 规范
- 密码使用 bcrypt 加密存储
- 使用 JWT Token 进行用户认证
+1
View File
@@ -0,0 +1 @@
# 山峡化工后端
+32
View File
@@ -0,0 +1,32 @@
"""API 路由包 — 山峡化工生产一体化门户"""
from app.api.public import router as public_router
from app.api.menu import router as menu_router
from app.api.admin import router as admin_router
from app.api.workflow import router as workflow_router
from app.api.leave import router as leave_router
from app.api.crm import router as crm_router
from app.api.monitor import router as monitor_router
from app.api.bx import bx_router
from app.api.db import db_router
from app.api.mini_auth import router as mini_auth_router
from app.api.doclib import router as doclib_router
from app.api.pl.vehicle_fuel_card import router as vehicle_fuel_card_router
from app.api.pl.dispatch_calendar import router as dispatch_calendar_router
from app.api.wechat_notices import router as wechat_notices_router
__all__ = [
"wechat_notices_router",
"public_router",
"menu_router",
"admin_router",
"workflow_router",
"leave_router",
"crm_router",
"monitor_router",
"bx_router",
"db_router",
"mini_auth_router",
"doclib_router",
"vehicle_fuel_card_router",
"dispatch_calendar_router",
]
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
"""报销(bx)API 路由聚合 — REST 风格,协议对齐 bx 原系统。"""
from fastapi import APIRouter
from app.api.bx import advance, attachment, expense_item, invoice, payment, reimburse, workflow
from app.schemas.bx.common import ApiResponse
bx_router = APIRouter(tags=["报销管理"])
bx_router.include_router(expense_item.router)
bx_router.include_router(workflow.router)
bx_router.include_router(advance.router)
bx_router.include_router(attachment.router)
bx_router.include_router(reimburse.router)
bx_router.include_router(payment.router)
bx_router.include_router(invoice.router)
@bx_router.get("/bx/health", response_model=ApiResponse[dict])
def bx_health():
"""P0 健康检查:验证 bx 路由已挂载且响应协议为 code=0。"""
return ApiResponse(data={"status": "ok", "module": "bx"})
+732
View File
@@ -0,0 +1,732 @@
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, status, Query
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.api.bx.export_common import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
BxApplyListExportBody,
dump_export_row,
respond_xlsx,
)
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.database import get_db
from app.core.tenant_context import get_tenant_no
from app.models.bx_models import BxAdvanceApply, BxWorkflowDef
from app.schemas.bx.advance import (
AdvanceApplyCreate,
AdvanceApplyOut,
AdvanceApplyUpdate,
AdvanceApprovalCreate,
AdvanceApprovalOut,
AdvanceApproverPendingStatsOut,
AdvanceMyStatsOut,
)
from app.schemas.bx.common import ApiResponse, PagedData
from app.services.bx.advance import AdvanceService
from app.services.bx.advance_list_filters import build_advance_column_filters
from app.services.bx.expense_item import ExpenseItemService
from app.services.bx.list_sort import order_advance, parse_sort_params
from app.services.bx_data_scope import apply_bx_scope
router = APIRouter(prefix="/advances", tags=["备用金管理"])
def _tenant(db: Session, user: BxUserContext) -> str:
return get_tenant_no(db, user.to_tenant_user_dict())
def _advance_order(params: dict):
sf, so = parse_sort_params(params)
return order_advance(sf, so)
def _fill_offset_amounts(db: Session, tenant_no: str, rows, out_rows: List[AdvanceApplyOut]) -> None:
if not out_rows:
return
offset_map = AdvanceService.offset_amount_map(db, tenant_no, [r.id for r in rows])
for out_row in out_rows:
out_row.offset_amount = offset_map.get(out_row.id, 0.0)
ADVANCE_EXPORT_COLUMNS = [
ExportColumn(title="申请单号", field="applyCode"),
ExportColumn(title="申请时间", field="applyTime"),
ExportColumn(title="申请人", field="applicantName"),
ExportColumn(title="申请原因", field="reason"),
ExportColumn(title="申请金额(元)", field="amount"),
ExportColumn(title="实际发放金额(元)", field="actualAmount"),
ExportColumn(title="冲抵总金额(元)", field="offsetAmount"),
ExportColumn(title="状态", field="status"),
ExportColumn(title="当前节点", field="currentNode"),
]
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _filters_from_params(params: dict, *, tenant_no: str = "") -> list:
ids = _param_get(params, "ids")
if isinstance(ids, str):
ids = [s.strip() for s in ids.split(",") if s.strip()]
return build_advance_column_filters(
tenant_no=tenant_no,
keyword=str(_param_get(params, "keyword") or ""),
status=_param_get(params, "status"),
status_in=_param_get(params, "statusIn", "status_in"),
apply_code=_param_get(params, "applyCode", "apply_code"),
apply_code_in=_param_get(params, "applyCodeIn", "apply_code_in"),
reason=_param_get(params, "reason"),
reason_in=_param_get(params, "reasonIn", "reason_in"),
applicant_id=_param_get(params, "applicantId", "applicant_id"),
applicant_name=_param_get(params, "applicantName", "applicant_name"),
applicant_name_in=_param_get(params, "applicantNameIn", "applicant_name_in"),
current_node=_param_get(params, "currentNode", "current_node"),
current_node_in=_param_get(params, "currentNodeIn", "current_node_in"),
issue_by=_param_get(params, "issueBy", "issue_by"),
issue_user_id=_param_get(params, "issueUserId", "issue_user_id"),
issue_user_name=_param_get(params, "issueUserName", "issue_user_name"),
issue_user_name_in=_param_get(params, "issueUserNameIn", "issue_user_name_in"),
amount_op=_param_get(params, "amountOp", "amount_op"),
amount=_param_get(params, "amount"),
amount_min=_param_get(params, "amountMin", "amount_min"),
amount_max=_param_get(params, "amountMax", "amount_max"),
actual_amount_op=_param_get(params, "actualAmountOp", "actual_amount_op"),
actual_amount=_param_get(params, "actualAmount", "actual_amount"),
actual_amount_min=_param_get(params, "actualAmountMin", "actual_amount_min"),
actual_amount_max=_param_get(params, "actualAmountMax", "actual_amount_max"),
offset_amount_op=_param_get(params, "offsetAmountOp", "offset_amount_op"),
offset_amount=_param_get(params, "offsetAmount", "offset_amount"),
offset_amount_min=_param_get(params, "offsetAmountMin", "offset_amount_min"),
offset_amount_max=_param_get(params, "offsetAmountMax", "offset_amount_max"),
apply_date=_param_get(params, "applyDate", "apply_date"),
apply_date_from=_param_get(params, "applyDateFrom", "apply_date_from"),
apply_date_to=_param_get(params, "applyDateTo", "apply_date_to"),
issue_time_from=_param_get(params, "issueTimeFrom", "issue_time_from"),
issue_time_to=_param_get(params, "issueTimeTo", "issue_time_to"),
ids=ids if isinstance(ids, list) else None,
)
def _body_to_params(body: BxApplyListExportBody) -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
def _advance_list_filters(body: BxApplyListExportBody, *, tenant_no: str = "") -> list:
return _filters_from_params(_body_to_params(body), tenant_no=tenant_no)
def _export_advance_rows(
db: Session,
tenant_no: str,
rows,
*,
with_offset: bool = True,
) -> List[dict]:
out_rows = [AdvanceApplyOut.model_validate(r) for r in rows]
if with_offset:
_fill_offset_amounts(db, tenant_no, rows, out_rows)
return [dump_export_row(r) for r in out_rows]
class AdvanceColumnFacetBody(BaseModel):
"""备用金申请列头可选值(去重;可附带列表上下文)"""
model_config = ConfigDict(populate_by_name=True, extra="allow")
field: str = Field(..., description="applyCode | applicantName | reason | currentNode | issueUserName")
scope: Optional[str] = Field(
default=None,
description=(
"列表视图:pending/approved=审批;mine=我的申请;"
"issue_pending/issue_issued=发放;省略则按通用数据权限"
),
)
keyword: Optional[str] = Field(default=None, description="列表快速搜索关键字")
limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
_ADVANCE_FACET_SCOPES = frozenset(
{"pending", "approved", "mine", "issue_pending", "issue_issued"}
)
_ADVANCE_FACET_COLUMNS = {
"applyCode": BxAdvanceApply.apply_code,
"applicantName": BxAdvanceApply.applicant_name,
"reason": BxAdvanceApply.reason,
"currentNode": BxAdvanceApply.current_node,
"issueUserName": BxAdvanceApply.issue_user_name,
}
@router.post("/column-facet-values", response_model=ApiResponse[dict])
def advance_column_facet_values(
body: AdvanceColumnFacetBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
"""备用金申请列头可选值:在列表上下文(排除本列)下去重;可按列表视图 scope 收窄。"""
from app.services.column_facet import list_column_facet_values
from app.services.pl.facet_context import strip_simple_facet_self_params
column = _ADVANCE_FACET_COLUMNS.get(body.field)
if column is None:
raise HTTPException(status_code=400, detail="不支持的列")
tenant_no = _tenant(db, user)
scope = (body.scope or "").strip() or None
if scope and scope not in _ADVANCE_FACET_SCOPES:
raise HTTPException(status_code=400, detail="不支持的 scope")
list_keyword = (body.keyword or "").strip() or None
params = strip_simple_facet_self_params(_body_to_params(body), body.field)
params.pop("scope", None)
params.pop("field", None)
params.pop("limit", None)
if list_keyword:
params["keyword"] = list_keyword
if scope in ("pending", "issue_pending", "issue_issued"):
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
extra_filters = _filters_from_params(params, tenant_no=tenant_no)
if scope:
try:
extra_filters = list(extra_filters) + [
AdvanceService.list_scope_filter(db, user, tenant_no, scope)
]
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
rows = list_column_facet_values(
db,
BxAdvanceApply,
column,
tenant_no=tenant_no,
keyword=None,
limit=body.limit if body.limit is not None else 500,
apply_scope=(
None
if scope == "pending"
else lambda query: apply_bx_scope(query, BxAdvanceApply, user, db, tenant_no)
),
extra_filters=extra_filters or None,
)
return ApiResponse(data={"list": rows})
@router.get("/", response_model=ApiResponse[PagedData[AdvanceApplyOut]])
def list_advances(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
status: Optional[str] = None,
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
status=status,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
filters = _filters_from_params(params, tenant_no=tenant_no)
rows, total = AdvanceService.get_paged(
db,
tenant_no,
page=page,
page_size=pageSize,
filters=filters,
user=user,
order_by=_advance_order(params),
)
out_rows = [AdvanceApplyOut.model_validate(r) for r in rows]
_fill_offset_amounts(db, tenant_no, rows, out_rows)
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/my", response_model=ApiResponse[PagedData[AdvanceApplyOut]])
def my_advances(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
status: Optional[str] = None,
keyword: str = "",
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
status=status,
keyword=keyword or None,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
filters = [
or_(
BxAdvanceApply.applicant_id == user.id,
BxAdvanceApply.create_by == user.id,
)
]
filters.extend(_filters_from_params(params, tenant_no=tenant_no))
rows, total = AdvanceService.get_paged(
db,
tenant_no,
page=page,
page_size=pageSize,
filters=filters,
user=user,
order_by=_advance_order(params),
)
out_rows = [AdvanceApplyOut.model_validate(r) for r in rows]
_fill_offset_amounts(db, tenant_no, rows, out_rows)
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/my/stats", response_model=ApiResponse[AdvanceMyStatsOut])
def my_advance_stats(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = AdvanceService.my_apply_stats(db, user, tenant_no)
return ApiResponse(data=AdvanceMyStatsOut.model_validate(data))
@router.get("/stats/status-counts", response_model=ApiResponse[dict])
def advance_status_counts(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
return ApiResponse(data=AdvanceService.global_status_counts(db, tenant_no, user=user))
@router.get("/pending-approval", response_model=ApiResponse[PagedData[AdvanceApplyOut]])
def pending_approval(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
# Tab 语义固定 pending;不把 status 列参传入 builder
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
extra_filters = _filters_from_params(params, tenant_no=tenant_no)
rows, total = AdvanceService.pending_approval(
db,
user,
tenant_no,
page=page,
page_size=pageSize,
extra_filters=extra_filters,
order_by=_advance_order(params),
)
out_rows = [AdvanceApplyOut.model_validate(r) for r in rows]
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/pending-approval/stats", response_model=ApiResponse[AdvanceApproverPendingStatsOut])
def advance_pending_approval_stats(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = AdvanceService.pending_approval_stats(db, user, tenant_no)
return ApiResponse(data=AdvanceApproverPendingStatsOut.model_validate(data))
@router.get("/approved-by-me", response_model=ApiResponse[PagedData[AdvanceApplyOut]])
def approved_by_me(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
extra_filters = _filters_from_params(params, tenant_no=tenant_no)
rows, total = AdvanceService.approved_by_me(
db,
user,
tenant_no,
page=page,
page_size=pageSize,
extra_filters=extra_filters,
order_by=_advance_order(params),
)
out_rows = [AdvanceApplyOut.model_validate(r) for r in rows]
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.post("/export")
def export_advances(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
filters = _filters_from_params(params, tenant_no=tenant_no)
rows, _ = AdvanceService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=_advance_order(params),
)
export_rows = _export_advance_rows(db, tenant_no, rows)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="备用金申请",
columns=ADVANCE_EXPORT_COLUMNS,
rows=export_rows,
filename_stem="备用金申请",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/my/export")
def export_my_advances(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
filters = [
or_(
BxAdvanceApply.applicant_id == user.id,
BxAdvanceApply.create_by == user.id,
)
]
filters.extend(_filters_from_params(params, tenant_no=tenant_no))
rows, _ = AdvanceService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=_advance_order(params),
)
export_rows = _export_advance_rows(db, tenant_no, rows)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="我的备用金",
columns=ADVANCE_EXPORT_COLUMNS,
rows=export_rows,
filename_stem="我的备用金申请",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/pending-approval/export")
def export_pending_approval_advances(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
extra_filters = _filters_from_params(params, tenant_no=tenant_no)
rows, _ = AdvanceService.pending_approval(
db,
user,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
extra_filters=extra_filters,
order_by=_advance_order(params),
)
export_rows = _export_advance_rows(db, tenant_no, rows, with_offset=False)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="备用金待审批",
columns=ADVANCE_EXPORT_COLUMNS,
rows=export_rows,
filename_stem="备用金待审批",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/approved-by-me/export")
def export_approved_by_me_advances(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
extra_filters = _filters_from_params(params, tenant_no=tenant_no)
rows, _ = AdvanceService.approved_by_me(
db,
user,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
extra_filters=extra_filters,
order_by=_advance_order(params),
)
export_rows = _export_advance_rows(db, tenant_no, rows, with_offset=False)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="备用金已审批",
columns=ADVANCE_EXPORT_COLUMNS,
rows=export_rows,
filename_stem="备用金已审批",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.get("/{advance_id}", response_model=ApiResponse[AdvanceApplyOut])
def get_advance(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
advance = AdvanceService.get_by_id(db, advance_id, tenant_no, user=user)
if not advance:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
out = AdvanceApplyOut.model_validate(advance)
offset_map = AdvanceService.offset_amount_map(db, tenant_no, [advance_id])
out.offset_amount = offset_map.get(advance_id, 0.0)
return ApiResponse(data=out)
@router.get("/{advance_id}/approvals", response_model=ApiResponse[List[AdvanceApprovalOut]])
def get_approvals(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not AdvanceService.get_by_id(db, advance_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
approvals = AdvanceService.get_approvals(db, advance_id, tenant_no, user=user)
return ApiResponse(data=[AdvanceApprovalOut.model_validate(a) for a in approvals])
@router.get("/{advance_id}/approval-history", response_model=ApiResponse[List[AdvanceApprovalOut]])
def get_approval_history(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not AdvanceService.get_by_id(db, advance_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
history = AdvanceService.get_approval_history(db, advance_id, tenant_no, user=user)
return ApiResponse(data=[AdvanceApprovalOut.model_validate(a) for a in history])
@router.post("/", response_model=ApiResponse[AdvanceApplyOut])
def create_advance(
body: AdvanceApplyCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = body.model_dump(exclude_unset=True)
eid = data.get("expense_item_id")
if eid:
if not ExpenseItemService.get_by_id(db, eid, tenant_no, user=user, skip_scope=True):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"费用项目 {eid} 不存在")
data["applicant_id"] = user.id
data["applicant_name"] = user.name
data["status"] = "draft"
wf = (
db.query(BxWorkflowDef)
.filter(
BxWorkflowDef.biz_type == "advance",
BxWorkflowDef.tenant_no == tenant_no,
BxWorkflowDef.del_flag == 0,
)
.first()
)
if wf:
data["wf_id"] = wf.id
advance = AdvanceService.create(db, data, user=user)
db.commit()
db.refresh(advance)
return ApiResponse(data=AdvanceApplyOut.model_validate(advance))
@router.put("/{advance_id}", response_model=ApiResponse[AdvanceApplyOut])
def update_advance(
advance_id: str,
body: AdvanceApplyUpdate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = body.model_dump(exclude_unset=True)
if data.get("expense_item_id"):
eid = data["expense_item_id"]
if not ExpenseItemService.get_by_id(db, eid, tenant_no, user=user, skip_scope=True):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"费用项目 {eid} 不存在")
advance = AdvanceService.update(db, advance_id, data, user=user)
if not advance:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
db.commit()
db.refresh(advance)
return ApiResponse(data=AdvanceApplyOut.model_validate(advance))
@router.post("/{advance_id}/submit", response_model=ApiResponse[AdvanceApplyOut])
def submit_advance(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
advance = AdvanceService.submit(db, advance_id, user)
if not advance:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
db.commit()
db.refresh(advance)
return ApiResponse(data=AdvanceApplyOut.model_validate(advance))
@router.post("/{advance_id}/approve", response_model=ApiResponse[AdvanceApplyOut])
def approve_advance(
advance_id: str,
body: AdvanceApprovalCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
advance = AdvanceService.approve(db, advance_id, user, body.approval_opinion or "")
if not advance:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在或无权审批")
db.commit()
db.refresh(advance)
return ApiResponse(data=AdvanceApplyOut.model_validate(advance))
@router.post("/{advance_id}/reject", response_model=ApiResponse[AdvanceApplyOut])
def reject_advance(
advance_id: str,
body: AdvanceApprovalCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
advance = AdvanceService.reject(db, advance_id, user, body.approval_opinion or "")
if not advance:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在或无权审批")
db.commit()
db.refresh(advance)
return ApiResponse(data=AdvanceApplyOut.model_validate(advance))
@router.post("/{advance_id}/withdraw", response_model=ApiResponse[AdvanceApplyOut])
def withdraw_advance(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
advance = AdvanceService.withdraw(db, advance_id, user)
if not advance:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="备用金申请不存在、非本人申请或当前状态不可撤回",
)
db.commit()
db.refresh(advance)
return ApiResponse(data=AdvanceApplyOut.model_validate(advance))
@router.delete("/{advance_id}", response_model=ApiResponse[None])
def delete_advance(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not AdvanceService.get_by_id(db, advance_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
AdvanceService.soft_delete(db, advance_id, user=user)
db.commit()
return ApiResponse(data=None)
+153
View File
@@ -0,0 +1,153 @@
import mimetypes
from typing import List
from urllib.parse import quote
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, status
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.database import get_db
from app.core.tenant_context import get_tenant_no
from app.schemas.bx.attachment import AttachmentOut
from app.schemas.bx.common import ApiResponse
from app.services.bx.attachment import AttachmentService
from app.services.bx.storage import (
download_file_bytes,
get_preview_url,
upload_bx_file,
)
router = APIRouter(prefix="/attachments", tags=["附件管理"])
def _tenant(db: Session, user: BxUserContext) -> str:
return get_tenant_no(db, user.to_tenant_user_dict())
def _parse_id_list(ids: str) -> List[str]:
return [x.strip() for x in (ids or "").split(",") if x.strip()]
@router.post("/upload", response_model=ApiResponse[AttachmentOut])
def upload_file(
file: UploadFile = File(...),
biz_type: str = "",
biz_id: str = "0",
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
if not file or not file.filename:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
file_data = file.file.read()
content_type = (
file.content_type
or mimetypes.guess_type(file.filename or "")[0]
or "application/octet-stream"
)
relative_path, _full_url = upload_bx_file(
file_data, file.filename or "unknown", biz_type=biz_type or "attachment"
)
biz_id_value = str(biz_id).strip() if biz_id else "0"
data = {
"biz_type": biz_type or "",
"biz_id": biz_id_value or "0",
"file_name": file.filename or "unknown",
"file_path": relative_path,
"file_type": content_type,
"file_size": len(file_data),
}
attachment = AttachmentService.create(db, data, user=user)
db.commit()
db.refresh(attachment)
return ApiResponse(data=AttachmentOut.model_validate(attachment))
@router.get("/download/{attachment_id}")
def download_file(
attachment_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
attachment = AttachmentService.get_by_id(db, attachment_id, tenant_no, user=user)
if not attachment:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
try:
file_data = download_file_bytes(attachment.file_path)
except FileNotFoundError as exc:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文件不存在") from exc
except Exception as exc:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="文件读取失败") from exc
encoded_name = quote(attachment.file_name or "download")
headers = {"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_name}"}
media_type = attachment.file_type or "application/octet-stream"
return StreamingResponse(iter([file_data]), media_type=media_type, headers=headers)
@router.delete("/{attachment_id}", response_model=ApiResponse[bool])
def delete_attachment(
attachment_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not AttachmentService.get_by_id(db, attachment_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
success = AttachmentService.soft_delete(db, attachment_id, user=user)
db.commit()
return ApiResponse(data=success)
@router.get("/preview/{attachment_id}", response_model=ApiResponse[dict])
def preview_attachment(
attachment_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
"""返回图片/附件预览 URL(MinIO 预签名或本地公开地址,对齐门户 storage 能力)。"""
tenant_no = _tenant(db, user)
attachment = AttachmentService.get_by_id(db, attachment_id, tenant_no, user=user)
if not attachment:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="附件不存在")
try:
url = get_preview_url(attachment.file_path, expires_seconds=3600)
except Exception as exc:
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="获取预览地址失败") from exc
return ApiResponse(
data={
"url": url,
"file_name": attachment.file_name,
"file_type": attachment.file_type,
}
)
@router.get("/list", response_model=ApiResponse[List[AttachmentOut]])
def list_by_biz(
biz_type: str = "",
biz_id: str = "0",
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
biz_id_value = str(biz_id).strip() if biz_id else "0"
attachments = AttachmentService.get_by_biz(
db, biz_type=biz_type, biz_id=biz_id_value, tenant_no=tenant_no, user=user
)
return ApiResponse(data=[AttachmentOut.model_validate(a) for a in attachments])
@router.put("/bind-biz", response_model=ApiResponse[int])
def bind_biz(
ids: str = Query(...),
biz_type: str = Query(...),
biz_id: str = Query(...),
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
id_list = _parse_id_list(ids)
biz_id_value = str(biz_id).strip() or "0"
count = AttachmentService.bind_biz(db, id_list, biz_type, biz_id_value, user=user)
db.commit()
return ApiResponse(data=count)
+157
View File
@@ -0,0 +1,157 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from app.api.bx.export_common import (
ExportColumn,
ExportValidationError,
BxExportBodyBase,
dump_export_row,
respond_xlsx,
status_label,
)
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.database import get_db
from app.core.tenant_context import get_tenant_no
from app.schemas.bx.common import ApiResponse
from app.schemas.bx.expense_item import ExpenseItemCreate, ExpenseItemOut, ExpenseItemUpdate
from app.services.bx.expense_item import ExpenseItemService
router = APIRouter(prefix="/expense-items", tags=["费用项目管理"])
@router.get("/tree", response_model=ApiResponse[List[ExpenseItemOut]])
def get_expense_item_tree(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
tree = ExpenseItemService.get_item_tree(db, tenant_no, user=user)
return ApiResponse(data=[ExpenseItemOut.model_validate(i) for i in tree])
EXPENSE_ITEM_EXPORT_COLUMNS = [
ExportColumn(title="项目名称", field="itemName"),
ExportColumn(title="项目编码", field="itemCode"),
ExportColumn(title="层级", field="level"),
ExportColumn(title="子项数", field="childCount"),
ExportColumn(title="排序", field="sortOrder"),
ExportColumn(title="状态", field="status"),
]
class ExpenseItemExportBody(BxExportBodyBase):
name: Optional[str] = None
status: Optional[str] = None
def _flatten_expense_tree(nodes: list, out: list) -> None:
for n in nodes:
out.append(n)
children = getattr(n, "children", None) or (n.get("children") if isinstance(n, dict) else None) or []
if children:
_flatten_expense_tree(list(children), out)
@router.post("/export")
def export_expense_items(
body: ExpenseItemExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
tree = ExpenseItemService.get_item_tree(db, tenant_no, user=user)
flat: list = []
_flatten_expense_tree(list(tree), flat)
outs = [ExpenseItemOut.model_validate(i) for i in flat]
if body.ids:
id_set = {str(i) for i in body.ids}
outs = [o for o in outs if str(o.id) in id_set]
if body.name:
kw = body.name.strip()
outs = [o for o in outs if kw in (o.item_name or "")]
if body.status not in (None, ""):
outs = [o for o in outs if str(o.status) == str(body.status)]
rows = []
for o in outs:
data = dump_export_row(o, status_fields=())
data["status"] = status_label(data.get("status"))
# childCount may be computed
if "childCount" not in data:
data["childCount"] = len(getattr(o, "children", None) or [])
rows.append(data)
return respond_xlsx(
db, tenant_no=tenant_no, sheet_title="费用科目", columns=EXPENSE_ITEM_EXPORT_COLUMNS,
rows=rows, filename_stem="费用科目", requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.get("/{item_id}", response_model=ApiResponse[ExpenseItemOut])
def get_expense_item(
item_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
item = ExpenseItemService.get_by_id(db, item_id, tenant_no, user=user)
if not item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="费用项目不存在")
return ApiResponse(data=ExpenseItemOut.model_validate(item))
@router.post("/", response_model=ApiResponse[ExpenseItemOut])
def create_expense_item(
body: ExpenseItemCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
item = ExpenseItemService.create(db, body.model_dump(exclude_unset=True), user=user)
db.commit()
db.refresh(item)
except ValueError as exc:
db.rollback()
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return ApiResponse(data=ExpenseItemOut.model_validate(item))
@router.put("/{item_id}", response_model=ApiResponse[ExpenseItemOut])
def update_expense_item(
item_id: str,
body: ExpenseItemUpdate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
item = ExpenseItemService.update(
db, item_id, body.model_dump(exclude_unset=True), user=user
)
if not item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="费用项目不存在")
db.commit()
db.refresh(item)
except ValueError as exc:
db.rollback()
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return ApiResponse(data=ExpenseItemOut.model_validate(item))
@router.delete("/{item_id}", response_model=ApiResponse[None])
def delete_expense_item(
item_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
item = ExpenseItemService.get_by_id(db, item_id, tenant_no, user=user)
if not item:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="费用项目不存在")
ExpenseItemService.soft_delete(db, item_id, user=user)
db.commit()
return ApiResponse(data=None)
+155
View File
@@ -0,0 +1,155 @@
"""bx 列表 Excel 导出公共辅助。"""
from __future__ import annotations
from datetime import date, datetime
from typing import Any, List, Mapping, Optional, Sequence
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.orm import Session
from app.utils.excel_export import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
BX_STATUS_LABELS = {
"draft": "待提交",
"pending": "审批中",
"approved": "审批通过",
"rejected": "审批驳回",
"issued": "已发放",
"paid": "已发放",
"offset": "已冲抵",
"processed": "已处理",
}
ISSUE_STATUS_LABELS = {
"issued": "已发放",
"pending": "待发放",
}
class BxExportBodyBase(BaseModel):
model_config = ConfigDict(populate_by_name=True, extra="allow")
ids: Optional[List[str]] = None
columns: Optional[List[str]] = None
class BxApplyListExportBody(BxExportBodyBase):
model_config = ConfigDict(populate_by_name=True, extra="allow")
status: Optional[str] = None
keyword: str = ""
applicant_id: Optional[str] = Field(default=None, alias="applicantId")
apply_date: Optional[str] = Field(default=None, alias="applyDate")
apply_date_from: Optional[str] = Field(default=None, alias="applyDateFrom")
apply_date_to: Optional[str] = Field(default=None, alias="applyDateTo")
expense_id: Optional[str] = Field(default=None, alias="expenseId")
expense_name: Optional[str] = Field(default=None, alias="expenseName")
apply_code: Optional[str] = Field(default=None, alias="applyCode")
title: Optional[str] = None
current_node: Optional[str] = Field(default=None, alias="currentNode")
status_in: Optional[str] = Field(default=None, alias="statusIn")
amount_op: Optional[str] = Field(default=None, alias="amountOp")
amount: Optional[str] = None
amount_min: Optional[str] = Field(default=None, alias="amountMin")
amount_max: Optional[str] = Field(default=None, alias="amountMax")
reason: Optional[str] = None
applicant_name: Optional[str] = Field(default=None, alias="applicantName")
actual_amount_op: Optional[str] = Field(default=None, alias="actualAmountOp")
actual_amount: Optional[str] = Field(default=None, alias="actualAmount")
actual_amount_min: Optional[str] = Field(default=None, alias="actualAmountMin")
actual_amount_max: Optional[str] = Field(default=None, alias="actualAmountMax")
offset_amount_op: Optional[str] = Field(default=None, alias="offsetAmountOp")
offset_amount: Optional[str] = Field(default=None, alias="offsetAmount")
offset_amount_min: Optional[str] = Field(default=None, alias="offsetAmountMin")
offset_amount_max: Optional[str] = Field(default=None, alias="offsetAmountMax")
issue_time_from: Optional[str] = Field(default=None, alias="issueTimeFrom")
issue_time_to: Optional[str] = Field(default=None, alias="issueTimeTo")
issue_user_id: Optional[str] = Field(default=None, alias="issueUserId")
issue_user_name: Optional[str] = Field(default=None, alias="issueUserName")
issue_by: Optional[str] = Field(default=None, alias="issueBy")
sort_field: Optional[str] = Field(default=None, alias="sortField")
sort_order: Optional[str] = Field(default=None, alias="sortOrder")
def status_label(status: Any) -> str:
if status is None:
return ""
if status in (0, "0"):
return "禁用"
if status in (1, "1"):
return "启用"
key = str(status)
return BX_STATUS_LABELS.get(key, key)
def issue_status_label(status: Any) -> str:
if status == "issued":
return "已发放"
return "待发放"
def dump_export_row(
obj: Any,
*,
status_fields: Sequence[str] = ("status",),
extra: Optional[Mapping[str, Any]] = None,
) -> dict:
if hasattr(obj, "model_dump"):
data = obj.model_dump(by_alias=True)
elif isinstance(obj, Mapping):
data = dict(obj)
else:
data = dict(obj)
for key, value in list(data.items()):
if isinstance(value, datetime):
data[key] = value.strftime("%Y-%m-%d %H:%M:%S")
elif isinstance(value, date):
data[key] = value.isoformat()
for field in status_fields:
if field in data:
data[field] = status_label(data.get(field))
if extra:
data.update(extra)
return data
def respond_xlsx(
db: Session,
*,
tenant_no: str,
sheet_title: str,
columns: Sequence[ExportColumn],
rows: Sequence[Mapping[str, Any]],
filename_stem: str,
requested_columns: Optional[Sequence[str]] = None,
):
cols = filter_export_columns(columns, requested_columns)
date_str = datetime.now().strftime("%Y%m%d")
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title=sheet_title,
columns=cols,
rows=rows,
filename_stem=f"{filename_stem}_{date_str}",
)
__all__ = [
"EXPORT_MAX_ROWS",
"ExportColumn",
"ExportValidationError",
"BxExportBodyBase",
"BxApplyListExportBody",
"status_label",
"issue_status_label",
"dump_export_row",
"respond_xlsx",
"ISSUE_STATUS_LABELS",
]
+404
View File
@@ -0,0 +1,404 @@
import mimetypes
from typing import Any, List, Optional, Set
from fastapi import APIRouter, Depends, HTTPException, Request, status, Query
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy.orm import Session
from starlette.datastructures import UploadFile as StarletteUploadFile
from app.api.bx.export_common import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
BxExportBodyBase,
dump_export_row,
respond_xlsx,
)
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.tenant_context import get_tenant_no
from app.core.database import get_db
from app.models.bx_models import BxInvoice
from app.schemas.bx.common import ApiResponse, PagedData
from app.schemas.bx.invoice import InvoiceOut, LedgerOut, WalletSummaryOut
from app.services.bx.invoice import InvoiceService
from app.services.bx.invoice_list_filters import (
build_invoice_column_filters,
build_ledger_column_filters,
build_wallet_column_filters,
)
from app.services.bx.list_sort import order_invoice, order_ledger, parse_sort_params
router = APIRouter(tags=["发票夹"])
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _wallet_filters_from_params(params: dict) -> list:
return build_wallet_column_filters(
keyword=str(_param_get(params, "keyword") or ""),
owner_user_name=_param_get(params, "ownerUserName", "owner_user_name"),
total_amount_op=_param_get(params, "totalAmountOp", "total_amount_op"),
total_amount=_param_get(params, "totalAmount", "total_amount"),
total_amount_min=_param_get(params, "totalAmountMin", "total_amount_min"),
total_amount_max=_param_get(params, "totalAmountMax", "total_amount_max"),
used_amount_op=_param_get(params, "usedAmountOp", "used_amount_op"),
used_amount=_param_get(params, "usedAmount", "used_amount"),
used_amount_min=_param_get(params, "usedAmountMin", "used_amount_min"),
used_amount_max=_param_get(params, "usedAmountMax", "used_amount_max"),
balance_op=_param_get(params, "balanceOp", "balance_op"),
balance=_param_get(params, "balance"),
balance_min=_param_get(params, "balanceMin", "balance_min"),
balance_max=_param_get(params, "balanceMax", "balance_max"),
invoice_count_op=_param_get(params, "invoiceCountOp", "invoice_count_op"),
invoice_count=_param_get(params, "invoiceCount", "invoice_count"),
invoice_count_min=_param_get(params, "invoiceCountMin", "invoice_count_min"),
invoice_count_max=_param_get(params, "invoiceCountMax", "invoice_count_max"),
)
def _invoice_filters_from_params(params: dict, *, tenant_no: str = "") -> list:
return build_invoice_column_filters(
tenant_no=tenant_no,
keyword=str(_param_get(params, "keyword") or ""),
amount_op=_param_get(params, "amountOp", "amount_op"),
amount=_param_get(params, "amount"),
amount_min=_param_get(params, "amountMin", "amount_min"),
amount_max=_param_get(params, "amountMax", "amount_max"),
remark=_param_get(params, "remark"),
remark_in=_param_get(params, "remarkIn", "remark_in"),
upload_by_name=_param_get(params, "uploadByName", "upload_by_name"),
upload_by_name_in=_param_get(params, "uploadByNameIn", "upload_by_name_in"),
create_time_from=_param_get(params, "createTimeFrom", "create_time_from"),
create_time_to=_param_get(params, "createTimeTo", "create_time_to"),
)
def _ledger_filters_from_params(params: dict) -> list:
return build_ledger_column_filters(
keyword=str(_param_get(params, "keyword") or ""),
entry_type=_param_get(params, "entryType", "entry_type"),
entry_type_in=_param_get(params, "entryTypeIn", "entry_type_in"),
amount_op=_param_get(params, "amountOp", "amount_op"),
amount=_param_get(params, "amount"),
amount_min=_param_get(params, "amountMin", "amount_min"),
amount_max=_param_get(params, "amountMax", "amount_max"),
remark=_param_get(params, "remark"),
create_time_from=_param_get(params, "createTimeFrom", "create_time_from"),
create_time_to=_param_get(params, "createTimeTo", "create_time_to"),
)
def _body_to_params(body: BxExportBodyBase) -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
class InvoiceColumnFacetBody(BaseModel):
"""发票档案列头可选值(去重;可附带列表上下文)"""
model_config = ConfigDict(populate_by_name=True, extra="allow")
field: str = Field(..., description="remark | uploadByName")
user_id: Optional[str] = Field(
default=None,
alias="userId",
description="钱包归属人;省略则当前用户(与发票列表一致)",
)
keyword: Optional[str] = Field(default=None, description="可选值关键字")
limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
_INVOICE_FACET_COLUMNS = {
"remark": BxInvoice.remark,
"uploadByName": BxInvoice.upload_by_name,
}
@router.post("/invoices/column-facet-values", response_model=ApiResponse[dict])
def invoice_column_facet_values(
body: InvoiceColumnFacetBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
"""发票档案列头可选值:按钱包归属人 + 列表上下文(排除本列)去重。"""
from app.core.tenant_context import get_tenant_no
from app.services.column_facet import list_column_facet_values
from app.services.pl.facet_context import strip_simple_facet_self_params
column = _INVOICE_FACET_COLUMNS.get(body.field)
if column is None:
raise HTTPException(status_code=400, detail="不支持的列")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
list_keyword = (body.keyword or "").strip() or None
params = strip_simple_facet_self_params(_body_to_params(body), body.field)
params.pop("userId", None)
params.pop("user_id", None)
params.pop("field", None)
params.pop("limit", None)
if list_keyword:
params["keyword"] = list_keyword
owner_id = InvoiceService._resolve_owner_for_query(
db, user, body.user_id or _param_get(params, "userId", "user_id")
)
extra_filters = list(_invoice_filters_from_params(params, tenant_no=tenant_no))
extra_filters.append(BxInvoice.owner_user_id == owner_id)
rows = list_column_facet_values(
db,
BxInvoice,
column,
tenant_no=tenant_no,
keyword=None,
limit=body.limit if body.limit is not None else 500,
extra_filters=extra_filters or None,
)
return ApiResponse(data={"list": rows})
@router.get("/invoice-wallets/mine/summary", response_model=ApiResponse[WalletSummaryOut])
def get_mine_wallet_summary(
userId: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
data = InvoiceService.get_mine_summary(db, user=user, owner_user_id=userId)
return ApiResponse(data=WalletSummaryOut.model_validate(data))
@router.get("/invoice-wallets", response_model=ApiResponse[PagedData[WalletSummaryOut]])
def list_invoice_wallets(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
params = _merge_query(request, keyword=keyword or None)
extra_filters = _wallet_filters_from_params(params)
rows, total = InvoiceService.list_wallets(
db,
user=user,
page=page,
page_size=pageSize,
keyword="",
extra_filters=extra_filters or None,
)
out_rows = [WalletSummaryOut.model_validate(InvoiceService._summary_to_dict(r)) for r in rows]
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
WALLET_EXPORT_COLUMNS = [
ExportColumn(title="员工", field="ownerUserName"),
ExportColumn(title="总额(元)", field="totalAmount"),
ExportColumn(title="已报销占用(元)", field="usedAmount"),
ExportColumn(title="余额(元)", field="balance"),
ExportColumn(title="发票张数", field="invoiceCount"),
]
class WalletExportBody(BxExportBodyBase):
model_config = ConfigDict(populate_by_name=True, extra="allow")
keyword: str = ""
@router.post("/invoice-wallets/export")
def export_invoice_wallets(
body: WalletExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
params = _body_to_params(body)
extra_filters = _wallet_filters_from_params(params)
rows, _ = InvoiceService.list_wallets(
db,
user=user,
page=1,
page_size=EXPORT_MAX_ROWS,
keyword="",
extra_filters=extra_filters or None,
)
outs = [WalletSummaryOut.model_validate(InvoiceService._summary_to_dict(r)) for r in rows]
if body.ids:
id_set = {str(i) for i in body.ids}
# wallet may key by ownerUserId
outs = [o for o in outs if str(getattr(o, "owner_user_id", None) or getattr(o, "id", "")) in id_set or str(o.model_dump(by_alias=True).get("ownerUserId") or o.model_dump(by_alias=True).get("id") or "") in id_set]
export_rows = [dump_export_row(o, status_fields=()) for o in outs]
return respond_xlsx(
db, tenant_no=tenant_no, sheet_title="发票夹", columns=WALLET_EXPORT_COLUMNS,
rows=export_rows, filename_stem="发票夹汇总", requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.get("/invoices", response_model=ApiResponse[PagedData[InvoiceOut]])
def list_invoices(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
userId: Optional[str] = None,
keyword: str = "",
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = InvoiceService._tenant_no(db, user)
params = _merge_query(request, userId=userId, keyword=keyword or None)
extra_filters = _invoice_filters_from_params(params, tenant_no=tenant_no)
sf, so = parse_sort_params(params)
rows, total = InvoiceService.list_invoices(
db,
user=user,
owner_user_id=userId,
page=page,
page_size=pageSize,
extra_filters=extra_filters or None,
order_by=order_invoice(sf, so),
)
out_rows = InvoiceService.out_rows_with_attachments(db, tenant_no, list(rows))
return ApiResponse(
data=PagedData(
rows=[InvoiceOut.model_validate(r) for r in out_rows],
total=total,
page=page,
page_size=pageSize,
)
)
@router.post("/invoices", response_model=ApiResponse[InvoiceOut])
async def create_invoice(
request: Request,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
"""一次上传一条发票:多文件挂同一档案,金额为总额,只写一条额度流水。
使用 request.form().getlist,兼容只传 1 个文件时 FastAPI List[UploadFile] 的 422。
"""
form = await request.form()
amount_raw = form.get("amount")
if amount_raw is None or str(amount_raw).strip() == "":
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请填写金额")
try:
amount = float(amount_raw)
except (TypeError, ValueError) as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="金额格式不正确"
) from exc
remark = str(form.get("remark") or "")
target_raw = form.get("targetUserId")
target_user_id = str(target_raw).strip() if target_raw not in (None, "") else None
upload_files: List[StarletteUploadFile] = []
seen_ids: Set[int] = set()
for key in ("files", "file"):
for item in form.getlist(key):
if not isinstance(item, StarletteUploadFile):
continue
obj_id = id(item)
if obj_id in seen_ids:
continue
seen_ids.add(obj_id)
upload_files.append(item)
if not upload_files:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
file_payload = []
for uf in upload_files:
if not uf.filename:
continue
data = await uf.read()
content_type = (
uf.content_type
or mimetypes.guess_type(uf.filename or "")[0]
or "application/octet-stream"
)
file_payload.append((data, uf.filename or "unknown", content_type))
if not file_payload:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请选择文件")
try:
invoice = InvoiceService.create(
db,
user=user,
amount=amount,
files=file_payload,
remark=remark,
target_user_id=target_user_id,
)
db.commit()
db.refresh(invoice)
except HTTPException:
db.rollback()
raise
except Exception as exc:
db.rollback()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="上传发票失败"
) from exc
tenant_no = InvoiceService._tenant_no(db, user)
out = InvoiceService.out_rows_with_attachments(db, tenant_no, [invoice])[0]
return ApiResponse(data=InvoiceOut.model_validate(out))
@router.delete("/invoices/{invoice_id}", response_model=ApiResponse[bool])
def delete_invoice(
invoice_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
success = InvoiceService.delete(db, user=user, invoice_id=invoice_id)
db.commit()
except HTTPException:
db.rollback()
raise
return ApiResponse(data=success)
@router.get("/invoice-ledgers", response_model=ApiResponse[List[LedgerOut]])
def list_invoice_ledgers(
request: Request,
userId: Optional[str] = None,
keyword: str = "",
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
params = _merge_query(request, userId=userId, keyword=keyword or None)
extra_filters = _ledger_filters_from_params(params)
sf, so = parse_sort_params(params)
rows = InvoiceService.list_ledgers(
db,
user=user,
owner_user_id=userId,
extra_filters=extra_filters or None,
order_by=order_ledger(sf, so),
)
return ApiResponse(data=[LedgerOut.model_validate(r) for r in rows])
+660
View File
@@ -0,0 +1,660 @@
import csv
import io
from datetime import datetime
from typing import Any, List, Optional
from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, Request, status, Query
from pydantic import Field
from fastapi.responses import StreamingResponse
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.api.bx.export_common import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
BxApplyListExportBody,
dump_export_row,
issue_status_label,
respond_xlsx,
)
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.database import get_db
from app.core.tenant_context import get_tenant_no
from app.models.bx_models import BxAdvanceApply, BxReimburseApply, BxReimburseOffset
from app.schemas.bx.advance import (
AdvanceFinanceIssueStatsOut,
AdvanceIssueOut,
AdvanceIssueRequest,
AdvanceOffsetRecordOut,
)
from app.schemas.bx.common import ApiResponse, PagedData
from app.schemas.bx.reimburse import (
BatchOffsetRequest,
OffsetRequest,
PayRequest,
PaymentFinanceStatsOut,
ReimburseApplyOut,
ReimburseOffsetRecordOut,
)
from app.services.bx.advance import AdvanceService
from app.services.bx.advance_list_filters import build_advance_column_filters
from app.services.bx.attachment import AttachmentService
from app.services.bx.list_sort import order_advance, order_reimburse, parse_sort_params
from app.services.bx.payment_list_filters import (
payment_filters_from_params as _payment_filters_from_params,
)
from app.services.bx.reimburse import ReimburseService
router = APIRouter(prefix="/payments", tags=["支付处理"])
def _tenant(db: Session, user: BxUserContext) -> str:
return get_tenant_no(db, user.to_tenant_user_dict())
def _wrap_reimburse_rows(outs: List[ReimburseApplyOut]) -> List[dict]:
return [{"type": "reimburse", "data": o.model_dump(by_alias=True)} for o in outs]
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _advance_filters_from_params(params: dict, *, tenant_no: str = "") -> list:
ids = _param_get(params, "ids")
if isinstance(ids, str):
ids = [s.strip() for s in ids.split(",") if s.strip()]
return build_advance_column_filters(
tenant_no=tenant_no,
keyword=str(_param_get(params, "keyword") or ""),
status=_param_get(params, "status"),
status_in=_param_get(params, "statusIn", "status_in"),
apply_code=_param_get(params, "applyCode", "apply_code"),
apply_code_in=_param_get(params, "applyCodeIn", "apply_code_in"),
reason=_param_get(params, "reason"),
reason_in=_param_get(params, "reasonIn", "reason_in"),
applicant_id=_param_get(params, "applicantId", "applicant_id"),
applicant_name=_param_get(params, "applicantName", "applicant_name"),
applicant_name_in=_param_get(params, "applicantNameIn", "applicant_name_in"),
current_node=_param_get(params, "currentNode", "current_node"),
current_node_in=_param_get(params, "currentNodeIn", "current_node_in"),
issue_by=_param_get(params, "issueBy", "issue_by"),
issue_user_id=_param_get(params, "issueUserId", "issue_user_id"),
issue_user_name=_param_get(params, "issueUserName", "issue_user_name"),
issue_user_name_in=_param_get(params, "issueUserNameIn", "issue_user_name_in"),
amount_op=_param_get(params, "amountOp", "amount_op"),
amount=_param_get(params, "amount"),
amount_min=_param_get(params, "amountMin", "amount_min"),
amount_max=_param_get(params, "amountMax", "amount_max"),
actual_amount_op=_param_get(params, "actualAmountOp", "actual_amount_op"),
actual_amount=_param_get(params, "actualAmount", "actual_amount"),
actual_amount_min=_param_get(params, "actualAmountMin", "actual_amount_min"),
actual_amount_max=_param_get(params, "actualAmountMax", "actual_amount_max"),
offset_amount_op=_param_get(params, "offsetAmountOp", "offset_amount_op"),
offset_amount=_param_get(params, "offsetAmount", "offset_amount"),
offset_amount_min=_param_get(params, "offsetAmountMin", "offset_amount_min"),
offset_amount_max=_param_get(params, "offsetAmountMax", "offset_amount_max"),
apply_date=_param_get(params, "applyDate", "apply_date"),
apply_date_from=_param_get(params, "applyDateFrom", "apply_date_from"),
apply_date_to=_param_get(params, "applyDateTo", "apply_date_to"),
issue_time_from=_param_get(params, "issueTimeFrom", "issue_time_from"),
issue_time_to=_param_get(params, "issueTimeTo", "issue_time_to"),
ids=ids if isinstance(ids, list) else None,
)
def _body_to_params(body: BxApplyListExportBody) -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
def _strip_tab_status_params(params: dict) -> None:
"""Tab 已固定 status 语义时,去掉冲突的 status 列参。"""
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
def _advance_issue_tab_filters(issue_status: Optional[str]) -> list:
filters = []
if issue_status == "pending":
filters.append(BxAdvanceApply.status == "approved")
filters.append(or_(BxAdvanceApply.issue_status.is_(None), BxAdvanceApply.issue_status != "issued"))
elif issue_status == "issued":
filters.append(BxAdvanceApply.status == "issued")
else:
filters.append(or_(BxAdvanceApply.status == "approved", BxAdvanceApply.status == "issued"))
return filters
@router.get("/pending", response_model=ApiResponse[PagedData[Any]])
def list_pending_payments(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
filters = [BxReimburseApply.status == "approved"]
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
# Tab 语义固定 approved;不把 status 列参传入 builder
_strip_tab_status_params(params)
filters.extend(_payment_filters_from_params(params, db=db, tenant_no=tenant_no))
sf, so = parse_sort_params(params)
rows, total = ReimburseService.get_paged(
db,
tenant_no,
page=page,
page_size=pageSize,
filters=filters,
user=user,
order_by=order_reimburse(sf, so),
)
outs = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return ApiResponse(
data=PagedData(rows=_wrap_reimburse_rows(outs), total=total, page=page, page_size=pageSize)
)
@router.get("/stats", response_model=ApiResponse[PaymentFinanceStatsOut])
def payment_finance_stats(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = ReimburseService.finance_payment_stats(db, tenant_no, user=user)
return ApiResponse(data=PaymentFinanceStatsOut.model_validate(data))
@router.get("/processed", response_model=ApiResponse[PagedData[Any]])
def list_processed_payments(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
filters = [BxReimburseApply.status.in_(["processed", "paid", "offset"])]
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
filters.extend(_payment_filters_from_params(params, db=db, tenant_no=tenant_no))
sf, so = parse_sort_params(params)
rows, total = ReimburseService.get_paged(
db,
tenant_no,
page=page,
page_size=pageSize,
filters=filters,
user=user,
order_by=order_reimburse(sf, so),
)
outs = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return ApiResponse(
data=PagedData(rows=_wrap_reimburse_rows(outs), total=total, page=page, page_size=pageSize)
)
@router.post("/{payment_id}/pay", response_model=ApiResponse[ReimburseApplyOut])
def pay(
payment_id: str,
body: Optional[PayRequest] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
pay_remark = body.pay_remark if body else ""
actual_amount = body.actual_amount if body else None
reimburse = ReimburseService.pay(
db, payment_id, user, pay_remark=pay_remark or "", actual_amount=actual_amount
)
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="支付记录不存在")
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
@router.post("/{payment_id}/offset", response_model=ApiResponse[ReimburseApplyOut])
def offset(
payment_id: str,
body: OffsetRequest,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.offset(
db,
payment_id,
body.advance_id,
body.offset_amount,
user,
remark=body.remark or "",
)
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="支付记录不存在")
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
@router.post("/{payment_id}/batch-offset", response_model=ApiResponse[ReimburseApplyOut])
def batch_offset(
payment_id: str,
body: BatchOffsetRequest,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.batch_offset(
db,
payment_id,
[item.model_dump() for item in body.items],
body.pay_amount,
user,
remark=body.remark or "",
)
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="支付记录不存在")
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
@router.get("/advance-issues", response_model=ApiResponse[PagedData[AdvanceIssueOut]])
def list_advance_issues(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
issue_status: Optional[str] = None,
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
filters = _advance_issue_tab_filters(issue_status)
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
# Tab 语义固定 status;不把 status 列参传入 builder
_strip_tab_status_params(params)
filters.extend(_advance_filters_from_params(params, tenant_no=tenant_no))
sf, so = parse_sort_params(params)
rows, total = AdvanceService.get_paged(
db,
tenant_no,
page=page,
page_size=pageSize,
filters=filters,
user=user,
order_by=order_advance(sf, so),
)
out_rows = [AdvanceIssueOut.model_validate(r) for r in rows]
if out_rows:
offset_map = AdvanceService.offset_amount_map(db, tenant_no, [r.id for r in rows])
for out_row in out_rows:
out_row.offset_amount = offset_map.get(out_row.id, 0.0)
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/advance-issues/stats", response_model=ApiResponse[AdvanceFinanceIssueStatsOut])
def advance_issue_stats(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = AdvanceService.finance_issue_stats(db, tenant_no, user=user)
return ApiResponse(data=AdvanceFinanceIssueStatsOut.model_validate(data))
PAYMENT_EXPORT_COLUMNS = [
ExportColumn(title="申请单号", field="applyCode"),
ExportColumn(title="申请时间", field="applyTime"),
ExportColumn(title="申请人", field="applicantName"),
ExportColumn(title="报销主题", field="title"),
ExportColumn(title="金额(元)", field="amount"),
ExportColumn(title="冲抵金额(元)", field="offsetAmount"),
ExportColumn(title="实付金额(元)", field="payAmount"),
ExportColumn(title="处理状态", field="status"),
ExportColumn(title="支付时间", field="payTime"),
]
ADVANCE_ISSUE_EXPORT_COLUMNS = [
ExportColumn(title="申请单号", field="applyCode"),
ExportColumn(title="申请时间", field="applyTime"),
ExportColumn(title="申请人", field="applicantName"),
ExportColumn(title="申请原因", field="reason"),
ExportColumn(title="申请金额(元)", field="amount"),
ExportColumn(title="实际发放金额(元)", field="actualAmount"),
ExportColumn(title="冲抵总金额(元)", field="offsetAmount"),
ExportColumn(title="审批通过时间", field="approveTime"),
ExportColumn(title="发放时间", field="issueTime"),
ExportColumn(title="发放人", field="issueUserName"),
ExportColumn(title="发放状态", field="issueStatus"),
]
class PaymentExportBody(BxApplyListExportBody):
issue_status: Optional[str] = Field(default=None, alias="issueStatus")
@router.post("/pending/export")
def export_pending_payments(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
filters = [BxReimburseApply.status == "approved"]
params = _body_to_params(body)
_strip_tab_status_params(params)
filters.extend(_payment_filters_from_params(params, db=db, tenant_no=tenant_no))
sf, so = parse_sort_params(params)
rows, _ = ReimburseService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=order_reimburse(sf, so),
)
outs = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
export_rows = [dump_export_row(o) for o in outs]
return respond_xlsx(
db, tenant_no=tenant_no, sheet_title="待付款", columns=PAYMENT_EXPORT_COLUMNS,
rows=export_rows, filename_stem="报销待付款", requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/processed/export")
def export_processed_payments(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
filters = [BxReimburseApply.status.in_(["processed", "paid", "offset"])]
params = _body_to_params(body)
filters.extend(_payment_filters_from_params(params, db=db, tenant_no=tenant_no))
sf, so = parse_sort_params(params)
rows, _ = ReimburseService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=order_reimburse(sf, so),
)
outs = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
export_rows = [dump_export_row(o) for o in outs]
return respond_xlsx(
db, tenant_no=tenant_no, sheet_title="已付款", columns=PAYMENT_EXPORT_COLUMNS,
rows=export_rows, filename_stem="报销已付款", requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/advance-issues/export-xlsx")
def export_advance_issues_xlsx(
body: PaymentExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
issue_status = body.issue_status or _param_get(params, "issueStatus", "issue_status")
filters = _advance_issue_tab_filters(issue_status)
_strip_tab_status_params(params)
filters.extend(_advance_filters_from_params(params, tenant_no=tenant_no))
sf, so = parse_sort_params(params)
rows, _ = AdvanceService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=order_advance(sf, so),
)
out_rows = [AdvanceIssueOut.model_validate(r) for r in rows]
export_rows = []
for o in out_rows:
data = dump_export_row(o, status_fields=())
data["issueStatus"] = issue_status_label(getattr(o, "issue_status", None) or data.get("issueStatus"))
export_rows.append(data)
return respond_xlsx(
db, tenant_no=tenant_no, sheet_title="备用金发放", columns=ADVANCE_ISSUE_EXPORT_COLUMNS,
rows=export_rows, filename_stem="备用金发放", requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.get("/advance-issues/export")
def export_advance_issues(
request: Request,
issue_status: Optional[str] = None,
keyword: str = "",
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
filters = _advance_issue_tab_filters(issue_status)
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
_strip_tab_status_params(params)
filters.extend(_advance_filters_from_params(params, tenant_no=tenant_no))
rows, _ = AdvanceService.get_paged(db, tenant_no, page=1, page_size=99999, filters=filters, user=user)
out_rows = [AdvanceIssueOut.model_validate(r) for r in rows]
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(
[
"申请单号",
"申请人",
"申请原因",
"申请金额",
"审批通过时间",
"发放状态",
"发放时间",
"发放操作人",
"实际发放金额",
"发放备注",
]
)
for row in out_rows:
writer.writerow(
[
row.apply_code,
row.applicant_name,
row.reason,
row.amount,
row.approve_time or "",
"已发放" if row.issue_status == "issued" else "待发放",
row.issue_time or "",
row.issue_user_name or "",
row.actual_amount or "",
row.issue_remark or "",
]
)
buf.seek(0)
filename = f"备用金发放列表_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
encoded_name = quote(filename)
return StreamingResponse(
iter([buf.getvalue()]),
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_name}"},
)
@router.post("/advance/{advance_id}/issue", response_model=ApiResponse[AdvanceIssueOut])
def issue_advance(
advance_id: str,
body: AdvanceIssueRequest,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
issue_atts = AttachmentService.get_by_biz(db, "advance_issue", advance_id, tenant_no, user=user)
if not issue_atts:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="请至少上传 1 个发放附件")
advance = AdvanceService.issue(
db, advance_id, user, body.issue_remark or "", body.actual_amount
)
if not advance:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="备用金申请不存在")
db.commit()
db.refresh(advance)
out = AdvanceIssueOut.model_validate(advance)
offset_map = AdvanceService.offset_amount_map(db, tenant_no, [advance_id])
out.offset_amount = offset_map.get(advance_id, 0.0)
return ApiResponse(data=out)
@router.get("/advance/{advance_id}/offset-records", response_model=ApiResponse[List[AdvanceOffsetRecordOut]])
def list_advance_offset_records(
advance_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
AdvanceService.get_by_id(db, advance_id, tenant_no, user=user)
rows = (
db.query(BxReimburseOffset, BxReimburseApply)
.join(
BxReimburseApply,
BxReimburseApply.id == BxReimburseOffset.reimburse_id,
)
.filter(
BxReimburseOffset.advance_id == advance_id,
BxReimburseOffset.tenant_no == tenant_no,
BxReimburseOffset.del_flag == 0,
BxReimburseApply.del_flag == 0,
BxReimburseApply.tenant_no == tenant_no,
)
.order_by(BxReimburseOffset.create_time.desc(), BxReimburseOffset.id.desc())
.all()
)
records = [
AdvanceOffsetRecordOut(
reimburse_id=reimburse.id,
reimburse_apply_code=reimburse.apply_code,
reimburse_title=reimburse.title,
reimburse_applicant_name=reimburse.applicant_name,
offset_amount=float(offset.offset_amount or 0),
remark=offset.remark,
operator=offset.create_by,
create_time=offset.create_time,
)
for offset, reimburse in rows
]
return ApiResponse(data=records)
@router.get("/{payment_id}/offset-records", response_model=ApiResponse[List[ReimburseOffsetRecordOut]])
def list_reimburse_offset_records(
payment_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
ReimburseService.get_by_id(db, payment_id, tenant_no, user=user)
rows = (
db.query(BxReimburseOffset, BxAdvanceApply)
.join(BxAdvanceApply, BxAdvanceApply.id == BxReimburseOffset.advance_id)
.filter(
BxReimburseOffset.reimburse_id == payment_id,
BxReimburseOffset.tenant_no == tenant_no,
BxReimburseOffset.del_flag == 0,
BxAdvanceApply.del_flag == 0,
BxAdvanceApply.tenant_no == tenant_no,
)
.order_by(BxReimburseOffset.create_time.desc(), BxReimburseOffset.id.desc())
.all()
)
records = [
ReimburseOffsetRecordOut(
advance_id=advance.id,
advance_apply_code=advance.apply_code,
advance_applicant_name=advance.applicant_name,
advance_reason=advance.reason,
offset_amount=float(offset.offset_amount or 0),
remark=offset.remark,
operator=offset.create_by,
create_time=offset.create_time,
)
for offset, advance in rows
]
return ApiResponse(data=records)
+892
View File
@@ -0,0 +1,892 @@
import io
from datetime import date as date_cls
from typing import Any, List, Optional
from urllib.parse import quote
from fastapi import APIRouter, Depends, File, HTTPException, Query, Request, UploadFile, status
from pydantic import BaseModel, ConfigDict, Field
from fastapi.responses import StreamingResponse
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.api.bx.export_common import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
BxApplyListExportBody,
dump_export_row,
respond_xlsx,
)
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.database import get_db
from app.core.tenant_context import get_tenant_no
from app.models.bx_models import BxReimburseApply, BxWorkflowDef
from app.schemas.bx.common import ApiResponse, PagedData
from app.schemas.bx.reimburse import (
ReimburseApplyCreate,
ReimburseApplyOut,
ReimburseApplyUpdate,
ReimburseApprovalCreate,
ReimburseApprovalOut,
ReimburseApproverPendingStatsOut,
ReimburseMyStatsOut,
ReimburseSubmitBody,
)
from app.services.bx.expense_item import ExpenseItemService
from app.services.bx.list_sort import order_reimburse, parse_sort_params
from app.services.bx.payment_list_filters import payment_filters_from_params
from app.services.bx.reimburse import ReimburseService
from app.services.bx.reimburse_import import (
build_applicant_label,
build_import_template_bytes,
import_reimburse_workbook,
load_applicant_options,
load_expense_nodes_flat,
)
from app.services.bx.reimburse_list_filters import build_reimburse_column_filters
from app.services.bx_data_scope import apply_bx_scope
from app.utils.bx_codegen import generate_title, parse_optional_date
router = APIRouter(prefix="/reimburses", tags=["报销管理"])
def _tenant(db: Session, user: BxUserContext) -> str:
return get_tenant_no(db, user.to_tenant_user_dict())
def _reimburse_order(params: dict):
sf, so = parse_sort_params(params)
return order_reimburse(sf, so)
REIMBURSE_EXPORT_COLUMNS = [
ExportColumn(title="申请单号", field="applyCode"),
ExportColumn(title="申请时间", field="applyTime"),
ExportColumn(title="申请人", field="applicantName"),
ExportColumn(title="报销主题", field="title"),
ExportColumn(title="费用科目", field="expenseName"),
ExportColumn(title="金额(元)", field="amount"),
ExportColumn(title="状态", field="status"),
ExportColumn(title="当前节点", field="currentNode"),
]
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _filters_from_params(params: dict, *, db: Session, tenant_no: str = "") -> list:
ids = _param_get(params, "ids")
if isinstance(ids, str):
ids = [s.strip() for s in ids.split(",") if s.strip()]
return build_reimburse_column_filters(
db=db,
tenant_no=tenant_no,
keyword=str(_param_get(params, "keyword") or ""),
status=_param_get(params, "status"),
status_in=_param_get(params, "statusIn", "status_in"),
apply_code=_param_get(params, "applyCode", "apply_code"),
apply_code_in=_param_get(params, "applyCodeIn", "apply_code_in"),
title=_param_get(params, "title"),
title_in=_param_get(params, "titleIn", "title_in"),
expense_name=_param_get(params, "expenseName", "expense_name"),
expense_id=_param_get(params, "expenseId", "expense_id"),
applicant_id=_param_get(params, "applicantId", "applicant_id"),
applicant_name=_param_get(params, "applicantName", "applicant_name"),
applicant_name_in=_param_get(params, "applicantNameIn", "applicant_name_in"),
current_node=_param_get(params, "currentNode", "current_node"),
current_node_in=_param_get(params, "currentNodeIn", "current_node_in"),
amount_op=_param_get(params, "amountOp", "amount_op"),
amount=_param_get(params, "amount"),
amount_min=_param_get(params, "amountMin", "amount_min"),
amount_max=_param_get(params, "amountMax", "amount_max"),
apply_date=_param_get(params, "applyDate", "apply_date"),
apply_date_from=_param_get(params, "applyDateFrom", "apply_date_from"),
apply_date_to=_param_get(params, "applyDateTo", "apply_date_to"),
occur_date_from=_param_get(params, "occurDateFrom", "occur_date_from"),
occur_date_to=_param_get(params, "occurDateTo", "occur_date_to"),
ids=ids if isinstance(ids, list) else None,
)
def _body_to_params(body: BxApplyListExportBody) -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
def _reimburse_list_filters(body: BxApplyListExportBody, db: Session, tenant_no: str) -> list:
return _filters_from_params(_body_to_params(body), db=db, tenant_no=tenant_no)
def _export_reimburse_rows(db: Session, tenant_no: str, rows) -> list:
out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return [dump_export_row(r) for r in out_rows]
def _build_details_data(
db: Session,
tenant_no: str,
body_details,
*,
user: BxUserContext,
) -> List[dict]:
details_data: List[dict] = []
for d in body_details:
item = ExpenseItemService.get_by_id(
db, d.expense_item_id, tenant_no, user=user, skip_scope=True
)
if not item:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"费用项目 {d.expense_item_id} 不存在",
)
try:
occur_date = parse_optional_date(d.occur_date)
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="发生时间格式无效,请使用 YYYY-MM-DD",
)
values = {
"id": d.id,
"expense_id": d.expense_item_id,
"expense_name": item.item_name,
"amount": d.amount,
}
if "remark" in d.model_fields_set:
values["remark"] = d.remark
if "occur_date" in d.model_fields_set:
values["occur_date"] = occur_date
details_data.append(values)
return details_data
@router.get("/generate-title", response_model=ApiResponse[str])
def get_generated_title(
reimburseDate: Optional[str] = None,
excludeApplyId: Optional[str] = None,
applicantId: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
exclude_id = str(excludeApplyId).strip() if excludeApplyId else None
_, applicant_name = ReimburseService.resolve_applicant(
db, user, applicantId, tenant_no=tenant_no
)
title = generate_title(db, applicant_name, tenant_no, reimburseDate, exclude_id)
return ApiResponse(data=title)
@router.get("/import-template")
def download_reimburse_import_template(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
nodes = load_expense_nodes_flat(db, tenant_no)
applicants = load_applicant_options(db, user=user, tenant_no=tenant_no)
me = next((a for a in applicants if a["id"] == user.id), None)
if me:
cur_label = build_applicant_label(me["nick_name"], me["user_no"], me["id"])
else:
cur_label = build_applicant_label(user.name or "", "", user.id)
applicants = [
{"id": user.id, "nick_name": user.name or "", "user_no": ""}
] + applicants
raw = build_import_template_bytes(
expense_nodes=nodes,
applicants=applicants,
current_applicant_label=cur_label,
today=date_cls.today(),
)
filename = quote("报销申请导入模板.xlsx")
return StreamingResponse(
io.BytesIO(raw),
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={
"Content-Disposition": f"attachment; filename={filename}; filename*=UTF-8''{filename}"
},
)
@router.post("/import", response_model=ApiResponse[dict])
def import_reimburses(
file: UploadFile = File(...),
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
content = file.file.read()
if not content:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件为空")
try:
result = import_reimburse_workbook(db, file_bytes=content, user=user)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
return ApiResponse(data=result)
class ReimburseColumnFacetBody(BaseModel):
"""报销申请列头可选值(去重;可附带列表上下文)"""
model_config = ConfigDict(populate_by_name=True, extra="allow")
field: str = Field(..., description="applyCode | applicantName | title | currentNode")
scope: Optional[str] = Field(
default=None,
description=(
"列表视图:pending/approved=审批;mine=我的申请;"
"payment_pending/payment_processed=付款;省略则按通用数据权限"
),
)
keyword: Optional[str] = Field(default=None, description="列表快速搜索关键字")
limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
_REIMBURSE_FACET_SCOPES = frozenset(
{"pending", "approved", "mine", "payment_pending", "payment_processed"}
)
_REIMBURSE_FACET_COLUMNS = {
"applyCode": BxReimburseApply.apply_code,
"applicantName": BxReimburseApply.applicant_name,
"title": BxReimburseApply.title,
"currentNode": BxReimburseApply.current_node,
}
@router.post("/column-facet-values", response_model=ApiResponse[dict])
def reimburse_column_facet_values(
body: ReimburseColumnFacetBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
"""报销申请列头可选值:在列表上下文(排除本列)下去重;可按列表视图 scope 收窄。"""
from app.services.column_facet import list_column_facet_values
from app.services.pl.facet_context import strip_simple_facet_self_params
column = _REIMBURSE_FACET_COLUMNS.get(body.field)
if column is None:
raise HTTPException(status_code=400, detail="不支持的列")
tenant_no = _tenant(db, user)
scope = (body.scope or "").strip() or None
if scope and scope not in _REIMBURSE_FACET_SCOPES:
raise HTTPException(status_code=400, detail="不支持的 scope")
# body.keyword 与列表快速搜索同名:先取出作列表上下文,再剥离本列键
list_keyword = (body.keyword or "").strip() or None
params = strip_simple_facet_self_params(_body_to_params(body), body.field)
params.pop("scope", None)
params.pop("field", None)
params.pop("limit", None)
if list_keyword:
params["keyword"] = list_keyword
# Tab/视图已固定 status 语义时,不吃 status 列参
if scope in ("pending", "payment_pending"):
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
if scope in ("payment_pending", "payment_processed"):
extra_filters = payment_filters_from_params(params, db=db, tenant_no=tenant_no)
else:
extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
if scope:
try:
extra_filters = list(extra_filters) + [
ReimburseService.list_scope_filter(db, user, tenant_no, scope)
]
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
rows = list_column_facet_values(
db,
BxReimburseApply,
column,
tenant_no=tenant_no,
keyword=None,
limit=body.limit if body.limit is not None else 500,
apply_scope=(
None
if scope == "pending"
else lambda query: apply_bx_scope(query, BxReimburseApply, user, db, tenant_no)
),
extra_filters=extra_filters or None,
)
return ApiResponse(data={"list": rows})
@router.get("/", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
def list_reimburses(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
status: Optional[str] = None,
keyword: str = "",
expense_id: Optional[str] = None,
expenseName: Optional[str] = None,
applicantId: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
status=status,
keyword=keyword or None,
expenseId=expense_id,
expenseName=expenseName,
applicantId=applicantId,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
rows, total = ReimburseService.get_paged(
db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user, order_by=_reimburse_order(params)
)
out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/my", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
def my_reimburses(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
status: Optional[str] = None,
keyword: str = "",
expenseName: Optional[str] = None,
applyCode: Optional[str] = None,
title: Optional[str] = None,
currentNode: Optional[str] = None,
statusIn: Optional[str] = None,
amountOp: Optional[str] = None,
amount: Optional[str] = None,
amountMin: Optional[str] = None,
amountMax: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
status=status,
keyword=keyword or None,
expenseName=expenseName,
applyCode=applyCode,
title=title,
currentNode=currentNode,
statusIn=statusIn,
amountOp=amountOp,
amount=amount,
amountMin=amountMin,
amountMax=amountMax,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
filters = [
or_(
BxReimburseApply.applicant_id == user.id,
BxReimburseApply.create_by == user.id,
)
]
filters.extend(_filters_from_params(params, db=db, tenant_no=tenant_no))
rows, total = ReimburseService.get_paged(
db, tenant_no, page=page, page_size=pageSize, filters=filters, user=user, order_by=_reimburse_order(params)
)
out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/my/stats", response_model=ApiResponse[ReimburseMyStatsOut])
def my_reimburse_stats(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = ReimburseService.my_apply_stats(db, user, tenant_no)
return ApiResponse(data=ReimburseMyStatsOut.model_validate(data))
@router.get("/stats/status-counts", response_model=ApiResponse[dict])
def reimburse_status_counts(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
return ApiResponse(data=ReimburseService.global_status_counts(db, tenant_no, user=user))
@router.get("/pending-approval", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
def pending_approval(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
applicantId: Optional[str] = None,
expenseName: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
expenseName=expenseName,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
# Tab 语义固定 pending;不把 status 列参传入 builder
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
rows, total = ReimburseService.pending_approval(
db,
user,
tenant_no,
page=page,
page_size=pageSize,
extra_filters=extra_filters,
order_by=_reimburse_order(params),
)
out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.get("/pending-approval/stats", response_model=ApiResponse[ReimburseApproverPendingStatsOut])
def pending_approval_stats(
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
data = ReimburseService.pending_approval_stats(db, user, tenant_no)
return ApiResponse(data=ReimburseApproverPendingStatsOut.model_validate(data))
@router.get("/approved-by-me", response_model=ApiResponse[PagedData[ReimburseApplyOut]])
def approved_by_me(
request: Request,
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
keyword: str = "",
applicantId: Optional[str] = None,
expenseName: Optional[str] = None,
applyDate: Optional[str] = None,
applyDateFrom: Optional[str] = None,
applyDateTo: Optional[str] = None,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
params = _merge_query(
request,
keyword=keyword or None,
applicantId=applicantId,
expenseName=expenseName,
applyDate=applyDate,
applyDateFrom=applyDateFrom,
applyDateTo=applyDateTo,
)
extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
rows, total = ReimburseService.approved_by_me(
db,
user,
tenant_no,
page=page,
page_size=pageSize,
extra_filters=extra_filters,
order_by=_reimburse_order(params),
)
out_rows = ReimburseService.out_rows_with_attachment_counts(db, tenant_no, list(rows))
return ApiResponse(data=PagedData(rows=out_rows, total=total, page=page, page_size=pageSize))
@router.post("/export")
def export_reimburses(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
rows, _ = ReimburseService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=_reimburse_order(params),
)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="报销申请",
columns=REIMBURSE_EXPORT_COLUMNS,
rows=_export_reimburse_rows(db, tenant_no, rows),
filename_stem="报销申请",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/my/export")
def export_my_reimburses(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
filters = [
or_(
BxReimburseApply.applicant_id == user.id,
BxReimburseApply.create_by == user.id,
)
]
filters.extend(_filters_from_params(params, db=db, tenant_no=tenant_no))
rows, _ = ReimburseService.get_paged(
db,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=filters,
user=user,
order_by=_reimburse_order(params),
)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="我的报销",
columns=REIMBURSE_EXPORT_COLUMNS,
rows=_export_reimburse_rows(db, tenant_no, rows),
filename_stem="我的报销申请",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/pending-approval/export")
def export_pending_approval_reimburses(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
params.pop("status", None)
params.pop("statusIn", None)
params.pop("status_in", None)
extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
rows, _ = ReimburseService.pending_approval(
db,
user,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
extra_filters=extra_filters,
order_by=_reimburse_order(params),
)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="报销待审批",
columns=REIMBURSE_EXPORT_COLUMNS,
rows=_export_reimburse_rows(db, tenant_no, rows),
filename_stem="报销待审批",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/approved-by-me/export")
def export_approved_by_me_reimburses(
body: BxApplyListExportBody,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
try:
tenant_no = _tenant(db, user)
params = _body_to_params(body)
extra_filters = _filters_from_params(params, db=db, tenant_no=tenant_no)
rows, _ = ReimburseService.approved_by_me(
db,
user,
tenant_no,
page=1,
page_size=EXPORT_MAX_ROWS,
extra_filters=extra_filters,
order_by=_reimburse_order(params),
)
return respond_xlsx(
db,
tenant_no=tenant_no,
sheet_title="报销已审批",
columns=REIMBURSE_EXPORT_COLUMNS,
rows=_export_reimburse_rows(db, tenant_no, rows),
filename_stem="报销已审批",
requested_columns=body.columns,
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.get("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
def get_reimburse(
reimburse_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user)
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
return ApiResponse(data=out)
@router.get("/{reimburse_id}/approvals", response_model=ApiResponse[List[ReimburseApprovalOut]])
def get_approvals(
reimburse_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
approvals = ReimburseService.get_approvals(db, reimburse_id, tenant_no, user=user)
return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in approvals])
@router.get("/{reimburse_id}/approval-history", response_model=ApiResponse[List[ReimburseApprovalOut]])
def get_approval_history(
reimburse_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
history = ReimburseService.get_approval_history(db, reimburse_id, tenant_no, user=user)
return ApiResponse(data=[ReimburseApprovalOut.model_validate(a) for a in history])
@router.post("/", response_model=ApiResponse[ReimburseApplyOut])
def create_reimburse(
body: ReimburseApplyCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
details_data = _build_details_data(db, tenant_no, body.details, user=user)
data = {
"status": "draft",
"remark": body.remark,
"reimburse_date": body.reimburse_date,
}
if body.title:
data["title"] = body.title
wf = (
db.query(BxWorkflowDef)
.filter(
BxWorkflowDef.biz_type == "reimburse",
BxWorkflowDef.tenant_no == tenant_no,
BxWorkflowDef.del_flag == 0,
)
.first()
)
if wf:
data["wf_id"] = wf.id
applicant_id, applicant_name = ReimburseService.resolve_applicant(
db, user, body.applicant_id, tenant_no=tenant_no
)
reimburse = ReimburseService.create_with_details(
db,
data,
details_data,
user=user,
applicant_id=applicant_id,
applicant_name=applicant_name,
)
if body.invoice_links is not None or body.invoice_ids is not None:
ReimburseService.sync_reimburse_invoices(
db,
reimburse.id,
body.invoice_ids,
tenant_no,
user,
applicant_id=applicant_id,
invoice_links=body.invoice_links,
)
db.commit()
db.refresh(reimburse)
out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
return ApiResponse(data=out)
@router.put("/{reimburse_id}", response_model=ApiResponse[ReimburseApplyOut])
def update_reimburse(
reimburse_id: str,
body: ReimburseApplyUpdate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
details_data = None
if body.details is not None:
details_data = _build_details_data(db, tenant_no, body.details, user=user)
main_data = {}
if body.remark is not None:
main_data["remark"] = body.remark
if body.reimburse_date is not None:
main_data["reimburse_date"] = body.reimburse_date
if body.title is not None:
main_data["title"] = body.title
if body.applicant_id is not None:
applicant_id, applicant_name = ReimburseService.resolve_applicant(
db, user, body.applicant_id, tenant_no=tenant_no
)
main_data["applicant_id"] = applicant_id
main_data["applicant_name"] = applicant_name
reimburse = ReimburseService.update_with_details(
db, reimburse_id, main_data, details_data, user=user
)
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
if body.invoice_links is not None or body.invoice_ids is not None:
ReimburseService.sync_reimburse_invoices(
db,
reimburse_id,
body.invoice_ids,
tenant_no,
user,
applicant_id=reimburse.applicant_id,
invoice_links=body.invoice_links,
)
db.commit()
db.refresh(reimburse)
out = ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse)
return ApiResponse(data=out)
@router.post("/{reimburse_id}/submit", response_model=ApiResponse[ReimburseApplyOut])
def submit_reimburse(
reimburse_id: str,
body: ReimburseSubmitBody = ReimburseSubmitBody(),
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.submit(
db,
reimburse_id,
user,
invoice_ids=body.invoice_ids,
invoice_links=body.invoice_links,
)
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
@router.post("/{reimburse_id}/approve", response_model=ApiResponse[ReimburseApplyOut])
def approve_reimburse(
reimburse_id: str,
body: ReimburseApprovalCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.approve(db, reimburse_id, user, body.approval_opinion or "")
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
@router.post("/{reimburse_id}/reject", response_model=ApiResponse[ReimburseApplyOut])
def reject_reimburse(
reimburse_id: str,
body: ReimburseApprovalCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.reject(db, reimburse_id, user, body.approval_opinion or "")
if not reimburse:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在或无权审批")
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.out_one_with_attachment_counts(db, tenant_no, reimburse))
@router.post("/{reimburse_id}/withdraw", response_model=ApiResponse[ReimburseApplyOut])
def withdraw_reimburse(
reimburse_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
reimburse = ReimburseService.withdraw(db, reimburse_id, user)
if not reimburse:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="报销单不存在、非本人申请或当前状态不可撤回",
)
db.commit()
db.refresh(reimburse)
return ApiResponse(data=ReimburseService.build_apply_out_with_details(db, tenant_no, reimburse))
@router.delete("/{reimburse_id}", response_model=ApiResponse[None])
def delete_reimburse(
reimburse_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = _tenant(db, user)
if not ReimburseService.get_by_id(db, reimburse_id, tenant_no, user=user):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="报销单不存在")
ReimburseService.soft_delete(db, reimburse_id, user=user)
db.commit()
return ApiResponse(data=None)
+161
View File
@@ -0,0 +1,161 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from app.core.bx_auth import BxUserContext, get_bx_current_user
from app.core.database import get_db
from app.core.tenant_context import get_tenant_no
from app.schemas.bx.common import ApiResponse, PagedData
from app.schemas.bx.workflow import (
WorkflowDefCreate,
WorkflowDefOut,
WorkflowDefUpdate,
WorkflowNodeCreate,
)
from app.services.bx.workflow import WorkflowService
router = APIRouter(prefix="/workflows", tags=["工作流配置"])
@router.get("/", response_model=ApiResponse[PagedData[WorkflowDefOut]])
def list_workflows(
page: int = 1,
pageSize: int = Query(10, ge=1, le=500),
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
rows, total = WorkflowService.get_paged(db, tenant_no, page=page, page_size=pageSize, user=user)
out_rows = [WorkflowDefOut.model_validate(r) for r in rows]
paged_data = PagedData(rows=out_rows, total=total, page=page, page_size=pageSize)
return ApiResponse(data=paged_data)
@router.get("/biz/{biz_type}", response_model=ApiResponse[WorkflowDefOut])
def get_workflow_by_biz_type(
biz_type: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
workflow = WorkflowService.ensure_by_biz_type(db, biz_type, user=user)
if not workflow:
return ApiResponse(data=None)
return ApiResponse(data=WorkflowDefOut.model_validate(workflow))
@router.get("/{workflow_id}", response_model=ApiResponse[WorkflowDefOut])
def get_workflow(
workflow_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
workflow = WorkflowService.get_by_id(db, workflow_id, tenant_no, user=user)
if not workflow:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="工作流不存在")
return ApiResponse(data=WorkflowDefOut.model_validate(workflow))
@router.post("/", response_model=ApiResponse[WorkflowDefOut])
def create_workflow(
body: WorkflowDefCreate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
data = body.model_dump(exclude_unset=True)
nodes_data = data.pop("nodes", []) or []
workflow = WorkflowService.create(db, data, user=user)
if nodes_data:
try:
WorkflowService.save_nodes(db, workflow.id, nodes_data, user=user)
except ValueError as exc:
db.rollback()
code = (
status.HTTP_404_NOT_FOUND
if str(exc) == "工作流不存在"
else status.HTTP_400_BAD_REQUEST
)
raise HTTPException(status_code=code, detail=str(exc)) from exc
db.commit()
db.refresh(workflow)
return ApiResponse(data=WorkflowDefOut.model_validate(workflow))
@router.put("/{workflow_id}", response_model=ApiResponse[WorkflowDefOut])
def update_workflow(
workflow_id: str,
body: WorkflowDefUpdate,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
data = body.model_dump(exclude_unset=True)
nodes_data = data.pop("nodes", None)
try:
workflow = WorkflowService.update(db, workflow_id, data, user=user)
except ValueError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not workflow:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="工作流不存在")
if nodes_data is not None:
try:
WorkflowService.save_nodes(db, workflow_id, nodes_data, user=user)
except ValueError as exc:
db.rollback()
code = (
status.HTTP_404_NOT_FOUND
if str(exc) == "工作流不存在"
else status.HTTP_400_BAD_REQUEST
)
raise HTTPException(status_code=code, detail=str(exc)) from exc
db.commit()
db.refresh(workflow)
return ApiResponse(data=WorkflowDefOut.model_validate(workflow))
@router.put("/{workflow_id}/nodes", response_model=ApiResponse[WorkflowDefOut])
def save_workflow_nodes(
workflow_id: str,
body: List[WorkflowNodeCreate],
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
nodes_data = [n.model_dump(exclude_unset=True) for n in body]
try:
WorkflowService.save_nodes(db, workflow_id, nodes_data, user=user)
except ValueError as exc:
db.rollback()
code = (
status.HTTP_404_NOT_FOUND
if str(exc) == "工作流不存在"
else status.HTTP_400_BAD_REQUEST
)
raise HTTPException(status_code=code, detail=str(exc)) from exc
workflow = WorkflowService.get_by_id(db, workflow_id, tenant_no, user=user)
if not workflow:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="工作流不存在")
db.commit()
db.refresh(workflow)
return ApiResponse(data=WorkflowDefOut.model_validate(workflow))
@router.delete("/{workflow_id}", response_model=ApiResponse[None])
def delete_workflow(
workflow_id: str,
db: Session = Depends(get_db),
user: BxUserContext = Depends(get_bx_current_user),
):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
workflow = WorkflowService.get_by_id(db, workflow_id, tenant_no, user=user)
if not workflow:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="工作流不存在")
try:
WorkflowService.soft_delete(db, workflow_id, user=user)
except ValueError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return ApiResponse(data=None)
File diff suppressed because it is too large. Load diff
+909
View File
@@ -0,0 +1,909 @@
"""CRM 合同 API 路由 — GET/PUT/DELETE/POST 对齐原 Java CRM"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from fastapi import Depends, Query, Request
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin, require_menu_code
from app.core.oper_log_decorator import oper_log
from app.core.response import error_response, success_response
from app.core.tenant_context import get_tenant_no
from app.crud.crm.data_scope_helpers import crm_user_info
from app.crud.crm.contract import (
batch_assign_owner,
batch_submit_contract_approval,
create_contract,
create_from_opportunity,
create_from_quote,
download_contract_pdf,
export_contracts,
finish_contract,
get_contract_detail,
get_template,
invalid_contract,
list_contract_column_facet_values,
list_contracts,
restore_contract,
query_expiring,
renew_contract,
save_template,
sign_contract,
soft_delete_contracts,
start_execute,
statistics_by_status,
statistics_by_type,
statistics_overview,
statistics_trend,
submit_contract_approval,
total_pages,
update_contract,
upload_attachments,
upload_attachments_with_category,
upload_file,
withdraw_contract_approval,
)
from app.crud.crm.contract_approval import (
approve_contract_by_contract_id,
list_contract_approvals,
)
from app.crud.crm.contract_approver_setting import get_setting as get_contract_approver_setting
from app.crud.crm.contract_approver_setting import save_setting as save_contract_approver_setting
from app.schemas.crm.contract_approver_setting import ContractApproverSettingSaveBody
from app.schemas.crm.contract import (
ContractApprovalActionBody,
ContractBatchAssignBody,
ContractBatchSubmitBody,
ContractColumnFacetBody,
ContractCreateBody,
ContractExportBody,
ContractInvalidBody,
ContractListQuery,
ContractRenewBody,
ContractSignBody,
ContractStatisticsOverviewQuery,
ContractStatisticsTrendQuery,
ContractStatusBody,
ContractSubmitBody,
ContractTemplateSaveBody,
ContractUpdateBody,
ContractUploadAttachmentsBody,
ContractUploadFileBody,
ContractWithdrawBody,
)
from app.utils.crm_export_columns import CONTRACT_EXPORT_COLUMNS
from app.utils.excel_export import (
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
from app.api.crm import _filter_export_rows_by_ids
def register_contract_routes(router):
@router.get("/contract/list")
async def contract_list(
request: Request,
pageNum: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=500),
keyword: Optional[str] = Query(
None,
description="即时检索:合同编号/合同名称/客户名称/合同产品名称/产品拼音首字母",
),
contractNo: Optional[str] = None,
contractName: Optional[str] = None,
customerName: Optional[str] = None,
customerId: Optional[str] = None,
opportunityId: Optional[str] = None,
quoteId: Optional[str] = None,
contractType: Optional[str] = None,
status: Optional[str] = None,
excludeStatus: Optional[str] = None,
approvalStatus: Optional[str] = None,
ownerUserId: Optional[str] = None,
pendingApprovalUserId: Optional[str] = None,
approvedByUserId: Optional[str] = None,
minAmount: Optional[float] = None,
maxAmount: Optional[float] = None,
signDateBegin: Optional[str] = None,
signDateEnd: Optional[str] = None,
beginTime: Optional[str] = None,
endTime: Optional[str] = None,
includeProducts: bool = Query(False, description="是否附带合同产品明细"),
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
query = ContractListQuery(
pageNum=pageNum,
pageSize=pageSize,
keyword=keyword,
contractNo=contractNo,
contractName=contractName,
customerName=customerName,
customerId=customerId,
opportunityId=opportunityId,
quoteId=quoteId,
contractType=contractType,
status=status,
excludeStatus=excludeStatus,
approvalStatus=approvalStatus,
ownerUserId=ownerUserId,
pendingApprovalUserId=pendingApprovalUserId,
approvedByUserId=approvedByUserId,
minAmount=minAmount,
maxAmount=maxAmount,
signDateBegin=signDateBegin,
signDateEnd=signDateEnd,
beginTime=beginTime,
endTime=endTime,
)
filters = query.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
# 列头漏斗等未在签名中声明的 query 参数一并透传
skip_keys = {
"pageNum",
"pageSize",
"includeProducts",
*filters.keys(),
}
for key, val in request.query_params.multi_items():
if key in skip_keys or val is None or str(val).strip() == "":
continue
filters[key] = val
rows, total = list_contracts(
db,
tenant_no,
user_info=user_info,
page=query.pageNum,
page_size=query.pageSize,
filters=filters,
current_user_id=user_id,
include_products=includeProducts,
)
tp = total_pages(total, query.pageSize)
return success_response(
{
"list": rows,
"rows": rows,
"total": total,
"pageNum": query.pageNum,
"pageSize": query.pageSize,
"totalPages": tp,
}
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/column-facet-values")
async def contract_column_facet_values(
body: ContractColumnFacetBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""合同列表列头可选值(编号/名称/客户去重;Excel 级联上下文)"""
try:
from app.services.crm.facet_context import facet_filter_kwargs_from_body
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
filter_kwargs = facet_filter_kwargs_from_body(body, body.field)
rows = list_contract_column_facet_values(
db,
tenant_no,
field=body.field,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
user_info=user_info,
filter_kwargs=filter_kwargs,
)
return success_response({"list": rows})
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract")
@oper_log(title="CRM合同管理", business_type=1, summary="新增合同【{contractName}】")
async def contract_add(
body: ContractCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
detail = create_contract(
db,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(detail["id"], message="新增成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract")
@oper_log(title="CRM合同管理", business_type=2, summary="修改合同【{contractName}】")
async def contract_edit(
body: ContractUpdateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
data = body.model_dump(by_alias=True, exclude_unset=True)
contract_id = data.pop("id")
detail = update_contract(
db,
contract_id,
tenant_no=tenant_no,
data=data,
user_id=user_id,
dept_id=dept_id,
user_info=user_info,
)
return success_response(detail, message="修改成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.delete("/contract/{ids}")
@oper_log(title="CRM合同管理", business_type=3, path_param="ids", summary="删除合同")
async def contract_remove(
ids: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
id_list = [x.strip() for x in ids.split(",") if x.strip()]
soft_delete_contracts(db, id_list, tenant_no=tenant_no, user_info=user_info)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/submitApproval")
async def contract_submit_approval(
body: ContractSubmitBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
submit_contract_approval(
db,
body.id,
tenant_no=tenant_no,
approver_ids=body.approverIds,
remark=body.remark,
user_id=user_id,
dept_id=dept_id,
user_info=user_info,
)
return success_response(None, message="提交成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/batchSubmitApproval")
async def contract_batch_submit_approval(
body: ContractBatchSubmitBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
count = batch_submit_contract_approval(
db,
body.ids,
tenant_no=tenant_no,
approver_ids=body.approverIds,
remark=body.remark,
user_id=user_id,
dept_id=dept_id,
user_info=user_info,
)
return success_response(count, message="批量提交完成")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/withdrawApproval")
async def contract_withdraw_approval(
body: ContractWithdrawBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
withdraw_contract_approval(
db,
body.id,
tenant_no=tenant_no,
remark=body.remark,
user_id=user_id,
user_info=user_info,
)
return success_response(None, message="撤回成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/startExecute")
async def contract_start_execute(
body: ContractStatusBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
start_execute(db, body.id, tenant_no=tenant_no, remark=body.remark, user_id=user_id)
return success_response(None, message="操作成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/finish")
async def contract_finish(
body: ContractStatusBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
finish_contract(db, body.id, tenant_no=tenant_no, remark=body.remark, user_id=user_id)
return success_response(None, message="操作成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/invalid")
@oper_log(title="CRM合同管理", business_type=2, summary="作废合同")
async def contract_invalid(
body: ContractInvalidBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
invalid_contract(
db,
body.id,
tenant_no=tenant_no,
invalid_reason=body.invalidReason,
remark=body.remark,
user_id=user_id,
user_info=user_info,
)
return success_response(None, message="作废成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/restore")
@oper_log(title="CRM合同管理", business_type=2, summary="作废恢复")
async def contract_restore(
body: ContractStatusBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
restore_contract(
db,
body.id,
tenant_no=tenant_no,
user_id=user_id,
user_info=user_info,
)
return success_response(None, message="已恢复为草稿")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/saveTemplate")
async def contract_save_template(
body: ContractTemplateSaveBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
save_template(
db,
body.id,
body.templateContent,
tenant_no=tenant_no,
settlement_clause_drafts=body.settlementClauseDrafts,
user_info=user_info,
)
return success_response(None, message="保存成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/getTemplate/{contract_id}")
async def contract_get_template(
contract_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
content = get_template(db, contract_id, tenant_no=tenant_no, user_info=user_info)
return success_response(content or "", message="获取模板成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/uploadFile")
async def contract_upload_file(
body: ContractUploadFileBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
upload_file(db, body.id, body.fileUrl, tenant_no=tenant_no)
return success_response(None, message="上传成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/uploadAttachments")
async def contract_upload_attachments(
body: ContractUploadAttachmentsBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
# attachments 显式传入(含 [])表示整表覆盖保存,允许清空扫描件
if body.attachments is not None:
upload_attachments_with_category(
db, body.id, body.attachments, tenant_no=tenant_no,
user_info=user_info,
)
elif body.ossIds:
upload_attachments(db, body.id, body.ossIds, tenant_no=tenant_no)
else:
return error_response(400, "附件参数不能为空")
return success_response(None, message="上传成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/export")
@oper_log(title="CRM合同管理", business_type=5, summary="导出合同列表")
async def contract_export(
body: ContractExportBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
list_body = body or ContractExportBody()
filters = list_body.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
rows = export_contracts(db, tenant_no, filters=filters)
rows = _filter_export_rows_by_ids(rows, getattr(list_body, "ids", None))
export_cols = filter_export_columns(CONTRACT_EXPORT_COLUMNS, getattr(list_body, "columns", None))
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="合同",
columns=export_cols,
rows=rows,
filename_stem=f"合同_{datetime.now().strftime('%Y%m%d%H%M%S')}",
include_legacy_filename=False,
)
except ExportValidationError as e:
return error_response(400, str(e))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/statistics/overview")
async def contract_statistics_overview(
ownerUserId: Optional[str] = None,
beginTime: Optional[str] = None,
endTime: Optional[str] = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
req = ContractStatisticsOverviewQuery(
ownerUserId=ownerUserId,
beginTime=beginTime,
endTime=endTime,
)
data = statistics_overview(
db,
tenant_no,
owner_user_id=req.ownerUserId,
begin_time=req.beginTime,
end_time=req.endTime,
user_info=user_info,
)
return success_response(data)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/statistics/status")
async def contract_statistics_status(
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
return success_response(statistics_by_status(db, tenant_no))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/statistics/type")
async def contract_statistics_type(
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
return success_response(statistics_by_type(db, tenant_no))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/statistics/trend")
async def contract_statistics_trend(
type: str = Query("month"),
beginTime: Optional[str] = None,
endTime: Optional[str] = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
req = ContractStatisticsTrendQuery(type=type, beginTime=beginTime, endTime=endTime)
data = statistics_trend(
db,
tenant_no,
period_type=req.type or "month",
begin_time=req.beginTime,
end_time=req.endTime,
user_info=user_info,
)
return success_response(data)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/statistics/expiring")
async def contract_statistics_expiring(
days: int = Query(30, ge=1),
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
rows = query_expiring(db, tenant_no, days=days)
return success_response(rows)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/renew/{parent_id}")
async def contract_renew(
parent_id: str,
body: ContractRenewBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
new_id = renew_contract(
db,
parent_id,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(new_id, message="续签成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/createFromQuote/{quote_id}")
async def contract_create_from_quote(
quote_id: str,
body: ContractCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
contract_id = create_from_quote(
db,
quote_id,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(contract_id, message="创建成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/createFromOpportunity/{opportunity_id}")
async def contract_create_from_opportunity(
opportunity_id: str,
body: ContractCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
contract_id = create_from_opportunity(
db,
opportunity_id,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(contract_id, message="创建成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/sign")
async def contract_sign(
body: ContractSignBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
sign_contract(
db,
body.id,
tenant_no=tenant_no,
actual_sign_date=body.actualSignDate,
contract_file=body.contractFile,
remark=body.remark or "",
user_id=user_id,
user_info=user_info,
)
return success_response(None, message="签订成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/batch/assign")
async def contract_batch_assign(
body: ContractBatchAssignBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
count = batch_assign_owner(
db,
body.ids,
tenant_no=tenant_no,
owner_user_id=body.ownerUserId,
remark=body.remark or "",
user_id=user_id,
user_info=user_info,
)
return success_response(count, message="分配成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/download/{contract_id}")
async def contract_download(
contract_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
file_path = download_contract_pdf(db, contract_id, tenant_no=tenant_no)
return success_response(file_path)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval")
async def contract_approval_by_contract_id(
body: ContractApprovalActionBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_id = _user.get("user_id", "") or _user.get("id", "")
approve_contract_by_contract_id(
db,
body.id,
approval_result=body.approvalResult,
approval_opinion=body.approvalOpinion or "",
attachments=body.attachments or "",
remark=body.remark or "",
user_id=user_id,
)
db.commit()
return success_response(None, message="审批成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/approval/flow/{contract_id}")
async def contract_approval_flow(
contract_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
rows = list_contract_approvals(db, contract_id, tenant_no=tenant_no)
return success_response(rows)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract-approver-setting/get")
async def contract_approver_setting_get(
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
data = get_contract_approver_setting(db, tenant_no=tenant_no)
return success_response(data or {"approverIds": [], "status": "0"})
except Exception as e:
return error_response(500, str(e))
@router.post("/contract-approver-setting/save")
async def contract_approver_setting_save(
body: ContractApproverSettingSaveBody,
_user: dict = Depends(require_menu_code("system:approverSetting")),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
data = save_contract_approver_setting(
db,
tenant_no=tenant_no,
approver_ids=body.approverIds or [],
status=body.status or "0",
user_id=user_id,
dept_id=dept_id,
)
return success_response(data, message="保存成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/{contract_id}")
async def contract_detail(
contract_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
detail = get_contract_detail(
db,
contract_id,
tenant_no=tenant_no,
current_user_id=user_id,
user_info=user_info,
)
return success_response(detail)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
+839
View File
@@ -0,0 +1,839 @@
"""CRM 合同子模块路由 — 变更/模板/审批独立页"""
from __future__ import annotations
from datetime import datetime
from typing import Optional
from fastapi import Depends, Query, Request
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin
from app.core.response import error_response, success_response
from app.core.tenant_context import get_tenant_no
from app.crud.crm.data_scope_helpers import crm_user_info
from app.crud.crm.contract import (
create_contract_change,
create_contract_template,
export_contract_changes,
export_contract_templates,
execute_change,
get_contract_change_detail,
get_contract_template_detail,
list_contract_change_column_facet_values,
list_contract_changes,
list_contract_template_column_facet_values,
list_contract_templates,
soft_delete_contract_changes,
soft_delete_contract_templates,
submit_change_approval,
toggle_contract_template_active,
total_pages,
update_contract_change,
update_contract_template,
withdraw_change,
)
from app.crud.crm.contract_approval import (
approve_pass,
approve_reject,
approve_transfer,
export_contract_approvals,
get_contract_approval_detail,
list_contract_approval_column_facet_values,
list_contract_approvals_page,
refresh_approver_names,
)
from app.schemas.crm.contract import (
ContractApprovalColumnFacetBody,
ContractApprovalExportBody,
ContractApprovalListQuery,
ContractApprovalPassBody,
ContractApprovalRefreshNamesBody,
ContractApprovalRejectBody,
ContractApprovalTransferBody,
ContractChangeColumnFacetBody,
ContractChangeCreateBody,
ContractChangeExportBody,
ContractChangeListQuery,
ContractChangeSubmitBody,
ContractChangeUpdateBody,
ContractTemplateColumnFacetBody,
ContractTemplateCreateBody,
ContractTemplateExportBody,
ContractTemplateListQuery,
ContractTemplateUpdateBody,
)
from app.utils.crm_export_columns import (
CONTRACT_APPROVAL_EXPORT_COLUMNS,
CONTRACT_CHANGE_EXPORT_COLUMNS,
CONTRACT_TEMPLATE_EXPORT_COLUMNS,
)
from app.utils.excel_export import (
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
from app.api.crm import _filter_export_rows_by_ids
def register_contract_sub_routes(router):
# --- 合同变更 ---
@router.get("/contract/change/list")
async def contract_change_list(
request: Request,
pageNum: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=500),
contractId: Optional[str] = None,
contractNo: Optional[str] = None,
contractName: Optional[str] = None,
changeType: Optional[str] = None,
approvalStatus: Optional[str] = None,
beginTime: Optional[str] = None,
endTime: Optional[str] = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
query = ContractChangeListQuery(
pageNum=pageNum,
pageSize=pageSize,
contractId=contractId,
contractNo=contractNo,
contractName=contractName,
changeType=changeType,
approvalStatus=approvalStatus,
beginTime=beginTime,
endTime=endTime,
)
filters = query.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
if query.model_extra:
filters.update(
{
k: v
for k, v in query.model_extra.items()
if v is not None and str(v).strip() != ""
}
)
# 列头漏斗等未在签名中声明的 query 参数一并透传
skip_keys = {"pageNum", "pageSize", *filters.keys()}
for key, val in request.query_params.multi_items():
if key in skip_keys or val is None or str(val).strip() == "":
continue
filters[key] = val
rows, total = list_contract_changes(
db,
tenant_no,
user_info=user_info,
page=query.pageNum,
page_size=query.pageSize,
filters=filters,
)
return success_response(
{
"list": rows,
"rows": rows,
"total": total,
"pageNum": query.pageNum,
"pageSize": query.pageSize,
"totalPages": total_pages(total, query.pageSize),
}
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/change/column-facet-values")
async def contract_change_column_facet_values(
body: ContractChangeColumnFacetBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""合同变更列表列头可选值(合同编号/名称去重;Excel 级联上下文)"""
try:
from app.services.crm.facet_context import facet_filter_kwargs_from_body
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
filter_kwargs = facet_filter_kwargs_from_body(body, body.field)
rows = list_contract_change_column_facet_values(
db,
tenant_no,
field=body.field,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
user_info=user_info,
filter_kwargs=filter_kwargs,
)
return success_response({"list": rows})
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/change/{change_id}")
async def contract_change_detail(
change_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
detail = get_contract_change_detail(db, change_id, tenant_no=tenant_no, user_info=user_info)
return success_response(detail)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/change")
async def contract_change_add(
body: ContractChangeCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
detail = create_contract_change(
db,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(detail["id"], message="新增成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/change")
async def contract_change_edit(
body: ContractChangeUpdateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
data = body.model_dump(by_alias=True)
change_id = data.pop("id")
detail = update_contract_change(
db,
change_id,
tenant_no=tenant_no,
data=data,
user_id=user_id,
user_info=user_info,
)
return success_response(detail, message="修改成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.delete("/contract/change/{ids}")
async def contract_change_remove(
ids: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
id_list = [x.strip() for x in ids.split(",") if x.strip()]
soft_delete_contract_changes(db, id_list, tenant_no=tenant_no, user_info=user_info)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/change/submitApproval")
async def contract_change_submit_approval(
body: ContractChangeSubmitBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
submit_change_approval(
db,
body.id,
tenant_no=tenant_no,
approver_ids=body.approverIds,
remark=body.remark or "",
user_id=user_id,
)
return success_response(None, message="提交成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/change/withdraw/{change_id}")
async def contract_change_withdraw(
change_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
withdraw_change(db, change_id, tenant_no=tenant_no, user_id=user_id)
return success_response(None, message="撤回成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/change/execute/{change_id}")
async def contract_change_execute(
change_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
execute_change(db, change_id, tenant_no=tenant_no, user_id=user_id)
return success_response(None, message="执行成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/change/export")
async def contract_change_export(
body: ContractChangeExportBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
list_body = body or ContractChangeExportBody()
filters = list_body.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
if list_body.model_extra:
filters.update(
{
k: v
for k, v in list_body.model_extra.items()
if v is not None and str(v).strip() != ""
}
)
rows = export_contract_changes(db, tenant_no, filters=filters)
rows = _filter_export_rows_by_ids(rows, getattr(list_body, "ids", None) or getattr(body, "ids", None))
export_cols = filter_export_columns(CONTRACT_CHANGE_EXPORT_COLUMNS, getattr(list_body, "columns", None) or getattr(body, "columns", None))
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="合同变更记录",
columns=export_cols,
rows=rows,
filename_stem=f"合同变更_{datetime.now().strftime('%Y%m%d%H%M%S')}",
include_legacy_filename=False,
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
# --- 合同模板库 ---
@router.get("/contract/template/list")
async def contract_template_list(
request: Request,
pageNum: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=500),
templateNo: Optional[str] = None,
templateName: Optional[str] = None,
templateType: Optional[str] = None,
isActive: Optional[int] = None,
beginTime: Optional[str] = None,
endTime: Optional[str] = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
query = ContractTemplateListQuery(
pageNum=pageNum,
pageSize=pageSize,
templateNo=templateNo,
templateName=templateName,
templateType=templateType,
isActive=isActive,
beginTime=beginTime,
endTime=endTime,
)
filters = query.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
if query.model_extra:
filters.update(
{
k: v
for k, v in query.model_extra.items()
if v is not None and str(v).strip() != ""
}
)
skip_keys = {"pageNum", "pageSize", *filters.keys()}
for key, val in request.query_params.multi_items():
if key in skip_keys or val is None or str(val).strip() == "":
continue
filters[key] = val
rows, total = list_contract_templates(
db,
tenant_no,
user_info=user_info,
page=query.pageNum,
page_size=query.pageSize,
filters=filters,
)
return success_response(
{
"list": rows,
"rows": rows,
"total": total,
"pageNum": query.pageNum,
"pageSize": query.pageSize,
"totalPages": total_pages(total, query.pageSize),
}
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/template/column-facet-values")
async def contract_template_column_facet_values(
body: ContractTemplateColumnFacetBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""合同模板列表列头可选值(编号/名称去重;Excel 级联上下文)"""
try:
from app.services.crm.facet_context import facet_filter_kwargs_from_body
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
filter_kwargs = facet_filter_kwargs_from_body(body, body.field)
rows = list_contract_template_column_facet_values(
db,
tenant_no,
field=body.field,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
user_info=user_info,
filter_kwargs=filter_kwargs,
)
return success_response({"list": rows})
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/template/{template_id}")
async def contract_template_detail(
template_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
detail = get_contract_template_detail(db, template_id, tenant_no=tenant_no)
return success_response(detail)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/template")
async def contract_template_add(
body: ContractTemplateCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
detail = create_contract_template(
db,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(detail["id"], message="新增成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/template")
async def contract_template_edit(
body: ContractTemplateUpdateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
data = body.model_dump(by_alias=True)
template_id = data.pop("id")
detail = update_contract_template(
db,
template_id,
tenant_no=tenant_no,
data=data,
user_id=user_id,
user_info=user_info,
)
return success_response(detail, message="修改成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.delete("/contract/template/{ids}")
async def contract_template_remove(
ids: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
id_list = [x.strip() for x in ids.split(",") if x.strip()]
soft_delete_contract_templates(db, id_list, tenant_no=tenant_no, user_info=user_info)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/template/enable/{template_id}")
async def contract_template_enable(
template_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
toggle_contract_template_active(
db, template_id, tenant_no=tenant_no, is_active=1, user_id=user_id
)
return success_response(None, message="启用成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.put("/contract/template/disable/{template_id}")
async def contract_template_disable(
template_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
toggle_contract_template_active(
db, template_id, tenant_no=tenant_no, is_active=0, user_id=user_id
)
return success_response(None, message="停用成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/template/export")
async def contract_template_export(
body: ContractTemplateExportBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
list_body = body or ContractTemplateExportBody()
filters = list_body.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
if list_body.model_extra:
filters.update(
{
k: v
for k, v in list_body.model_extra.items()
if v is not None and str(v).strip() != ""
}
)
rows = export_contract_templates(db, tenant_no, filters=filters)
rows = _filter_export_rows_by_ids(rows, getattr(list_body, "ids", None) or getattr(body, "ids", None))
export_cols = filter_export_columns(CONTRACT_TEMPLATE_EXPORT_COLUMNS, getattr(list_body, "columns", None) or getattr(body, "columns", None))
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="合同模板",
columns=export_cols,
rows=rows,
filename_stem=f"合同模板_{datetime.now().strftime('%Y%m%d%H%M%S')}",
include_legacy_filename=False,
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
# --- 审批记录独立页 ---
@router.get("/contract/approval/list")
async def contract_approval_list(
request: Request,
pageNum: int = Query(1, ge=1),
pageSize: int = Query(10, ge=1, le=500),
contractId: Optional[str] = None,
contractNo: Optional[str] = None,
contractName: Optional[str] = None,
approverName: Optional[str] = None,
approvalResult: Optional[str] = None,
beginTime: Optional[str] = None,
endTime: Optional[str] = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
query = ContractApprovalListQuery(
pageNum=pageNum,
pageSize=pageSize,
contractId=contractId,
contractNo=contractNo,
contractName=contractName,
approverName=approverName,
approvalResult=approvalResult,
beginTime=beginTime,
endTime=endTime,
)
filters = query.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
if query.model_extra:
filters.update(
{
k: v
for k, v in query.model_extra.items()
if v is not None and str(v).strip() != ""
}
)
skip_keys = {"pageNum", "pageSize", *filters.keys()}
for key, val in request.query_params.multi_items():
if key in skip_keys or val is None or str(val).strip() == "":
continue
filters[key] = val
rows, total = list_contract_approvals_page(
db,
tenant_no,
page=query.pageNum,
page_size=query.pageSize,
filters=filters,
)
return success_response(
{
"list": rows,
"rows": rows,
"total": total,
"pageNum": query.pageNum,
"pageSize": query.pageSize,
"totalPages": total_pages(total, query.pageSize),
}
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval/column-facet-values")
async def contract_approval_column_facet_values(
body: ContractApprovalColumnFacetBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""合同审批记录列头可选值(合同编号/名称去重;Excel 级联上下文)"""
try:
from app.services.crm.facet_context import facet_filter_kwargs_from_body
tenant_no = get_tenant_no(db, _user)
filter_kwargs = facet_filter_kwargs_from_body(body, body.field)
rows = list_contract_approval_column_facet_values(
db,
tenant_no,
field=body.field,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
filter_kwargs=filter_kwargs,
)
return success_response({"list": rows})
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.get("/contract/approval/{approval_id}")
async def contract_approval_detail(
approval_id: str,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
detail = get_contract_approval_detail(db, approval_id, tenant_no=tenant_no)
return success_response(detail)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval/pass")
async def contract_approval_pass(
body: ContractApprovalPassBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
user_id = _user.get("user_id", "") or _user.get("id", "")
approve_pass(db, body.id, approval_opinion=body.approvalOpinion or "", user_id=user_id)
db.commit()
return success_response(None, message="审批通过")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval/reject")
async def contract_approval_reject(
body: ContractApprovalRejectBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
user_id = _user.get("user_id", "") or _user.get("id", "")
approve_reject(db, body.id, approval_opinion=body.approvalOpinion, user_id=user_id)
db.commit()
return success_response(None, message="已驳回")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval/transfer")
async def contract_approval_transfer(
body: ContractApprovalTransferBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
user_id = _user.get("user_id", "") or _user.get("id", "")
approve_transfer(
db,
body.id,
target_approver_id=body.targetApproverId,
transfer_reason=body.transferReason,
user_id=user_id,
)
db.commit()
return success_response(None, message="转审成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval/export")
async def contract_approval_export(
body: ContractApprovalExportBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
list_body = body or ContractApprovalExportBody()
filters = list_body.model_dump(
by_alias=True,
exclude={"pageNum", "pageSize"},
exclude_none=True,
)
if list_body.model_extra:
filters.update(
{
k: v
for k, v in list_body.model_extra.items()
if v is not None and str(v).strip() != ""
}
)
rows = export_contract_approvals(db, tenant_no, filters=filters)
rows = _filter_export_rows_by_ids(rows, getattr(list_body, "ids", None) or getattr(body, "ids", None))
export_cols = filter_export_columns(CONTRACT_APPROVAL_EXPORT_COLUMNS, getattr(list_body, "columns", None) or getattr(body, "columns", None))
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="合同审批记录",
columns=export_cols,
rows=rows,
filename_stem=f"合同审批_{datetime.now().strftime('%Y%m%d%H%M%S')}",
include_legacy_filename=False,
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/contract/approval/refreshNames")
async def contract_approval_refresh_names(
body: ContractApprovalRefreshNamesBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
req = body or ContractApprovalRefreshNamesBody()
count = refresh_approver_names(db, contract_id=req.contractId)
db.commit()
return success_response(count)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
+866
View File
@@ -0,0 +1,866 @@
"""CRM 报价单 API 路由 — 挂接到 crm.router"""
from __future__ import annotations
from datetime import datetime
from fastapi import Depends
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.menu_guard import require_admin_or_super_admin, require_menu_code
from app.core.response import error_response, success_response
from app.core.tenant_context import get_tenant_no
from app.crud.crm.contact import list_contacts_by_customer
from app.crud.crm.customer import get_customer
from app.crud.crm.data_scope_helpers import crm_user_info, ensure_crm_owner_row_in_scope
from app.crud.crm.quote import (
accept_quote,
create_new_version,
create_quote,
generate_pdf,
generate_share,
get_quote_detail,
get_template,
invalid_quote,
list_quote_column_facet_values,
list_quotes,
query_versions,
reject_quote,
save_template,
soft_delete_quotes,
statistics_overview,
statistics_status,
statistics_trend,
submit_quote,
to_contract,
total_pages as quote_total_pages,
update_quote,
)
from app.crud.crm.quote_approver_setting import get_setting, save_setting
from app.crud.crm.quote_approval import (
approve_quote,
list_quote_approvals,
refresh_approver_names,
withdraw_approval,
)
from app.crud.crm.quote_product import (
insert_quote_product,
list_quote_products,
soft_delete_quote_products,
update_quote_product,
)
from app.crud.crm.quote_share_log import list_share_logs, share_log_statistics
from app.schemas.crm.quote_approver_setting import QuoteApproverSettingSaveBody
from app.schemas.crm.quote import (
QuoteAcceptBody,
QuoteApprovalApproveBody,
QuoteApprovalListBody,
QuoteApprovalRefreshNamesBody,
QuoteApprovalWithdrawBody,
QuoteColumnFacetBody,
QuoteCreateBody,
QuoteDeleteBody,
QuoteDetailBody,
QuoteInvalidBody,
QuoteListBody,
QuoteNewVersionBody,
QuotePdfBody,
QuoteProductCreateBody,
QuoteProductDeleteBody,
QuoteProductListBody,
QuoteProductUpdateBody,
QuoteRejectBody,
QuoteShareGenerateBody,
QuoteShareLogListBody,
QuoteShareLogStatisticsBody,
QuoteStatisticsOverviewBody,
QuoteStatisticsTrendBody,
QuoteSubmitBody,
QuoteTemplateGetBody,
QuoteTemplateSaveBody,
QuoteToContractBody,
QuoteUpdateBody,
QuoteVersionsBody,
)
from app.utils.crm_export_columns import QUOTE_EXPORT_COLUMNS
from app.utils.excel_export import (
EXPORT_MAX_ROWS,
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
from app.api.crm import _filter_export_rows_by_ids
def _mobile_quote_contact_snapshot(db, body, *, tenant_no, user_info):
"""移动保存先校验归属和权限,再将可信联系人快照交给原更新事务。"""
current = get_quote_detail(db, body.id, tenant_no=tenant_no, user_info=user_info)
customer_id = body.customerId
customer = get_customer(db, customer_id)
if not customer or customer.tenant_no != tenant_no:
raise ValueError("客户不存在")
ensure_crm_owner_row_in_scope(
db, customer, user_info, tenant_no, message="无权访问该客户"
)
if "contactId" in body.model_fields_set:
contact_id = (body.contactId or "").strip()
elif customer_id == str(current.get("customerId") or ""):
contact_id = str(current.get("contactId") or "").strip()
else:
# 更换客户却未选联系人时,不能继续携带上一个客户的联系人。
contact_id = ""
if not contact_id:
return {"id": "", "contactName": "", "mobile": "", "email": ""}
# 客户权限已在清空分支前统一校验,此处只查询该租户、客户的有效联系人。
contacts = list_contacts_by_customer(db, tenant_no, customer_id)
contact = next((row for row in contacts if str(row["id"]) == contact_id), None)
if not contact:
raise ValueError("所选联系人不存在或不属于当前客户")
return {
"id": contact_id,
"contactName": contact.get("contactName") or "",
"mobile": contact.get("mobile") or "",
"email": contact.get("email") or "",
}
def register_quote_routes(router):
@router.post("/quote/list")
async def quote_list(
body: QuoteListBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
list_body = body or QuoteListBody()
user_id = _user.get("user_id", "") or _user.get("id", "")
rows, total = list_quotes(
db,
tenant_no,
user_info=user_info,
page=list_body.page,
page_size=list_body.pageSize,
filters=list_body.model_dump(by_alias=True, exclude={"page", "pageSize"}),
current_user_id=user_id,
)
tp = quote_total_pages(total, list_body.pageSize)
return success_response(
{
"list": rows,
"rows": rows,
"total": total,
"page": list_body.page,
"pageSize": list_body.pageSize,
"totalPages": tp,
}
)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/column-facet-values")
async def quote_column_facet_values(
body: QuoteColumnFacetBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
"""报价列表列头可选值(单号/客户去重;Excel 级联上下文)"""
try:
from app.services.crm.facet_context import facet_filter_kwargs_from_body
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
filter_kwargs = facet_filter_kwargs_from_body(body, body.field)
rows = list_quote_column_facet_values(
db,
tenant_no,
field=body.field,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
user_info=user_info,
filter_kwargs=filter_kwargs,
)
return success_response({"list": rows})
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/detail")
async def quote_detail(
body: QuoteDetailBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
detail = get_quote_detail(db, body.id, tenant_no=tenant_no, user_info=user_info)
return success_response(detail)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/add")
async def quote_add(
body: QuoteCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
detail = create_quote(
db,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
return success_response(detail, message="新增成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/update")
async def quote_update(
body: QuoteUpdateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
data = body.model_dump(by_alias=True, exclude_unset=True)
quote_id = data.pop("id")
detail = update_quote(
db,
quote_id,
tenant_no=tenant_no,
data=data,
user_id=user_id,
dept_id=dept_id,
user_info=user_info,
)
return success_response(detail, message="修改成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/mobile-update")
async def quote_mobile_update(
body: QuoteUpdateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
snapshot = _mobile_quote_contact_snapshot(
db, body, tenant_no=tenant_no, user_info=user_info
)
data = body.model_dump(by_alias=True, exclude_unset=True)
quote_id = data.pop("id")
data["contactId"] = snapshot["id"]
detail = update_quote(
db,
quote_id,
tenant_no=tenant_no,
data=data,
user_id=_user.get("user_id", "") or _user.get("id", ""),
dept_id=_user.get("dept_id", "") or _user.get("create_dept_id", "") or "",
user_info=user_info,
canonical_contact_snapshot=snapshot,
)
return success_response(detail, message="修改成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/delete")
async def quote_delete(
body: QuoteDeleteBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
soft_delete_quotes(db, body.ids, tenant_no=tenant_no, user_info=user_info)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/submit")
async def quote_submit(
body: QuoteSubmitBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
submit_quote(
db,
body.id,
tenant_no=tenant_no,
approver_ids=body.approverIds,
remark=body.remark,
user_info=user_info,
)
return success_response(None, message="提交成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/saveTemplate")
async def quote_save_template(
body: QuoteTemplateSaveBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
save_template(db, body.id, body.templateContent, tenant_no=tenant_no)
return success_response(None, message="保存成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/getTemplate")
async def quote_get_template(
body: QuoteTemplateGetBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
content = get_template(db, body.id, tenant_no=tenant_no, user_info=user_info)
return success_response(content or "")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/generatePdf")
async def quote_generate_pdf(
body: QuotePdfBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
pdf_url = generate_pdf(db, body.id, tenant_no=tenant_no)
return success_response(pdf_url)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/generateShare")
async def quote_generate_share(
body: QuoteShareGenerateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
link = generate_share(
db,
body.id,
tenant_no=tenant_no,
validity_days=body.validityDays,
password=body.password or "",
user_info=user_info,
)
return success_response(link)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/accept")
async def quote_accept(
body: QuoteAcceptBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
accept_quote(db, body.id, tenant_no=tenant_no, remark=body.remark)
return success_response(None, message="操作成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/reject")
async def quote_reject(
body: QuoteRejectBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
reject_quote(
db,
body.id,
tenant_no=tenant_no,
reject_reason=body.rejectReason,
remark=body.remark,
user_info=user_info,
)
return success_response(None, message="操作成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/toContract")
async def quote_to_contract(
body: QuoteToContractBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
contract_id = to_contract(
db,
body.id,
tenant_no=tenant_no,
contract_no=body.contractNo,
contract_title=body.contractTitle,
sign_date=body.signDate,
start_date=body.startDate,
end_date=body.endDate,
user_id=user_id,
dept_id=dept_id,
user_info=user_info,
)
return success_response(contract_id)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/newVersion")
async def quote_new_version(
body: QuoteNewVersionBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
new_id = create_new_version(
db,
body.id,
tenant_no=tenant_no,
version=body.version,
remark=body.remark,
user_id=user_id,
dept_id=dept_id,
user_info=user_info,
)
return success_response(new_id)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/versions")
async def quote_versions(
body: QuoteVersionsBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
rows = query_versions(db, body.quoteNo, tenant_no=tenant_no)
return success_response(rows)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/invalid")
async def quote_invalid(
body: QuoteInvalidBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
invalid_quote(
db,
body.id,
tenant_no=tenant_no,
invalid_reason=body.invalidReason or "",
remark=body.remark or "",
user_info=user_info,
)
return success_response(None, message="作废成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/export")
async def quote_export(
body: QuoteListBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
list_body = body or QuoteListBody()
rows, _ = list_quotes(
db,
tenant_no,
user_info=user_info,
page=1,
page_size=EXPORT_MAX_ROWS,
filters=list_body.model_dump(by_alias=True, exclude={"page", "pageSize"}),
)
rows = _filter_export_rows_by_ids(rows, getattr(list_body, "ids", None))
export_cols = filter_export_columns(QUOTE_EXPORT_COLUMNS, getattr(list_body, "columns", None))
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="报价单",
columns=export_cols,
rows=rows,
filename_stem=f"报价单_{datetime.now().strftime('%Y%m%d%H%M%S')}",
include_legacy_filename=False,
)
except ExportValidationError as e:
return error_response(400, str(e))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/statistics/overview")
async def quote_statistics_overview(
body: QuoteStatisticsOverviewBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
req = body or QuoteStatisticsOverviewBody()
data = statistics_overview(
db,
tenant_no,
owner_user_id=req.ownerUserId,
begin_time=req.beginTime,
end_time=req.endTime,
user_info=user_info,
)
return success_response(data)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/statistics/status")
async def quote_statistics_status(
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
return success_response(statistics_status(db, tenant_no))
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/statistics/trend")
async def quote_statistics_trend(
body: QuoteStatisticsTrendBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
req = body or QuoteStatisticsTrendBody()
data = statistics_trend(
db,
tenant_no,
period_type=req.type or "month",
begin_time=req.beginTime,
end_time=req.endTime,
user_info=user_info,
)
return success_response(data)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/product/list")
async def quote_product_list(
body: QuoteProductListBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
rows = list_quote_products(db, body.quoteId, tenant_no=tenant_no)
return success_response(rows)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/product/add")
async def quote_product_add(
body: QuoteProductCreateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
obj = insert_quote_product(
db,
tenant_no=tenant_no,
data=body.model_dump(by_alias=True),
user_id=user_id,
dept_id=dept_id,
)
from app.crud.crm.quote_product import product_row_to_dict
return success_response(product_row_to_dict(obj), message="新增成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/product/update")
async def quote_product_update(
body: QuoteProductUpdateBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
user_id = _user.get("user_id", "") or _user.get("id", "")
data = body.model_dump(by_alias=True)
line_id = data.pop("id")
obj = update_quote_product(
db,
line_id,
tenant_no=tenant_no,
data=data,
user_id=user_id,
user_info=user_info,
)
from app.crud.crm.quote_product import product_row_to_dict
return success_response(product_row_to_dict(obj), message="修改成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/product/delete")
async def quote_product_delete(
body: QuoteProductDeleteBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
soft_delete_quote_products(db, body.ids, tenant_no=tenant_no, user_info=user_info)
return success_response(None, message="删除成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/approval/list")
async def quote_approval_list(
body: QuoteApprovalListBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
rows = list_quote_approvals(db, body.quoteId, tenant_no=tenant_no)
return success_response(rows)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/approval/approve")
async def quote_approval_approve(
body: QuoteApprovalApproveBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_id = _user.get("user_id", "") or _user.get("id", "")
approve_quote(
db,
body.id,
tenant_no=tenant_no,
approval_result=body.approvalResult,
approval_opinion=body.approvalOpinion or "",
remark=body.remark or "",
user_id=user_id,
)
return success_response(None, message="审批成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/approval/withdraw")
async def quote_approval_withdraw(
body: QuoteApprovalWithdrawBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_id = _user.get("user_id", "") or _user.get("id", "")
withdraw_approval(
db,
body.quoteId,
tenant_no=tenant_no,
remark=body.remark or "",
user_id=user_id,
)
return success_response(None, message="撤回成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/approval/refreshNames")
async def quote_approval_refresh_names(
body: QuoteApprovalRefreshNamesBody = None,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
req = body or QuoteApprovalRefreshNamesBody()
count = refresh_approver_names(db, quote_id=req.quoteId)
return success_response(count)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/shareLog/list")
async def quote_share_log_list(
body: QuoteShareLogListBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
rows = list_share_logs(db, body.quoteId, tenant_no=tenant_no)
return success_response(rows)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote/shareLog/statistics")
async def quote_share_log_statistics(
body: QuoteShareLogStatisticsBody,
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_info = crm_user_info(_user)
stats = share_log_statistics(db, body.quoteId, tenant_no=tenant_no)
return success_response(stats)
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
@router.post("/quote-approver-setting/get")
async def quote_approver_setting_get(
_user: dict = Depends(require_admin_or_super_admin),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
data = get_setting(db, tenant_no=tenant_no)
# 无配置时默认「启用」,避免设置页首次打开落到「停用」导致保存后无法预填
return success_response(data or {"approverIds": [], "status": "0"})
except Exception as e:
return error_response(500, str(e))
@router.post("/quote-approver-setting/save")
async def quote_approver_setting_save(
body: QuoteApproverSettingSaveBody,
_user: dict = Depends(require_menu_code("system:approverSetting")),
db: Session = Depends(get_db),
):
try:
tenant_no = get_tenant_no(db, _user)
user_id = _user.get("user_id", "") or _user.get("id", "")
dept_id = _user.get("dept_id", "") or _user.get("create_dept_id", "") or ""
data = save_setting(
db,
tenant_no=tenant_no,
approver_ids=body.approverIds or [],
status=body.status or "0",
user_id=user_id,
dept_id=dept_id,
)
return success_response(data, message="保存成功")
except ValueError as e:
return error_response(400, str(e))
except Exception as e:
return error_response(500, str(e))
+16
View File
@@ -0,0 +1,16 @@
"""地磅 API 路由聚合 — REST 风格,协议对齐原 simple-dibang-xiaoshou。"""
from fastapi import APIRouter
from app.api.db import dashboard, inventory, plans, weighing
db_router = APIRouter(tags=["地磅管理"])
db_router.include_router(plans.router)
db_router.include_router(inventory.router)
db_router.include_router(weighing.router)
db_router.include_router(dashboard.router)
@db_router.get("/db/health")
def db_health():
"""P0 健康检查:验证 db 路由已挂载。"""
return {"status": "ok", "module": "db"}
+194
View File
@@ -0,0 +1,194 @@
from __future__ import annotations
from datetime import date
from typing import Dict
from fastapi import APIRouter, Depends
from sqlalchemy import func
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user
from app.core.tenant_context import get_tenant_no
from app.models.db_models import DbInboundOutbound, DbWeighingSlip
from app.schemas.db.dashboard import (
DashboardCargoStat,
DashboardPartnerCargoStat,
DashboardStats,
)
from app.services.db_data_scope import apply_db_scope
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
def _scoped_inventory_query(db: Session, tenant_no: str, user: DbUserContext):
query = db.query(DbInboundOutbound).filter(
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.tenant_no == tenant_no,
)
return apply_db_scope(query, DbInboundOutbound, user, db, tenant_no)
def _scoped_weighing_query(db: Session, tenant_no: str, user: DbUserContext):
query = db.query(DbWeighingSlip).filter(
DbWeighingSlip.is_voided == 0,
DbWeighingSlip.del_flag == 0,
DbWeighingSlip.tenant_no == tenant_no,
)
return apply_db_scope(query, DbWeighingSlip, user, db, tenant_no)
@router.get("/stats", response_model=DashboardStats)
def get_dashboard_stats(
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> DashboardStats:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
today = date.today()
today_inbound = float(
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == "入库",
)
.with_entities(func.coalesce(func.sum(DbInboundOutbound.quantity), 0))
.scalar()
or 0
)
today_outbound = float(
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == "出库",
)
.with_entities(func.coalesce(func.sum(DbInboundOutbound.quantity), 0))
.scalar()
or 0
)
abnormal_orders = int(
_scoped_weighing_query(db, tenant_no, user)
.with_entities(func.count(DbWeighingSlip.id))
.scalar()
or 0
)
return DashboardStats(
today_inbound=today_inbound,
today_outbound=today_outbound,
abnormal_orders=abnormal_orders,
)
@router.get("/inbound/by-cargo", response_model=list[DashboardCargoStat])
def get_inbound_by_cargo(
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> list[DashboardCargoStat]:
return _cargo_stats(db, user, business_type="入库")
@router.get("/inbound/by-partner-cargo", response_model=list[DashboardPartnerCargoStat])
def get_inbound_by_partner_cargo(
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> list[DashboardPartnerCargoStat]:
return _partner_cargo_stats(db, user, business_type="入库")
@router.get("/outbound/by-cargo", response_model=list[DashboardCargoStat])
def get_outbound_by_cargo(
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> list[DashboardCargoStat]:
return _cargo_stats(db, user, business_type="出库")
@router.get("/outbound/by-partner-cargo", response_model=list[DashboardPartnerCargoStat])
def get_outbound_by_partner_cargo(
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> list[DashboardPartnerCargoStat]:
return _partner_cargo_stats(db, user, business_type="出库")
def _weighing_actual_map(
db: Session, tenant_no: str, user: DbUserContext, inventory_ids: list[str]
) -> Dict[str, float]:
if not inventory_ids:
return {}
rows = (
_scoped_weighing_query(db, tenant_no, user)
.filter(DbWeighingSlip.inbound_outbound_id.in_(inventory_ids))
.all()
)
actual_map: Dict[str, float] = {}
for row in rows:
if not row.inbound_outbound_id:
continue
actual_map[row.inbound_outbound_id] = actual_map.get(row.inbound_outbound_id, 0.0) + (
float(row.net_weight or 0) / 1000.0
)
return actual_map
def _cargo_stats(db: Session, user: DbUserContext, *, business_type: str) -> list[DashboardCargoStat]:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
today = date.today()
inventories = (
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == business_type,
)
.all()
)
actual_map = _weighing_actual_map(db, tenant_no, user, [inv.id for inv in inventories])
agg: Dict[str, Dict[str, float]] = {}
for inv in inventories:
label = (inv.product or "").strip() or "未填写货物"
bucket = agg.setdefault(label, {"planned": 0.0, "actual": 0.0})
bucket["planned"] += float(inv.quantity or 0)
bucket["actual"] += actual_map.get(inv.id, 0.0)
return [
DashboardCargoStat(label=label, planned=values["planned"], actual=values["actual"])
for label, values in sorted(agg.items(), key=lambda item: item[1]["planned"], reverse=True)
]
def _partner_cargo_stats(
db: Session,
user: DbUserContext,
*,
business_type: str,
) -> list[DashboardPartnerCargoStat]:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
today = date.today()
inventories = (
_scoped_inventory_query(db, tenant_no, user)
.filter(
DbInboundOutbound.date == today,
DbInboundOutbound.business_type == business_type,
)
.all()
)
actual_map = _weighing_actual_map(db, tenant_no, user, [inv.id for inv in inventories])
agg: Dict[str, Dict[str, float]] = {}
for inv in inventories:
product = (inv.product or "").strip() or "未填写货物"
label = f"{inv.partner_company or ''} - {product}"
bucket = agg.setdefault(label, {"planned": 0.0, "actual": 0.0})
bucket["planned"] += float(inv.quantity or 0)
bucket["actual"] += actual_map.get(inv.id, 0.0)
return [
DashboardPartnerCargoStat(label=label, planned=values["planned"], actual=values["actual"])
for label, values in sorted(
agg.items(), key=lambda item: (item[0].split(" - ", 1)[0], -item[1]["planned"])
)
]
+849
View File
@@ -0,0 +1,849 @@
from typing import Any, List, Optional, Tuple
import re
from datetime import datetime
from types import SimpleNamespace
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user, get_db_current_user_optional
from app.core.delete_guard import assert_row_deletable_by_creator, user_info_from_context
from app.core.tenant_context import get_tenant_no
from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
from app.services.db.inventory_id import next_inbound_outbound_id
from app.services.db.inventory_list_filters import build_inventory_column_filters
from app.services.db.list_sort import order_inventory, parse_sort_params
from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
from app.schemas.db.inventory import (
CreateLinkForPlanPayload,
InboundOutboundCreate,
InboundOutboundListResponse,
InboundOutboundRead,
InboundOutboundUpdate,
)
from app.schemas.db.public_inventory import InventorySiteUrlRead
from app.schemas.db.plans import PurchasePlanRead
from app.schemas.db.weighing import WeighingSlipRead
from app.services.db.mappers import (
EMPTY_INVENTORY_DATE,
inventory_to_read,
is_empty_inventory_date,
load_user_display_name_map,
parse_date_str,
plan_to_read,
weighing_to_read,
)
from app.services.db.product_helpers import (
apply_product_snapshot_to_inventory,
resolve_crm_product,
)
from app.services.db_inventory_site_token import build_site_inventory_url, ensure_site_access_token
from app.utils.excel_export import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
router = APIRouter(prefix="/inventory", tags=["inventory"])
STATUS_THIRD_PARTY_FILL = "待三方填写"
_INVENTORY_REMARK_FIELD = "remarks"
def _base_query(db: Session, tenant_no: str):
return db.query(DbInboundOutbound).filter(
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
)
def _generate_batch_no(db: Session, tenant_no: str) -> str:
rows = (
db.query(DbInboundOutbound.batch_no)
.filter(
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.batch_no.like("CRKDH%"),
)
.all()
)
max_seq = 0
pattern = re.compile(r"^CRKDH(\d+)$")
for (batch_no,) in rows:
if batch_no:
match = pattern.match(batch_no)
if match:
max_seq = max(max_seq, int(match.group(1)))
return f"CRKDH{max_seq + 1:07d}"
def _resolve_tenant_no(
db: Session,
user: Optional[DbUserContext],
purchase_plan_id: Optional[str] = None,
) -> str:
if user:
return get_tenant_no(db, user.to_tenant_user_dict())
if purchase_plan_id:
plan = (
db.query(DbPurchasePlan)
.filter(DbPurchasePlan.id == purchase_plan_id, DbPurchasePlan.del_flag == 0)
.one_or_none()
)
if plan:
return plan.tenant_no
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="无法确定租户")
def _get_inventory_by_id(db: Session, inventory_id: str) -> DbInboundOutbound:
row = (
db.query(DbInboundOutbound)
.filter(DbInboundOutbound.id == inventory_id, DbInboundOutbound.del_flag == 0)
.one_or_none()
)
if row is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Inventory {inventory_id} not found",
)
return row
def _get_inventory(
db: Session, tenant_no: str, inventory_id: str, user: DbUserContext
) -> DbInboundOutbound:
row = (
_base_query(db, tenant_no)
.filter(DbInboundOutbound.id == inventory_id)
.one_or_none()
)
if row is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Inventory {inventory_id} not found",
)
assert_db_row_in_scope(db, row, DbInboundOutbound, user, tenant_no)
return row
def _apply_inventory_product_update(
db: Session, tenant_no: str, row: DbInboundOutbound, payload_dict: dict
) -> None:
if "product" in payload_dict and "product_id" not in payload_dict:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="请从 CRM 重新选择产品",
)
product_id = payload_dict.pop("product_id", None)
payload_dict.pop("product", None)
payload_dict.pop("specification", None)
if product_id is not None:
snapshot = resolve_crm_product(db, tenant_no, product_id)
apply_product_snapshot_to_inventory(row, snapshot)
def _normalize_plan_no(value: Any) -> Optional[str]:
if value is None:
return None
text = str(value).strip()
return text or None
def _pick_plan_for_inventory(plans: list, preferred_id: Optional[str]):
"""同一计划号命中多条时,优先已关联的计划,其次唯一产品。"""
if preferred_id:
for plan in plans:
if plan.id == preferred_id:
return plan
if len(plans) == 1:
return plans[0]
product_ids = {plan.product_id for plan in plans if plan.product_id}
if len(product_ids) == 1 and all(plan.product_id for plan in plans):
return plans[0]
return None
def _text(value: Any) -> str:
if value is None:
return ""
return str(value).strip()
def _enforce_inventory_plan_on_edit(db: Session, row: DbInboundOutbound, payload_dict: dict) -> None:
"""新增和编辑:有计划号则必须存在,且产品、往来单位、业务类型与计划一致;没有计划号不限制。"""
watched = ("plan_no", "product_id", "partner_company", "business_type")
if not any(key in payload_dict for key in watched):
return
if "plan_no" in payload_dict:
plan_no = _normalize_plan_no(payload_dict.get("plan_no"))
payload_dict["plan_no"] = plan_no
else:
plan_no = _normalize_plan_no(row.plan_no)
if not plan_no:
if "plan_no" in payload_dict:
payload_dict["purchase_plan_id"] = None
return
plans = (
db.query(DbPurchasePlan)
.filter(
DbPurchasePlan.tenant_no == row.tenant_no,
DbPurchasePlan.del_flag == 0,
DbPurchasePlan.plan_no == plan_no,
)
.all()
)
if not plans:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="计划号不存在")
preferred_id = payload_dict.get("purchase_plan_id") or row.purchase_plan_id
plan = _pick_plan_for_inventory(plans, preferred_id)
if plan is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="计划号对应多条计划,无法确定产品",
)
if not plan.product_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="该计划未关联产品,请先编辑计划并选择产品",
)
submitted_product_id = (
payload_dict.get("product_id") if "product_id" in payload_dict else row.product_id
)
if submitted_product_id != plan.product_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="有计划号时,产品只能选择该计划的产品",
)
submitted_partner = (
_text(payload_dict.get("partner_company"))
if "partner_company" in payload_dict
else _text(row.partner_company)
)
if submitted_partner != _text(plan.customer_name):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="有计划号时,往来单位必须与该计划一致",
)
submitted_business_type = (
_text(payload_dict.get("business_type"))
if "business_type" in payload_dict
else _text(row.business_type)
)
if submitted_business_type != _text(plan.business_type):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="有计划号时,业务类型必须与该计划一致",
)
payload_dict["plan_no"] = (plan.plan_no or "").strip() or plan_no
payload_dict["product_id"] = plan.product_id
payload_dict["partner_company"] = _text(plan.customer_name)
payload_dict["business_type"] = _text(plan.business_type)
payload_dict["purchase_plan_id"] = plan.id
def _apply_inventory_update(row: DbInboundOutbound, payload_dict: dict) -> None:
for key, value in payload_dict.items():
if key == _INVENTORY_REMARK_FIELD:
if isinstance(value, str):
value = value.strip()
row.remark = value
continue
if key == "date":
if value is None or (isinstance(value, str) and not value.strip()):
row.date = EMPTY_INVENTORY_DATE
else:
row.date = parse_date_str(str(value)) or EMPTY_INVENTORY_DATE
continue
if isinstance(value, str):
value = value.strip()
setattr(row, key, value)
def _maybe_promote_third_party_status(row: DbInboundOutbound) -> None:
if row.status != STATUS_THIRD_PARTY_FILL:
return
has_date = not is_empty_inventory_date(row.date)
has_qty = row.quantity is not None and row.quantity != 0
has_vehicle = bool(row.vehicle_no and row.vehicle_no.strip())
if has_date and has_qty and has_vehicle:
row.status = "待入库" if row.business_type == "入库" else "待出库"
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _filters_from_params(params: dict) -> list:
return build_inventory_column_filters(
plan_no=_param_get(params, "planNo", "plan_no"),
plan_no_in=_param_get(params, "planNoIn", "plan_no_in"),
batch_no=_param_get(params, "batchNo", "batch_no"),
batch_no_in=_param_get(params, "batchNoIn", "batch_no_in"),
partner_company=_param_get(params, "partnerCompany", "partner_company"),
partner_company_in=_param_get(params, "partnerCompanyIn", "partner_company_in"),
product=_param_get(params, "product"),
product_in=_param_get(params, "productIn", "product_in"),
specification=_param_get(params, "specification"),
specification_in=_param_get(params, "specificationIn", "specification_in"),
vehicle_no=_param_get(params, "vehicleNo", "vehicle_no"),
vehicle_no_in=_param_get(params, "vehicleNoIn", "vehicle_no_in"),
business_type=_param_get(params, "businessType", "business_type"),
business_type_in=_param_get(params, "businessTypeIn", "business_type_in"),
status=_param_get(params, "status"),
status_in=_param_get(params, "statusIn", "status_in"),
date_from=_param_get(params, "dateFrom", "date_from"),
date_to=_param_get(params, "dateTo", "date_to"),
quantity_op=_param_get(params, "quantityOp", "quantity_op"),
quantity=_param_get(params, "quantity"),
quantity_min=_param_get(params, "quantityMin", "quantity_min"),
quantity_max=_param_get(params, "quantityMax", "quantity_max"),
)
def _body_to_params(body: "InventoryExportBody") -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
data.pop("ids", None)
data.pop("columns", None)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
def _inventory_query(db: Session, user: DbUserContext, params: dict):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
query = _base_query(db, tenant_no)
q = _param_get(params, "q")
if q:
keyword = str(q).lower()
query = query.filter(
or_(
func.lower(DbInboundOutbound.partner_company).contains(keyword),
func.lower(DbInboundOutbound.product).contains(keyword),
func.lower(DbInboundOutbound.plan_no).contains(keyword),
func.lower(DbInboundOutbound.batch_no).contains(keyword),
func.lower(DbInboundOutbound.vehicle_no).contains(keyword),
)
)
column_filters = _filters_from_params(params)
if column_filters:
query = query.filter(*column_filters)
query = apply_db_scope(query, DbInboundOutbound, user, db, tenant_no)
sf, so = parse_sort_params(params)
query = query.order_by(
order_inventory(sf, so, default=DbInboundOutbound.date.desc()),
DbInboundOutbound.id.desc(),
)
return query, tenant_no
def _map_inventories(
db: Session, tenant_no: str, inventories: list
) -> list[InboundOutboundRead]:
inventory_ids = [inv.id for inv in inventories]
weighing_map: dict[str, DbWeighingSlip] = {}
if inventory_ids:
weighings = (
db.query(DbWeighingSlip)
.filter(
DbWeighingSlip.tenant_no == tenant_no,
DbWeighingSlip.del_flag == 0,
DbWeighingSlip.inbound_outbound_id.in_(inventory_ids),
DbWeighingSlip.is_voided == 0,
)
.order_by(DbWeighingSlip.id.asc())
.all()
)
for weighing in weighings:
if (
weighing.inbound_outbound_id
and weighing.inbound_outbound_id not in weighing_map
):
weighing_map[weighing.inbound_outbound_id] = weighing
result_list: list[InboundOutboundRead] = []
user_name_map = load_user_display_name_map(db, [inv.create_by for inv in inventories])
for inventory in inventories:
try:
result_list.append(
inventory_to_read(
inventory,
weighing=weighing_map.get(inventory.id),
user_name_map=user_name_map,
)
)
except Exception:
continue
return result_list
def _fetch_inventory(
db: Session,
user: DbUserContext,
params: dict,
*,
page: Optional[int] = None,
page_size: Optional[int] = None,
) -> Tuple[list[InboundOutboundRead], int]:
query, tenant_no = _inventory_query(db, user, params)
if page is not None and page_size is not None:
total = query.order_by(None).count()
inventories = query.offset((page - 1) * page_size).limit(page_size).all()
return _map_inventories(db, tenant_no, inventories), total
inventories = query.all()
items = _map_inventories(db, tenant_no, inventories)
return items, len(items)
@router.get("/")
def list_inventory(
request: Request,
q: Optional[str] = Query(default=None, description="模糊搜索关键词"),
plan_no: Optional[str] = Query(default=None, alias="planNo", description="计划号"),
batch_no: Optional[str] = Query(default=None, alias="batchNo", description="出入库单号"),
partner_company: Optional[str] = Query(
default=None, alias="partnerCompany", description="往来单位"
),
product: Optional[str] = Query(default=None, description="产品"),
vehicle_no: Optional[str] = Query(default=None, alias="vehicleNo", description="车牌号"),
date_from: Optional[str] = Query(default=None, alias="dateFrom", description="开始日期"),
date_to: Optional[str] = Query(default=None, alias="dateTo", description="结束日期"),
status_filter: Optional[str] = Query(default=None, alias="status", description="状态筛选"),
business_type: Optional[str] = Query(default=None, alias="businessType", description="业务类型"),
page: Optional[int] = Query(default=None, ge=1, description="页码;传入则返回分页结构"),
page_size: Optional[int] = Query(
default=None, ge=1, le=500, alias="pageSize", description="每页条数"
),
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
params = _merge_query(
request,
q=q,
planNo=plan_no,
batchNo=batch_no,
partnerCompany=partner_company,
product=product,
vehicleNo=vehicle_no,
dateFrom=date_from,
dateTo=date_to,
status=status_filter,
businessType=business_type,
)
paged = page is not None
size = page_size if page_size is not None else 20
page_num = page if page is not None else 1
items, total = _fetch_inventory(
db,
user,
params,
page=page_num if paged else None,
page_size=size if paged else None,
)
if paged:
body = InboundOutboundListResponse(
items=items, total=total, page=page_num, pageSize=size
)
return JSONResponse(content=body.model_dump(by_alias=True))
return JSONResponse(content=[item.model_dump(by_alias=True) for item in items])
class InventoryColumnFacetBody(BaseModel):
"""出入库单列头可选值(去重;可附带列表上下文)"""
model_config = ConfigDict(populate_by_name=True, extra="allow")
field: str = Field(..., description="planNo | batchNo | partnerCompany | product | specification | vehicleNo")
keyword: Optional[str] = Field(default=None, description="可选值关键字")
limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
_INVENTORY_FACET_COLUMNS = {
"planNo": DbInboundOutbound.plan_no,
"batchNo": DbInboundOutbound.batch_no,
"partnerCompany": DbInboundOutbound.partner_company,
"product": DbInboundOutbound.product,
"specification": DbInboundOutbound.specification,
"vehicleNo": DbInboundOutbound.vehicle_no,
}
@router.post("/column-facet-values")
def inventory_column_facet_values(
body: InventoryColumnFacetBody,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
"""出入库单列头可选值:在列表上下文(排除本列)下去重。"""
from app.services.column_facet import list_column_facet_values
from app.services.pl.facet_context import strip_simple_facet_self_params
column = _INVENTORY_FACET_COLUMNS.get(body.field)
if column is None:
raise HTTPException(status_code=400, detail="不支持的列")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
params = strip_simple_facet_self_params(_body_to_params(body), body.field)
extra_filters = list(_filters_from_params(params))
qv = _param_get(params, "q")
if qv:
keyword = str(qv).lower()
extra_filters.append(
or_(
func.lower(DbInboundOutbound.partner_company).contains(keyword),
func.lower(DbInboundOutbound.product).contains(keyword),
func.lower(DbInboundOutbound.plan_no).contains(keyword),
func.lower(DbInboundOutbound.batch_no).contains(keyword),
func.lower(DbInboundOutbound.vehicle_no).contains(keyword),
)
)
rows = list_column_facet_values(
db,
DbInboundOutbound,
column,
tenant_no=tenant_no,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
apply_scope=lambda q: apply_db_scope(q, DbInboundOutbound, user, db, tenant_no),
extra_filters=extra_filters or None,
)
return {"list": rows}
INVENTORY_EXPORT_COLUMNS = [
ExportColumn(title="ID", field="id"),
ExportColumn(title="计划号", field="planNo"),
ExportColumn(title="出入库单号", field="batchNo"),
ExportColumn(title="日期", field="date"),
ExportColumn(title="往来单位", field="partnerCompany"),
ExportColumn(title="业务类型", field="businessType"),
ExportColumn(title="状态", field="status"),
ExportColumn(title="产品", field="product"),
ExportColumn(title="规格", field="specification"),
ExportColumn(title="车牌号", field="vehicleNo"),
ExportColumn(title="数量(吨)", field="quantity"),
ExportColumn(title="净重(吨)", field="netWeight"),
ExportColumn(title="毛重(吨)", field="grossWeight"),
ExportColumn(title="毛重时间", field="grossWeightTime"),
ExportColumn(title="皮重(吨)", field="tareWeight"),
ExportColumn(title="皮重时间", field="tareWeightTime"),
ExportColumn(title="扣杂(吨)", field="deduction"),
ExportColumn(title="备注", field="remarks"),
ExportColumn(title="创建人", field="createByName"),
]
class InventoryExportBody(BaseModel):
q: Optional[str] = None
plan_no: Optional[str] = Field(default=None, alias="planNo")
batch_no: Optional[str] = Field(default=None, alias="batchNo")
partner_company: Optional[str] = Field(default=None, alias="partnerCompany")
product: Optional[str] = None
vehicle_no: Optional[str] = Field(default=None, alias="vehicleNo")
date_from: Optional[str] = Field(default=None, alias="dateFrom")
date_to: Optional[str] = Field(default=None, alias="dateTo")
status: Optional[str] = None
business_type: Optional[str] = Field(default=None, alias="businessType")
sort_field: Optional[str] = Field(default=None, alias="sortField")
sort_order: Optional[str] = Field(default=None, alias="sortOrder")
ids: Optional[List[str]] = None
columns: Optional[List[str]] = None
model_config = {"populate_by_name": True, "extra": "allow"}
@router.post("/export")
def export_inventory(
body: InventoryExportBody,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
"""导出出入库列表(当前筛选全量,或 ids 已选)。"""
try:
items, _total = _fetch_inventory(db, user, _body_to_params(body))
if body.ids:
id_set = set(body.ids)
items = [x for x in items if x.id in id_set]
if len(items) > EXPORT_MAX_ROWS:
raise ExportValidationError(f"导出超过 {EXPORT_MAX_ROWS} 条,请缩小筛选范围")
rows = []
for item in items:
data = item.model_dump(by_alias=True)
if not data.get("createByName"):
data["createByName"] = data.get("createBy") or ""
rows.append(data)
cols = filter_export_columns(INVENTORY_EXPORT_COLUMNS, body.columns)
date_str = datetime.now().strftime("%Y%m%d")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="出入库列表",
columns=cols,
rows=rows,
filename_stem=f"出入库列表_{date_str}",
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/", response_model=InboundOutboundRead, status_code=status.HTTP_201_CREATED)
def create_inventory(
payload: InboundOutboundCreate,
db: Session = Depends(get_db),
user: Optional[DbUserContext] = Depends(get_db_current_user_optional),
) -> InboundOutboundRead:
tenant_no = _resolve_tenant_no(db, user, payload.purchase_plan_id)
plan_fields = {
"plan_no": payload.plan_no,
"product_id": payload.product_id,
"partner_company": payload.partner_company,
"business_type": payload.business_type,
"purchase_plan_id": payload.purchase_plan_id,
}
_enforce_inventory_plan_on_edit(
db,
SimpleNamespace(
tenant_no=tenant_no,
plan_no=None,
product_id=None,
partner_company=None,
business_type=None,
purchase_plan_id=None,
),
plan_fields,
)
batch_no = payload.batch_no.strip() if payload.batch_no else None
if not batch_no:
batch_no = _generate_batch_no(db, tenant_no)
status_value = (
payload.status.strip()
if payload.status and str(payload.status).strip()
else ("待入库" if payload.business_type == "入库" else "待出库")
)
snapshot = resolve_crm_product(db, tenant_no, plan_fields["product_id"])
row = DbInboundOutbound(
id=next_inbound_outbound_id(db, tenant_no),
tenant_no=tenant_no,
date=parse_date_str(payload.date) or datetime.now().date(),
partner_company=_text(plan_fields.get("partner_company")),
business_type=_text(plan_fields.get("business_type")) or payload.business_type,
quantity=payload.quantity,
plan_no=plan_fields.get("plan_no"),
batch_no=batch_no,
vehicle_no=payload.vehicle_no.strip(),
status=status_value,
remark=payload.remarks,
purchase_plan_id=plan_fields.get("purchase_plan_id"),
create_by=user.id if user else None,
create_dept_id=user.dept_id if user else "",
)
apply_product_snapshot_to_inventory(row, snapshot)
ensure_site_access_token(row)
db.add(row)
db.commit()
db.refresh(row)
return inventory_to_read(row, db=db)
@router.post(
"/create-link-for-plan",
response_model=InboundOutboundRead,
status_code=status.HTTP_201_CREATED,
)
def create_link_for_plan(
payload: CreateLinkForPlanPayload,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> InboundOutboundRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = (
db.query(DbPurchasePlan)
.filter(
DbPurchasePlan.id == payload.purchase_plan_id,
DbPurchasePlan.tenant_no == tenant_no,
DbPurchasePlan.del_flag == 0,
)
.one_or_none()
)
if not plan:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Plan not found")
if not plan.product_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="计划未关联 CRM 产品,请先编辑计划并选择产品",
)
row = DbInboundOutbound(
id=next_inbound_outbound_id(db, tenant_no),
tenant_no=tenant_no,
date=EMPTY_INVENTORY_DATE,
partner_company=(plan.customer_name or "").strip() or "待填写",
business_type=plan.business_type,
product_id=plan.product_id,
product=(plan.product or "").strip(),
specification=plan.specification,
quantity=0.0,
plan_no=(plan.plan_no or "").strip() or None,
batch_no=_generate_batch_no(db, tenant_no),
vehicle_no="",
status=STATUS_THIRD_PARTY_FILL,
remark=payload.remarks,
purchase_plan_id=plan.id,
create_by=user.id,
create_dept_id=user.dept_id,
)
ensure_site_access_token(row)
db.add(row)
db.commit()
db.refresh(row)
return inventory_to_read(row, db=db)
@router.get("/{id}/site-url", response_model=InventorySiteUrlRead)
def get_inventory_site_url(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> InventorySiteUrlRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_inventory(db, tenant_no, id, user)
token = ensure_site_access_token(row)
db.commit()
return InventorySiteUrlRead(site_url=build_site_inventory_url(token))
@router.get("/{id}", response_model=InboundOutboundRead)
def get_inventory(
id: str,
db: Session = Depends(get_db),
) -> InboundOutboundRead:
"""单条查询(三方 H5 填写页无需门户登录)。"""
row = _get_inventory_by_id(db, id)
weighing = (
db.query(DbWeighingSlip)
.filter(
DbWeighingSlip.inbound_outbound_id == row.id,
DbWeighingSlip.is_voided == 0,
DbWeighingSlip.del_flag == 0,
)
.order_by(DbWeighingSlip.id.asc())
.first()
)
return inventory_to_read(row, weighing=weighing, db=db)
@router.patch("/{id}", response_model=InboundOutboundRead)
def update_inventory(
id: str,
payload: InboundOutboundUpdate,
db: Session = Depends(get_db),
) -> InboundOutboundRead:
"""更新(三方 H5 填写页无需门户登录)。"""
row = _get_inventory_by_id(db, id)
payload_dict = payload.model_dump(exclude_unset=True)
_enforce_inventory_plan_on_edit(db, row, payload_dict)
_apply_inventory_product_update(db, row.tenant_no, row, payload_dict)
_apply_inventory_update(row, payload_dict)
_maybe_promote_third_party_status(row)
db.commit()
db.refresh(row)
return inventory_to_read(row, db=db)
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_inventory(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_inventory(db, tenant_no, id, user)
if row.status == "已完成":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="已完成的记录不能删除",
)
assert_row_deletable_by_creator(row, user_info_from_context(user))
row.del_flag = 1
row.update_by = user.id
db.commit()
class InventoryRelatedData(BaseModel):
plan: Optional[PurchasePlanRead]
weighing: Optional[WeighingSlipRead]
@router.get("/{id}/related", response_model=InventoryRelatedData)
def get_inventory_related(
id: str,
db: Session = Depends(get_db),
) -> InventoryRelatedData:
row = _get_inventory_by_id(db, id)
plan = None
if row.purchase_plan_id:
plan = (
db.query(DbPurchasePlan)
.filter(
DbPurchasePlan.id == row.purchase_plan_id,
DbPurchasePlan.del_flag == 0,
)
.one_or_none()
)
weighing = (
db.query(DbWeighingSlip)
.filter(
DbWeighingSlip.inbound_outbound_id == row.id,
DbWeighingSlip.is_voided == 0,
DbWeighingSlip.del_flag == 0,
)
.limit(1)
.first()
)
return InventoryRelatedData(
plan=plan_to_read(plan, db=db) if plan else None,
weighing=weighing_to_read(weighing, db=db) if weighing else None,
)
+742
View File
@@ -0,0 +1,742 @@
from typing import Any, List, Optional, Tuple
from datetime import date, datetime
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user
from app.core.delete_guard import assert_row_deletable_by_creator, user_info_from_context
from app.core.tenant_context import get_tenant_no
from app.core.utils import generate_uuid
from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
from app.schemas.db.inventory import InboundOutboundRead
from app.schemas.db.plans import (
PurchasePlanCreate,
PurchasePlanListResponse,
PurchasePlanRead,
PurchasePlanUpdate,
PurchasePlanWithFillLink,
)
from app.schemas.db.weighing import WeighingSlipRead
from app.services.db.mappers import (
inventory_to_read,
load_user_display_name_map,
parse_date_str,
parse_datetime_str,
plan_to_read,
plan_to_read_with_fill_link,
weighing_to_read,
)
from app.services.db.plan_list_filters import build_plan_column_filters
from app.services.db.product_helpers import (
apply_product_snapshot_to_plan,
resolve_crm_product,
)
from app.utils.excel_export import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
router = APIRouter(prefix="/plans", tags=["plans"])
STATUS_THIRD_PARTY_FILL = "待三方填写"
_PLAN_DATE_FIELDS = {"plan_date", "start_date", "end_date"}
_PLAN_REMARK_FIELD = "remarks"
def _base_query(db: Session, tenant_no: str):
return db.query(DbPurchasePlan).filter(
DbPurchasePlan.tenant_no == tenant_no,
DbPurchasePlan.del_flag == 0,
)
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _filters_from_params(params: dict) -> list:
return build_plan_column_filters(
plan_no=_param_get(params, "planNo", "plan_no"),
plan_no_in=_param_get(params, "planNoIn", "plan_no_in"),
customer_name=_param_get(params, "customerName", "customer_name"),
customer_name_in=_param_get(params, "customerNameIn", "customer_name_in"),
product=_param_get(params, "product"),
product_in=_param_get(params, "productIn", "product_in"),
specification=_param_get(params, "specification"),
specification_in=_param_get(params, "specificationIn", "specification_in"),
business_type=_param_get(params, "businessType", "business_type"),
business_type_in=_param_get(params, "businessTypeIn", "business_type_in"),
execution_status=_param_get(params, "executionStatus", "execution_status"),
execution_status_in=_param_get(params, "executionStatusIn", "execution_status_in"),
planned_quantity_op=_param_get(params, "plannedQuantityOp", "planned_quantity_op"),
planned_quantity=_param_get(params, "plannedQuantity", "planned_quantity"),
planned_quantity_min=_param_get(params, "plannedQuantityMin", "planned_quantity_min"),
planned_quantity_max=_param_get(params, "plannedQuantityMax", "planned_quantity_max"),
executed_quantity_op=_param_get(params, "executedQuantityOp", "executed_quantity_op"),
executed_quantity=_param_get(params, "executedQuantity", "executed_quantity"),
executed_quantity_min=_param_get(params, "executedQuantityMin", "executed_quantity_min"),
executed_quantity_max=_param_get(params, "executedQuantityMax", "executed_quantity_max"),
created_from=_param_get(params, "createdFrom", "created_from"),
created_to=_param_get(params, "createdTo", "created_to"),
start_date_from=_param_get(params, "startDateFrom", "start_date_from"),
start_date_to=_param_get(params, "startDateTo", "start_date_to"),
)
def _body_to_params(body: "PlanExportBody") -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
data.pop("ids", None)
data.pop("columns", None)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
def _plans_query(db: Session, user: DbUserContext, params: dict):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
query = _base_query(db, tenant_no).order_by(DbPurchasePlan.create_time.desc())
q = _param_get(params, "q")
if q:
keyword = str(q).lower()
query = query.filter(
or_(
func.lower(DbPurchasePlan.customer_name).contains(keyword),
func.lower(DbPurchasePlan.product).contains(keyword),
func.lower(DbPurchasePlan.plan_no).contains(keyword),
)
)
column_filters = _filters_from_params(params)
if column_filters:
query = query.filter(*column_filters)
return apply_db_scope(query, DbPurchasePlan, user, db, tenant_no), tenant_no
def _map_plans(
db: Session, tenant_no: str, plans: list
) -> list[PurchasePlanWithFillLink]:
if not plans:
return []
plan_ids = [p.id for p in plans]
fill_links = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.purchase_plan_id.in_(plan_ids),
DbInboundOutbound.status == STATUS_THIRD_PARTY_FILL,
)
.all()
)
plan_id_to_inv_id = {
inv.purchase_plan_id: inv.id for inv in fill_links if inv.purchase_plan_id
}
plan_nos = [p.plan_no for p in plans if p.plan_no]
executed_sum_map: dict[tuple[Optional[str], Optional[str]], float] = {}
if plan_ids or plan_nos:
weighing_filters = [DbWeighingSlip.is_voided == 0, DbWeighingSlip.del_flag == 0]
weighing_filters.append(DbWeighingSlip.tenant_no == tenant_no)
id_filters = []
if plan_ids:
id_filters.append(DbWeighingSlip.purchase_plan_id.in_(plan_ids))
if plan_nos:
id_filters.append(DbWeighingSlip.plan_no.in_(plan_nos))
weighing_filters.append(or_(*id_filters))
weighing_rows = (
db.query(
DbWeighingSlip.purchase_plan_id,
DbWeighingSlip.plan_no,
func.sum(DbWeighingSlip.net_weight).label("total_executed"),
)
.filter(*weighing_filters)
.group_by(DbWeighingSlip.purchase_plan_id, DbWeighingSlip.plan_no)
.all()
)
for row in weighing_rows:
key = (row.purchase_plan_id, row.plan_no)
executed_sum_map[key] = float(row.total_executed or 0)
def calc_executed_for_plan(plan: DbPurchasePlan) -> float:
if not executed_sum_map:
return 0.0
total = 0.0
for (pid, pno), executed in executed_sum_map.items():
if pid is not None and pid == plan.id:
total += executed
elif pno and plan.plan_no and pno == plan.plan_no:
total += executed
return total
user_name_map = load_user_display_name_map(db, [p.create_by for p in plans])
result_list: list[PurchasePlanWithFillLink] = []
for plan in plans:
result_list.append(
plan_to_read_with_fill_link(
plan,
executed_quantity=calc_executed_for_plan(plan),
fill_link_inventory_id=plan_id_to_inv_id.get(plan.id),
user_name_map=user_name_map,
)
)
return result_list
def _fetch_plans(
db: Session,
user: DbUserContext,
params: dict,
*,
page: Optional[int] = None,
page_size: Optional[int] = None,
) -> Tuple[list[PurchasePlanWithFillLink], int]:
query, tenant_no = _plans_query(db, user, params)
if page is not None and page_size is not None:
total = query.order_by(None).count()
plans = query.offset((page - 1) * page_size).limit(page_size).all()
return _map_plans(db, tenant_no, plans), total
plans = query.all()
items = _map_plans(db, tenant_no, plans)
return items, len(items)
@router.get("/")
def list_plans(
request: Request,
q: Optional[str] = Query(default=None, description="模糊搜索往来单位或产品"),
plan_no: Optional[str] = Query(default=None, alias="planNo", description="计划号"),
customer_name: Optional[str] = Query(
default=None, alias="customerName", description="往来单位"
),
product: Optional[str] = Query(default=None, description="产品"),
business_type: Optional[str] = Query(default=None, alias="businessType", description="业务类型"),
execution_status: Optional[str] = Query(
default=None, alias="executionStatus", description="执行状态"
),
created_from: Optional[str] = Query(default=None, alias="createdFrom", description="创建开始日期"),
created_to: Optional[str] = Query(default=None, alias="createdTo", description="创建结束日期"),
start_date_from: Optional[str] = Query(
default=None,
alias="startDateFrom",
description="筛选区间开始:与计划有效期(起始~截止)有交集",
),
start_date_to: Optional[str] = Query(
default=None,
alias="startDateTo",
description="筛选区间结束:与计划有效期(起始~截止)有交集",
),
page: Optional[int] = Query(default=None, ge=1, description="页码;传入则返回分页结构"),
page_size: Optional[int] = Query(
default=None, ge=1, le=500, alias="pageSize", description="每页条数"
),
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
params = _merge_query(
request,
q=q,
planNo=plan_no,
customerName=customer_name,
product=product,
businessType=business_type,
executionStatus=execution_status,
createdFrom=created_from,
createdTo=created_to,
startDateFrom=start_date_from,
startDateTo=start_date_to,
)
paged = page is not None
size = page_size if page_size is not None else 20
page_num = page if page is not None else 1
items, total = _fetch_plans(
db,
user,
params,
page=page_num if paged else None,
page_size=size if paged else None,
)
if paged:
body = PurchasePlanListResponse(
items=items, total=total, page=page_num, pageSize=size
)
return JSONResponse(content=body.model_dump(by_alias=True))
return JSONResponse(content=[item.model_dump(by_alias=True) for item in items])
PLAN_EXPORT_COLUMNS = [
ExportColumn(title="计划号", field="planNo"),
ExportColumn(title="业务类型", field="businessType"),
ExportColumn(title="往来单位", field="customerName"),
ExportColumn(title="计划日期", field="planDate"),
ExportColumn(title="起始日期", field="startDate"),
ExportColumn(title="截止日期", field="endDate"),
ExportColumn(title="产品", field="product"),
ExportColumn(title="规格", field="specification"),
ExportColumn(title="车牌号", field="vehicleNo"),
ExportColumn(title="计划量(吨)", field="plannedQuantity"),
ExportColumn(title="已执行量(吨)", field="executedQuantity"),
ExportColumn(title="执行状态", field="executionStatus"),
ExportColumn(title="备注", field="remarks"),
ExportColumn(title="自动生成", field="autoGenerate"),
ExportColumn(title="创建人", field="createByName"),
]
class PlanColumnFacetBody(BaseModel):
"""地磅计划列头可选值(去重;可附带列表上下文)"""
model_config = ConfigDict(populate_by_name=True, extra="allow")
field: str = Field(..., description="planNo | customerName | product | specification")
keyword: Optional[str] = Field(default=None, description="可选值关键字")
limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
_PLAN_FACET_COLUMNS = {
"planNo": DbPurchasePlan.plan_no,
"customerName": DbPurchasePlan.customer_name,
"product": DbPurchasePlan.product,
"specification": DbPurchasePlan.specification,
}
@router.post("/column-facet-values")
def plan_column_facet_values(
body: PlanColumnFacetBody,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
"""地磅计划列头可选值:在列表上下文(排除本列)下去重。"""
from app.services.column_facet import list_column_facet_values
from app.services.pl.facet_context import strip_simple_facet_self_params
column = _PLAN_FACET_COLUMNS.get(body.field)
if column is None:
raise HTTPException(status_code=400, detail="不支持的列")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
params = strip_simple_facet_self_params(_body_to_params(body), body.field)
extra_filters = list(_filters_from_params(params))
qv = _param_get(params, "q")
if qv:
keyword = str(qv).lower()
extra_filters.append(
or_(
func.lower(DbPurchasePlan.customer_name).contains(keyword),
func.lower(DbPurchasePlan.product).contains(keyword),
func.lower(DbPurchasePlan.plan_no).contains(keyword),
)
)
rows = list_column_facet_values(
db,
DbPurchasePlan,
column,
tenant_no=tenant_no,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
apply_scope=lambda q: apply_db_scope(q, DbPurchasePlan, user, db, tenant_no),
extra_filters=extra_filters or None,
)
return {"list": rows}
class PlanExportBody(BaseModel):
q: Optional[str] = None
plan_no: Optional[str] = Field(default=None, alias="planNo")
customer_name: Optional[str] = Field(default=None, alias="customerName")
product: Optional[str] = None
business_type: Optional[str] = Field(default=None, alias="businessType")
execution_status: Optional[str] = Field(default=None, alias="executionStatus")
created_from: Optional[str] = Field(default=None, alias="createdFrom")
created_to: Optional[str] = Field(default=None, alias="createdTo")
start_date_from: Optional[str] = Field(default=None, alias="startDateFrom")
start_date_to: Optional[str] = Field(default=None, alias="startDateTo")
ids: Optional[List[str]] = None
columns: Optional[List[str]] = None
model_config = {"populate_by_name": True, "extra": "allow"}
@router.post("/export")
def export_plans(
body: PlanExportBody,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
"""导出计划列表(当前筛选全量,或 ids 已选)。"""
try:
items, _total = _fetch_plans(db, user, _body_to_params(body))
if body.ids:
id_set = set(body.ids)
items = [x for x in items if x.id in id_set]
if len(items) > EXPORT_MAX_ROWS:
raise ExportValidationError(f"导出超过 {EXPORT_MAX_ROWS} 条,请缩小筛选范围")
rows = []
for item in items:
data = item.model_dump(by_alias=True)
data["autoGenerate"] = "是" if data.get("autoGenerateEnabled") else "否"
eq = data.get("executedQuantity") or 0
try:
data["executedQuantity"] = round(float(eq) / 1000, 2)
except (TypeError, ValueError):
data["executedQuantity"] = 0
if not data.get("createByName"):
data["createByName"] = data.get("createBy") or ""
rows.append(data)
cols = filter_export_columns(PLAN_EXPORT_COLUMNS, body.columns)
date_str = datetime.now().strftime("%Y%m%d")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="计划列表",
columns=cols,
rows=rows,
filename_stem=f"计划列表_{date_str}",
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
def _generate_plan_no() -> str:
from app.services.db.plan_helpers import generate_plan_no
return generate_plan_no()
@router.post("/", response_model=PurchasePlanRead, status_code=status.HTTP_201_CREATED)
def create_plan(
payload: PurchasePlanCreate,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> PurchasePlanRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan_no = payload.plan_no if payload.plan_no else _generate_plan_no()
execution_status = payload.execution_status
if not execution_status:
execution_status = "待入库" if payload.business_type == "入库" else "待出库"
snapshot = resolve_crm_product(db, tenant_no, payload.product_id)
plan = DbPurchasePlan(
id=generate_uuid(),
tenant_no=tenant_no,
plan_no=plan_no,
plan_date=parse_date_str(payload.plan_date) or date.today(),
start_date=parse_date_str(payload.start_date),
end_date=parse_date_str(payload.end_date),
business_type=payload.business_type,
planned_quantity=payload.planned_quantity,
vehicle_no=payload.vehicle_no or "",
customer_name=payload.customer_name.strip() if payload.customer_name else None,
remark=payload.remarks,
execution_status=execution_status,
executed_at=None,
last_weighing_slip_id=None,
executed_quantity=0,
auto_generate_enabled=payload.auto_generate_enabled or 0,
auto_generate_end_month=payload.auto_generate_end_month,
auto_generate_last_month=None,
create_by=user.id,
create_dept_id=user.dept_id,
)
apply_product_snapshot_to_plan(plan, snapshot)
db.add(plan)
db.commit()
db.refresh(plan)
return plan_to_read(plan, db=db)
class AutoGenerateMonthlyResult(BaseModel):
created_count: int
skipped_reason: Optional[str] = None
current_month: str
@router.post("/run-auto-generate", response_model=AutoGenerateMonthlyResult)
def run_auto_generate_monthly(
force: bool = Query(default=False, description="true 时跳过「仅每月1日」限制,供验收手动触发"),
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> AutoGenerateMonthlyResult:
"""手动触发计划按月自动生成(定时任务同款逻辑)。"""
get_tenant_no(db, user.to_tenant_user_dict())
from app.services.db.auto_generate_plans import run_auto_generate_monthly_plans
result = run_auto_generate_monthly_plans(db, force=force)
return AutoGenerateMonthlyResult(**result)
@router.get("/{id}", response_model=PurchasePlanRead)
def get_plan(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> PurchasePlanRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id, user)
return plan_to_read(plan, db=db)
@router.patch("/{id}", response_model=PurchasePlanRead)
def update_plan(
id: str,
payload: PurchasePlanUpdate,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> PurchasePlanRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id, user)
payload_dict = payload.model_dump(exclude_unset=True)
_apply_plan_product_update(db, tenant_no, plan, payload_dict)
_apply_plan_update(plan, payload_dict)
plan.update_by = user.id
db.commit()
db.refresh(plan)
return plan_to_read(plan, db=db)
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_plan(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id, user)
if plan.execution_status in ("已入库", "已出库"):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="已完成的计划不能删除",
)
assert_row_deletable_by_creator(plan, user_info_from_context(user))
plan.del_flag = 1
plan.update_by = user.id
db.commit()
def _get_plan(
db: Session, tenant_no: str, plan_id: str, user: DbUserContext
) -> DbPurchasePlan:
plan = (
_base_query(db, tenant_no)
.filter(DbPurchasePlan.id == plan_id)
.one_or_none()
)
if plan is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Plan {plan_id} not found",
)
assert_db_row_in_scope(db, plan, DbPurchasePlan, user, tenant_no)
return plan
def _get_plan_by_id_only(db: Session, plan_id: str) -> DbPurchasePlan:
plan = (
db.query(DbPurchasePlan)
.filter(DbPurchasePlan.id == plan_id, DbPurchasePlan.del_flag == 0)
.one_or_none()
)
if plan is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Plan {plan_id} not found",
)
return plan
def _apply_plan_product_update(
db: Session, tenant_no: str, plan: DbPurchasePlan, payload_dict: dict
) -> None:
if "product" in payload_dict and "product_id" not in payload_dict:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="请从 CRM 重新选择产品",
)
product_id = payload_dict.pop("product_id", None)
payload_dict.pop("product", None)
payload_dict.pop("specification", None)
if product_id is not None:
snapshot = resolve_crm_product(db, tenant_no, product_id)
apply_product_snapshot_to_plan(plan, snapshot)
def _apply_plan_update(plan: DbPurchasePlan, payload_dict: dict) -> None:
for key, value in payload_dict.items():
if key == _PLAN_REMARK_FIELD:
if isinstance(value, str):
value = value.strip()
plan.remark = value
continue
if key in _PLAN_DATE_FIELDS:
if value is None:
setattr(plan, key, None)
else:
setattr(plan, key, parse_date_str(str(value)))
continue
if key == "executed_at":
plan.executed_at = parse_datetime_str(str(value)) if value else None
continue
if isinstance(value, str):
value = value.strip()
setattr(plan, key, value)
class PlanRelatedData(BaseModel):
inventories: list[InboundOutboundRead]
weighings: list[WeighingSlipRead]
@router.get("/{id}/related", response_model=PlanRelatedData)
def get_plan_related(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> PlanRelatedData:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
plan = _get_plan(db, tenant_no, id, user)
inventories = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.purchase_plan_id == plan.id,
)
.order_by(DbInboundOutbound.date.desc(), DbInboundOutbound.id.desc())
.all()
)
weighing_query = db.query(DbWeighingSlip).filter(
DbWeighingSlip.tenant_no == tenant_no,
DbWeighingSlip.del_flag == 0,
DbWeighingSlip.is_voided == 0,
)
if plan.plan_no:
weighing_query = weighing_query.filter(
or_(
DbWeighingSlip.plan_no == plan.plan_no,
DbWeighingSlip.purchase_plan_id == plan.id,
)
)
else:
weighing_query = weighing_query.filter(DbWeighingSlip.purchase_plan_id == plan.id)
weighings = weighing_query.order_by(DbWeighingSlip.create_time.desc()).all()
user_name_map = load_user_display_name_map(
db,
[inv.create_by for inv in inventories] + [w.create_by for w in weighings],
)
return PlanRelatedData(
inventories=[inventory_to_read(inv, user_name_map=user_name_map) for inv in inventories],
weighings=[weighing_to_read(w, user_name_map=user_name_map) for w in weighings],
)
class ThirdPartyPlanPageData(BaseModel):
plan: PurchasePlanRead
today_inventories: list[InboundOutboundRead]
month_inventories: list[InboundOutboundRead]
@router.get("/{id}/third-party-page", response_model=ThirdPartyPlanPageData)
def get_third_party_plan_page(
id: str,
db: Session = Depends(get_db),
) -> ThirdPartyPlanPageData:
"""三方 H5 填写页初始化数据(无需门户登录,与原系统一致)。"""
plan = _get_plan_by_id_only(db, id)
tenant_no = plan.tenant_no
today = date.today()
start = plan.start_date
end = plan.end_date
if start and today < start:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="计划尚未生效,当前日期不允许填写出入库单",
)
if end and today > end:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="计划已过期,当前日期不允许填写出入库单",
)
today_str = today.strftime("%Y-%m-%d")
today_date = parse_date_str(today_str)
inventories = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.purchase_plan_id == plan.id,
DbInboundOutbound.date == today_date,
)
.order_by(DbInboundOutbound.date.desc(), DbInboundOutbound.id.desc())
.all()
)
month_start = today.replace(day=1)
month_history = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
DbInboundOutbound.purchase_plan_id == plan.id,
DbInboundOutbound.date >= month_start,
DbInboundOutbound.date < today,
)
.order_by(DbInboundOutbound.date.desc(), DbInboundOutbound.id.desc())
.all()
)
user_name_map = load_user_display_name_map(
db,
[plan.create_by]
+ [inv.create_by for inv in inventories]
+ [inv.create_by for inv in month_history],
)
return ThirdPartyPlanPageData(
plan=plan_to_read(plan, user_name_map=user_name_map),
today_inventories=[
inventory_to_read(inv, user_name_map=user_name_map) for inv in inventories
],
month_inventories=[
inventory_to_read(inv, user_name_map=user_name_map) for inv in month_history
],
)
+206
View File
@@ -0,0 +1,206 @@
"""地磅出入库单 · 工厂现场人员免登录公共 API"""
from __future__ import annotations
import json
import os
from datetime import date, datetime
from typing import Optional
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from sqlalchemy.orm import Session
from app.core.attachment_biz import resolve_upload_folder
from app.core.config import settings
from app.core.database import get_db
from app.core.response import error_response, success_response
from app.core.storage import storage
from app.crud import oss as oss_svc
from app.models.db_models import DbInboundOutbound
from app.models.pl_models import PlPlan, PlTransportDbLink
from app.schemas.db.public_inventory import PublicInventoryFeedback, PublicInventoryPageRead
from app.services.db.mappers import inventory_date_to_api
from app.services.db.pound_qr_public import build_public_pound_qr_read
router = APIRouter(prefix="/public/db/inventory", tags=["地磅-出入库现场公共"])
COMPLETED_STATUS = "已完成"
def _parse_feedback_images(raw: Optional[str]) -> list[str]:
if not raw:
return []
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
return [str(item) for item in parsed if item]
except (TypeError, json.JSONDecodeError):
pass
return [part.strip() for part in raw.split(",") if part.strip()]
def _get_inventory_by_token(db: Session, token: str) -> DbInboundOutbound:
row = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.site_access_token == token,
DbInboundOutbound.del_flag == 0,
)
.first()
)
if not row:
raise HTTPException(status_code=404, detail="链接无效或已失效")
return row
def _resolve_plan_voided(db: Session, inventory: DbInboundOutbound) -> bool:
link = (
db.query(PlTransportDbLink)
.filter(
PlTransportDbLink.db_inventory_id == inventory.id,
PlTransportDbLink.del_flag == 0,
)
.order_by(PlTransportDbLink.create_time.desc())
.first()
)
if not link:
return False
plan = db.query(PlPlan).filter(PlPlan.id == link.plan_id, PlPlan.del_flag == 0).first()
return bool(plan and plan.follow_status == "cancelled")
def _assert_editable(inventory: DbInboundOutbound, voided: bool) -> None:
if voided:
raise HTTPException(status_code=400, detail="运输计划已作废,无法提交回执")
if (inventory.status or "").strip() == COMPLETED_STATUS:
raise HTTPException(status_code=400, detail="单据已完成,无法修改回执")
def _build_public_page(db: Session, inventory: DbInboundOutbound) -> PublicInventoryPageRead:
voided = _resolve_plan_voided(db, inventory)
read_only = (inventory.status or "").strip() == COMPLETED_STATUS
return PublicInventoryPageRead(
batch_no=inventory.batch_no,
business_type=inventory.business_type,
date=inventory_date_to_api(inventory.date) or None,
partner_company=inventory.partner_company,
product=inventory.product,
specification=inventory.specification,
quantity=float(inventory.quantity or 0),
vehicle_no=inventory.vehicle_no or "",
plan_no=inventory.plan_no,
status=inventory.status,
remark=inventory.remark,
site_feedback_remark=inventory.site_feedback_remark,
site_feedback_images=_parse_feedback_images(inventory.site_feedback_images),
site_feedback_time=inventory.site_feedback_time,
read_only=read_only,
voided=voided,
)
@router.get("/{inventory_id}/pound-qr")
def get_public_pound_qr(inventory_id: str, db: Session = Depends(get_db)):
row = (
db.query(DbInboundOutbound)
.filter(DbInboundOutbound.id == inventory_id, DbInboundOutbound.del_flag == 0)
.first()
)
if not row:
raise HTTPException(status_code=404, detail="链接无效或单据不存在")
read = build_public_pound_qr_read(row, quantity_unit="吨")
return success_response(read.model_dump(by_alias=True))
@router.get("/{token}")
def get_public_inventory(token: str, db: Session = Depends(get_db)):
inventory = _get_inventory_by_token(db, token)
page = _build_public_page(db, inventory)
return success_response(page.model_dump(by_alias=True))
@router.post("/{token}/feedback")
def save_public_feedback(
token: str,
payload: PublicInventoryFeedback,
db: Session = Depends(get_db),
):
inventory = _get_inventory_by_token(db, token)
page = _build_public_page(db, inventory)
if page.voided:
return error_response(400, "运输计划已作废,无法提交回执")
if page.read_only:
return error_response(400, "单据已完成,无法修改回执")
if payload.site_feedback_images is not None:
inventory.site_feedback_images = json.dumps(payload.site_feedback_images)
if payload.site_feedback_remark is not None:
inventory.site_feedback_remark = payload.site_feedback_remark
inventory.site_feedback_time = datetime.now()
db.commit()
return success_response({"success": True, "message": "保存成功"})
def _format_file_size(size_bytes: int) -> str:
if size_bytes < 1024:
return f"{size_bytes} B"
if size_bytes < 1024 * 1024:
return f"{size_bytes / 1024:.1f} KB"
return f"{size_bytes / (1024 * 1024):.1f} MB"
@router.post("/{token}/attachments")
def upload_public_attachment(
token: str,
file: UploadFile = File(...),
folder: Optional[str] = Form(""),
db: Session = Depends(get_db),
):
inventory = _get_inventory_by_token(db, token)
page = _build_public_page(db, inventory)
if page.voided:
return error_response(400, "运输计划已作废,无法上传附件")
if page.read_only:
return error_response(400, "单据已完成,无法修改回执")
if not file or not file.filename:
return error_response(400, "请选择文件")
try:
effective_folder = resolve_upload_folder(
folder=folder or "", biz_type="db_inventory_site_feedback"
)
file_content = file.file.read()
full_url = storage.upload_file(file_content, file.filename, effective_folder)
base_url = settings.MINIO_BASE_URL.rstrip("/") if settings.MINIO_BASE_URL else ""
if base_url and full_url.startswith(base_url + "/"):
file_url = full_url[len(base_url) + 1 :]
else:
file_url = full_url
record = oss_svc.create_oss(
db,
tenant_no=inventory.tenant_no,
url=file_url,
original_name=file.filename,
file_suffix=os.path.splitext(file.filename)[1].lstrip(".") if file.filename else "",
file_size=len(file_content),
file_type=file.content_type or "",
biz_type="db_inventory_site_feedback",
user_id=None,
ext1=effective_folder or None,
)
db.commit()
return success_response(
{
"id": record.id,
"fileName": record.original_name,
"fileUrl": record.url,
"fileSize": record.file_size,
"fileSizeDisplay": _format_file_size(record.file_size or 0),
"fileType": record.file_type,
}
)
except Exception as exc:
db.rollback()
return error_response(500, f"上传失败: {str(exc)}")
+66
View File
@@ -0,0 +1,66 @@
"""地磅公共只读:免登车牌 options(现场填写页)"""
from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.models.db_models import DbInboundOutbound, DbPurchasePlan
from app.models.pl_models import PlVehicle
router = APIRouter(prefix="/public/db", tags=["地磅-公共车牌"])
def _resolve_tenant_no(
db: Session,
inventory_id: Optional[str],
plan_id: Optional[str],
) -> str:
if inventory_id:
row = (
db.query(DbInboundOutbound)
.filter(DbInboundOutbound.id == inventory_id, DbInboundOutbound.del_flag == 0)
.first()
)
if not row:
raise HTTPException(status_code=404, detail="出入库单不存在")
return row.tenant_no
if plan_id:
plan = (
db.query(DbPurchasePlan)
.filter(DbPurchasePlan.id == plan_id, DbPurchasePlan.del_flag == 0)
.first()
)
if not plan:
raise HTTPException(status_code=404, detail="计划不存在")
return plan.tenant_no
raise HTTPException(status_code=400, detail="需要提供 inventoryId 或 planId")
@router.get("/vehicle-plates")
def list_public_vehicle_plates(
q: Optional[str] = Query(None),
inventory_id: Optional[str] = Query(None, alias="inventoryId"),
plan_id: Optional[str] = Query(None, alias="planId"),
db: Session = Depends(get_db),
):
"""免登:按出入库/计划解析 tenant_no,返回 pl_vehicle 车牌(self + carrier)。"""
tenant_no = _resolve_tenant_no(db, inventory_id, plan_id)
query = db.query(PlVehicle).filter(
PlVehicle.tenant_no == tenant_no,
PlVehicle.del_flag == 0,
PlVehicle.vehicle_type.in_(["self", "carrier"]),
)
kw = (q or "").strip()
if kw:
query = query.filter(PlVehicle.license_plate.contains(kw))
rows = (
query.order_by(PlVehicle.create_time.desc()).limit(100).all()
)
return [
{"licensePlate": r.license_plate, "vehicleType": r.vehicle_type}
for r in rows
if r.license_plate
]
+705
View File
@@ -0,0 +1,705 @@
from typing import Any, List, Optional, Tuple
from datetime import datetime
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.db_auth import DbUserContext, get_db_current_user
from app.core.delete_guard import assert_row_deletable_by_creator, user_info_from_context
from app.core.tenant_context import get_tenant_no
from app.core.utils import generate_uuid
from app.services.db_data_scope import apply_db_scope, assert_db_row_in_scope
from app.models.db_models import DbInboundOutbound, DbPurchasePlan, DbWeighingSlip
from app.schemas.db.inventory import InboundOutboundRead
from app.schemas.db.plans import PurchasePlanRead
from app.schemas.db.weighing import (
WeighingSlipCreate,
WeighingSlipListResponse,
WeighingSlipRead,
WeighingSlipUpdate,
)
from app.schemas.pl.cancel_reason import VoidReasonBody, normalize_optional_reason
from app.services.db.mappers import (
inventory_date_to_api,
inventory_to_read,
load_user_display_name_map,
parse_datetime_str,
plan_to_read,
weighing_to_read,
)
from app.services.db.list_sort import (
order_weighing,
parse_sort_params,
weighing_needs_inventory_join,
)
from app.services.db.weighing_list_filters import build_weighing_column_filters
from app.services.db.weighing_logic import process_weighing_business_logic
from app.services.db.product_helpers import (
apply_product_snapshot_to_weighing,
resolve_crm_product,
)
from app.utils.excel_export import (
EXPORT_MAX_ROWS,
ExportColumn,
ExportValidationError,
export_rows_to_xlsx_response,
filter_export_columns,
)
router = APIRouter(prefix="/weighing", tags=["weighing"])
_WEIGHING_REMARK_FIELD = "remarks"
def _base_query(db: Session, tenant_no: str):
return db.query(DbWeighingSlip).filter(
DbWeighingSlip.tenant_no == tenant_no,
DbWeighingSlip.del_flag == 0,
DbWeighingSlip.is_voided == 0,
)
def _merge_query(request: Request, **known) -> dict:
out = {k: v for k, v in known.items() if v is not None and v != ""}
for k, v in request.query_params.multi_items():
if k in ("page", "pageSize"):
continue
if k not in out and v not in (None, ""):
out[k] = v
return out
def _param_get(params: dict, *keys: str) -> Any:
for key in keys:
if key in params and params[key] not in (None, ""):
return params[key]
return None
def _filters_from_params(params: dict) -> list:
return build_weighing_column_filters(
plan_no=_param_get(params, "planNo", "plan_no"),
plan_no_in=_param_get(params, "planNoIn", "plan_no_in"),
batch_no=_param_get(params, "batchNo", "batch_no"),
batch_no_in=_param_get(params, "batchNoIn", "batch_no_in"),
vehicle_no=_param_get(params, "vehicleNo", "vehicle_no"),
vehicle_no_in=_param_get(params, "vehicleNoIn", "vehicle_no_in"),
cargo_name=_param_get(params, "cargoName", "cargo_name"),
cargo_name_in=_param_get(params, "cargoNameIn", "cargo_name_in"),
supplier=_param_get(params, "supplier"),
supplier_in=_param_get(params, "supplierIn", "supplier_in"),
consignee=_param_get(params, "consignee"),
consignee_in=_param_get(params, "consigneeIn", "consignee_in"),
business_type=_param_get(params, "businessType", "business_type"),
business_type_in=_param_get(params, "businessTypeIn", "business_type_in"),
date_from=_param_get(params, "dateFrom", "date_from"),
date_to=_param_get(params, "dateTo", "date_to"),
net_weight_op=_param_get(params, "netWeightOp", "net_weight_op"),
net_weight=_param_get(params, "netWeight", "net_weight"),
net_weight_min=_param_get(params, "netWeightMin", "net_weight_min"),
net_weight_max=_param_get(params, "netWeightMax", "net_weight_max"),
gross_weight_op=_param_get(params, "grossWeightOp", "gross_weight_op"),
gross_weight=_param_get(params, "grossWeight", "gross_weight"),
gross_weight_min=_param_get(params, "grossWeightMin", "gross_weight_min"),
gross_weight_max=_param_get(params, "grossWeightMax", "gross_weight_max"),
)
def _body_to_params(body: "WeighingExportBody") -> dict:
data = body.model_dump(by_alias=True, exclude_none=True)
data.pop("ids", None)
data.pop("columns", None)
extra = getattr(body, "model_extra", None) or {}
for key, value in extra.items():
if key not in data and value not in (None, ""):
data[key] = value
return data
def _weighing_query(db: Session, user: DbUserContext, params: dict):
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
query = _base_query(db, tenant_no)
q = _param_get(params, "q")
if q:
keyword = str(q).lower()
query = query.filter(
or_(
func.lower(DbWeighingSlip.vehicle_no).contains(keyword),
func.lower(DbWeighingSlip.plan_no).contains(keyword),
func.lower(DbWeighingSlip.batch_no).contains(keyword),
func.lower(DbWeighingSlip.cargo_name).contains(keyword),
func.lower(DbWeighingSlip.supplier).contains(keyword),
func.lower(DbWeighingSlip.consignee).contains(keyword),
)
)
column_filters = _filters_from_params(params)
if column_filters:
query = query.filter(*column_filters)
query = apply_db_scope(query, DbWeighingSlip, user, db, tenant_no)
sf, so = parse_sort_params(params)
if weighing_needs_inventory_join(sf, so):
query = query.outerjoin(
DbInboundOutbound,
and_(
DbWeighingSlip.inbound_outbound_id == DbInboundOutbound.id,
DbInboundOutbound.del_flag == 0,
),
)
query = query.order_by(
order_weighing(sf, so, default=DbWeighingSlip.gross_weight_time.desc()),
DbWeighingSlip.id.desc(),
)
return query
def _map_weighings(db: Session, weighings: list) -> list[WeighingSlipRead]:
inventory_ids = [w.inbound_outbound_id for w in weighings if w.inbound_outbound_id]
inventory_date_map: dict[str, str] = {}
if inventory_ids:
inventories = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.id.in_(inventory_ids),
DbInboundOutbound.del_flag == 0,
)
.all()
)
for inventory in inventories:
inventory_date_map[inventory.id] = inventory_date_to_api(inventory.date)
user_name_map = load_user_display_name_map(db, [w.create_by for w in weighings])
return [
weighing_to_read(
weighing,
inventory_date=inventory_date_map.get(weighing.inbound_outbound_id or ""),
user_name_map=user_name_map,
)
for weighing in weighings
]
def _fetch_weighing(
db: Session,
user: DbUserContext,
params: dict,
*,
page: Optional[int] = None,
page_size: Optional[int] = None,
) -> Tuple[list[WeighingSlipRead], int]:
query = _weighing_query(db, user, params)
if page is not None and page_size is not None:
total = query.order_by(None).count()
weighings = query.offset((page - 1) * page_size).limit(page_size).all()
return _map_weighings(db, weighings), total
weighings = query.all()
items = _map_weighings(db, weighings)
return items, len(items)
def _get_weighing(
db: Session, tenant_no: str, weighing_id: str, user: DbUserContext
) -> DbWeighingSlip:
row = (
db.query(DbWeighingSlip)
.filter(
DbWeighingSlip.id == weighing_id,
DbWeighingSlip.tenant_no == tenant_no,
DbWeighingSlip.del_flag == 0,
)
.one_or_none()
)
if row is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Weighing {weighing_id} not found",
)
assert_db_row_in_scope(db, row, DbWeighingSlip, user, tenant_no)
return row
def _apply_weighing_product_update(
db: Session, tenant_no: str, row: DbWeighingSlip, payload_dict: dict
) -> None:
if "cargo_name" in payload_dict and "product_id" not in payload_dict:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="请从 CRM 重新选择产品",
)
product_id = payload_dict.pop("product_id", None)
payload_dict.pop("cargo_name", None)
payload_dict.pop("specification", None)
if product_id is not None:
snapshot = resolve_crm_product(db, tenant_no, product_id)
apply_product_snapshot_to_weighing(row, snapshot)
def _apply_weighing_update(row: DbWeighingSlip, payload_dict: dict) -> None:
for key, value in payload_dict.items():
if key == _WEIGHING_REMARK_FIELD:
if isinstance(value, str):
value = value.strip()
row.remark = value
continue
if key in {"gross_weight_time", "tare_weight_time"}:
if value is None or (isinstance(value, str) and not str(value).strip()):
setattr(row, key, None)
else:
parsed = parse_datetime_str(str(value))
if parsed:
setattr(row, key, parsed)
continue
if isinstance(value, str):
value = value.strip()
setattr(row, key, value)
@router.get("/")
def list_weighing(
request: Request,
q: Optional[str] = Query(default=None, description="模糊搜索关键词"),
date_from: Optional[str] = Query(default=None, alias="dateFrom", description="开始日期"),
date_to: Optional[str] = Query(default=None, alias="dateTo", description="结束日期"),
plan_no: Optional[str] = Query(default=None, alias="planNo", description="计划号"),
batch_no: Optional[str] = Query(default=None, alias="batchNo", description="出入库单号"),
vehicle_no: Optional[str] = Query(default=None, alias="vehicleNo", description="车牌号"),
cargo_name: Optional[str] = Query(default=None, alias="cargoName", description="货物名称"),
supplier: Optional[str] = Query(default=None, description="供货单位"),
consignee: Optional[str] = Query(default=None, description="收货单位"),
business_type: Optional[str] = Query(default=None, alias="businessType", description="业务类型"),
page: Optional[int] = Query(default=None, ge=1, description="页码;传入则返回分页结构"),
page_size: Optional[int] = Query(
default=None, ge=1, le=500, alias="pageSize", description="每页条数"
),
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
params = _merge_query(
request,
q=q,
dateFrom=date_from,
dateTo=date_to,
planNo=plan_no,
batchNo=batch_no,
vehicleNo=vehicle_no,
cargoName=cargo_name,
supplier=supplier,
consignee=consignee,
businessType=business_type,
)
# 管理端未传 page:仍返回全量数组(前端本地分页);小程序传 page/pageSize 走服务端分页
paged = page is not None
size = page_size if page_size is not None else 20
page_num = page if page is not None else 1
items, total = _fetch_weighing(
db,
user,
params,
page=page_num if paged else None,
page_size=size if paged else None,
)
if paged:
body = WeighingSlipListResponse(
items=items, total=total, page=page_num, pageSize=size
)
return JSONResponse(content=body.model_dump(by_alias=True))
return JSONResponse(
content=[item.model_dump(by_alias=True) for item in items]
)
class WeighingColumnFacetBody(BaseModel):
"""地磅单列头可选值(去重;可附带列表上下文)"""
model_config = ConfigDict(populate_by_name=True, extra="allow")
field: str = Field(..., description="planNo | batchNo | vehicleNo | cargoName | supplier | consignee")
keyword: Optional[str] = Field(default=None, description="可选值关键字")
limit: Optional[int] = Field(default=500, ge=1, le=500, description="返回条数上限")
_WEIGHING_FACET_COLUMNS = {
"planNo": DbWeighingSlip.plan_no,
"batchNo": DbWeighingSlip.batch_no,
"vehicleNo": DbWeighingSlip.vehicle_no,
"cargoName": DbWeighingSlip.cargo_name,
"supplier": DbWeighingSlip.supplier,
"consignee": DbWeighingSlip.consignee,
}
@router.post("/column-facet-values")
def weighing_column_facet_values(
body: WeighingColumnFacetBody,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
"""地磅单列头可选值:在列表上下文(排除本列)下去重;未作废单据。"""
from app.services.column_facet import list_column_facet_values
from app.services.pl.facet_context import strip_simple_facet_self_params
column = _WEIGHING_FACET_COLUMNS.get(body.field)
if column is None:
raise HTTPException(status_code=400, detail="不支持的列")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
params = strip_simple_facet_self_params(_body_to_params(body), body.field)
extra_filters = [DbWeighingSlip.is_voided == 0]
extra_filters.extend(_filters_from_params(params))
qv = _param_get(params, "q")
if qv:
keyword = str(qv).lower()
extra_filters.append(
or_(
func.lower(DbWeighingSlip.vehicle_no).contains(keyword),
func.lower(DbWeighingSlip.plan_no).contains(keyword),
func.lower(DbWeighingSlip.batch_no).contains(keyword),
func.lower(DbWeighingSlip.cargo_name).contains(keyword),
func.lower(DbWeighingSlip.supplier).contains(keyword),
func.lower(DbWeighingSlip.consignee).contains(keyword),
)
)
rows = list_column_facet_values(
db,
DbWeighingSlip,
column,
tenant_no=tenant_no,
keyword=body.keyword,
limit=body.limit if body.limit is not None else 500,
apply_scope=lambda q: apply_db_scope(q, DbWeighingSlip, user, db, tenant_no),
extra_filters=extra_filters,
)
return {"list": rows}
WEIGHING_EXPORT_COLUMNS = [
ExportColumn(title="日期", field="inventoryDate"),
ExportColumn(title="计划单号", field="planNo"),
ExportColumn(title="出入库单号", field="batchNo"),
ExportColumn(title="车牌号", field="vehicleNo"),
ExportColumn(title="货物名称", field="cargoName"),
ExportColumn(title="规格", field="specification"),
ExportColumn(title="业务类型", field="businessType"),
ExportColumn(title="单据状态", field="docStatus"),
ExportColumn(title="供货单位", field="supplier"),
ExportColumn(title="收货单位", field="consignee"),
ExportColumn(title="本次量(吨)", field="currentQuantity"),
ExportColumn(title="净重(吨)", field="netWeight"),
ExportColumn(title="毛重(kg)", field="grossWeight"),
ExportColumn(title="毛重时间", field="grossWeightTime"),
ExportColumn(title="皮重(kg)", field="tareWeight"),
ExportColumn(title="皮重时间", field="tareWeightTime"),
ExportColumn(title="扣杂(kg)", field="deduction"),
ExportColumn(title="创建人", field="createByName"),
]
class WeighingExportBody(BaseModel):
q: Optional[str] = None
date_from: Optional[str] = Field(default=None, alias="dateFrom")
date_to: Optional[str] = Field(default=None, alias="dateTo")
plan_no: Optional[str] = Field(default=None, alias="planNo")
batch_no: Optional[str] = Field(default=None, alias="batchNo")
vehicle_no: Optional[str] = Field(default=None, alias="vehicleNo")
cargo_name: Optional[str] = Field(default=None, alias="cargoName")
supplier: Optional[str] = None
consignee: Optional[str] = None
business_type: Optional[str] = Field(default=None, alias="businessType")
sort_field: Optional[str] = Field(default=None, alias="sortField")
sort_order: Optional[str] = Field(default=None, alias="sortOrder")
ids: Optional[List[str]] = None
columns: Optional[List[str]] = None
model_config = {"populate_by_name": True, "extra": "allow"}
def _kg_to_ton(value) -> float:
try:
return round(float(value or 0) / 1000, 2)
except (TypeError, ValueError):
return 0.0
@router.post("/export")
def export_weighing(
body: WeighingExportBody,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
):
"""导出地磅单列表(当前筛选全量,或 ids 已选)。"""
try:
items, _total = _fetch_weighing(db, user, _body_to_params(body))
if body.ids:
id_set = set(body.ids)
items = [x for x in items if x.id in id_set]
if len(items) > EXPORT_MAX_ROWS:
raise ExportValidationError(f"导出超过 {EXPORT_MAX_ROWS} 条,请缩小筛选范围")
rows = []
for item in items:
data = item.model_dump(by_alias=True)
data["docStatus"] = "已作废" if data.get("isVoided") == 1 else "正常"
data["currentQuantity"] = _kg_to_ton(data.get("currentQuantity"))
data["netWeight"] = _kg_to_ton(data.get("netWeight"))
if not data.get("inventoryDate"):
gwt = data.get("grossWeightTime") or ""
data["inventoryDate"] = str(gwt)[:10] if gwt else ""
if not data.get("createByName"):
data["createByName"] = data.get("createBy") or ""
rows.append(data)
cols = filter_export_columns(WEIGHING_EXPORT_COLUMNS, body.columns)
date_str = datetime.now().strftime("%Y%m%d")
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
return export_rows_to_xlsx_response(
db,
tenant_no=tenant_no,
sheet_title="地磅单列表",
columns=cols,
rows=rows,
filename_stem=f"地磅单列表_{date_str}",
)
except ExportValidationError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
@router.post("/", response_model=WeighingSlipRead, status_code=status.HTTP_201_CREATED)
def create_weighing(
payload: WeighingSlipCreate,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingSlipRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
inbound_outbound_id = payload.inbound_outbound_id
if inbound_outbound_id:
existing = (
db.query(DbWeighingSlip)
.filter(
DbWeighingSlip.inbound_outbound_id == inbound_outbound_id,
DbWeighingSlip.is_voided == 0,
DbWeighingSlip.del_flag == 0,
)
.first()
)
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="该出入库单已经存在关联的地磅单,无法重复创建",
)
planned_quantity = payload.planned_quantity
current_quantity = payload.current_quantity
purchase_plan_id = payload.purchase_plan_id
batch_no = payload.batch_no.strip() if payload.batch_no else None
if inbound_outbound_id:
inventory = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.id == inbound_outbound_id,
DbInboundOutbound.tenant_no == tenant_no,
DbInboundOutbound.del_flag == 0,
)
.one_or_none()
)
if inventory:
if current_quantity is None:
current_quantity = inventory.quantity * 1000
if purchase_plan_id is None and inventory.purchase_plan_id:
purchase_plan_id = inventory.purchase_plan_id
if purchase_plan_id:
plan = (
db.query(DbPurchasePlan)
.filter(DbPurchasePlan.id == purchase_plan_id)
.one_or_none()
)
if plan and planned_quantity is None:
planned_quantity = plan.planned_quantity * 1000
if not batch_no and inventory.batch_no:
batch_no = inventory.batch_no
gross_weight = payload.gross_weight or 0
gross_time = parse_datetime_str(payload.gross_weight_time) if payload.gross_weight_time else None
# 没填毛重时不要补当前时间,否则只填皮重也会把出入库单标成已完成
if gross_time is None and gross_weight > 0:
gross_time = datetime.now()
tare_time = (
parse_datetime_str(payload.tare_weight_time)
if payload.tare_weight_time and payload.tare_weight_time.strip()
else None
)
snapshot = resolve_crm_product(db, tenant_no, payload.product_id)
row = DbWeighingSlip(
id=generate_uuid(),
tenant_no=tenant_no,
vehicle_no=payload.vehicle_no.strip(),
plan_no=payload.plan_no.strip() if payload.plan_no else None,
business_type=payload.business_type,
batch_no=batch_no,
supplier=payload.supplier.strip(),
consignee=payload.consignee.strip(),
gross_weight=gross_weight,
gross_weight_time=gross_time,
tare_weight=payload.tare_weight or 0,
tare_weight_time=tare_time,
deduction=payload.deduction or 0,
net_weight=payload.net_weight or 0,
planned_quantity=planned_quantity,
executed_quantity=payload.executed_quantity,
purchase_plan_id=purchase_plan_id,
inbound_outbound_id=inbound_outbound_id,
weighing_point=payload.weighing_point or "山峡化工",
remark=payload.remarks,
current_quantity=current_quantity,
is_voided=0,
create_by=user.id,
create_dept_id=user.dept_id,
)
apply_product_snapshot_to_weighing(row, snapshot)
db.add(row)
db.commit()
db.refresh(row)
process_weighing_business_logic(db, row)
db.refresh(row)
return weighing_to_read(row, db=db)
@router.get("/{id}", response_model=WeighingSlipRead)
def get_weighing(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingSlipRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id, user)
return weighing_to_read(row, db=db)
@router.patch("/{id}", response_model=WeighingSlipRead)
def update_weighing(
id: str,
payload: WeighingSlipUpdate,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingSlipRead:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id, user)
if row.is_voided == 1:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot update voided weighing record",
)
payload_dict = payload.model_dump(exclude_unset=True)
_apply_weighing_product_update(db, tenant_no, row, payload_dict)
_apply_weighing_update(row, payload_dict)
row.update_by = user.id
db.commit()
db.refresh(row)
process_weighing_business_logic(db, row)
db.refresh(row)
return weighing_to_read(row, db=db)
@router.post("/{id}/void", status_code=status.HTTP_204_NO_CONTENT)
def void_weighing(
id: str,
body: Optional[VoidReasonBody] = Body(default=None),
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id, user)
if row.is_voided == 1:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Weighing record is already voided",
)
now = datetime.now()
row.is_voided = 1
row.void_reason = normalize_optional_reason(body.void_reason if body else None)
row.void_time = now
row.void_by = user.id
row.update_by = user.id
db.commit()
process_weighing_business_logic(db, row)
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_weighing(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> None:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id, user)
assert_row_deletable_by_creator(row, user_info_from_context(user))
row.is_voided = 1
row.update_by = user.id
db.commit()
process_weighing_business_logic(db, row)
class WeighingRelatedData(BaseModel):
plan: Optional[PurchasePlanRead]
inventory: Optional[InboundOutboundRead]
@router.get("/{id}/related", response_model=WeighingRelatedData)
def get_weighing_related(
id: str,
db: Session = Depends(get_db),
user: DbUserContext = Depends(get_db_current_user),
) -> WeighingRelatedData:
tenant_no = get_tenant_no(db, user.to_tenant_user_dict())
row = _get_weighing(db, tenant_no, id, user)
plan = None
if row.purchase_plan_id:
plan = (
db.query(DbPurchasePlan)
.filter(
DbPurchasePlan.id == row.purchase_plan_id,
DbPurchasePlan.del_flag == 0,
)
.one_or_none()
)
elif row.plan_no:
plan = (
db.query(DbPurchasePlan)
.filter(
DbPurchasePlan.plan_no == row.plan_no,
DbPurchasePlan.tenant_no == tenant_no,
DbPurchasePlan.del_flag == 0,
)
.limit(1)
.first()
)
inventory = None
if row.inbound_outbound_id:
inventory = (
db.query(DbInboundOutbound)
.filter(
DbInboundOutbound.id == row.inbound_outbound_id,
DbInboundOutbound.del_flag == 0,
)
.one_or_none()
)
return WeighingRelatedData(
plan=plan_to_read(plan, db=db) if plan else None,
inventory=inventory_to_read(inventory, db=db) if inventory else None,
)
+102
View File
@@ -0,0 +1,102 @@
"""门户进入文档库。"""
from fastapi import APIRouter, Depends, File, Form, Query, UploadFile
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.doclib_upload_route import DoclibRoute
from app.schemas.doclib import DeleteFilesBody, FolderCreateBody, FolderUpdateBody, ShareBody
from app.services.doclib_service import DoclibService
from app.services.doclib_storage import download_document, upload_document
from app.core.auth import get_current_user
from app.core.response import error_response, success_response
from app.services.doclib_sso import consume_ticket, open_session
router = APIRouter(tags=["文档库"], route_class=DoclibRoute)
@router.post("/web/doclib/sso")
def doclib_sso(user: dict = Depends(get_current_user)):
"""当前门户用户换取文档库一次性进入地址。所有已登录角色都可调用。"""
try:
data = open_session(user["user_id"], user.get("real_name") or user.get("username") or "")
except Exception as exc:
return error_response(502, str(exc) or "无法连接文档库")
return success_response(data)
@router.get("/public/doclib/exchange")
def doclib_exchange(code: str = ""):
"""文档库页面用一次性票据换登录会话。票据 60 秒内只能用一次。"""
login = consume_ticket(code)
if not login:
return error_response(400, "进入票据无效或已过期")
return success_response(login)
# 门户内文档库复用此路由;上面的旧 SSO 接口保留用于迁移期间兼容。
def service(db: Session = Depends(get_db), user: dict = Depends(get_current_user)):
return DoclibService(db, user)
@router.get('/web/doclib/tree')
def document_tree(svc: DoclibService = Depends(service)):
return success_response(svc.tree())
@router.get('/web/doclib/users')
def document_users(keyword: str = Query('', max_length=100), svc: DoclibService = Depends(service)):
return success_response(svc.users(keyword))
@router.get('/web/doclib/files')
def document_list(scope: str = 'mine', folderId: str = Query('', max_length=64),
keyword: str = Query('', max_length=255), page: int = Query(1, ge=1),
pageSize: int = Query(20, ge=1, le=100), svc: DoclibService = Depends(service)):
return success_response(svc.list_files(scope, folderId, keyword, page, pageSize))
@router.post('/web/doclib/folders')
def create_document_folder(body: FolderCreateBody, svc: DoclibService = Depends(service)):
return success_response(svc.create_folder(body.name, body.parentId))
@router.put('/web/doclib/folders/{folder_id}')
def rename_document_folder(folder_id: str, body: FolderUpdateBody, svc: DoclibService = Depends(service)):
return success_response(svc.rename_folder(folder_id, body.name))
@router.delete('/web/doclib/folders/{folder_id}')
def delete_document_folder(folder_id: str, svc: DoclibService = Depends(service)):
svc.delete_folder(folder_id)
return success_response()
@router.post('/web/doclib/upload')
def upload_document_file(file: UploadFile = File(...), folderId: str = Form(''),
svc: DoclibService = Depends(service)):
try:
return success_response(upload_document(svc, file, folderId))
finally:
file.file.close()
@router.post('/web/doclib/files/batch-delete')
def delete_document_files(body: DeleteFilesBody, svc: DoclibService = Depends(service)):
svc.delete_files(body.ids)
return success_response()
@router.get('/web/doclib/files/{file_id}')
def document_detail(file_id: str, svc: DoclibService = Depends(service)):
return success_response(svc.get_file(file_id))
@router.put('/web/doclib/files/{file_id}/shares')
def share_document(file_id: str, body: ShareBody, svc: DoclibService = Depends(service)):
return success_response(svc.set_shares(file_id, body.userIds))
@router.get('/web/doclib/files/{file_id}/download')
def download_document_file(file_id: str, svc: DoclibService = Depends(service)):
return download_document(svc, file_id)
Loaded 100 of 3072 files, more files were not shown because too many files have changed in this diff. Show more