@parall/cli 1.79.0 → 1.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/commands/apps-access.d.ts.map +1 -1
  2. package/dist/commands/apps-access.js +19 -9
  3. package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
  4. package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
  5. package/dist/commands/apps-actions-sdk.generated.js +1 -1
  6. package/dist/commands/apps-actions.d.ts.map +1 -1
  7. package/dist/commands/apps-actions.js +19 -1
  8. package/dist/commands/apps-add.js +1 -1
  9. package/dist/commands/apps-blocks.d.ts.map +1 -1
  10. package/dist/commands/apps-blocks.js +8 -0
  11. package/dist/commands/apps-local-runner.generated.d.ts +1 -1
  12. package/dist/commands/apps-local-runner.generated.d.ts.map +1 -1
  13. package/dist/commands/apps-local-runner.generated.js +1 -1
  14. package/dist/commands/apps-placement.d.ts +13 -0
  15. package/dist/commands/apps-placement.d.ts.map +1 -0
  16. package/dist/commands/apps-placement.js +20 -0
  17. package/dist/commands/apps-scaffold.d.ts +7 -1
  18. package/dist/commands/apps-scaffold.d.ts.map +1 -1
  19. package/dist/commands/apps-scaffold.js +88 -30
  20. package/dist/commands/apps-template-catalog.d.ts +85 -0
  21. package/dist/commands/apps-template-catalog.d.ts.map +1 -0
  22. package/dist/commands/apps-template-catalog.gen.d.ts +3 -0
  23. package/dist/commands/apps-template-catalog.gen.d.ts.map +1 -0
  24. package/dist/commands/apps-template-catalog.gen.js +228 -0
  25. package/dist/commands/apps-template-catalog.js +49 -0
  26. package/dist/commands/apps-template-init.d.ts +39 -0
  27. package/dist/commands/apps-template-init.d.ts.map +1 -0
  28. package/dist/commands/apps-template-init.js +118 -0
  29. package/dist/commands/apps-template.d.ts +11 -0
  30. package/dist/commands/apps-template.d.ts.map +1 -1
  31. package/dist/commands/apps-template.js +18 -7
  32. package/dist/commands/apps-templates.gen.d.ts +1 -0
  33. package/dist/commands/apps-templates.gen.d.ts.map +1 -1
  34. package/dist/commands/apps-templates.gen.js +11 -2
  35. package/dist/commands/apps.d.ts.map +1 -1
  36. package/dist/commands/apps.js +6 -2
  37. package/dist/commands/browser.js +2 -2
  38. package/dist/commands/clip-connection.d.ts.map +1 -1
  39. package/dist/commands/clip-connection.js +11 -11
  40. package/dist/commands/clip.d.ts +6 -0
  41. package/dist/commands/clip.d.ts.map +1 -1
  42. package/dist/commands/clip.js +57 -41
  43. package/dist/commands/db-plane.d.ts.map +1 -1
  44. package/dist/commands/db-plane.js +10 -6
  45. package/dist/commands/dbs.d.ts +3 -2
  46. package/dist/commands/dbs.d.ts.map +1 -1
  47. package/dist/commands/dbs.js +10 -5
  48. package/dist/commands/messages-react.d.ts +15 -0
  49. package/dist/commands/messages-react.d.ts.map +1 -0
  50. package/dist/commands/messages-react.js +65 -0
  51. package/dist/commands/messages.d.ts.map +1 -1
  52. package/dist/commands/messages.js +2 -15
  53. package/dist/lib/connector-ref.d.ts +3 -0
  54. package/dist/lib/connector-ref.d.ts.map +1 -0
  55. package/dist/lib/connector-ref.js +2 -0
  56. package/dist/lib/publish-source.js +4 -4
  57. package/package.json +5 -5
@@ -0,0 +1,228 @@
1
+ export const APP_TEMPLATES = [
2
+ {
3
+ "id": "pipeline",
4
+ "intro": {
5
+ "id": "pipeline",
6
+ "cli": "1.80.0",
7
+ "name": {
8
+ "en": "Customer / partner pipeline",
9
+ "zh": "客户 / 合作管线"
10
+ },
11
+ "summary": {
12
+ "en": "Customers, brand deals or creator partnerships: where each one stands and what happens next, on one board.",
13
+ "zh": "客户、品牌商单、达人合作,每一家走到哪一步、下一步做什么,都在一块看板上。"
14
+ },
15
+ "short": {
16
+ "en": "Where each customer or partner deal stands",
17
+ "zh": "客户、商单、达人合作的进度"
18
+ },
19
+ "agent": {
20
+ "en": "Tells you who to follow up each day and drafts the message",
21
+ "zh": "每天提醒该跟进谁,替你起草跟进消息"
22
+ },
23
+ "pages": [
24
+ {
25
+ "id": "board",
26
+ "icon": "square-kanban",
27
+ "name": {
28
+ "en": "Pipeline board",
29
+ "zh": "管线看板"
30
+ },
31
+ "description": {
32
+ "en": "A card for each deal, laid out by stage. The stages are your own words — for brand deals, say, Inquiry → Quote → Contract → Delivery → Payment.",
33
+ "zh": "每个合作一张卡片,按阶段排开。阶段按你们的叫法,比如商单是 询价 → 报价 → 签约 → 执行 → 结款。"
34
+ }
35
+ },
36
+ {
37
+ "id": "followups",
38
+ "icon": "list-todo",
39
+ "name": {
40
+ "en": "Follow up today",
41
+ "zh": "今天该跟进"
42
+ },
43
+ "description": {
44
+ "en": "The agent lays out each day who to follow up and why, with a message drafted for you.",
45
+ "zh": "agent 每天排好:跟谁、为什么,还有它替你起草的消息。"
46
+ }
47
+ },
48
+ {
49
+ "id": "partners",
50
+ "icon": "building-2",
51
+ "name": {
52
+ "en": "Partner details",
53
+ "zh": "合作方详情"
54
+ },
55
+ "description": {
56
+ "en": "Contacts, the history with them, the next step and its date.",
57
+ "zh": "联系人、往来记录、下一步和截止日期。"
58
+ }
59
+ }
60
+ ],
61
+ "questions": [
62
+ {
63
+ "en": "Are you following customers, brand deals or creator partnerships? The stages will be named the way you name them.",
64
+ "zh": "跟进的是客户、品牌商单,还是达人合作?阶段名按你们平时的叫法来。"
65
+ },
66
+ {
67
+ "en": "Where is this kept today — a spreadsheet, a channel, email?",
68
+ "zh": "这些信息现在记在哪?表格、某个频道,还是邮件里?"
69
+ },
70
+ {
71
+ "en": "Who follows up? Should each person get their own view?",
72
+ "zh": "谁负责跟进?要不要按人分开看?"
73
+ },
74
+ {
75
+ "en": "Should amounts go in?",
76
+ "zh": "金额要不要录进来?"
77
+ },
78
+ {
79
+ "en": "What time each day should it go through the pipeline?",
80
+ "zh": "每天几点帮你巡检一遍?"
81
+ }
82
+ ],
83
+ "data": [
84
+ {
85
+ "kind": "channels",
86
+ "name": {
87
+ "en": "Channels",
88
+ "zh": "频道"
89
+ },
90
+ "text": {
91
+ "en": "Past messages in a channel such as #deals. The agent must be in the channel to read it.",
92
+ "zh": "比如 #商务合作 里的历史消息。它得先在频道里,才能读到。"
93
+ }
94
+ },
95
+ {
96
+ "kind": "tasks",
97
+ "name": {
98
+ "en": "Tasks",
99
+ "zh": "任务"
100
+ },
101
+ "text": {
102
+ "en": "Tasks about your partners.",
103
+ "zh": "和合作方有关的任务。"
104
+ }
105
+ },
106
+ {
107
+ "kind": "wiki",
108
+ "name": {
109
+ "en": "Wiki",
110
+ "zh": "知识库"
111
+ },
112
+ "text": {
113
+ "en": "Documents such as price lists and how deals are run.",
114
+ "zh": "报价单、合作流程这类文档。"
115
+ }
116
+ },
117
+ {
118
+ "kind": "connections",
119
+ "name": {
120
+ "en": "Connections",
121
+ "zh": "外部连接"
122
+ },
123
+ "text": {
124
+ "en": "Mailboxes and spreadsheets the organization has connected (the sales Gmail, say) for the exchanges with your partners. For a connection it cannot use yet, it asks for access in the DM first.",
125
+ "zh": "组织里连着的邮箱、表格(比如商务邮箱的 Gmail)里和合作方的往来。它用不了的连接,会先在私信里申请。"
126
+ }
127
+ }
128
+ ],
129
+ "data_note": {
130
+ "en": "Exactly what it reads, and how far back, it agrees with you in the DM first.",
131
+ "zh": "具体读哪些、读多久以前的,它会在私信里先跟你确认。"
132
+ },
133
+ "visibility": {
134
+ "en": "The partners, contacts, amounts and stages it reads go into the app. By default everyone in the organization can see them; to keep them to a few people, set everyone else in the organization to not readable and add those people one by one.",
135
+ "zh": "读到的合作方、联系人、金额和阶段会写进 app。默认组织里所有人都能看到;要只给少数人看,把 app 的「组织里的其他人」设成不可读,再单独加人。"
136
+ },
137
+ "routine": [
138
+ {
139
+ "en": "Goes through the pipeline each day, lays out who to follow up today and drafts the message for each owner.",
140
+ "zh": "每天巡检一遍,排出「今天该跟进」,替负责人起草跟进消息。"
141
+ },
142
+ {
143
+ "en": "Tells the owner when a deal has sat in one stage too long.",
144
+ "zh": "合作在一个阶段停太久,提醒负责人。"
145
+ },
146
+ {
147
+ "en": "When someone moves a deal or adds to the history, takes a look and fills in the next step and its date.",
148
+ "zh": "有人改了阶段或加了跟进记录,它看一眼,补上下一步和截止日期。"
149
+ }
150
+ ],
151
+ "wake": [
152
+ {
153
+ "kind": "data_changed",
154
+ "name": {
155
+ "en": "When someone writes in the app",
156
+ "zh": "有人在 app 里写入时"
157
+ },
158
+ "text": {
159
+ "en": "Moving a deal or adding to the history wakes it to take a look.",
160
+ "zh": "改阶段、加跟进记录,它都会被叫醒看一眼。"
161
+ }
162
+ },
163
+ {
164
+ "kind": "daily",
165
+ "name": {
166
+ "en": "Once a day",
167
+ "zh": "每天一次"
168
+ },
169
+ "text": {
170
+ "en": "At a time you agree with it in the DM, such as 9:00 every day.",
171
+ "zh": "几点在私信里跟它定,比如每天 9:00。"
172
+ }
173
+ }
174
+ ],
175
+ "limits": [
176
+ {
177
+ "kind": "visibility",
178
+ "text": {
179
+ "en": "Everyone who can open the app sees the amounts and contacts' phone numbers and emails; they cannot be hidden from some of them. To keep the whole app to a few people, set everyone else in the organization to not readable and add those people one by one.",
180
+ "zh": "能打开这个 app 的人都能看到金额、联系人的电话和邮箱,不能只对其中一部分人藏起来;要整个 app 只给少数人看,把「组织里的其他人」设成不可读,再单独加人。"
181
+ }
182
+ },
183
+ {
184
+ "kind": "uploads",
185
+ "text": {
186
+ "en": "The pages cannot take file uploads. Send contracts, price lists and receipts to the agent instead.",
187
+ "zh": "页面上不能上传文件。合同、报价单、凭证这类附件,直接发给 agent。"
188
+ }
189
+ },
190
+ {
191
+ "kind": "links",
192
+ "text": {
193
+ "en": "Links to Parall (channels, tasks, documents) do not open from inside the app.",
194
+ "zh": "app 里点不开 Parall 的链接(频道、任务、文档)。"
195
+ }
196
+ }
197
+ ]
198
+ },
199
+ "skill": "# 应用模板:客户 / 合作管线(pipeline)\n\n有人要一个跟进客户、品牌商单或达人合作的 app 时,照这份 skill 做:先和发起的人对清楚、讲明要读哪些数据,对方同意后用模板源码和组织里的真数据建好 app,配好叫醒,之后每次被叫醒照「平时」一节做。建 app 的通用做法、PostgreSQL 写法和订阅数据变化的写法在能力说明和脚手架的 `AGENTS.md` 里,这里只写这个模板特有的。\n\n用对方的语言和对方说话;app 里的阶段名和文案也用对方团队的说法。\n\n## 1. 对齐\n\n在私信里一条消息问完下面几件事,每件带上默认值;对方没答的按默认:\n\n1. 跟进的是什么(客户、品牌商单、达人合作……),阶段怎么叫。默认:模板自带的 询价 → 报价 → 签约 → 执行 → 结款。\n2. 这些信息现在记在哪:表格、某个频道、邮件、任务还是 Wiki。默认:只用对方在私信里发给你的内容。\n3. 谁负责跟进,要不要按人分开看。默认:发起人自己负责,看板上可以按负责人筛选。\n4. 金额要不要录进来(录了能打开这个 app 的人都看得到)。默认:不录。\n5. 每天几点巡检一遍,用哪个时区。默认:每天 9:00,发起人所在的时区。\n\n## 2. 讲明数据\n\n同一条消息里,在读任何数据之前讲明:\n\n- 要读哪些:具体到哪个频道、哪些任务、哪几篇 Wiki、组织层的哪个连接,读多久以前的。\n- 读到的什么会写进 app:合作方、联系人、阶段、金额(如果录)、下一步和往来摘要。\n- 写进 app 后默认组织里所有人都能看到;要只给少数人看,把 app 的「组织里的其他人」设成不可读,再单独加人。写类调用的参数记在调用记录里,只有作者、组织 owner / admin 和调用者本人看得到。\n- 你读不到的:请对方把你拉进频道,或者按审批卡申请连接,不绕路。\n\n对方同意之前,不读这些数据,也不建 app。\n\n要读的内容里,发起人自己看不到的(发起人不在的频道——公开频道也一样,非成员读不到消息;发起人没有权限的任务或 Wiki;别人的个人连接),先在私信里问你的负责人,没有负责人就问 org admin:说清是谁要建什么、要读哪些内容、写进 app 后谁能看到(默认组织里所有人)。他同意了才读这部分;不同意,就只用发起人看得到的。拿不准发起人看不看得到,按看不到处理。频道看成员名单:`parall chats members list <chat>`。\n\n## 3. 建\n\n1. `parall app create --name \"<名字>\"`,记下 `app_…`。对方要只给少数人看的,建的时候加 `--members none`(先建开放的再改,名字已经出现在别人的列表里),建好后用 `parall app access add <app_…> <usr_…> --level read` 逐个加人,要能改的用 `--level write`。\n2. `parall app init <dir> --template pipeline --app <app_…>`:写出模板源码和这份 skill(项目根目录的 `SKILL.md`)。这个 app 的 Database 在 TiDB 上时它会拒绝:照它的说明告诉对方,不要自己改写成 MySQL。\n3. 按回答改:阶段在 `shared/pipeline.ts` 的 `STAGES`(改名就改 `en` / `zh`,`id` 是存进数据的值),不录金额就把 `AMOUNTS` 改成 `false`,币种是 `CURRENCY`;文案在 `src/pages/*/messages.ts`;要多记的字段,在 `db/schema.sql` 加列(`ALTER TABLE … ADD COLUMN IF NOT EXISTS`),再改 `actions/` 和页面。\n4. 建表:`parall app db exec --app <app_…> --file db/schema.sql`。\n5. 导入真数据,只从对方同意的来源:合作方进 `partners`(同名按 `lower(name)` 去重),每个合作进 `deals`,往来进 `activities`(`source` 写来源,比如 `#商务合作`、`Gmail`;你整理的写 `by_agent = true`)。负责人写成员的 `usr_…` 和名字。读不到的字段留空:不猜金额、日期或联系方式,不编合作方或往来。一次 exec 最多 256 KiB,大的分几次。\n6. `pnpm install && pnpm build` → `parall app check dist` → `parall app publish dist --app <app_…> --source .`。\n\n## 4. 叫醒\n\n- 订阅这个 app 的数据变化,只盯 `deals` 与 `activities`:`parall triggers create --source-kind platform_event --event-types app.data.changed --name \"<app 名>有写入\" --target-ids <你的 usr_…> --filter '…' --template '…'`。过滤条件写这个 app(`\"<app_…>\" in entity.app_ids`)和这两张表(`entity.tables != null && (\"deals\" in entity.tables || \"activities\" in entity.tables)`;过滤条件不支持 `exists` 这类循环宏)。`--template` 是叫醒你时发来的话(Liquid),写明是哪个 app、怎么处理,比如 `「<app 名>」prll://<app_…> 有新写入:表 {{ entity.tables | json }},写入的人 {{ entity.actor_ids | json }}。照 <dir>/SKILL.md 的「平时」处理。`\n- 再建一个每天一次的定时任务,时间按对方说的:`parall schedules create --name \"…\" --description \"…\" --target-ids <你的 usr_…> --cron-expr \"0 9 * * *\" --timezone <对方的时区>`;`--description` 写清这是哪个 app 的巡检、照 `SKILL.md` 的「平时」做。\n- 你自己写入不会叫醒你。平时读数据用 `parall app db query`:用 `parall app db exec` 跑查询也算一次写入,而且表名记为未知,按表过滤就失效了。\n\n## 5. 交付\n\n在私信里回 app 链接(`prll://app_…`),说明导入了什么(几个合作方、几个合作、几条往来,各来自哪里)、什么时候会被叫醒(有人在 app 里改阶段或加记录时,以及每天几点),问要不要发到频道。\n\n## 6. 平时\n\n- 每天的巡检:读进行中的合作(`parall app db query`)。下一步今天到期或已经逾期的,写清为什么要跟进,再替负责人起草一条跟进消息:`parall app action run <app_…> followups_draft --params '{\"id\": \"<deal id>\", \"reason\": \"…\", \"draft\": \"…\"}'`,页面「今天该跟进」就会列出来。在一个阶段停了太久(默认 14 天没有变化)的,私信提醒负责人。\n- 有人在 app 里写入时:看改了什么。下一步空了的,按往来记录补上下一步和日期;拿不准就问负责人。\n- 只读对方同意过的来源。要读新的来源,先按「讲明数据」再问一次。\n- 改 app 前,本地没有项目就先 `parall app pull <app_…> --out <dir>` 取回当前版本的源码。\n- 要人拍板的事去问,不替人决定:改金额、改负责人、把合作标为完成或未成、删除合作方或合作。\n",
200
+ "overlay": {
201
+ "_overlay.json": "{\n \"remove\": [\"public/manifest.json\", \"src/pages/items\", \"actions/items.ts\", \"shared/items.ts\"],\n \"blocks\": []\n}\n",
202
+ "actions/checks.ts": "import { STAGES } from '@shared/pipeline';\nimport { ActionError } from './parall-actions';\n\n// Checks the pipeline's actions share. The platform has already checked the\n// params against public/manifest.json; these are the rules a JSON Schema\n// cannot say. Messages reach the caller as they are (ActionError).\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** An id of a row; anything else cannot exist. */\nexport function uuid(id: unknown, what: string): string {\n if (typeof id !== 'string' || !UUID.test(id)) {\n throw new ActionError(`This ${what} does not exist.`);\n }\n return id;\n}\n\n/** A YYYY-MM-DD that is a real day; '' or nothing is null. */\nexport function optionalDate(value: string | undefined, field: string): string | null {\n if (!value) return null;\n const day = new Date(`${value}T00:00:00Z`);\n if (!DATE.test(value) || Number.isNaN(day.getTime()) || !day.toISOString().startsWith(value)) {\n throw new ActionError(`${field} is not a date (YYYY-MM-DD).`);\n }\n return value;\n}\n\n/** Trimmed text, required. */\nexport function required(value: string | undefined, field: string): string {\n const text = (value ?? '').trim();\n if (!text) throw new ActionError(`${field} is required.`);\n return text;\n}\n\n/** A stage of shared/pipeline.ts. */\nexport function stage(id: string): string {\n if (!STAGES.some((s) => s.id === id)) {\n throw new ActionError(\n `Unknown stage ${JSON.stringify(id)}; the stages are ${STAGES.map((s) => s.id).join(', ')}.`,\n );\n }\n return id;\n}\n\n/** An amount of money: a finite number, not negative; nothing is null. */\nexport function amount(value: number | undefined): number | null {\n if (value === undefined) return null;\n if (!Number.isFinite(value) || value < 0) throw new ActionError('The amount is not valid.');\n return Math.round(value * 100) / 100;\n}\n",
203
+ "actions/deals.ts": "import type {\n Deal,\n DealInput,\n DealMoveInput,\n FollowupDoneInput,\n FollowupDraftInput,\n FollowupSnoozeInput,\n} from '@shared/pipeline';\nimport { DEAL_STATUSES } from '@shared/pipeline';\nimport { amount, optionalDate, required, stage, uuid } from './checks';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// Deals and the follow-ups on them (src/pages/board, src/pages/followups).\n// Everyone who can open the app (by default, the whole organization) reads\n// every deal, and those who can change it create, edit and move deals and\n// mark follow-ups done; a deal is deleted by its creator or an org\n// owner/admin. Tighten these here: past the app's access setting, the\n// actions are the only gate.\n\nconst DEAL_COLUMNS = `d.id, d.partner_id, p.name AS partner_name, d.title, d.stage, d.status,\n d.amount, d.owner_id, d.owner_name, d.next_step,\n to_char(d.next_step_due, 'YYYY-MM-DD') AS next_step_due,\n d.followup_reason, d.followup_draft, d.followup_by_name, d.created_by, d.updated_at`;\n// $1 = ctx.viewer.id, $2 = ctx.viewer.role\nconst CAN_DELETE = `(d.created_by = $1 OR $2 IN ('owner', 'admin'))`;\n\nexport async function readDeals(ctx: ActionContext, where: string, params: unknown[]) {\n const { rows } = await ctx.db.query(\n `SELECT ${DEAL_COLUMNS}, ${CAN_DELETE} AS can_delete\n FROM deals d JOIN partners p ON p.id = d.partner_id\n WHERE ${where}\n ORDER BY d.next_step_due NULLS LAST, d.updated_at DESC\n LIMIT 2000`,\n [ctx.viewer.id, ctx.viewer.role, ...params],\n );\n return rows as unknown as Deal[];\n}\n\nasync function readDeal(ctx: ActionContext, id: string): Promise<Deal> {\n const [deal] = await readDeals(ctx, 'd.id = $3', [id]);\n if (!deal) throw new ActionError('This deal does not exist.');\n return deal;\n}\n\n/** The deal's partner: partner_id, or the partner of that name (created\n * when there is none). */\nasync function partnerFor(ctx: ActionContext, input: DealInput): Promise<string> {\n if (input.partner_id) {\n const id = uuid(input.partner_id, 'partner');\n const { rows } = await ctx.db.query(`SELECT id FROM partners WHERE id = $1`, [id]);\n if (!rows[0]) throw new ActionError('This partner does not exist.');\n return id;\n }\n const name = required(input.partner_name, 'The partner');\n // The no-op update makes RETURNING give the existing partner's id.\n const { rows } = await ctx.db.exec(\n `INSERT INTO partners (name, owner_id, owner_name, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT ((lower(name))) DO UPDATE SET name = partners.name\n RETURNING id`,\n [\n name,\n input.owner_id || null,\n input.owner_id ? (input.owner_name ?? null) : null,\n ctx.viewer.id,\n ctx.viewer.display_name,\n ],\n );\n return rows[0]?.id as string;\n}\n\nexport const dealActions = {\n /** read: the open deals — the board and the follow-ups page. */\n async pipeline_board(ctx: ActionContext): Promise<Deal[]> {\n return readDeals(ctx, `d.status = 'open'`, []);\n },\n\n /** write: creates a deal (no id) or rewrites one; see DealInput. */\n async deals_save(ctx: ActionContext, input: DealInput): Promise<Deal> {\n const id = input.id === undefined ? null : uuid(input.id, 'deal');\n const title = required(input.title, 'A title');\n const stageId = stage(input.stage);\n const value = amount(input.amount);\n const due = optionalDate(input.next_step_due, 'next_step_due');\n const ownerId = input.owner_id || null;\n const ownerName = ownerId ? (input.owner_name ?? '').trim() || null : null;\n const nextStep = (input.next_step ?? '').trim();\n if (id !== null) {\n // Before partnerFor: an edit of a deal that is gone must not leave a new partner behind.\n const { rows } = await ctx.db.query(`SELECT 1 FROM deals WHERE id = $1`, [id]);\n if (!rows[0]) throw new ActionError('This deal does not exist.');\n }\n const partnerId = await partnerFor(ctx, input);\n\n if (id === null) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO deals (partner_id, title, stage, amount, owner_id, owner_name,\n next_step, next_step_due, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n RETURNING id`,\n params: [\n partnerId,\n title,\n stageId,\n value,\n ownerId,\n ownerName,\n nextStep,\n due,\n ctx.viewer.id,\n ctx.viewer.display_name,\n ],\n },\n ]);\n return readDeal(ctx, results[1]?.rows[0]?.id as string);\n }\n\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals\n SET partner_id = $1, title = $2, stage = $3, amount = $4, owner_id = $5,\n owner_name = $6, next_step = $7, next_step_due = $8, updated_at = now()\n WHERE id = $9`,\n params: [partnerId, title, stageId, value, ownerId, ownerName, nextStep, due, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal does not exist.');\n return readDeal(ctx, id);\n },\n\n /** write: moves a deal to another stage and/or closes or reopens it. */\n async deals_move(ctx: ActionContext, input: DealMoveInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n if (input.stage === undefined && input.status === undefined) {\n throw new ActionError('Give a stage or a status.');\n }\n const stageId = input.stage === undefined ? null : stage(input.stage);\n if (input.status !== undefined && !DEAL_STATUSES.includes(input.status)) {\n throw new ActionError(`Unknown status ${input.status}.`);\n }\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals\n SET stage = COALESCE($1, stage), status = COALESCE($2, status), updated_at = now()\n WHERE id = $3`,\n params: [stageId, input.status ?? null, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal does not exist.');\n return readDeal(ctx, id);\n },\n\n /** write: deletes a deal; its history stays with the partner. */\n async deals_delete(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = uuid(params.id, 'deal');\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM deals d WHERE d.id = $3 AND ${CAN_DELETE}`,\n [ctx.viewer.id, ctx.viewer.role, id],\n );\n if (rows_affected === 0) {\n throw new ActionError('Only its creator or an org admin can delete this deal.');\n }\n return { id };\n },\n\n /** write: the owner followed up. The note goes into the partner's\n * history and the next step is cleared, for the agent (or a person) to\n * set the following one. */\n async followups_done(ctx: ActionContext, input: FollowupDoneInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n const note = required(input.note, 'A note');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO activities (partner_id, deal_id, kind, body, actor_name, created_by,\n created_by_name, by_agent)\n SELECT partner_id, id, 'note', $2::text, $3::text, $4::text, $3::text, $5::boolean\n FROM deals WHERE id = $1 AND status = 'open'`,\n params: [id, note, ctx.viewer.display_name, ctx.viewer.id, ctx.viewer.is_agent],\n },\n {\n sql: `UPDATE deals\n SET next_step = '', next_step_due = NULL, followup_reason = '',\n followup_draft = '', followup_by_name = '', updated_at = now()\n WHERE id = $1 AND status = 'open'`,\n params: [id],\n },\n ]);\n if (!results[2]?.rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n\n /** write: moves the deal's next step to another day. */\n async followups_snooze(ctx: ActionContext, input: FollowupSnoozeInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n const until = optionalDate(input.until, 'until');\n if (!until) throw new ActionError('Give the day to move the follow-up to.');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals SET next_step_due = $1, updated_at = now()\n WHERE id = $2 AND status = 'open'`,\n params: [until, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n\n /** write (the agent's daily run): why to follow up the deal and the\n * message drafted for its owner; due also sets the next step's day. */\n async followups_draft(ctx: ActionContext, input: FollowupDraftInput): Promise<Deal> {\n const id = uuid(input.id, 'deal');\n const due = optionalDate(input.due, 'due');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE deals\n SET followup_reason = $1, followup_draft = $2, followup_by_name = $3,\n next_step_due = COALESCE($4::date, next_step_due), updated_at = now()\n WHERE id = $5 AND status = 'open'`,\n params: [input.reason.trim(), input.draft.trim(), ctx.viewer.display_name, due, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n};\n",
204
+ "actions/index.ts": "import { dealActions } from './deals';\nimport { defineActions } from './parall-actions';\nimport { partnerActions } from './partners';\nimport { peopleActions } from './people';\n// parall:action-imports — `parall app add` puts block imports above this line.\n\n// Every action is declared in public/manifest.json under actions.functions\n// (kind read | write, params as a JSON Schema) and implemented here;\n// `parall app check dist` compares the two, and publish runs it too. The\n// loader looks the module up by the export name ActionRunner.\nexport const ActionRunner = defineActions({\n ...peopleActions,\n ...dealActions,\n ...partnerActions,\n // parall:actions — `parall app add` puts block actions above this line.\n});\n",
205
+ "actions/partners.ts": "import type {\n Activity,\n ActivityInput,\n Partner,\n PartnerDetail,\n PartnerInput,\n PartnerSummary,\n} from '@shared/pipeline';\nimport { ACTIVITY_KINDS } from '@shared/pipeline';\nimport { required, uuid } from './checks';\nimport { readDeals } from './deals';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { rememberViewer } from './people';\n\n// Partners and their history (src/pages/partners). Everyone who can open\n// the app (by default, the whole organization) reads every partner, and those\n// who can change it edit partners and add to their history.\n\nconst PARTNER_COLUMNS = `p.id, p.name, p.kind, p.contact_name, p.contact_phone, p.contact_email,\n p.owner_id, p.owner_name, p.notes, p.updated_at`;\nconst ACTIVITY_COLUMNS = `a.id, a.partner_id, a.deal_id, a.kind, a.body, a.happened_at,\n a.actor_name, a.source, a.by_agent`;\n\nasync function readPartner(ctx: ActionContext, id: string): Promise<Partner> {\n const { rows } = await ctx.db.query(`SELECT ${PARTNER_COLUMNS} FROM partners p WHERE p.id = $1`, [\n id,\n ]);\n if (!rows[0]) throw new ActionError('This partner does not exist.');\n return rows[0] as unknown as Partner;\n}\n\n/** Another partner already has this name, whatever the case. */\nasync function nameTaken(ctx: ActionContext, name: string, id: string | null): Promise<boolean> {\n const { rows } = await ctx.db.query(\n `SELECT 1 FROM partners WHERE lower(name) = lower($1) AND id IS DISTINCT FROM $2::uuid`,\n [name, id],\n );\n return rows.length > 0;\n}\n\nexport const partnerActions = {\n /** read: every partner with its open deals, the amounts of its deals and\n * when it was last in touch. */\n async partners_list(ctx: ActionContext): Promise<PartnerSummary[]> {\n const { rows } = await ctx.db.query(\n `SELECT ${PARTNER_COLUMNS},\n (SELECT count(*) FROM deals d\n WHERE d.partner_id = p.id AND d.status = 'open')::int AS open_deals,\n (SELECT sum(d.amount) FROM deals d\n WHERE d.partner_id = p.id AND d.status <> 'lost') AS total_amount,\n (SELECT max(a.happened_at) FROM activities a\n WHERE a.partner_id = p.id) AS last_activity_at\n FROM partners p\n ORDER BY last_activity_at DESC NULLS LAST, p.name\n LIMIT 1000`,\n );\n return rows as unknown as PartnerSummary[];\n },\n\n /** read: one partner, all its deals and its history, newest first. */\n async partner_get(ctx: ActionContext, params: { id: string }): Promise<PartnerDetail> {\n const id = uuid(params.id, 'partner');\n const partner = await readPartner(ctx, id);\n const deals = await readDeals(ctx, 'd.partner_id = $3', [id]);\n const { rows } = await ctx.db.query(\n `SELECT ${ACTIVITY_COLUMNS} FROM activities a\n WHERE a.partner_id = $1\n ORDER BY a.happened_at DESC\n LIMIT 500`,\n [id],\n );\n return { partner, deals, activities: rows as unknown as Activity[] };\n },\n\n /** write: creates a partner (no id) or rewrites one; '' clears a field. */\n async partners_save(ctx: ActionContext, input: PartnerInput): Promise<Partner> {\n const name = required(input.name, 'A name');\n const id = input.id === undefined ? null : uuid(input.id, 'partner');\n if (await nameTaken(ctx, name, id)) {\n throw new ActionError(`There is already a partner named ${name}.`);\n }\n const ownerId = input.owner_id || null;\n const fields = [\n name,\n (input.kind ?? '').trim(),\n (input.contact_name ?? '').trim(),\n (input.contact_phone ?? '').trim(),\n (input.contact_email ?? '').trim(),\n ownerId,\n ownerId ? (input.owner_name ?? '').trim() || null : null,\n (input.notes ?? '').trim(),\n ];\n if (id === null) {\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO partners (name, kind, contact_name, contact_phone, contact_email,\n owner_id, owner_name, notes, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n RETURNING id`,\n params: [...fields, ctx.viewer.id, ctx.viewer.display_name],\n },\n ]);\n return readPartner(ctx, results[1]?.rows[0]?.id as string);\n }\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `UPDATE partners\n SET name = $1, kind = $2, contact_name = $3, contact_phone = $4,\n contact_email = $5, owner_id = $6, owner_name = $7, notes = $8,\n updated_at = now()\n WHERE id = $9`,\n params: [...fields, id],\n },\n ]);\n if (!results[1]?.rows_affected) throw new ActionError('This partner does not exist.');\n return readPartner(ctx, id);\n },\n\n /** write: adds an entry to a partner's history, by the caller. */\n async activities_add(ctx: ActionContext, input: ActivityInput): Promise<Activity> {\n const partnerId = uuid(input.partner_id, 'partner');\n const dealId = input.deal_id ? uuid(input.deal_id, 'deal') : null;\n if (!ACTIVITY_KINDS.includes(input.kind)) throw new ActionError(`Unknown kind ${input.kind}.`);\n const body = required(input.body, 'The text');\n const at = input.happened_at ? new Date(input.happened_at) : new Date();\n if (Number.isNaN(at.getTime())) throw new ActionError('happened_at is not a time.');\n const { results } = await ctx.db.batch([\n rememberViewer(ctx),\n {\n sql: `INSERT INTO activities (partner_id, deal_id, kind, body, happened_at, actor_name,\n created_by, created_by_name, by_agent)\n SELECT p.id, $2::uuid, $3::text, $4::text, $5::timestamptz, $6::text, $7::text,\n $6::text, $8::boolean\n FROM partners p\n WHERE p.id = $1\n AND ($2::uuid IS NULL\n OR EXISTS (SELECT 1 FROM deals d WHERE d.id = $2::uuid AND d.partner_id = p.id))\n RETURNING id, partner_id, deal_id, kind, body, happened_at, actor_name, source,\n by_agent`,\n params: [\n partnerId,\n dealId,\n input.kind,\n body,\n at.toISOString(),\n ctx.viewer.display_name,\n ctx.viewer.id,\n ctx.viewer.is_agent,\n ],\n },\n ]);\n const row = results[1]?.rows[0];\n if (!row) throw new ActionError('This partner or deal does not exist.');\n return row as unknown as Activity;\n },\n};\n",
206
+ "db/schema.sql": "-- The pipeline's tables. The Database is PostgreSQL (not SQLite): uuid,\n-- timestamptz, numeric, ILIKE, ON CONFLICT and gen_random_uuid() all work.\n--\n-- Apply (safe to run again — everything is IF NOT EXISTS):\n-- parall app db exec --app <app_…> --file db/schema.sql\n--\n-- The template brings no rows: what goes in is the team's own data, read\n-- from the sources the person agreed to (SKILL.md). Add a column the team\n-- needs with ALTER TABLE … ADD COLUMN IF NOT EXISTS …; an agent cannot DROP\n-- or TRUNCATE a table or drop a column.\n\n-- People who used the app. Write actions remember the caller here\n-- (actions/people.ts rememberViewer), so pages can offer them as owners.\n-- ctx.viewer is the only trustworthy identity.\nCREATE TABLE IF NOT EXISTS app_people (\n user_id text PRIMARY KEY,\n display_name text NOT NULL,\n is_agent boolean NOT NULL DEFAULT false,\n last_seen_at timestamptz NOT NULL DEFAULT now()\n);\n\n-- The customers, brands or creators the team works with. owner_id is the\n-- teammate (usr_…) who looks after the partner.\nCREATE TABLE IF NOT EXISTS partners (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n name text NOT NULL CHECK (length(name) BETWEEN 1 AND 200),\n kind text NOT NULL DEFAULT '',\n contact_name text NOT NULL DEFAULT '',\n contact_phone text NOT NULL DEFAULT '',\n contact_email text NOT NULL DEFAULT '',\n owner_id text,\n owner_name text,\n notes text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n-- One partner per name, whatever the case: imports and the new-deal form\n-- reuse it (ON CONFLICT ((lower(name))) …).\nCREATE UNIQUE INDEX IF NOT EXISTS partners_name_key ON partners (lower(name));\n\n-- One piece of business with a partner. stage is an id of STAGES in\n-- shared/pipeline.ts (the action checks it, so renaming stages needs no\n-- schema change); status open shows it on the board, won and lost close it.\n-- followup_* are what the agent writes each day for the follow-ups page.\nCREATE TABLE IF NOT EXISTS deals (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n partner_id uuid NOT NULL REFERENCES partners (id),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n stage text NOT NULL CHECK (length(stage) BETWEEN 1 AND 64),\n status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'won', 'lost')),\n amount numeric(14, 2) CHECK (amount >= 0),\n owner_id text,\n owner_name text,\n next_step text NOT NULL DEFAULT '',\n next_step_due date,\n followup_reason text NOT NULL DEFAULT '',\n followup_draft text NOT NULL DEFAULT '',\n followup_by_name text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS deals_partner_idx ON deals (partner_id);\nCREATE INDEX IF NOT EXISTS deals_open_idx ON deals (status, next_step_due);\n\n-- A partner's history: emails, calls, meetings, messages and notes, from\n-- the app or imported (source names where: a mailbox, a channel). A deleted\n-- deal leaves its history on the partner.\nCREATE TABLE IF NOT EXISTS activities (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n partner_id uuid NOT NULL REFERENCES partners (id),\n deal_id uuid REFERENCES deals (id) ON DELETE SET NULL,\n kind text NOT NULL DEFAULT 'note'\n CHECK (kind IN ('email', 'call', 'meeting', 'message', 'note')),\n body text NOT NULL CHECK (length(body) BETWEEN 1 AND 5000),\n happened_at timestamptz NOT NULL DEFAULT now(),\n actor_name text NOT NULL,\n source text NOT NULL DEFAULT '',\n created_by text NOT NULL,\n created_by_name text NOT NULL,\n by_agent boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS activities_partner_idx ON activities (partner_id, happened_at DESC);\n\n-- Who may open the app, and who may also call its write actions, is the\n-- app's access setting (parall app access); within that, who may change\n-- what is decided in the actions, from ctx.viewer. Here everyone who can\n-- open the app reads and edits partners, deals and history (a team's shared\n-- pipeline); a deal is deleted by its creator or an org owner/admin\n-- (actions/deals.ts). Amounts, phone numbers and emails are visible to\n-- everyone who can open the app — by default the whole organization; to keep\n-- them to a few people, set everyone else in the organization to not\n-- readable and add those people one by one — and what a write action is\n-- passed is kept in the app's call log, which only the app's authors, org\n-- owners/admins and the caller can read.\n",
207
+ "public/manifest.json": "{\n \"entry\": \"index.html\",\n \"sdk_version\": \"0.1.0\",\n \"capabilities\": [],\n \"actions\": {\n \"entry\": \"_actions/index.js\",\n \"functions\": {\n \"people_list\": { \"kind\": \"read\" },\n \"pipeline_board\": { \"kind\": \"read\" },\n \"deals_save\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"partner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"partner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"stage\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 },\n \"amount\": { \"type\": \"number\", \"minimum\": 0, \"maximum\": 999999999999 },\n \"owner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"owner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"next_step\": { \"type\": \"string\", \"maxLength\": 500 },\n \"next_step_due\": { \"type\": \"string\", \"maxLength\": 10 }\n },\n \"required\": [\"title\", \"stage\"]\n }\n },\n \"deals_move\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"stage\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 },\n \"status\": { \"type\": \"string\", \"enum\": [\"open\", \"won\", \"lost\"] }\n },\n \"required\": [\"id\"]\n }\n },\n \"deals_delete\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"followups_done\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"note\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 5000 }\n },\n \"required\": [\"id\", \"note\"]\n }\n },\n \"followups_snooze\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"until\": { \"type\": \"string\", \"format\": \"date\" }\n },\n \"required\": [\"id\", \"until\"]\n }\n },\n \"followups_draft\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"reason\": { \"type\": \"string\", \"maxLength\": 1000 },\n \"draft\": { \"type\": \"string\", \"maxLength\": 5000 },\n \"due\": { \"type\": \"string\", \"format\": \"date\" }\n },\n \"required\": [\"id\", \"reason\", \"draft\"]\n }\n },\n \"partners_list\": { \"kind\": \"read\" },\n \"partner_get\": {\n \"kind\": \"read\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"partners_save\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"name\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"kind\": { \"type\": \"string\", \"maxLength\": 200 },\n \"contact_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"contact_phone\": { \"type\": \"string\", \"maxLength\": 100 },\n \"contact_email\": { \"type\": \"string\", \"maxLength\": 200 },\n \"owner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"owner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"notes\": { \"type\": \"string\", \"maxLength\": 5000 }\n },\n \"required\": [\"name\"]\n }\n },\n \"activities_add\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"partner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"deal_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"kind\": { \"type\": \"string\", \"enum\": [\"email\", \"call\", \"meeting\", \"message\", \"note\"] },\n \"body\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 5000 },\n \"happened_at\": { \"type\": \"string\", \"format\": \"date-time\" }\n },\n \"required\": [\"partner_id\", \"kind\", \"body\"]\n }\n }\n }\n }\n}\n",
208
+ "shared/pipeline.ts": "// Types shared by the pipeline's actions (actions/deals.ts, actions/partners.ts)\n// and its pages (src/pages/board, followups, partners): the actions return\n// rows of these shapes.\n\nexport type StageColor = 'gray' | 'blue' | 'violet' | 'amber' | 'rose' | 'green';\n\nexport interface Stage {\n /** What deals.stage stores. Keep an id once deals use it; to retire one,\n * move its deals to another stage in SQL first. */\n id: string;\n /** The stage's name, as the team says it. */\n en: string;\n zh: string;\n color: StageColor;\n}\n\n/** The stages a deal moves through, in board order. They are the team's own\n * words: rename, add or drop them to match what the team calls them. */\nexport const STAGES: Stage[] = [\n { id: 'inquiry', en: 'Inquiry', zh: '询价', color: 'gray' },\n { id: 'quote', en: 'Quote', zh: '报价', color: 'blue' },\n { id: 'contract', en: 'Contract', zh: '签约', color: 'violet' },\n { id: 'delivery', en: 'Delivery', zh: '执行', color: 'amber' },\n { id: 'payment', en: 'Payment', zh: '结款', color: 'green' },\n];\n\n/** Whether the team records amounts. false hides them on every page (the\n * column stays, empty). */\nexport const AMOUNTS: boolean = true;\n\n/** The ISO 4217 currency amounts are kept in. */\nexport const CURRENCY = 'CNY';\n\n/** open: on the board; won: done and paid; lost: did not happen. */\nexport type DealStatus = 'open' | 'won' | 'lost';\nexport const DEAL_STATUSES: DealStatus[] = ['open', 'won', 'lost'];\n\n/** One piece of business with a partner. */\nexport interface Deal {\n id: string;\n partner_id: string;\n partner_name: string;\n title: string;\n /** A Stage id. */\n stage: string;\n status: DealStatus;\n /** Null when no amount is recorded (not quoted yet, or the team keeps\n * amounts out of the app). */\n amount: number | null;\n owner_id: string | null;\n owner_name: string | null;\n /** What happens next, and by when (YYYY-MM-DD). */\n next_step: string;\n next_step_due: string | null;\n /** Why to follow up and the message drafted for the owner, written by the\n * agent for the follow-ups page (followups_draft); '' when there is none. */\n followup_reason: string;\n followup_draft: string;\n /** Who drafted it. */\n followup_by_name: string;\n created_by: string;\n updated_at: string;\n /** Whether the caller may delete it: its creator or an org owner/admin. */\n can_delete: boolean;\n}\n\n/** deals_save params: no id creates a deal. The partner is partner_id, or a\n * name: the partner of that name (any case) is reused, else created. Every\n * field is written as given; '' clears owner_id and next_step_due, and a\n * missing amount clears it. */\nexport interface DealInput {\n id?: string;\n partner_id?: string;\n partner_name?: string;\n title: string;\n stage: string;\n amount?: number;\n owner_id?: string;\n owner_name?: string;\n next_step?: string;\n next_step_due?: string;\n}\n\n/** deals_move params: a new stage, a new status, or both. */\nexport interface DealMoveInput {\n id: string;\n stage?: string;\n status?: DealStatus;\n}\n\n/** followups_done params: the note goes into the partner's history. */\nexport interface FollowupDoneInput {\n id: string;\n note: string;\n}\n\n/** followups_snooze params: the deal's next step moves to this day. */\nexport interface FollowupSnoozeInput {\n id: string;\n until: string;\n}\n\n/** followups_draft params (the agent's daily run): why to follow up and the\n * message drafted for the owner; due sets the next step's date too. */\nexport interface FollowupDraftInput {\n id: string;\n reason: string;\n draft: string;\n due?: string;\n}\n\n/** A customer, brand or creator the team works with. */\nexport interface Partner {\n id: string;\n name: string;\n /** What kind of partner, in the team's words (industry, category…). */\n kind: string;\n contact_name: string;\n contact_phone: string;\n contact_email: string;\n owner_id: string | null;\n owner_name: string | null;\n notes: string;\n updated_at: string;\n}\n\n/** partners_list rows: the partner with its deals summed up. */\nexport interface PartnerSummary extends Partner {\n open_deals: number;\n /** The amounts of every deal that did not fall through; null when none\n * has an amount. */\n total_amount: number | null;\n last_activity_at: string | null;\n}\n\n/** partners_save params: no id creates a partner; '' clears a field. */\nexport interface PartnerInput {\n id?: string;\n name: string;\n kind?: string;\n contact_name?: string;\n contact_phone?: string;\n contact_email?: string;\n owner_id?: string;\n owner_name?: string;\n notes?: string;\n}\n\nexport type ActivityKind = 'email' | 'call' | 'meeting' | 'message' | 'note';\nexport const ACTIVITY_KINDS: ActivityKind[] = ['email', 'call', 'meeting', 'message', 'note'];\n\n/** One entry of a partner's history: an email, a call, a message, a note. */\nexport interface Activity {\n id: string;\n partner_id: string;\n deal_id: string | null;\n kind: ActivityKind;\n body: string;\n /** When it happened (ISO timestamp). */\n happened_at: string;\n /** Who did it: a teammate, someone at the partner, or the agent. */\n actor_name: string;\n /** Where it was recorded from (a mailbox, a channel); '' when typed in\n * the app. */\n source: string;\n /** Written by an agent. */\n by_agent: boolean;\n}\n\n/** activities_add params. */\nexport interface ActivityInput {\n partner_id: string;\n deal_id?: string;\n kind: ActivityKind;\n body: string;\n /** ISO timestamp; now when absent. */\n happened_at?: string;\n}\n\n/** partner_get: one partner with all its deals and its history. */\nexport interface PartnerDetail {\n partner: Partner;\n deals: Deal[];\n activities: Activity[];\n}\n",
209
+ "src/components/owner-filter.tsx": "import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';\nimport { t } from '@/lib/pipeline';\nimport { cn } from '@/lib/utils';\n\nexport const ALL_OWNERS = '__all__';\n\n/** \"All\" or one owner, as a row of toggles; with counts when given. */\nexport function OwnerFilter({\n owners,\n value,\n onChange,\n counts,\n total,\n className,\n}: {\n owners: Array<{ id: string; name: string }>;\n value: string;\n onChange: (value: string) => void;\n counts?: Record<string, number>;\n total?: number;\n className?: string;\n}) {\n if (owners.length === 0) return null;\n return (\n <ToggleGroup\n type=\"single\"\n variant=\"outline\"\n size=\"sm\"\n value={value}\n onValueChange={(next) => next && onChange(next)}\n className={cn('no-scrollbar max-w-full overflow-x-auto', className)}\n >\n <ToggleGroupItem value={ALL_OWNERS} className=\"shrink-0 gap-1.5 px-3\">\n {t('everyone')}\n {total !== undefined ? (\n <span className=\"text-muted-foreground text-xs tabular-nums\">{total}</span>\n ) : null}\n </ToggleGroupItem>\n {owners.map((owner) => (\n <ToggleGroupItem key={owner.id} value={owner.id} className=\"shrink-0 gap-1.5 px-3\">\n {owner.name}\n {counts ? (\n <span className=\"text-muted-foreground text-xs tabular-nums\">\n {counts[owner.id] ?? 0}\n </span>\n ) : null}\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n );\n}\n",
210
+ "src/lib/pipeline.ts": "import {\n AMOUNTS,\n CURRENCY,\n type Deal,\n type DealStatus,\n STAGES,\n type Stage,\n type StageColor,\n} from '@shared/pipeline';\nimport { defineMessages, formatLocale, locale } from '@/lib/i18n';\n\n// What the pipeline's pages share: stage names and colors, money, days and\n// the people deals can be given to.\n\nexport const t = defineMessages({\n en: {\n today: 'Today',\n tomorrow: 'Tomorrow',\n overdueDays: '{n} days late',\n overdueOneDay: '1 day late',\n noAmount: 'No quote yet',\n open: 'Open',\n won: 'Done',\n lost: 'Did not happen',\n everyone: 'All',\n unassigned: 'No owner',\n },\n zh: {\n today: '今天',\n tomorrow: '明天',\n overdueDays: '逾期 {n} 天',\n overdueOneDay: '逾期 1 天',\n noAmount: '待报价',\n open: '进行中',\n won: '已完成',\n lost: '未成',\n everyone: '全部',\n unassigned: '未分配',\n },\n});\n\nexport function stageOf(id: string): Stage | undefined {\n return STAGES.find((stage) => stage.id === id);\n}\n\n/** The stage's name in the viewer's language; an unknown id as it is. */\nexport function stageName(id: string): string {\n const stage = stageOf(id);\n return stage ? stage[locale] : id;\n}\n\nexport const STAGE_DOT: Record<StageColor, string> = {\n gray: 'bg-zinc-400',\n blue: 'bg-sky-500',\n violet: 'bg-violet-500',\n amber: 'bg-amber-500',\n rose: 'bg-rose-500',\n green: 'bg-emerald-500',\n};\n\nexport function stageDot(id: string): string {\n return STAGE_DOT[stageOf(id)?.color ?? 'gray'];\n}\n\nexport function statusName(status: DealStatus): string {\n return t(status);\n}\n\n// Whole amounts read \"¥12,800\"; an amount with cents shows them as the\n// currency writes them (\"¥100.49\"), so a card never rounds what was saved.\nconst money = new Intl.NumberFormat(formatLocale, { style: 'currency', currency: CURRENCY });\nconst wholeMoney = new Intl.NumberFormat(formatLocale, {\n style: 'currency',\n currency: CURRENCY,\n maximumFractionDigits: 0,\n});\nconst compactMoney = new Intl.NumberFormat(formatLocale, {\n style: 'currency',\n currency: CURRENCY,\n notation: 'compact',\n maximumFractionDigits: 1,\n});\n\n/** '' when there is no amount, or the team keeps amounts out (AMOUNTS). */\nexport function formatMoney(amount: number | null | undefined): string {\n if (!AMOUNTS || amount === null || amount === undefined) return '';\n const value = Number(amount);\n // By cents, not Number.isInteger: a sum of saved amounts can be 300.99999999999994.\n return (Math.round(value * 100) % 100 === 0 ? wholeMoney : money).format(value);\n}\n\n/** A sum as it fits a column header (\"¥54.6万\", \"CN¥546K\"). */\nexport function formatCompactMoney(amount: number): string {\n return compactMoney.format(amount);\n}\n\n/** The sum of the amounts that are recorded; null when none is (or the\n * team keeps amounts out). */\nexport function sumAmounts(deals: Deal[]): number | null {\n if (!AMOUNTS) return null;\n const known = deals.filter((deal) => deal.amount !== null);\n return known.length === 0 ? null : known.reduce((sum, deal) => sum + Number(deal.amount), 0);\n}\n\n/** The viewer's own date as YYYY-MM-DD, days from today. */\nexport function localDay(offsetDays = 0): string {\n const day = new Date();\n day.setDate(day.getDate() + offsetDays);\n const pad = (n: number) => String(n).padStart(2, '0');\n return `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`;\n}\n\n/** Whole days from a to b (YYYY-MM-DD each). */\nfunction daysBetween(a: string, b: string): number {\n return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);\n}\n\nexport type DueState = 'overdue' | 'today' | 'soon' | 'later';\n\n/** How a next step's day stands against today. */\nexport function dueState(due: string | null): DueState | null {\n if (!due) return null;\n const days = daysBetween(localDay(), due);\n if (days < 0) return 'overdue';\n if (days === 0) return 'today';\n return days <= 2 ? 'soon' : 'later';\n}\n\nconst shortDate = new Intl.DateTimeFormat(formatLocale, { month: 'numeric', day: 'numeric' });\n\n/** \"Today\", \"Tomorrow\" or a short date. */\nexport function formatDue(due: string): string {\n const days = daysBetween(localDay(), due);\n if (days === 0) return t('today');\n if (days === 1) return t('tomorrow');\n return shortDate.format(new Date(`${due}T12:00:00`));\n}\n\nconst shortDateTime = new Intl.DateTimeFormat(formatLocale, {\n month: 'numeric',\n day: 'numeric',\n hour: '2-digit',\n minute: '2-digit',\n});\n\n/** \"10/19 16:02\" for a history entry (an ISO timestamp). */\nexport function formatWhen(value: string): string {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? '' : shortDateTime.format(date);\n}\n\n/** \"2 days late\" for a day before today; '' otherwise. */\nexport function lateness(due: string | null): string {\n if (!due) return '';\n const days = daysBetween(due, localDay());\n if (days <= 0) return '';\n return days === 1 ? t('overdueOneDay') : t('overdueDays', { n: days });\n}\n\nexport interface Owner {\n id: string;\n name: string;\n}\n\n/** Everyone a deal can be given to: the people who used the app and the\n * owners the deals already have (imported owners may not have opened it). */\nexport function ownersOf(people: Array<{ id: string; display_name: string }>, deals: Deal[]) {\n const out = new Map<string, Owner>();\n for (const person of people) out.set(person.id, { id: person.id, name: person.display_name });\n for (const deal of deals) {\n if (deal.owner_id && !out.has(deal.owner_id)) {\n out.set(deal.owner_id, { id: deal.owner_id, name: deal.owner_name ?? deal.owner_id });\n }\n }\n return [...out.values()];\n}\n\n/** `owners` plus the owner a deal or partner already has, when that owner is\n * not among them (say, of a closed deal, never in the app): a dialog lists\n * it and keeps it on save, instead of saving no owner. */\nexport function ownersWith(\n owners: Owner[],\n id: string | null | undefined,\n name: string | null | undefined,\n): Owner[] {\n if (!id || owners.some((o) => o.id === id)) return owners;\n return [...owners, { id, name: name || id }];\n}\n",
211
+ "src/pages/board/BoardPage.tsx": "import { type Deal, type DealMoveInput, type DealStatus, STAGES } from '@shared/pipeline';\nimport { Plus, SquareKanban } from 'lucide-react';\nimport { type ReactNode, useEffect, useMemo, useState } from 'react';\nimport { toast } from 'sonner';\nimport type { PageProps } from '@/components/app-shell';\nimport { ConfirmDialog } from '@/components/confirm-dialog';\nimport { ALL_OWNERS, OwnerFilter } from '@/components/owner-filter';\nimport { PageContainer, PageHeader } from '@/components/page';\nimport { EmptyState, ErrorState, LoadingState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { useAction, useMutation } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { usePeople } from '@/hooks/use-people';\nimport { describeError } from '@/lib/errors';\nimport { locale } from '@/lib/i18n';\nimport { t as common } from '@/lib/messages';\nimport {\n formatCompactMoney,\n ownersOf,\n STAGE_DOT,\n stageName,\n statusName,\n sumAmounts,\n} from '@/lib/pipeline';\nimport { cn } from '@/lib/utils';\nimport { DealCard } from './DealCard';\nimport { DealDialog, type DealDraft } from './DealDialog';\nimport { t } from './messages';\n\nconst NO_DEALS: Deal[] = [];\n\n/**\n * The pipeline board: one column per stage (shared/pipeline.ts), each open\n * deal a card, read from pipeline_board. Cards move between stages and\n * close from their menu (the same on phones), and open for editing on a\n * click. A link prll://app_…#board/<deal id> opens that deal. Someone who\n * can only view the app sees no control that would write (useCanEdit);\n * a card opens read-only for them.\n */\nexport function BoardPage({ route }: PageProps) {\n const board = useAction<Deal[]>('pipeline_board');\n const move = useMutation<Deal, DealMoveInput>('deals_move');\n const remove = useMutation<{ id: string }, { id: string }>('deals_delete');\n const { people } = usePeople();\n const canEdit = useCanEdit();\n\n const [owner, setOwner] = useState(ALL_OWNERS);\n const [draft, setDraft] = useState<DealDraft | null>(null);\n const [deleting, setDeleting] = useState<Deal | null>(null);\n const [openedRoute, setOpenedRoute] = useState<string | null>(null);\n\n const deals = board.data ?? NO_DEALS;\n const owners = useMemo(() => ownersOf(people, deals), [people, deals]);\n // The filter offers the owners deals have, in the order they appear.\n const dealOwners = useMemo(\n () => owners.filter((o) => deals.some((deal) => deal.owner_id === o.id)),\n [owners, deals],\n );\n const columns = useMemo(() => {\n const shown = deals.filter((deal) => owner === ALL_OWNERS || deal.owner_id === owner);\n const out = new Map(STAGES.map((stage) => [stage.id, [] as Deal[]]));\n // A deal in a stage that is no longer listed shows in the first column.\n for (const deal of shown) (out.get(deal.stage) ?? out.get(STAGES[0]?.id ?? ''))?.push(deal);\n return out;\n }, [deals, owner]);\n\n // Open the deal a link points at, once it has loaded.\n useEffect(() => {\n if (!route) {\n setOpenedRoute(null);\n return;\n }\n const deal = deals.find((d) => d.id === route);\n if (deal && openedRoute !== route) {\n setOpenedRoute(route);\n setDraft({ mode: 'edit', deal });\n }\n }, [route, deals, openedRoute]);\n\n function replace(deal: Deal) {\n board.setData((current = []) =>\n deal.status === 'open'\n ? [...current.filter((d) => d.id !== deal.id), deal]\n : current.filter((d) => d.id !== deal.id),\n );\n }\n\n async function moveDeal(deal: Deal, stage: string) {\n replace({ ...deal, stage });\n try {\n replace(await move.run({ id: deal.id, stage }));\n toast.success(t('moved', { stage: stageName(stage) }));\n } catch (err) {\n toast.error(describeError(err).message);\n board.reload();\n }\n }\n\n async function closeDeal(deal: Deal, status: DealStatus) {\n replace({ ...deal, status });\n try {\n await move.run({ id: deal.id, status });\n toast.success(t('closed', { status: statusName(status) }));\n } catch (err) {\n toast.error(describeError(err).message);\n board.reload();\n }\n }\n\n async function confirmDelete() {\n if (!deleting) return;\n try {\n await remove.run({ id: deleting.id });\n board.setData((current = []) => current.filter((d) => d.id !== deleting.id));\n toast.success(t('deleted'));\n setDeleting(null);\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n const newDeal = canEdit ? (\n <Button onClick={() => setDraft({ mode: 'create' })}>\n <Plus />\n {t('newDeal')}\n </Button>\n ) : undefined;\n const header = (\n <PageHeader\n title={t('title')}\n description={t('description')}\n actions={\n <>\n <OwnerFilter owners={dealOwners} value={owner} onChange={setOwner} />\n {newDeal}\n </>\n }\n />\n );\n\n let body: ReactNode;\n if (board.loading) {\n body = <LoadingState variant=\"board\" />;\n } else if (board.error && !board.data) {\n body = <ErrorState error={board.error} onRetry={board.reload} />;\n } else if (deals.length === 0) {\n body = (\n <EmptyState\n icon={SquareKanban}\n title={t('emptyTitle')}\n description={canEdit ? t('emptyBody') : t('emptyBodyViewOnly')}\n action={newDeal}\n />\n );\n } else {\n body = (\n <>\n {/* Phones show a column or so at a time: the stages jump to theirs. */}\n <div className=\"no-scrollbar -mx-4 mb-3 flex gap-1.5 overflow-x-auto px-4 md:hidden\">\n {STAGES.map((stage) => (\n <button\n key={stage.id}\n type=\"button\"\n onClick={() =>\n document\n .getElementById(`stage-${stage.id}`)\n ?.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' })\n }\n className=\"inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border px-3 text-sm\"\n >\n <span className={cn('size-1.5 rounded-full', STAGE_DOT[stage.color])} />\n {stage[locale]}\n <span className=\"text-muted-foreground text-xs tabular-nums\">\n {columns.get(stage.id)?.length ?? 0}\n </span>\n </button>\n ))}\n </div>\n <div className=\"-mx-4 flex min-h-0 flex-1 snap-x snap-mandatory gap-3 overflow-x-auto px-4 pb-2 md:mx-0 md:snap-none md:px-0\">\n {STAGES.map((stage) => {\n const cards = columns.get(stage.id) ?? NO_DEALS;\n const sum = sumAmounts(cards);\n return (\n <section\n key={stage.id}\n id={`stage-${stage.id}`}\n aria-label={stage[locale]}\n className=\"flex w-[85%] shrink-0 snap-start flex-col gap-2 rounded-xl bg-muted/50 p-2 sm:w-72\"\n >\n <header className=\"flex h-8 items-center gap-2 px-1.5\">\n <span className={cn('size-2 rounded-full', STAGE_DOT[stage.color])} />\n <h2 className=\"font-medium text-sm\">{stage[locale]}</h2>\n <span className=\"text-muted-foreground text-xs tabular-nums\">{cards.length}</span>\n {sum !== null && sum > 0 ? (\n <span className=\"ml-auto text-muted-foreground text-xs tabular-nums\">\n {formatCompactMoney(sum)}\n </span>\n ) : (\n <span className=\"ml-auto\" />\n )}\n {canEdit ? (\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('addToStage', { stage: stage[locale] })}\n className=\"text-muted-foreground\"\n onClick={() => setDraft({ mode: 'create', stage: stage.id })}\n >\n <Plus />\n </Button>\n ) : null}\n </header>\n <div className=\"flex flex-col gap-2\">\n {cards.length === 0 ? (\n <p className=\"px-1.5 py-3 text-muted-foreground text-xs\">{t('emptyColumn')}</p>\n ) : (\n cards.map((deal) => (\n <DealCard\n key={deal.id}\n deal={deal}\n onOpen={(d) => setDraft({ mode: 'edit', deal: d })}\n onMove={moveDeal}\n onClose={closeDeal}\n onDelete={setDeleting}\n />\n ))\n )}\n </div>\n </section>\n );\n })}\n </div>\n </>\n );\n }\n\n return (\n <PageContainer width=\"full\">\n {header}\n {body}\n <DealDialog\n draft={draft}\n owners={owners}\n onClose={() => setDraft(null)}\n onSaved={(deal) => {\n replace(deal);\n toast.success(t('saved'));\n }}\n />\n <ConfirmDialog\n open={deleting !== null}\n onOpenChange={(open) => !open && setDeleting(null)}\n title={t('deleteTitle', { title: deleting?.title ?? '' })}\n description={t('deleteBody')}\n confirmText={common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </PageContainer>\n );\n}\n",
212
+ "src/pages/board/DealCard.tsx": "import { AMOUNTS, type Deal, type DealStatus, STAGES } from '@shared/pipeline';\nimport {\n ArrowRight,\n CalendarClock,\n CircleCheck,\n CircleX,\n Ellipsis,\n Pencil,\n Trash2,\n} from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n} from '@/components/ui/dropdown-menu';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { locale } from '@/lib/i18n';\nimport { t as common } from '@/lib/messages';\nimport { dueState, formatDue, formatMoney, STAGE_DOT, t as shared } from '@/lib/pipeline';\nimport { cn } from '@/lib/utils';\nimport { t } from './messages';\n\n/** One deal on the board: the partner, the amount, what it is, the next\n * step with its day, and the owner. A click (or Enter) opens it; the menu\n * moves it to another stage, closes it or deletes it — no menu for someone\n * who can only view the app. */\nexport function DealCard({\n deal,\n onOpen,\n onMove,\n onClose,\n onDelete,\n}: {\n deal: Deal;\n onOpen: (deal: Deal) => void;\n onMove: (deal: Deal, stage: string) => void;\n onClose: (deal: Deal, status: DealStatus) => void;\n onDelete: (deal: Deal) => void;\n}) {\n const due = dueState(deal.next_step_due);\n const canEdit = useCanEdit();\n return (\n <div className=\"relative flex flex-col gap-1.5 rounded-lg border bg-card p-3 text-left shadow-xs transition-colors hover:border-ring/50\">\n {/* The whole card opens the deal: one transparent button over it. */}\n <button\n type=\"button\"\n onClick={() => onOpen(deal)}\n aria-label={`${deal.partner_name} · ${deal.title}`}\n className=\"absolute inset-0 cursor-pointer rounded-lg outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n />\n <div className=\"flex items-start gap-2\">\n <p className=\"min-w-0 flex-1 truncate font-medium text-sm\">{deal.partner_name}</p>\n {AMOUNTS ? (\n <span\n className={cn(\n 'shrink-0 text-sm tabular-nums',\n deal.amount === null ? 'text-muted-foreground text-xs leading-5' : 'font-medium',\n )}\n >\n {deal.amount === null ? shared('noAmount') : formatMoney(deal.amount)}\n </span>\n ) : null}\n {canEdit ? (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('dealActions', { title: deal.title })}\n className=\"-mt-0.5 -mr-1 relative z-10 shrink-0 text-muted-foreground\"\n >\n <Ellipsis />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-48\">\n <DropdownMenuItem onSelect={() => onOpen(deal)}>\n <Pencil />\n {common('edit')}\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuLabel className=\"text-muted-foreground text-xs\">\n {t('moveTo')}\n </DropdownMenuLabel>\n {STAGES.filter((s) => s.id !== deal.stage).map((s) => (\n <DropdownMenuItem key={s.id} onSelect={() => onMove(deal, s.id)}>\n <span className={cn('size-2 rounded-full', STAGE_DOT[s.color])} />\n {s[locale]}\n <ArrowRight className=\"ml-auto\" />\n </DropdownMenuItem>\n ))}\n <DropdownMenuSeparator />\n <DropdownMenuItem onSelect={() => onClose(deal, 'won')}>\n <CircleCheck />\n {t('markWon')}\n </DropdownMenuItem>\n <DropdownMenuItem onSelect={() => onClose(deal, 'lost')}>\n <CircleX />\n {t('markLost')}\n </DropdownMenuItem>\n {deal.can_delete ? (\n <>\n <DropdownMenuSeparator />\n <DropdownMenuItem variant=\"destructive\" onSelect={() => onDelete(deal)}>\n <Trash2 />\n {common('delete')}\n </DropdownMenuItem>\n </>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </div>\n <p className=\"line-clamp-2 text-muted-foreground text-xs leading-relaxed\">{deal.title}</p>\n {deal.next_step_due || deal.next_step || deal.owner_name ? (\n <div className=\"mt-0.5 flex items-center gap-2\">\n {deal.next_step_due || deal.next_step ? (\n <span\n className={cn(\n 'inline-flex min-w-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-muted-foreground text-xs',\n due === 'overdue' && 'bg-destructive/10 text-destructive',\n (due === 'today' || due === 'soon') &&\n 'bg-amber-500/15 text-amber-700 dark:text-amber-300',\n )}\n >\n <CalendarClock className=\"size-3.5 shrink-0\" />\n <span className=\"truncate\">\n {[deal.next_step_due ? formatDue(deal.next_step_due) : '', deal.next_step]\n .filter(Boolean)\n .join(' ')}\n </span>\n </span>\n ) : null}\n {deal.owner_name ? (\n <UserAvatar\n id={deal.owner_id ?? deal.owner_name}\n name={deal.owner_name}\n size=\"sm\"\n className=\"ml-auto shrink-0\"\n title={deal.owner_name}\n />\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n",
213
+ "src/pages/board/DealDialog.tsx": "import { AMOUNTS, type Deal, type DealInput, type PartnerSummary, STAGES } from '@shared/pipeline';\nimport { Lock } from 'lucide-react';\nimport { useEffect, useId, useState } from 'react';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@/components/ui/select';\nimport { useAction, useMutation } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { describeError } from '@/lib/errors';\nimport { locale } from '@/lib/i18n';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { type Owner, ownersWith } from '@/lib/pipeline';\nimport { t } from './messages';\n\nconst NO_OWNER = '__none__';\n\n/** What the dialog starts from: a deal to edit, or the stage and partner a\n * new one goes to. */\nexport type DealDraft =\n | { mode: 'edit'; deal: Deal }\n | { mode: 'create'; stage?: string; partner?: { id: string; name: string } };\n\n/** Creates or edits a deal through deals_save; for someone who can only\n * view the app it shows the deal read-only. */\nexport function DealDialog({\n draft,\n owners,\n onClose,\n onSaved,\n}: {\n draft: DealDraft | null;\n owners: Owner[];\n onClose: () => void;\n onSaved: (deal: Deal) => void;\n}) {\n const formId = useId();\n const open = draft !== null;\n const readOnly = !useCanEdit();\n const save = useMutation<Deal, DealInput>('deals_save');\n const resetSave = save.reset;\n // Partner names to pick from; read only while the dialog is open.\n const partners = useAction<PartnerSummary[]>('partners_list', undefined, { enabled: open });\n const [partner, setPartner] = useState('');\n const [title, setTitle] = useState('');\n const [stage, setStage] = useState(STAGES[0]?.id ?? '');\n const [amount, setAmount] = useState('');\n const [owner, setOwner] = useState(NO_OWNER);\n const [nextStep, setNextStep] = useState('');\n const [due, setDue] = useState('');\n\n const deal = draft?.mode === 'edit' ? draft.deal : null;\n const ownerOptions = ownersWith(owners, deal?.owner_id, deal?.owner_name);\n // The partner the deal keeps when its name is left as it was.\n const fixedPartner =\n draft?.mode === 'edit'\n ? { id: draft.deal.partner_id, name: draft.deal.partner_name }\n : draft?.partner;\n\n useEffect(() => {\n if (!draft) return;\n const d = draft.mode === 'edit' ? draft.deal : null;\n setPartner(d?.partner_name ?? (draft.mode === 'create' ? (draft.partner?.name ?? '') : ''));\n setTitle(d?.title ?? '');\n setStage(\n d?.stage ?? (draft.mode === 'create' ? draft.stage : undefined) ?? STAGES[0]?.id ?? '',\n );\n setAmount(d?.amount === null || d?.amount === undefined ? '' : String(d.amount));\n setOwner(d?.owner_id ?? NO_OWNER);\n setNextStep(d?.next_step ?? '');\n setDue(d?.next_step_due ?? '');\n resetSave();\n }, [draft, resetSave]);\n\n const ready = partner.trim() !== '' && title.trim() !== '' && stage !== '';\n\n async function submit() {\n if (readOnly || !ready || save.pending) return;\n const picked = ownerOptions.find((o) => o.id === owner);\n const value = amount.trim() === '' ? undefined : Number(amount);\n const keepPartner = fixedPartner && partner.trim() === fixedPartner.name;\n try {\n const saved = await save.run({\n ...(deal ? { id: deal.id } : {}),\n ...(keepPartner ? { partner_id: fixedPartner.id } : { partner_name: partner.trim() }),\n title: title.trim(),\n stage,\n ...(value !== undefined && Number.isFinite(value) ? { amount: value } : {}),\n owner_id: picked?.id ?? '',\n owner_name: picked?.name ?? '',\n next_step: nextStep.trim(),\n next_step_due: due,\n });\n onSaved(saved);\n onClose();\n } catch {\n // Shown under the form from save.error.\n }\n }\n\n const field = (id: string) => `${formId}-${id}`;\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={(next) => !next && onClose()}\n title={readOnly ? t('dealDetails') : deal ? t('editDeal') : t('newDeal')}\n footer={\n readOnly ? (\n <Button variant=\"outline\" onClick={onClose}>\n {common('close')}\n </Button>\n ) : (\n <>\n <Button variant=\"outline\" onClick={onClose} disabled={save.pending}>\n {common('cancel')}\n </Button>\n <Button onClick={submit} disabled={save.pending || !ready}>\n {save.pending ? common('saving') : common('save')}\n </Button>\n </>\n )\n }\n >\n <div className=\"flex flex-col gap-4\">\n {readOnly ? (\n <p className=\"flex items-center gap-2 rounded-lg bg-muted px-3 py-2 text-muted-foreground text-sm\">\n <Lock className=\"size-4 shrink-0\" />\n {common('viewOnly')}\n </p>\n ) : null}\n <fieldset disabled={readOnly} className=\"flex flex-col gap-4\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('partner')}>{t('fieldPartner')}</Label>\n <Input\n id={field('partner')}\n list={field('partners')}\n value={partner}\n onChange={(e) => setPartner(e.target.value)}\n placeholder={t('partnerPlaceholder')}\n maxLength={200}\n autoFocus={!deal}\n onKeyDown={onEnter(submit)}\n />\n <datalist id={field('partners')}>\n {(partners.data ?? []).map((p) => (\n <option key={p.id} value={p.name} />\n ))}\n </datalist>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('title')}>{t('fieldTitle')}</Label>\n <Input\n id={field('title')}\n value={title}\n onChange={(e) => setTitle(e.target.value)}\n placeholder={t('titlePlaceholder')}\n maxLength={200}\n onKeyDown={onEnter(submit)}\n />\n </div>\n <div className={AMOUNTS ? 'grid grid-cols-2 gap-3' : 'grid gap-3'}>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('stage')}>{t('fieldStage')}</Label>\n <Select value={stage} onValueChange={setStage}>\n <SelectTrigger id={field('stage')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {STAGES.map((s) => (\n <SelectItem key={s.id} value={s.id}>\n {s[locale]}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n {AMOUNTS ? (\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('amount')}>{t('fieldAmount')}</Label>\n <Input\n id={field('amount')}\n type=\"number\"\n inputMode=\"decimal\"\n min={0}\n step=\"any\"\n value={amount}\n onChange={(e) => setAmount(e.target.value)}\n placeholder={t('amountPlaceholder')}\n onKeyDown={onEnter(submit)}\n />\n </div>\n ) : null}\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('owner')}>{t('fieldOwner')}</Label>\n <Select value={owner} onValueChange={setOwner}>\n <SelectTrigger id={field('owner')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={NO_OWNER}>{t('noOwner')}</SelectItem>\n {ownerOptions.map((o) => (\n <SelectItem key={o.id} value={o.id}>\n {o.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"grid grid-cols-[minmax(0,1fr)_auto] gap-3\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('next')}>{t('fieldNextStep')}</Label>\n <Input\n id={field('next')}\n value={nextStep}\n onChange={(e) => setNextStep(e.target.value)}\n placeholder={t('nextStepPlaceholder')}\n maxLength={500}\n onKeyDown={onEnter(submit)}\n />\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('due')}>{t('fieldDue')}</Label>\n <Input\n id={field('due')}\n type=\"date\"\n value={due}\n onChange={(e) => setDue(e.target.value)}\n className=\"w-40\"\n />\n </div>\n </div>\n </fieldset>\n {save.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(save.error).message}\n </p>\n ) : null}\n </div>\n </ResponsiveDialog>\n );\n}\n",
214
+ "src/pages/board/index.ts": "import { SquareKanban } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { BoardPage } from './BoardPage';\nimport { t } from './messages';\n\nexport const boardPage: AppPage = {\n id: 'board',\n title: t('tab'),\n icon: SquareKanban,\n component: BoardPage,\n};\n",
215
+ "src/pages/board/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Pipeline',\n tab: 'Pipeline',\n description: 'Every deal, stage by stage, with its next step.',\n newDeal: 'New deal',\n editDeal: 'Edit deal',\n dealDetails: 'Deal',\n addToStage: 'Add a deal to {stage}',\n owner: 'Owner',\n emptyTitle: 'No deals yet',\n emptyBody: 'Add the first one, or ask the agent that looks after this app to import yours.',\n emptyBodyViewOnly: 'Nothing has been added yet.',\n emptyColumn: 'Nothing here',\n dealActions: 'Actions for {title}',\n moveTo: 'Move to',\n markWon: 'Mark as done',\n markLost: 'Did not happen',\n moved: 'Moved to {stage}',\n closed: 'Closed: {status}',\n deleteTitle: 'Delete “{title}”?',\n deleteBody: 'The deal is removed for everyone; its history stays with the partner.',\n deleted: 'Deleted',\n saved: 'Saved',\n fieldPartner: 'Partner',\n partnerPlaceholder: 'Who it is with',\n fieldTitle: 'Deal',\n titlePlaceholder: 'What it is about',\n fieldStage: 'Stage',\n fieldAmount: 'Amount',\n amountPlaceholder: 'Leave empty if not quoted',\n fieldOwner: 'Owner',\n noOwner: 'No owner',\n fieldNextStep: 'Next step',\n nextStepPlaceholder: 'What happens next',\n fieldDue: 'By',\n },\n zh: {\n title: '管线',\n tab: '管线',\n description: '每个合作走到哪一步、下一步做什么。',\n newDeal: '新建合作',\n editDeal: '编辑合作',\n dealDetails: '合作详情',\n addToStage: '在「{stage}」新建合作',\n owner: '负责人',\n emptyTitle: '还没有合作',\n emptyBody: '新建第一个,或者请负责这个应用的 agent 把你们的导进来。',\n emptyBodyViewOnly: '还没有人添加。',\n emptyColumn: '暂无',\n dealActions: '{title} 的操作',\n moveTo: '移到',\n markWon: '标为已完成',\n markLost: '标为未成',\n moved: '已移到「{stage}」',\n closed: '已标为{status}',\n deleteTitle: '删除“{title}”?',\n deleteBody: '所有人都将看不到这个合作;它的往来记录仍留在合作方下。',\n deleted: '已删除',\n saved: '已保存',\n fieldPartner: '合作方',\n partnerPlaceholder: '和谁合作',\n fieldTitle: '合作内容',\n titlePlaceholder: '比如:秋季新品种草',\n fieldStage: '阶段',\n fieldAmount: '金额',\n amountPlaceholder: '还没报价就留空',\n fieldOwner: '负责人',\n noOwner: '未分配',\n fieldNextStep: '下一步',\n nextStepPlaceholder: '接下来做什么',\n fieldDue: '截止',\n },\n});\n",
216
+ "src/pages/followups/FollowupsPage.tsx": "import type { Deal, FollowupDoneInput, FollowupSnoozeInput } from '@shared/pipeline';\nimport { Bot, Check, Clock, Copy, ListTodo } from 'lucide-react';\nimport { type ReactNode, useMemo, useState } from 'react';\nimport { toast } from 'sonner';\nimport type { PageProps } from '@/components/app-shell';\nimport { ALL_OWNERS, OwnerFilter } from '@/components/owner-filter';\nimport { PageContainer, PageHeader } from '@/components/page';\nimport { EmptyState, ErrorState, LoadingState } from '@/components/states';\nimport { Badge } from '@/components/ui/badge';\nimport { Button } from '@/components/ui/button';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { useAction, useMutation } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { describeError } from '@/lib/errors';\nimport { lateness, localDay, stageDot, stageName } from '@/lib/pipeline';\nimport { cn } from '@/lib/utils';\nimport { t } from './messages';\n\nconst NO_DEALS: Deal[] = [];\n\n/** Copies text; the frame may not allow the clipboard, then it says so. */\nasync function copy(text: string) {\n try {\n await navigator.clipboard.writeText(text);\n toast.success(t('copied'));\n } catch {\n toast.error(t('copyFailed'));\n }\n}\n\n/**\n * Today's follow-ups: the open deals whose next step is due today or\n * earlier (read from pipeline_board, the board's own read), with why and\n * the message drafted for the owner (followups_draft, the agent's daily\n * run). \"Followed up\" records it in the partner's history and clears the\n * next step (followups_done); \"Tomorrow\" moves it (followups_snooze).\n * Someone who can only view the app sees the follow-ups and copies a\n * draft, with no button that would write (useCanEdit).\n */\nexport function FollowupsPage(_props: PageProps) {\n const board = useAction<Deal[]>('pipeline_board');\n const done = useMutation<Deal, FollowupDoneInput>('followups_done');\n const snooze = useMutation<Deal, FollowupSnoozeInput>('followups_snooze');\n const [owner, setOwner] = useState(ALL_OWNERS);\n const [busy, setBusy] = useState<string | null>(null);\n const canEdit = useCanEdit();\n\n const today = localDay();\n const due = useMemo(\n () =>\n (board.data ?? NO_DEALS)\n .filter((deal) => deal.next_step_due !== null && deal.next_step_due <= today)\n .sort((a, b) => (a.next_step_due ?? '').localeCompare(b.next_step_due ?? '')),\n [board.data, today],\n );\n const owners = useMemo(() => {\n const out = new Map<string, { id: string; name: string }>();\n for (const deal of due) {\n if (deal.owner_id) out.set(deal.owner_id, { id: deal.owner_id, name: deal.owner_name ?? '' });\n }\n return [...out.values()];\n }, [due]);\n const counts = useMemo(() => {\n const out: Record<string, number> = {};\n for (const deal of due) if (deal.owner_id) out[deal.owner_id] = (out[deal.owner_id] ?? 0) + 1;\n return out;\n }, [due]);\n const shown = due.filter((deal) => owner === ALL_OWNERS || deal.owner_id === owner);\n\n async function run(deal: Deal, write: () => Promise<Deal>, message: string) {\n setBusy(deal.id);\n try {\n const saved = await write();\n board.setData((current = []) => current.map((d) => (d.id === saved.id ? saved : d)));\n toast.success(message);\n } catch (err) {\n toast.error(describeError(err).message);\n board.reload();\n } finally {\n setBusy(null);\n }\n }\n\n const header = (\n <PageHeader\n title={t('title')}\n description={canEdit ? t('description') : t('descriptionViewOnly')}\n actions={\n <OwnerFilter\n owners={owners}\n value={owner}\n onChange={setOwner}\n counts={counts}\n total={due.length}\n />\n }\n />\n );\n\n let body: ReactNode;\n if (board.loading) {\n body = <LoadingState variant=\"cards\" rows={3} />;\n } else if (board.error && !board.data) {\n body = <ErrorState error={board.error} onRetry={board.reload} />;\n } else if (due.length === 0) {\n body = <EmptyState icon={ListTodo} title={t('emptyTitle')} description={t('emptyBody')} />;\n } else if (shown.length === 0) {\n body = <EmptyState icon={ListTodo} title={t('noMatch')} />;\n } else {\n body = (\n <ul className=\"flex flex-col gap-3\">\n {shown.map((deal) => {\n const late = lateness(deal.next_step_due);\n const pending = busy === deal.id;\n return (\n <li key={deal.id} className=\"flex flex-col gap-3 rounded-xl border bg-card p-4\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <Badge variant=\"outline\" className=\"gap-1.5\">\n <span className={cn('size-1.5 rounded-full', stageDot(deal.stage))} />\n {stageName(deal.stage)}\n </Badge>\n <span className=\"font-medium\">{deal.partner_name}</span>\n <span className=\"text-muted-foreground text-sm\">{deal.title}</span>\n {late ? (\n <Badge variant=\"outline\" className=\"border-destructive/30 text-destructive\">\n <Clock />\n {late}\n </Badge>\n ) : null}\n {deal.owner_name ? (\n <span className=\"ml-auto flex items-center gap-1.5 text-sm\">\n <UserAvatar\n id={deal.owner_id ?? deal.owner_name}\n name={deal.owner_name}\n size=\"sm\"\n />\n {deal.owner_name}\n </span>\n ) : null}\n </div>\n <p className=\"text-sm leading-relaxed\">{deal.followup_reason || deal.next_step}</p>\n {deal.followup_draft ? (\n <div className=\"flex flex-col gap-1 rounded-lg bg-muted/60 p-3\">\n <span className=\"flex items-center gap-1.5 text-muted-foreground text-xs\">\n <Bot className=\"size-3.5\" />\n {t('draftBy', { name: deal.followup_by_name || '—' })}\n </span>\n <p className=\"select-text whitespace-pre-wrap text-sm leading-relaxed\">\n {deal.followup_draft}\n </p>\n </div>\n ) : null}\n {deal.followup_draft || canEdit ? (\n <div className=\"flex flex-wrap items-center gap-2\">\n {deal.followup_draft ? (\n <Button variant=\"outline\" size=\"sm\" onClick={() => copy(deal.followup_draft)}>\n <Copy />\n {t('copy')}\n </Button>\n ) : null}\n {canEdit ? (\n <>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={pending}\n onClick={() =>\n run(\n deal,\n () =>\n done.run({\n id: deal.id,\n note: deal.next_step\n ? t('doneNote', { step: deal.next_step })\n : t('doneNoteNoStep'),\n }),\n t('doneToast'),\n )\n }\n >\n <Check />\n {t('done')}\n </Button>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n disabled={pending}\n aria-label={t('snoozeLabel')}\n onClick={() =>\n run(\n deal,\n () => snooze.run({ id: deal.id, until: localDay(1) }),\n t('snoozed'),\n )\n }\n >\n {t('snooze')}\n </Button>\n </>\n ) : null}\n </div>\n ) : null}\n </li>\n );\n })}\n </ul>\n );\n }\n\n return (\n <PageContainer>\n {header}\n {body}\n </PageContainer>\n );\n}\n",
217
+ "src/pages/followups/index.ts": "import { ListTodo } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { FollowupsPage } from './FollowupsPage';\nimport { t } from './messages';\n\nexport const followupsPage: AppPage = {\n id: 'followups',\n title: t('tab'),\n icon: ListTodo,\n component: FollowupsPage,\n};\n",
218
+ "src/pages/followups/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Follow up today',\n tab: 'Follow up',\n description:\n 'Deals whose next step is due, with a message drafted for the owner. Mark one followed up and it goes into the partner’s history.',\n descriptionViewOnly: 'Deals whose next step is due, with a message drafted for the owner.',\n emptyTitle: 'Nothing to follow up today',\n emptyBody: 'Deals show up here on the day their next step is due.',\n noMatch: 'Nothing for this owner today.',\n draftBy: 'Drafted by {name}',\n copy: 'Copy',\n copied: 'Copied',\n copyFailed: 'Could not copy here; select the text and copy it.',\n done: 'Followed up',\n snooze: 'Tomorrow',\n snoozeLabel: 'Move to tomorrow',\n doneToast: 'Recorded in the history',\n snoozed: 'Moved to tomorrow',\n doneNote: 'Followed up: {step}',\n doneNoteNoStep: 'Followed up.',\n },\n zh: {\n title: '今天该跟进',\n tab: '今天该跟进',\n description:\n '下一步到期的合作,附带替负责人起草的消息。跟进完点「已跟进」,会记进合作方的往来记录。',\n descriptionViewOnly: '下一步到期的合作,附带替负责人起草的消息。',\n emptyTitle: '今天没有要跟进的',\n emptyBody: '合作的下一步到期那天,会出现在这里。',\n noMatch: '这位负责人今天没有要跟进的。',\n draftBy: '{name}起草的消息',\n copy: '复制',\n copied: '已复制',\n copyFailed: '这里复制不了,请选中文字手动复制。',\n done: '已跟进',\n snooze: '改到明天',\n snoozeLabel: '改到明天',\n doneToast: '已记进往来记录',\n snoozed: '已改到明天',\n doneNote: '已跟进:{step}',\n doneNoteNoStep: '已跟进。',\n },\n});\n",
219
+ "src/pages/partners/ActivityDialog.tsx": "import {\n ACTIVITY_KINDS,\n type Activity,\n type ActivityInput,\n type ActivityKind,\n type Deal,\n} from '@shared/pipeline';\nimport { useEffect, useId, useState } from 'react';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@/components/ui/select';\nimport { Textarea } from '@/components/ui/textarea';\nimport { useMutation } from '@/hooks/use-action';\nimport { describeError } from '@/lib/errors';\nimport { t as common } from '@/lib/messages';\nimport { kindName, t } from './messages';\n\nconst NO_DEAL = '__none__';\n\n/** \"2026-10-15T09:30\" in the viewer's own time, for a datetime-local field. */\nfunction localNow(): string {\n const now = new Date();\n now.setMinutes(now.getMinutes() - now.getTimezoneOffset());\n return now.toISOString().slice(0, 16);\n}\n\n/** Adds an entry to a partner's history through activities_add. */\nexport function ActivityDialog({\n open,\n partnerId,\n deals,\n onOpenChange,\n onAdded,\n}: {\n open: boolean;\n partnerId: string;\n deals: Deal[];\n onOpenChange: (open: boolean) => void;\n onAdded: (activity: Activity) => void;\n}) {\n const formId = useId();\n const add = useMutation<Activity, ActivityInput>('activities_add');\n const resetAdd = add.reset;\n const [kind, setKind] = useState<ActivityKind>('note');\n const [body, setBody] = useState('');\n const [when, setWhen] = useState('');\n const [deal, setDeal] = useState(NO_DEAL);\n\n useEffect(() => {\n if (!open) return;\n setKind('note');\n setBody('');\n setWhen(localNow());\n // The open deal, when there is just one.\n const open_ = deals.filter((d) => d.status === 'open');\n setDeal(open_.length === 1 && open_[0] ? open_[0].id : NO_DEAL);\n resetAdd();\n }, [open, deals, resetAdd]);\n\n async function submit() {\n if (!body.trim() || add.pending) return;\n const at = when ? new Date(when) : null;\n try {\n const added = await add.run({\n partner_id: partnerId,\n ...(deal !== NO_DEAL ? { deal_id: deal } : {}),\n kind,\n body: body.trim(),\n ...(at && !Number.isNaN(at.getTime()) ? { happened_at: at.toISOString() } : {}),\n });\n onAdded(added);\n onOpenChange(false);\n } catch {\n // Shown under the form from add.error.\n }\n }\n\n const field = (id: string) => `${formId}-${id}`;\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={onOpenChange}\n title={t('addActivity')}\n footer={\n <>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)} disabled={add.pending}>\n {common('cancel')}\n </Button>\n <Button onClick={submit} disabled={add.pending || !body.trim()}>\n {add.pending ? common('saving') : common('save')}\n </Button>\n </>\n }\n >\n <div className=\"flex flex-col gap-4\">\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('kind')}>{t('fieldActivityKind')}</Label>\n <Select value={kind} onValueChange={(value) => setKind(value as ActivityKind)}>\n <SelectTrigger id={field('kind')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {ACTIVITY_KINDS.map((k) => (\n <SelectItem key={k} value={k}>\n {kindName(k)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('when')}>{t('fieldWhen')}</Label>\n <Input\n id={field('when')}\n type=\"datetime-local\"\n value={when}\n onChange={(e) => setWhen(e.target.value)}\n />\n </div>\n </div>\n {deals.length > 0 ? (\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('deal')}>{t('fieldDeal')}</Label>\n <Select value={deal} onValueChange={setDeal}>\n <SelectTrigger id={field('deal')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={NO_DEAL}>{t('noDeal')}</SelectItem>\n {deals.map((d) => (\n <SelectItem key={d.id} value={d.id}>\n {d.title}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ) : null}\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('body')}>{t('fieldBody')}</Label>\n <Textarea\n id={field('body')}\n value={body}\n onChange={(e) => setBody(e.target.value)}\n placeholder={t('bodyPlaceholder')}\n rows={4}\n maxLength={5000}\n autoFocus\n />\n </div>\n {add.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(add.error).message}\n </p>\n ) : null}\n </div>\n </ResponsiveDialog>\n );\n}\n",
220
+ "src/pages/partners/PartnerDetail.tsx": "import { type Activity, AMOUNTS, type Deal, type PartnerDetail as Detail } from '@shared/pipeline';\nimport { Bot, ChevronLeft, Flag, Pencil, Plus } from 'lucide-react';\nimport { type ReactNode, useState } from 'react';\nimport { toast } from 'sonner';\nimport { PageHeader } from '@/components/page';\nimport { Badge } from '@/components/ui/badge';\nimport { Button } from '@/components/ui/button';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { useCanEdit } from '@/hooks/use-host';\nimport {\n formatDue,\n formatMoney,\n formatWhen,\n type Owner,\n stageDot,\n stageName,\n statusName,\n sumAmounts,\n} from '@/lib/pipeline';\nimport { cn } from '@/lib/utils';\nimport { DealDialog, type DealDraft } from '../board/DealDialog';\nimport { ActivityDialog } from './ActivityDialog';\nimport { kindName, t } from './messages';\nimport { PartnerDialog } from './PartnerDialog';\n\n/** The open deal whose next step comes first. */\nfunction nextDeal(deals: Deal[]): Deal | undefined {\n return deals\n .filter((d) => d.status === 'open' && (d.next_step || d.next_step_due))\n .sort((a, b) => (a.next_step_due ?? '9999').localeCompare(b.next_step_due ?? '9999'))[0];\n}\n\nfunction Row({ label, children }: { label: string; children: ReactNode }) {\n return (\n <>\n <dt className=\"text-muted-foreground\">{label}</dt>\n <dd className=\"min-w-0 break-words\">{children || '—'}</dd>\n </>\n );\n}\n\n/** One partner: contact and deals on the left, the next step and the\n * history on the right (one column on phones). Someone who can only view the\n * app sees it all and opens deals read-only, with no control that would\n * write (useCanEdit). */\nexport function PartnerDetail({\n detail,\n owners,\n onBack,\n onChanged,\n}: {\n detail: Detail;\n owners: Owner[];\n onBack: () => void;\n onChanged: () => void;\n}) {\n const { partner, deals, activities } = detail;\n const [editing, setEditing] = useState(false);\n const canEdit = useCanEdit();\n const [adding, setAdding] = useState(false);\n const [draft, setDraft] = useState<DealDraft | null>(null);\n const next = nextDeal(deals);\n const total = sumAmounts(deals.filter((d) => d.status !== 'lost'));\n\n const contact = (\n <div className=\"flex flex-col gap-4 rounded-xl border bg-card p-4\">\n <div className=\"flex items-center gap-3\">\n <span className=\"flex size-10 shrink-0 items-center justify-center rounded-lg bg-amber-500/15 font-medium text-amber-800 dark:text-amber-300\">\n {partner.name.slice(0, 1)}\n </span>\n <div className=\"min-w-0\">\n <p className=\"truncate font-semibold\">{partner.name}</p>\n <p className=\"text-muted-foreground text-sm\">\n {partner.kind\n ? t('kindLine', { kind: partner.kind, n: deals.length })\n : t('dealsLine', { n: deals.length })}\n </p>\n </div>\n </div>\n <dl className=\"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 border-t pt-4 text-sm\">\n <Row label={t('contact')}>{partner.contact_name}</Row>\n <Row label={t('phone')}>{partner.contact_phone}</Row>\n <Row label={t('email')}>{partner.contact_email}</Row>\n <Row label={t('owner')}>{partner.owner_name}</Row>\n {AMOUNTS ? <Row label={t('total')}>{formatMoney(total)}</Row> : null}\n </dl>\n {partner.notes ? (\n <p className=\"whitespace-pre-wrap border-t pt-4 text-muted-foreground text-sm\">\n {partner.notes}\n </p>\n ) : null}\n <div className=\"flex flex-col gap-2 border-t pt-4\">\n <div className=\"flex items-center\">\n <p className=\"font-medium text-sm\">{t('deals')}</p>\n {canEdit ? (\n <Button\n variant=\"ghost\"\n size=\"xs\"\n className=\"ml-auto text-muted-foreground\"\n onClick={() =>\n setDraft({ mode: 'create', partner: { id: partner.id, name: partner.name } })\n }\n >\n <Plus />\n {t('newDeal')}\n </Button>\n ) : null}\n </div>\n {deals.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">{t('noDeals')}</p>\n ) : (\n deals.map((deal) => (\n <button\n key={deal.id}\n type=\"button\"\n onClick={() => setDraft({ mode: 'edit', deal })}\n className=\"flex items-center gap-2 rounded-md py-1 text-left text-sm hover:bg-accent\"\n >\n <span className={cn('size-2 shrink-0 rounded-full', stageDot(deal.stage))} />\n <span className=\"min-w-0 flex-1 truncate\">\n {deal.title}\n <span className=\"text-muted-foreground\">\n {' · '}\n {deal.status === 'open' ? stageName(deal.stage) : statusName(deal.status)}\n </span>\n </span>\n <span className=\"shrink-0 text-muted-foreground tabular-nums\">\n {formatMoney(deal.amount)}\n </span>\n </button>\n ))\n )}\n </div>\n </div>\n );\n\n const nextStep = (\n <div className=\"flex flex-wrap items-center gap-3 rounded-xl border bg-card p-4\">\n <Badge\n variant=\"outline\"\n className=\"border-amber-500/30 bg-amber-500/10 text-amber-800 dark:text-amber-300\"\n >\n <Flag />\n {t('nextStep')}\n </Badge>\n {next ? (\n <>\n {/* A 12rem basis, not 0: on a phone the date and the button wrap\n below the step instead of squeezing it into a sliver. */}\n <span className=\"min-w-0 flex-[1_1_12rem] font-medium text-sm\">\n {next.next_step || next.title}\n </span>\n {next.next_step_due ? (\n <span className=\"text-muted-foreground text-sm tabular-nums\">\n {t('by', { date: formatDue(next.next_step_due) })}\n </span>\n ) : null}\n {next.owner_name ? (\n <UserAvatar id={next.owner_id ?? next.owner_name} name={next.owner_name} size=\"sm\" />\n ) : null}\n {canEdit ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setDraft({ mode: 'edit', deal: next })}\n >\n {t('edit')}\n </Button>\n ) : null}\n </>\n ) : (\n <span className=\"text-muted-foreground text-sm\">{t('noNextStep')}</span>\n )}\n </div>\n );\n\n const history = (\n <div className=\"flex flex-col gap-3 rounded-xl border bg-card p-4\">\n <p className=\"font-medium text-sm\">{t('history')}</p>\n {activities.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">{t('noHistory')}</p>\n ) : (\n <ol className=\"flex flex-col gap-4\">\n {activities.map((a: Activity) => (\n <li key={a.id} className=\"flex gap-3\">\n <UserAvatar id={a.actor_name} name={a.actor_name} size=\"sm\" className=\"shrink-0\" />\n <div className=\"min-w-0 flex-1\">\n <p className=\"flex flex-wrap items-center gap-x-2 text-sm\">\n <span className=\"font-medium\">{a.actor_name}</span>\n {a.by_agent ? <Bot className=\"size-3.5 text-muted-foreground\" /> : null}\n <span className=\"text-muted-foreground text-xs\">\n {[\n formatWhen(a.happened_at),\n kindName(a.kind),\n a.source ? t('via', { source: a.source }) : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </span>\n </p>\n <p\n className={cn(\n 'mt-1 whitespace-pre-wrap text-sm leading-relaxed',\n a.by_agent && 'rounded-lg bg-muted/60 px-3 py-2',\n )}\n >\n {a.body}\n </p>\n </div>\n </li>\n ))}\n </ol>\n )}\n </div>\n );\n\n return (\n <>\n <button\n type=\"button\"\n onClick={onBack}\n className=\"mb-1 inline-flex items-center gap-1 self-start text-muted-foreground text-sm hover:text-foreground\"\n >\n <ChevronLeft className=\"size-4\" />\n {t('back')}\n </button>\n <PageHeader\n title={partner.name}\n actions={\n canEdit ? (\n <>\n <Button variant=\"outline\" onClick={() => setEditing(true)}>\n <Pencil />\n {t('edit')}\n </Button>\n <Button onClick={() => setAdding(true)}>\n <Plus />\n {t('addActivity')}\n </Button>\n </>\n ) : undefined\n }\n />\n <div className=\"grid items-start gap-4 lg:grid-cols-[minmax(0,22rem)_minmax(0,1fr)]\">\n {contact}\n <div className=\"flex min-w-0 flex-col gap-4\">\n {nextStep}\n {history}\n </div>\n </div>\n <PartnerDialog\n open={editing}\n partner={partner}\n owners={owners}\n onOpenChange={setEditing}\n onSaved={() => {\n toast.success(t('saved'));\n onChanged();\n }}\n />\n <ActivityDialog\n open={adding}\n partnerId={partner.id}\n deals={deals}\n onOpenChange={setAdding}\n onAdded={() => {\n toast.success(t('added'));\n onChanged();\n }}\n />\n <DealDialog\n draft={draft}\n owners={owners}\n onClose={() => setDraft(null)}\n onSaved={() => {\n toast.success(t('saved'));\n onChanged();\n }}\n />\n </>\n );\n}\n",
221
+ "src/pages/partners/PartnerDialog.tsx": "import type { Partner, PartnerInput } from '@shared/pipeline';\nimport { useEffect, useId, useState } from 'react';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { Label } from '@/components/ui/label';\nimport {\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n} from '@/components/ui/select';\nimport { Textarea } from '@/components/ui/textarea';\nimport { useMutation } from '@/hooks/use-action';\nimport { describeError } from '@/lib/errors';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { type Owner, ownersWith } from '@/lib/pipeline';\nimport { t } from './messages';\n\nconst NO_OWNER = '__none__';\n\n/** Creates a partner (partner = null) or edits one, through partners_save. */\nexport function PartnerDialog({\n open,\n partner,\n owners,\n onOpenChange,\n onSaved,\n}: {\n open: boolean;\n partner: Partner | null;\n owners: Owner[];\n onOpenChange: (open: boolean) => void;\n onSaved: (partner: Partner) => void;\n}) {\n const formId = useId();\n const save = useMutation<Partner, PartnerInput>('partners_save');\n const resetSave = save.reset;\n const [name, setName] = useState('');\n const [kind, setKind] = useState('');\n const [contact, setContact] = useState('');\n const [phone, setPhone] = useState('');\n const [email, setEmail] = useState('');\n const [owner, setOwner] = useState(NO_OWNER);\n const [notes, setNotes] = useState('');\n const ownerOptions = ownersWith(owners, partner?.owner_id, partner?.owner_name);\n\n useEffect(() => {\n if (!open) return;\n setName(partner?.name ?? '');\n setKind(partner?.kind ?? '');\n setContact(partner?.contact_name ?? '');\n setPhone(partner?.contact_phone ?? '');\n setEmail(partner?.contact_email ?? '');\n setOwner(partner?.owner_id ?? NO_OWNER);\n setNotes(partner?.notes ?? '');\n resetSave();\n }, [open, partner, resetSave]);\n\n async function submit() {\n if (!name.trim() || save.pending) return;\n const picked = ownerOptions.find((o) => o.id === owner);\n try {\n const saved = await save.run({\n ...(partner ? { id: partner.id } : {}),\n name: name.trim(),\n kind,\n contact_name: contact,\n contact_phone: phone,\n contact_email: email,\n owner_id: picked?.id ?? '',\n owner_name: picked?.name ?? '',\n notes,\n });\n onSaved(saved);\n onOpenChange(false);\n } catch {\n // Shown under the form from save.error.\n }\n }\n\n const field = (id: string) => `${formId}-${id}`;\n const text = (id: string, label: string, value: string, set: (v: string) => void, max = 200) => (\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field(id)}>{label}</Label>\n <Input\n id={field(id)}\n value={value}\n onChange={(e) => set(e.target.value)}\n maxLength={max}\n onKeyDown={onEnter(submit)}\n />\n </div>\n );\n\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={onOpenChange}\n title={partner ? t('editPartner') : t('newPartner')}\n footer={\n <>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)} disabled={save.pending}>\n {common('cancel')}\n </Button>\n <Button onClick={submit} disabled={save.pending || !name.trim()}>\n {save.pending ? common('saving') : common('save')}\n </Button>\n </>\n }\n >\n <div className=\"flex flex-col gap-4\">\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {text('name', t('fieldName'), name, setName)}\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('kind')}>{t('fieldKind')}</Label>\n <Input\n id={field('kind')}\n value={kind}\n onChange={(e) => setKind(e.target.value)}\n placeholder={t('kindPlaceholder')}\n maxLength={200}\n onKeyDown={onEnter(submit)}\n />\n </div>\n {text('contact', t('fieldContact'), contact, setContact)}\n {text('phone', t('fieldPhone'), phone, setPhone, 100)}\n {text('email', t('fieldEmail'), email, setEmail)}\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('owner')}>{t('fieldOwner')}</Label>\n <Select value={owner} onValueChange={setOwner}>\n <SelectTrigger id={field('owner')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={NO_OWNER}>{t('noOwner')}</SelectItem>\n {ownerOptions.map((o) => (\n <SelectItem key={o.id} value={o.id}>\n {o.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('notes')}>{t('fieldNotes')}</Label>\n <Textarea\n id={field('notes')}\n value={notes}\n onChange={(e) => setNotes(e.target.value)}\n rows={3}\n maxLength={5000}\n />\n </div>\n {save.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(save.error).message}\n </p>\n ) : null}\n </div>\n </ResponsiveDialog>\n );\n}\n",
222
+ "src/pages/partners/PartnersPage.tsx": "import type { Deal, PartnerDetail as Detail, PartnerSummary } from '@shared/pipeline';\nimport { Building2, Plus, Search } from 'lucide-react';\nimport { type ReactNode, useEffect, useMemo, useState } from 'react';\nimport { toast } from 'sonner';\nimport type { PageProps } from '@/components/app-shell';\nimport { PageContainer, PageHeader } from '@/components/page';\nimport { EmptyState, ErrorState, LoadingState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { useAction } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { usePeople } from '@/hooks/use-people';\nimport { formatRelative } from '@/lib/format';\nimport { formatMoney, ownersOf } from '@/lib/pipeline';\nimport { t } from './messages';\nimport { PartnerDetail } from './PartnerDetail';\nimport { PartnerDialog } from './PartnerDialog';\n\nconst NO_PARTNERS: PartnerSummary[] = [];\nconst NO_DEALS: Deal[] = [];\n\n/**\n * The partners: a searchable list (partners_list) and, for the one picked,\n * its contact, deals and history (partner_get). A link\n * prll://app_…#partners/<partner id> opens that partner. Someone who can\n * only view the app sees no control that would write (useCanEdit).\n */\nexport function PartnersPage({ route }: PageProps) {\n const [selectedId, setSelectedId] = useState<string | null>(route || null);\n const [query, setQuery] = useState('');\n const [creating, setCreating] = useState(false);\n const canEdit = useCanEdit();\n const list = useAction<PartnerSummary[]>('partners_list');\n const detail = useAction<Detail>(\n 'partner_get',\n { id: selectedId ?? '' },\n { enabled: selectedId !== null },\n );\n const board = useAction<Deal[]>('pipeline_board');\n const { people } = usePeople();\n const owners = useMemo(() => ownersOf(people, board.data ?? NO_DEALS), [people, board.data]);\n\n useEffect(() => {\n if (route) setSelectedId(route);\n }, [route]);\n\n const partners = list.data ?? NO_PARTNERS;\n const shown = useMemo(() => {\n const needle = query.trim().toLowerCase();\n if (!needle) return partners;\n return partners.filter((p) =>\n [p.name, p.kind, p.contact_name, p.owner_name ?? ''].some((v) =>\n v.toLowerCase().includes(needle),\n ),\n );\n }, [partners, query]);\n\n let body: ReactNode;\n if (selectedId !== null) {\n if (detail.loading) {\n body = <LoadingState variant=\"cards\" rows={2} />;\n } else if (detail.error && !detail.data) {\n body = (\n <EmptyState\n icon={Building2}\n title={t('notFound')}\n action={\n <Button variant=\"outline\" onClick={() => setSelectedId(null)}>\n {t('back')}\n </Button>\n }\n />\n );\n } else if (detail.data) {\n body = (\n <PartnerDetail\n detail={detail.data}\n owners={owners}\n onBack={() => setSelectedId(null)}\n onChanged={() => {\n detail.reload();\n list.reload();\n }}\n />\n );\n }\n return <PageContainer>{body}</PageContainer>;\n }\n\n if (list.loading) {\n body = <LoadingState />;\n } else if (list.error && !list.data) {\n body = <ErrorState error={list.error} onRetry={list.reload} />;\n } else if (partners.length === 0) {\n body = (\n <EmptyState\n icon={Building2}\n title={t('emptyTitle')}\n description={canEdit ? t('emptyBody') : t('emptyBodyViewOnly')}\n />\n );\n } else {\n body = (\n <>\n <div className=\"relative mb-3\">\n <Search className=\"-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground\" />\n <Input\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={t('searchPlaceholder')}\n aria-label={t('searchPlaceholder')}\n className=\"pl-9\"\n />\n </div>\n {shown.length === 0 ? (\n <EmptyState icon={Search} title={t('noMatch')} />\n ) : (\n <ul className=\"flex flex-col divide-y overflow-hidden rounded-xl border bg-card\">\n {shown.map((p) => (\n <li key={p.id}>\n <button\n type=\"button\"\n onClick={() => setSelectedId(p.id)}\n className=\"flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-accent\"\n >\n <span className=\"flex size-9 shrink-0 items-center justify-center rounded-lg bg-amber-500/15 font-medium text-amber-800 text-sm dark:text-amber-300\">\n {p.name.slice(0, 1)}\n </span>\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate font-medium text-sm\">{p.name}</span>\n <span className=\"block truncate text-muted-foreground text-xs\">\n {[\n p.kind,\n p.open_deals > 0 ? t('openDeals', { n: p.open_deals }) : '',\n p.last_activity_at\n ? t('lastTouch', { when: formatRelative(p.last_activity_at) })\n : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </span>\n </span>\n <span className=\"hidden shrink-0 text-muted-foreground text-sm tabular-nums sm:block\">\n {formatMoney(p.total_amount)}\n </span>\n {p.owner_name ? (\n <UserAvatar\n id={p.owner_id ?? p.owner_name}\n name={p.owner_name}\n size=\"sm\"\n title={p.owner_name}\n />\n ) : null}\n </button>\n </li>\n ))}\n </ul>\n )}\n </>\n );\n }\n\n return (\n <PageContainer>\n <PageHeader\n title={t('title')}\n description={t('description')}\n actions={\n canEdit ? (\n <Button onClick={() => setCreating(true)}>\n <Plus />\n {t('newPartner')}\n </Button>\n ) : undefined\n }\n />\n {body}\n <PartnerDialog\n open={creating}\n partner={null}\n owners={owners}\n onOpenChange={setCreating}\n onSaved={(partner) => {\n toast.success(t('saved'));\n list.reload();\n setSelectedId(partner.id);\n }}\n />\n </PageContainer>\n );\n}\n",
223
+ "src/pages/partners/index.ts": "import { Building2 } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { t } from './messages';\nimport { PartnersPage } from './PartnersPage';\n\nexport const partnersPage: AppPage = {\n id: 'partners',\n title: t('tab'),\n icon: Building2,\n component: PartnersPage,\n};\n",
224
+ "src/pages/partners/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Partners',\n tab: 'Partners',\n description: 'Who the team works with: contacts, deals and the history with each.',\n newPartner: 'New partner',\n editPartner: 'Edit partner',\n searchPlaceholder: 'Search partners',\n emptyTitle: 'No partners yet',\n emptyBody: 'They appear here with their first deal, or add one.',\n emptyBodyViewOnly: 'They appear here with their first deal.',\n noMatch: 'No partner matches.',\n openDeals: '{n} open',\n lastTouch: 'Last in touch {when}',\n back: 'Partners',\n edit: 'Edit',\n addActivity: 'Add to history',\n contact: 'Contact',\n phone: 'Phone',\n email: 'Email',\n owner: 'Owner',\n total: 'Total',\n kindLine: '{kind} · {n} deals',\n dealsLine: '{n} deals',\n deals: 'Deals',\n noDeals: 'No deals yet.',\n newDeal: 'New deal',\n nextStep: 'Next step',\n noNextStep: 'No next step set.',\n by: 'By {date}',\n history: 'History',\n noHistory: 'Nothing recorded yet.',\n via: 'from {source}',\n notes: 'Notes',\n saved: 'Saved',\n added: 'Added to the history',\n notFound: 'This partner does not exist any more.',\n fieldName: 'Name',\n fieldKind: 'Kind',\n kindPlaceholder: 'What kind of partner',\n fieldContact: 'Contact',\n fieldPhone: 'Phone',\n fieldEmail: 'Email',\n fieldOwner: 'Owner',\n noOwner: 'No owner',\n fieldNotes: 'Notes',\n fieldActivityKind: 'How',\n fieldBody: 'What happened',\n bodyPlaceholder: 'What was said or agreed',\n fieldWhen: 'When',\n fieldDeal: 'Deal',\n noDeal: 'Not about one deal',\n email_kind: 'Email',\n call: 'Call',\n meeting: 'Meeting',\n message: 'Message',\n note: 'Note',\n },\n zh: {\n title: '合作方',\n tab: '合作方',\n description: '团队在合作的客户、品牌和达人:联系人、合作和往来记录。',\n newPartner: '新建合作方',\n editPartner: '编辑合作方',\n searchPlaceholder: '搜索合作方',\n emptyTitle: '还没有合作方',\n emptyBody: '新建合作时会自动加进来,也可以直接新建。',\n emptyBodyViewOnly: '有了第一个合作,合作方就会出现在这里。',\n noMatch: '没有匹配的合作方。',\n openDeals: '{n} 个进行中',\n lastTouch: '最近往来 {when}',\n back: '合作方',\n edit: '编辑',\n addActivity: '加跟进记录',\n contact: '联系人',\n phone: '电话',\n email: '邮箱',\n owner: '负责人',\n total: '累计金额',\n kindLine: '{kind} · 合作 {n} 次',\n dealsLine: '合作 {n} 次',\n deals: '合作',\n noDeals: '还没有合作。',\n newDeal: '新建合作',\n nextStep: '下一步',\n noNextStep: '还没定下一步。',\n by: '截止 {date}',\n history: '往来记录',\n noHistory: '还没有记录。',\n via: '从 {source} 记下',\n notes: '备注',\n saved: '已保存',\n added: '已加进往来记录',\n notFound: '这个合作方已经不存在了。',\n fieldName: '名称',\n fieldKind: '类型',\n kindPlaceholder: '比如:连锁咖啡',\n fieldContact: '联系人',\n fieldPhone: '电话',\n fieldEmail: '邮箱',\n fieldOwner: '负责人',\n noOwner: '未分配',\n fieldNotes: '备注',\n fieldActivityKind: '方式',\n fieldBody: '内容',\n bodyPlaceholder: '聊了什么、定了什么',\n fieldWhen: '时间',\n fieldDeal: '相关合作',\n noDeal: '不限某个合作',\n email_kind: '邮件',\n call: '电话',\n meeting: '会议',\n message: '消息',\n note: '记录',\n },\n});\n\n/** The word for how something happened (Activity.kind). */\nexport function kindName(kind: string): string {\n switch (kind) {\n case 'email':\n return t('email_kind');\n case 'call':\n return t('call');\n case 'meeting':\n return t('meeting');\n case 'message':\n return t('message');\n default:\n return t('note');\n }\n}\n",
225
+ "src/pages.tsx": "import type { AppPage } from '@/components/app-shell';\nimport { boardPage } from '@/pages/board';\nimport { followupsPage } from '@/pages/followups';\nimport { partnersPage } from '@/pages/partners';\n// parall:page-imports — `parall app add` puts block imports above this line.\n\n/** The app's pages, in tab order; the first one opens by default. */\nexport const pages: AppPage[] = [\n boardPage,\n followupsPage,\n partnersPage,\n // parall:pages — `parall app add` puts block pages above this line.\n];\n"
226
+ }
227
+ }
228
+ ];
@@ -0,0 +1,49 @@
1
+ import { printError, printJson, printProgress } from '../lib/output.js';
2
+ import { APP_TEMPLATES } from './apps-template-catalog.gen.js';
3
+ export function findAppTemplate(id) {
4
+ return APP_TEMPLATES.find((template) => template.id === id);
5
+ }
6
+ /** What `parall app templates` prints. */
7
+ export function listAppTemplates() {
8
+ return APP_TEMPLATES.map(({ id, intro }) => ({ id, name: intro.name, summary: intro.summary }));
9
+ }
10
+ /** The version of the CLI that runs (the root command's). */
11
+ export function cliVersion(command) {
12
+ let root = command;
13
+ while (root.parent)
14
+ root = root.parent;
15
+ return root.version() ?? 'unknown';
16
+ }
17
+ /** The error for an id this CLI does not carry: what it has, and that the
18
+ * template may be newer than this CLI. */
19
+ export function unknownTemplateError(id, version) {
20
+ const known = APP_TEMPLATES.map(({ id: known, intro }) => `${known} (${intro.name.en}; ${intro.name.zh})`).join(', ');
21
+ return new Error(`No app template ${JSON.stringify(id)} in this CLI (parall ${version}); it has: ${known || 'none'}. ` +
22
+ 'A template may be newer than this CLI: update it once — npm install -g @parall/cli@latest, ' +
23
+ 'or where that is not allowed npm install --prefix ~/.parall-cli @parall/cli@latest — ' +
24
+ 'then run parall app templates again.');
25
+ }
26
+ export function registerAppTemplatesCommand(app) {
27
+ const templates = app
28
+ .command('templates')
29
+ .description('List ready-made app templates (a customer / partner pipeline, …) to build an app from; parall app templates show <id> prints how')
30
+ .action(() => {
31
+ printJson(listAppTemplates());
32
+ printProgress('Read one before building: parall app templates show <id> prints its skill — what to agree with the person first, then parall app init <dir> --template <id> --app <app_…>');
33
+ });
34
+ templates
35
+ .command('show')
36
+ .description("Print a template's skill (Markdown): what to agree with the person and the data to read, how to build the app, and what to do once it runs")
37
+ .argument('<id>', 'Template id (parall app templates)')
38
+ .action((id, _opts, command) => {
39
+ try {
40
+ const template = findAppTemplate(id);
41
+ if (!template)
42
+ throw unknownTemplateError(id, cliVersion(command));
43
+ process.stdout.write(template.skill.endsWith('\n') ? template.skill : `${template.skill}\n`);
44
+ }
45
+ catch (err) {
46
+ printError(err);
47
+ }
48
+ });
49
+ }