@parall/cli 1.81.0 → 1.83.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.
- package/dist/commands/apps-actions-sdk.generated.d.ts +1 -1
- package/dist/commands/apps-actions-sdk.generated.d.ts.map +1 -1
- package/dist/commands/apps-actions-sdk.generated.js +1 -1
- package/dist/commands/apps-local-runner.generated.d.ts +1 -1
- package/dist/commands/apps-local-runner.generated.d.ts.map +1 -1
- package/dist/commands/apps-local-runner.generated.js +1 -1
- package/dist/commands/apps-template-catalog.d.ts +19 -23
- package/dist/commands/apps-template-catalog.d.ts.map +1 -1
- package/dist/commands/apps-template-catalog.gen.d.ts.map +1 -1
- package/dist/commands/apps-template-catalog.gen.js +158 -144
- package/dist/commands/apps-template-catalog.js +1 -1
- package/dist/commands/apps-template-init.d.ts +9 -0
- package/dist/commands/apps-template-init.d.ts.map +1 -1
- package/dist/commands/apps-template-init.js +23 -4
- package/dist/commands/apps-template.d.ts +8 -0
- package/dist/commands/apps-template.d.ts.map +1 -1
- package/dist/commands/apps-template.js +20 -0
- package/dist/commands/apps-templates.gen.d.ts.map +1 -1
- package/dist/commands/apps-templates.gen.js +14 -16
- package/dist/commands/teams.d.ts +2 -0
- package/dist/commands/teams.d.ts.map +1 -1
- package/dist/commands/teams.js +42 -6
- package/package.json +4 -4
|
@@ -1,213 +1,227 @@
|
|
|
1
1
|
export const APP_TEMPLATES = [
|
|
2
2
|
{
|
|
3
|
-
"id": "
|
|
3
|
+
"id": "content-calendar",
|
|
4
4
|
"intro": {
|
|
5
|
-
"id": "
|
|
6
|
-
"cli": "1.
|
|
7
|
-
"name":
|
|
8
|
-
|
|
9
|
-
|
|
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
|
-
},
|
|
5
|
+
"id": "content-calendar",
|
|
6
|
+
"cli": "1.82.0",
|
|
7
|
+
"name": "Content calendar",
|
|
8
|
+
"summary": "What goes out on each platform and when, who owns it and how far along it is: a calendar and a topic board in one app.",
|
|
9
|
+
"short": "What goes out on each platform, and when",
|
|
10
|
+
"agent": "Splits a pasted brief into posts and reminds owners the day before",
|
|
23
11
|
"pages": [
|
|
12
|
+
{
|
|
13
|
+
"id": "calendar",
|
|
14
|
+
"icon": "calendar-days",
|
|
15
|
+
"name": "Calendar",
|
|
16
|
+
"description": "Every post by month, week or as a list, colored by platform. Paste a brief here and the agent splits it into posts."
|
|
17
|
+
},
|
|
24
18
|
{
|
|
25
19
|
"id": "board",
|
|
26
20
|
"icon": "square-kanban",
|
|
27
|
-
"name":
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
21
|
+
"name": "Topic board",
|
|
22
|
+
"description": "Every topic laid out by step. The steps are your own words — say, Idea → In progress → Ready → Published."
|
|
23
|
+
}
|
|
24
|
+
],
|
|
25
|
+
"questions": [
|
|
26
|
+
"Which platforms do you publish on? Each gets its own color on the calendar.",
|
|
27
|
+
"What steps does a post go through? The board's columns will use your words.",
|
|
28
|
+
"Where does the plan live today — a spreadsheet, a channel, a doc?",
|
|
29
|
+
"Who owns posts, and who should be reminded before one goes out?",
|
|
30
|
+
"What time each day should it check what goes out tomorrow and what is late?",
|
|
31
|
+
"Who should see the app? By default everyone in the organization can."
|
|
32
|
+
],
|
|
33
|
+
"data": [
|
|
34
|
+
{
|
|
35
|
+
"kind": "channels",
|
|
36
|
+
"name": "Channels",
|
|
37
|
+
"text": "Past messages in a channel such as #content or #marketing, where briefs and plans are posted. The agent must be in the channel to read it."
|
|
35
38
|
},
|
|
36
39
|
{
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
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
|
-
}
|
|
40
|
+
"kind": "tasks",
|
|
41
|
+
"name": "Tasks",
|
|
42
|
+
"text": "Tasks about upcoming posts, campaigns and launches."
|
|
47
43
|
},
|
|
48
44
|
{
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
"
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
"
|
|
56
|
-
|
|
57
|
-
"zh": "联系人、往来记录、下一步和截止日期。"
|
|
58
|
-
}
|
|
45
|
+
"kind": "wiki",
|
|
46
|
+
"name": "Wiki",
|
|
47
|
+
"text": "Documents such as the content strategy, the brand voice and a calendar kept as a page."
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"kind": "connections",
|
|
51
|
+
"name": "Connections",
|
|
52
|
+
"text": "Spreadsheets and calendars the organization has connected (the content plan in Google Sheets, say). For a connection it cannot use yet, it asks for access in the DM first."
|
|
59
53
|
}
|
|
60
54
|
],
|
|
61
|
-
"
|
|
55
|
+
"data_note": "Exactly what it reads, and how far back, it agrees with you in the DM first.",
|
|
56
|
+
"visibility": "The posts, days, owners and links it reads go into the app, and so do the briefs people paste. By default everyone in the organization can see them; to keep them to a few people, set “Everyone else in the organization” to “Can’t view” in the app’s Access and add those people one by one.",
|
|
57
|
+
"routine": [
|
|
58
|
+
"When someone pastes a brief, splits it into posts — platform, day and time, owner — and puts them on the calendar.",
|
|
59
|
+
"The day before a post goes out, reminds its owner, and says what is still missing.",
|
|
60
|
+
"Tells the owner when a post's time has passed and it is not marked published."
|
|
61
|
+
],
|
|
62
|
+
"wake": [
|
|
63
|
+
{
|
|
64
|
+
"kind": "data_changed",
|
|
65
|
+
"name": "When someone writes in the app",
|
|
66
|
+
"text": "Pasting a brief or changing a post wakes it to take a look."
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
"kind": "daily",
|
|
70
|
+
"name": "Once a day",
|
|
71
|
+
"text": "At a time you agree with it in the DM, such as 9:00 every day."
|
|
72
|
+
}
|
|
73
|
+
],
|
|
74
|
+
"limits": [
|
|
62
75
|
{
|
|
63
|
-
"
|
|
64
|
-
"
|
|
76
|
+
"kind": "visibility",
|
|
77
|
+
"text": "Everyone who can open the app sees every post, brief and link in it; they cannot be hidden from some of them. To keep the whole app to a few people, set “Everyone else in the organization” to “Can’t view” in the app’s Access and add those people one by one."
|
|
65
78
|
},
|
|
66
79
|
{
|
|
67
|
-
"
|
|
68
|
-
"
|
|
80
|
+
"kind": "uploads",
|
|
81
|
+
"text": "The pages cannot take file uploads. Send drafts, images and videos to the agent instead; a post keeps links to where they are."
|
|
69
82
|
},
|
|
70
83
|
{
|
|
71
|
-
"
|
|
72
|
-
"
|
|
84
|
+
"kind": "links",
|
|
85
|
+
"text": "Links do not open from inside the app — those to Parall (channels, tasks, documents) and those to drafts elsewhere alike. Copy a post's link and open it outside."
|
|
86
|
+
}
|
|
87
|
+
]
|
|
88
|
+
},
|
|
89
|
+
"skill": "# App template: Content calendar (content-calendar)\n\nWhen someone wants an app to plan what goes out on which platform and when — a content calendar, a social media calendar, a posting schedule — follow this skill: first agree on the details with the person who asked and tell them which data you will read; once they agree, build the app from the template's source and the organization's real data, set up the wake-ups, and from then on, each time you are woken, do what \"Day to day\" says. How to build an app in general, how to write PostgreSQL and how to subscribe to data changes are in your Mini App instructions and the scaffold's `AGENTS.md`; this skill covers only what is particular to this template.\n\nTalk to the person in their language; the platform and step names and the copy in the app use their team's own words too.\n\n## 1. Agree first\n\nIn the DM, ask all of the following in one message, each with its default; whatever they leave unanswered takes the default:\n\n1. Which platforms they publish on, and what they call them. Default: Instagram, TikTok, YouTube and LinkedIn.\n2. The steps a post goes through, in their words. Default: the template's Idea → In progress → Ready → Published.\n3. Where the plan lives today: a spreadsheet, a channel, a doc, tasks or the wiki, and how far back to bring it in. Default: nothing imported; the calendar fills from the briefs they paste and the posts they add.\n4. Who owns posts, and who is reminded before one goes out. Default: each post's owner; a post with no owner goes to the person who asked.\n5. What time each day to check what goes out tomorrow and what is late, and in which time zone. Default: 9:00 every day, in the person's time zone.\n6. Who should see the app. Once something is written into the app, everyone in the organization can see it by default; to keep it to a few people, set the app's \"Everyone else in the organization\" to \"Can't view\" (in the app's Access) and add those people one by one. Default: everyone in the organization.\n\n## 2. Explain the data\n\nIn the same message, before you read any data, say:\n\n- What you will read: which channel, which tasks, which wiki pages, which of the organization's connections, and how far back.\n- What of it goes into the app: posts (title, platform, day and time, owner, step), what each post is about, links to drafts and assets, and the briefs people paste.\n- The parameters of write calls are kept in the app's call records, which only its authors, org owners / admins and the person who made the call can see.\n- What you cannot read: ask them to add you to the channel, or request the connection through the approval card; no detours.\n\nUntil they agree, do not read this data and do not create the app.\n\nAnything you would read that the person who asked cannot see themselves (a channel they are not in — public channels too, since non-members cannot read its messages; tasks or wiki pages they have no access to; someone else's personal connection): first ask your manager in a DM, or an org admin if you have no manager — say who wants to build what, which content you would read, and who will see it once it is in the app (everyone in the organization by default). Read that part only once they agree; if they do not, use only what the person can see. When you are not sure whether the person can see something, treat it as something they cannot. A channel's members: `parall chats members list <chat>`.\n\n## 3. Build\n\n1. `parall app create --name \"<name>\"`, and note the `app_…`. If only a few people should see it, add `--members none` when you create it (an app created open and changed later has already shown its name in everyone's list), then add each of them with `parall app access add <app_…> <usr_…> --level read`, or `--level write` for those who should be able to change it.\n2. `parall app init <dir> --template content-calendar --app <app_…>` writes the template's source and this skill (`SKILL.md` at the project root). It refuses when the app's Database is on TiDB: tell the person what it says; do not rewrite the template for MySQL yourself.\n3. Adapt it to the answers, in `shared/content.ts`: the platforms are `PLATFORMS` (to rename one, change its `en` and `zh`; `id` is the value stored in the data; `color` is one of the `ContentColor` names, a different one for each); the steps are `STATUSES`, in board order — rename, add or drop them, but keep the one whose id is `PUBLISHED` (`published`) as the step that means a post is out, renaming only its `en` and `zh`. The copy is in `src/pages/*/messages.ts` and `src/components/post-messages.ts`; for a field they want to keep as well, add a column in `db/schema.sql` (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), then change `actions/` and the pages.\n4. Create the tables: `parall app db exec --app <app_…> --file db/schema.sql`.\n5. Import the real data, from the sources they agreed to only, each post into `posts`: `platform` and `status` are ids from step 3; a post with a time has `publish_at`, written with the team's offset (`2026-11-03T12:00:00-05:00`); one with only a day has `publish_date`; a topic with no day yet has neither. Owners are members: their `usr_…` and name. `brief` is what the post is about, `links` are one per line; `created_by` and `created_by_name` are your own `usr_…` and name. Leave empty what you cannot read: do not guess days, times, owners or links, and do not make up posts. One exec takes at most 256 KiB; split a large import.\n6. `pnpm install && pnpm build` → `parall app check dist` → `parall app publish dist --app <app_…> --source .`.\n\n## 4. Wake-ups\n\n- Subscribe to this app's data changes, watching `briefs` and `posts` only: `parall triggers create --source-kind platform_event --event-types app.data.changed --name \"Writes to <app name>\" --target-ids <your usr_…> --filter '…' --template '…'`. The filter names this app (`\"<app_…>\" in entity.app_ids`) and the two tables (`entity.tables != null && (\"briefs\" in entity.tables || \"posts\" in entity.tables)`; filters do not support loop macros such as `exists`). `--template` is what you are told when it wakes you (Liquid): say which app and what to do, such as `\"<app name>\" prll://<app_…> has new writes: tables {{ entity.tables | json }}, by {{ entity.actor_ids | json }}. Handle them as \"Day to day\" in <dir>/SKILL.md says.`\n- Then a daily schedule at the time they gave: `parall schedules create --name \"…\" --description \"…\" --target-ids <your usr_…> --cron-expr \"0 9 * * *\" --timezone <their time zone>`; `--description` says which app's daily pass this is, the team's time zone, who asked for the app (their `usr_…`) and to follow \"Day to day\" in `SKILL.md`.\n- Your own writes do not wake you. Read data with `parall app db query`: a query run with `parall app db exec` counts as a write, with its tables recorded as unknown, so filtering by table no longer works.\n\n## 5. Hand over\n\nReply in the DM with the app's link (`prll://app_…`), say what you imported (how many posts, from where) and when you will be woken (when someone pastes a brief or changes a post in the app, and at what time each day), tell them that \"Paste a brief\" on the Calendar page is how to hand you a brief to split into posts, and ask whether to post it in a channel.\n\n## 6. Day to day\n\n- A new brief (a row of `briefs` with status `new`): read it with `parall app db query` and split it into posts — one per platform and day: a title, the platform, the day and time if the brief gives them (in the team's time zone), the owner if it names one (a member's `usr_…` and name), the step (the first, unless the brief says a post is further along), what the post is about (the angle, the message, the call to action) and the links the brief gives for it. Write them all at once: put `{\"id\": \"<brief id>\", \"note\": \"…\", \"posts\": [{\"title\": \"…\", \"platform\": \"…\", \"publish_at\": \"…\", \"owner_id\": \"usr_…\", \"owner_name\": \"…\", \"brief\": \"…\"}, …]}` in a file and run `parall app action run <app_…> briefs_plan --params-file <file>`, which adds the posts and marks the brief planned. A brief is planned once: when it answers that the brief is already split, an earlier call went through (perhaps its reply was lost), so read that brief's posts rather than plan it again. The note tells whoever pasted it, in a sentence or two, how you split it and what you assumed. What the brief does not say, leave out — a post with no day waits on the topic board — rather than invent a day, a time or an owner. When something keeps you from splitting it at all, ask whoever pasted it in a DM, and plan it once they answer.\n- A brief someone sends you in the DM instead: add it with `parall app action run <app_…> briefs_add --params '{\"body\": \"…\"}'` so it shows in the app, then plan it the same way.\n- The daily pass: read the posts not in the `published` step that go out tomorrow, and the late ones, in the team's time zone — tomorrow is `(publish_at AT TIME ZONE '<tz>')::date` or `publish_date` equal to `(now() AT TIME ZONE '<tz>')::date + 1`; late is `publish_at < now()`, or `publish_date < (now() AT TIME ZONE '<tz>')::date` for a post with a day and no time (it is late from the day after). DM each owner once, with what goes out tomorrow (title, platform, time, step and its link `prll://<app_…>#calendar/<post id>`) and what is still missing (no draft link, not at the step before published), and which of theirs are late. A post with no owner goes to whoever pasted its brief (`briefs.created_by`) or added it by hand (`posts.created_by`); one you imported or added yourself goes to the person who asked for the app, named in the schedule's description. For a post late more than 3 days, ask its owner whether to move it or drop it instead of repeating the reminder.\n- When someone changes posts in the app: look at what changed (`updated_at`). A post that now goes out before your next daily pass, whose owner you have not told: tell them now. Do not undo or redo what a person changed.\n- Read only the sources the person agreed to. To read a new one, first ask again as \"Explain the data\" says.\n- Before changing the app, if you have no local project, fetch the current version's source with `parall app pull <app_…> --out <dir>`.\n- Ask about what a person has to decide, and do not decide it for them: moving a post to another day, changing its owner, deleting a post, marking a post published.\n",
|
|
90
|
+
"overlay": {
|
|
91
|
+
"_overlay.json": "{\n \"remove\": [\"public/manifest.json\", \"src/pages/items\", \"actions/items.ts\", \"shared/items.ts\"],\n \"blocks\": []\n}\n",
|
|
92
|
+
"actions/briefs.ts": "import type { Brief, BriefInput, BriefPlan, BriefPlanInput } from '@shared/content';\nimport { postRow, required, uuid } from './checks';\nimport { type ActionContext, ActionError } from './parall-actions';\nimport { readPosts } from './posts';\n\n// The briefs people paste into the app (\"Paste a brief\" on the calendar).\n// A new one wakes the agent that looks after the app (its app.data.changed\n// trigger watches this table); the agent splits it into posts with\n// briefs_plan, which marks it planned. Everyone who can open the app reads\n// every brief; whoever pasted one, or an org owner/admin, deletes it — its\n// posts stay.\n\n// $1 = ctx.viewer.id, $2 = ctx.viewer.role\nconst BRIEF_COLUMNS = `b.id, b.body, b.status, b.note, b.planned_by_name, b.planned_at,\n b.created_by, b.created_by_name, b.created_at,\n (SELECT count(*) FROM posts p WHERE p.brief_id = b.id)::int AS post_count,\n (b.created_by = $1 OR $2 IN ('owner', 'admin')) AS can_delete`;\n\nasync function readBrief(ctx: ActionContext, id: string): Promise<Brief> {\n const { rows } = await ctx.db.query(`SELECT ${BRIEF_COLUMNS} FROM briefs b WHERE b.id = $3`, [\n ctx.viewer.id,\n ctx.viewer.role,\n id,\n ]);\n if (!rows[0]) throw new ActionError('This brief does not exist.');\n return rows[0] as unknown as Brief;\n}\n\nexport const briefActions = {\n /** read: the 30 latest briefs, newest first. */\n async briefs_list(ctx: ActionContext): Promise<Brief[]> {\n const { rows } = await ctx.db.query(\n `SELECT ${BRIEF_COLUMNS} FROM briefs b ORDER BY b.created_at DESC LIMIT 30`,\n [ctx.viewer.id, ctx.viewer.role],\n );\n return rows as unknown as Brief[];\n },\n\n /** write: adds a brief, waiting for the agent. */\n async briefs_add(ctx: ActionContext, input: BriefInput): Promise<Brief> {\n const body = required(input.body, 'The brief');\n const { rows } = await ctx.db.exec(\n `INSERT INTO briefs (body, created_by, created_by_name) VALUES ($1, $2, $3) RETURNING id`,\n [body, ctx.viewer.id, ctx.viewer.display_name],\n );\n return readBrief(ctx, rows[0]?.id as string);\n },\n\n /** write: deletes a brief; the posts split from it stay. */\n async briefs_delete(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = uuid(params.id, 'brief');\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM briefs b WHERE b.id = $3 AND (b.created_by = $1 OR $2 IN ('owner', 'admin'))`,\n [ctx.viewer.id, ctx.viewer.role, id],\n );\n if (rows_affected === 0) {\n throw new ActionError('Only whoever pasted this brief or an org admin can delete it.');\n }\n return { id };\n },\n\n /**\n * write (the agent): the posts a brief is split into, and a note for\n * whoever pasted it — what it assumed, what it still needs. A brief is\n * planned once: one statement marks it planned and adds its posts, and\n * only while it is still new, so a second call for it (a retry after a\n * lost reply, or two runs at once) adds nothing and says so.\n */\n async briefs_plan(ctx: ActionContext, input: BriefPlanInput): Promise<BriefPlan> {\n const id = uuid(input.id, 'brief');\n const rows = input.posts.map(postRow);\n const { rows: found } = await ctx.db.query(`SELECT 1 FROM briefs WHERE id = $1`, [id]);\n if (!found[0]) throw new ActionError('This brief does not exist.');\n const { rows: done } = await ctx.db.exec(\n `WITH planned AS (\n UPDATE briefs\n SET status = 'planned', note = $5, planned_by_name = $4, planned_at = now(),\n updated_at = now()\n WHERE id = $2 AND status = 'new'\n RETURNING id\n ), added AS (\n INSERT INTO posts (title, platform, status, publish_at, publish_date, owner_id,\n owner_name, brief, links, brief_id, created_by, created_by_name)\n SELECT r.title, r.platform, r.status, r.publish_at, r.publish_date, r.owner_id,\n r.owner_name, r.brief, r.links, planned.id, $3::text, $4::text\n FROM planned,\n jsonb_to_recordset($1::jsonb) AS r(title text, platform text, status text,\n publish_at timestamptz, publish_date date, owner_id text, owner_name text,\n brief text, links text)\n RETURNING id\n )\n SELECT (SELECT count(*) FROM planned)::int AS planned`,\n // The posts as one JSON array: one statement however many there are.\n [rows, id, ctx.viewer.id, ctx.viewer.display_name, (input.note ?? '').trim()],\n );\n if (!done[0]?.planned) {\n throw new ActionError(\n 'This brief is already split into posts, so these were not added. Read its posts instead of planning it again.',\n );\n }\n return {\n brief: await readBrief(ctx, id),\n posts: await readPosts(ctx, 'p.brief_id = $3', [id]),\n };\n },\n};\n",
|
|
93
|
+
"actions/checks.ts": "import { PLATFORMS, type PostFields, STATUSES } from '@shared/content';\nimport { ActionError } from './parall-actions';\n\n// Checks the content calendar's actions share. The platform has already\n// checked the params against public/manifest.json; these are the rules a\n// JSON Schema cannot say. Messages reach the caller as they are\n// (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/** 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 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/** An instant (ISO 8601, with its offset); '' or nothing is null. */\nexport function optionalInstant(value: string | undefined, field: string): string | null {\n if (!value) return null;\n const at = new Date(value);\n if (Number.isNaN(at.getTime())) throw new ActionError(`${field} is not a time.`);\n return at.toISOString();\n}\n\n/** A platform of shared/content.ts; '' or nothing is not decided yet. */\nexport function platform(id: string | undefined): string | null {\n if (!id) return null;\n if (!PLATFORMS.some((p) => p.id === id)) {\n throw new ActionError(\n `Unknown platform ${JSON.stringify(id)}; the platforms are ${PLATFORMS.map((p) => p.id).join(', ')}.`,\n );\n }\n return id;\n}\n\n/** A step of shared/content.ts. */\nexport function status(id: string): string {\n if (!STATUSES.some((s) => s.id === id)) {\n throw new ActionError(\n `Unknown status ${JSON.stringify(id)}; the statuses are ${STATUSES.map((s) => s.id).join(', ')}.`,\n );\n }\n return id;\n}\n\n/** Links one per line, trimmed, empty lines dropped. */\nexport function links(value: string | undefined): string {\n return (value ?? '')\n .split('\\n')\n .map((line) => line.trim())\n .filter(Boolean)\n .join('\\n');\n}\n\n/** A post's columns, checked, as posts_save and briefs_plan write them. */\nexport interface PostRow {\n title: string;\n platform: string | null;\n status: string;\n publish_at: string | null;\n publish_date: string | null;\n owner_id: string | null;\n owner_name: string | null;\n brief: string;\n links: string;\n}\n\n/** Checks a post's fields; a missing status is the first step. */\nexport function postRow(input: PostFields): PostRow {\n const at = optionalInstant(input.publish_at, 'publish_at');\n const day = optionalDate(input.publish_date, 'publish_date');\n if (at && day) {\n throw new ActionError(\n 'Give publish_at (a day and a time) or publish_date (a day with no time yet), not both.',\n );\n }\n const ownerId = input.owner_id || null;\n return {\n title: required(input.title, 'A title'),\n platform: platform(input.platform),\n status: status(input.status ?? STATUSES[0]?.id ?? ''),\n publish_at: at,\n publish_date: day,\n owner_id: ownerId,\n owner_name: ownerId ? (input.owner_name ?? '').trim() || null : null,\n brief: (input.brief ?? '').trim(),\n links: links(input.links),\n };\n}\n",
|
|
94
|
+
"actions/index.ts": "import { briefActions } from './briefs';\nimport { defineActions } from './parall-actions';\nimport { peopleActions } from './people';\nimport { postActions } from './posts';\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 ...postActions,\n ...briefActions,\n // parall:actions — `parall app add` puts block actions above this line.\n});\n",
|
|
95
|
+
"actions/posts.ts": "import type { Post, PostInput, PostRange, PostStatusInput } from '@shared/content';\nimport { PUBLISHED } from '@shared/content';\nimport { optionalDate, optionalInstant, postRow, status, uuid } from './checks';\nimport { type ActionContext, ActionError } from './parall-actions';\n\n// The posts: the calendar (src/pages/calendar) and the topic board\n// (src/pages/board). Everyone who can open the app (by default, the whole\n// organization) reads every post, and those who can change it create, edit\n// and move posts; a post is deleted by its creator or an org owner/admin.\n// Tighten these here: past the app's access setting, the actions are the\n// only gate.\n\nconst POST_COLUMNS = `p.id, p.title, p.platform, p.status, p.publish_at,\n to_char(p.publish_date, 'YYYY-MM-DD') AS publish_date, p.owner_id, p.owner_name,\n p.brief, p.links, p.brief_id, b.created_by_name AS brief_by_name, b.created_at AS brief_at,\n p.created_by, p.updated_at`;\n// $1 = ctx.viewer.id, $2 = ctx.viewer.role\nconst CAN_DELETE = `(p.created_by = $1 OR $2 IN ('owner', 'admin'))`;\n// A calendar view shows six weeks at most; a wider range is a mistake.\nconst MAX_RANGE_DAYS = 62;\n\nexport async function readPosts(\n ctx: ActionContext,\n where: string,\n params: unknown[],\n limit = 1000,\n): Promise<Post[]> {\n const { rows } = await ctx.db.query(\n `SELECT ${POST_COLUMNS}, ${CAN_DELETE} AS can_delete\n FROM posts p LEFT JOIN briefs b ON b.id = p.brief_id\n WHERE ${where}\n ORDER BY coalesce(p.publish_at, p.publish_date::timestamptz) NULLS LAST, p.updated_at DESC\n LIMIT ${limit}`,\n [ctx.viewer.id, ctx.viewer.role, ...params],\n );\n return rows as unknown as Post[];\n}\n\nasync function readPost(ctx: ActionContext, id: string): Promise<Post> {\n const [post] = await readPosts(ctx, 'p.id = $3', [id], 1);\n if (!post) throw new ActionError('This post does not exist.');\n return post;\n}\n\nexport const postActions = {\n /** read: the posts going out in a calendar view's days. */\n async posts_range(ctx: ActionContext, range: PostRange): Promise<Post[]> {\n const from = optionalInstant(range.from, 'from');\n const to = optionalInstant(range.to, 'to');\n const fromDate = optionalDate(range.from_date, 'from_date');\n const toDate = optionalDate(range.to_date, 'to_date');\n if (!from || !to || !fromDate || !toDate || from > to || fromDate > toDate) {\n throw new ActionError('Give the range as from ≤ to and from_date ≤ to_date.');\n }\n if (Date.parse(to) - Date.parse(from) > MAX_RANGE_DAYS * 86_400_000) {\n throw new ActionError(`Ask for ${MAX_RANGE_DAYS} days at most.`);\n }\n return readPosts(\n ctx,\n `(p.publish_at >= $3::timestamptz AND p.publish_at < $4::timestamptz)\n OR (p.publish_date BETWEEN $5::date AND $6::date)`,\n [from, to, fromDate, toDate],\n );\n },\n\n /** read: the topic board — every post not published yet, and those\n * published in the last 30 days: by the day it went out, or, for one with\n * no day, by when it last changed. */\n async posts_board(ctx: ActionContext): Promise<Post[]> {\n return readPosts(\n ctx,\n `p.status <> $3\n OR coalesce(p.publish_at, p.publish_date::timestamptz, p.updated_at)\n >= now() - interval '30 days'`,\n [PUBLISHED],\n );\n },\n\n /** read: one post (a link to it: prll://app_…#calendar/<id>). */\n async post_get(ctx: ActionContext, params: { id: string }): Promise<Post> {\n return readPost(ctx, uuid(params.id, 'post'));\n },\n\n /** write: creates a post (no id) or rewrites one; see PostInput. */\n async posts_save(ctx: ActionContext, input: PostInput): Promise<Post> {\n const id = input.id === undefined ? null : uuid(input.id, 'post');\n const row = postRow(input);\n const values = [\n row.title,\n row.platform,\n row.status,\n row.publish_at,\n row.publish_date,\n row.owner_id,\n row.owner_name,\n row.brief,\n row.links,\n ];\n if (id === null) {\n const { rows } = await ctx.db.exec(\n `INSERT INTO posts (title, platform, status, publish_at, publish_date, owner_id,\n owner_name, brief, links, created_by, created_by_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING id`,\n [...values, ctx.viewer.id, ctx.viewer.display_name],\n );\n return readPost(ctx, rows[0]?.id as string);\n }\n const { rows_affected } = await ctx.db.exec(\n `UPDATE posts\n SET title = $1, platform = $2, status = $3, publish_at = $4, publish_date = $5,\n owner_id = $6, owner_name = $7, brief = $8, links = $9, updated_at = now()\n WHERE id = $10`,\n [...values, id],\n );\n if (!rows_affected) throw new ActionError('This post does not exist.');\n return readPost(ctx, id);\n },\n\n /** write: moves a post to another step (the board, \"Mark as published\"). */\n async posts_status(ctx: ActionContext, input: PostStatusInput): Promise<Post> {\n const id = uuid(input.id, 'post');\n const { rows_affected } = await ctx.db.exec(\n `UPDATE posts SET status = $1, updated_at = now() WHERE id = $2`,\n [status(input.status), id],\n );\n if (!rows_affected) throw new ActionError('This post does not exist.');\n return readPost(ctx, id);\n },\n\n /** write: deletes a post. */\n async posts_delete(ctx: ActionContext, params: { id: string }): Promise<{ id: string }> {\n const id = uuid(params.id, 'post');\n const { rows_affected } = await ctx.db.exec(\n `DELETE FROM posts p WHERE p.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 post.');\n }\n return { id };\n },\n};\n",
|
|
96
|
+
"db/schema.sql": "-- The content calendar's tables. The Database is PostgreSQL (not SQLite):\n-- uuid, timestamptz, 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-- The organization's members are not a table here: actions/people.ts lists\n-- them with ctx.parall.members(), and pages offer them as owners. Tables\n-- keep a member's id (usr_…). ctx.viewer is the only trustworthy identity.\n\n-- A brief someone pasted into the app for the agent to split into posts\n-- (briefs_plan). status new waits for the agent; planned has been split, and\n-- note is what the agent says about it.\nCREATE TABLE IF NOT EXISTS briefs (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n body text NOT NULL CHECK (length(body) BETWEEN 1 AND 20000),\n status text NOT NULL DEFAULT 'new' CHECK (status IN ('new', 'planned')),\n note text NOT NULL DEFAULT '',\n planned_by_name text NOT NULL DEFAULT '',\n planned_at timestamptz,\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 briefs_created_idx ON briefs (created_at DESC);\n\n-- One post on one platform. platform and status are ids of PLATFORMS and\n-- STATUSES in shared/content.ts (the actions check them, so renaming needs\n-- no schema change); platform is null while it is not decided. A post with\n-- a time has publish_at (an instant); one with only a day has publish_date,\n-- the same calendar day wherever the viewer is; a topic with no day yet has\n-- neither. links are one per line. brief_id is the pasted brief it was\n-- split from; deleting the brief keeps the post.\nCREATE TABLE IF NOT EXISTS posts (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n title text NOT NULL CHECK (length(title) BETWEEN 1 AND 200),\n platform text CHECK (length(platform) BETWEEN 1 AND 64),\n status text NOT NULL CHECK (length(status) BETWEEN 1 AND 64),\n publish_at timestamptz,\n publish_date date,\n owner_id text,\n owner_name text,\n brief text NOT NULL DEFAULT '' CHECK (length(brief) <= 5000),\n links text NOT NULL DEFAULT '' CHECK (length(links) <= 2000),\n brief_id uuid REFERENCES briefs (id) ON DELETE SET NULL,\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 CHECK (publish_at IS NULL OR publish_date IS NULL)\n);\nCREATE INDEX IF NOT EXISTS posts_publish_at_idx ON posts (publish_at);\nCREATE INDEX IF NOT EXISTS posts_publish_date_idx ON posts (publish_date);\nCREATE INDEX IF NOT EXISTS posts_status_idx ON posts (status, updated_at DESC);\nCREATE INDEX IF NOT EXISTS posts_brief_idx ON posts (brief_id);\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 posts and pastes briefs (a team's shared\n-- calendar); a post is deleted by its creator or an org owner/admin, a brief\n-- by whoever pasted it or an org owner/admin (actions/posts.ts, briefs.ts).\n-- Posts, briefs and links are visible to everyone who can open the app — by\n-- default the whole organization; to keep them to a few people, set everyone\n-- else in the organization to not readable and add those people one by one\n-- — and what a write action is passed is kept in the app's call log, which\n-- only the app's authors, org owners/admins and the caller can read.\n",
|
|
97
|
+
"package.json": "{\n \"dependencies\": {\n \"date-fns\": \"4.4.0\"\n }\n}\n",
|
|
98
|
+
"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 \"posts_range\": {\n \"kind\": \"read\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"from\": { \"type\": \"string\", \"format\": \"date-time\" },\n \"to\": { \"type\": \"string\", \"format\": \"date-time\" },\n \"from_date\": { \"type\": \"string\", \"format\": \"date\" },\n \"to_date\": { \"type\": \"string\", \"format\": \"date\" }\n },\n \"required\": [\"from\", \"to\", \"from_date\", \"to_date\"]\n }\n },\n \"posts_board\": { \"kind\": \"read\" },\n \"post_get\": {\n \"kind\": \"read\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"posts_save\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"platform\": { \"type\": \"string\", \"maxLength\": 64 },\n \"status\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 },\n \"publish_at\": { \"type\": \"string\", \"format\": \"date-time\" },\n \"publish_date\": { \"type\": \"string\", \"format\": \"date\" },\n \"owner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"owner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"brief\": { \"type\": \"string\", \"maxLength\": 5000 },\n \"links\": { \"type\": \"string\", \"maxLength\": 2000 }\n },\n \"required\": [\"title\", \"status\"]\n }\n },\n \"posts_status\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"status\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 }\n },\n \"required\": [\"id\", \"status\"]\n }\n },\n \"posts_delete\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"briefs_list\": { \"kind\": \"read\" },\n \"briefs_add\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"body\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 20000 } },\n \"required\": [\"body\"]\n }\n },\n \"briefs_delete\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": { \"id\": { \"type\": \"string\", \"maxLength\": 64 } },\n \"required\": [\"id\"]\n }\n },\n \"briefs_plan\": {\n \"kind\": \"write\",\n \"params\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"note\": { \"type\": \"string\", \"maxLength\": 2000 },\n \"posts\": {\n \"type\": \"array\",\n \"maxItems\": 60,\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"title\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 200 },\n \"platform\": { \"type\": \"string\", \"maxLength\": 64 },\n \"status\": { \"type\": \"string\", \"minLength\": 1, \"maxLength\": 64 },\n \"publish_at\": { \"type\": \"string\", \"format\": \"date-time\" },\n \"publish_date\": { \"type\": \"string\", \"format\": \"date\" },\n \"owner_id\": { \"type\": \"string\", \"maxLength\": 64 },\n \"owner_name\": { \"type\": \"string\", \"maxLength\": 200 },\n \"brief\": { \"type\": \"string\", \"maxLength\": 5000 },\n \"links\": { \"type\": \"string\", \"maxLength\": 2000 }\n },\n \"required\": [\"title\"]\n }\n }\n },\n \"required\": [\"id\", \"note\", \"posts\"]\n }\n }\n }\n }\n}\n",
|
|
99
|
+
"shared/content.ts": "// Types shared by the content calendar's actions (actions/posts.ts,\n// actions/briefs.ts) and its pages (src/pages/calendar, src/pages/board):\n// the actions return rows of these shapes.\n\nexport type ContentColor =\n | 'fuchsia'\n | 'red'\n | 'orange'\n | 'amber'\n | 'emerald'\n | 'teal'\n | 'sky'\n | 'blue'\n | 'violet'\n | 'zinc';\n\nexport interface Platform {\n /** What posts.platform stores. Keep an id once posts use it; to retire\n * one, move its posts to another platform in SQL first. */\n id: string;\n /** The platform's name, as the team says it. */\n en: string;\n zh: string;\n /** Its color on the calendar and the board. */\n color: ContentColor;\n}\n\n/** The platforms the team publishes on, in the order the calendar's legend\n * and the pickers list them: add, rename or drop them to match the team\n * (a newsletter, a blog, X…), each with a color of its own. */\nexport const PLATFORMS: Platform[] = [\n { id: 'instagram', en: 'Instagram', zh: 'Instagram', color: 'fuchsia' },\n { id: 'tiktok', en: 'TikTok', zh: 'TikTok', color: 'zinc' },\n { id: 'youtube', en: 'YouTube', zh: 'YouTube', color: 'red' },\n { id: 'linkedin', en: 'LinkedIn', zh: 'LinkedIn', color: 'blue' },\n];\n\nexport interface Status {\n /** What posts.status stores. Keep an id once posts use it. */\n id: string;\n /** The step's name, as the team says it. */\n en: string;\n zh: string;\n color: ContentColor;\n}\n\n/** The id of the step that means a post is out. Reminders skip it, and a\n * post whose time has passed in any other step is late. Rename the step\n * in STATUSES as the team says it, but keep this id. */\nexport const PUBLISHED = 'published';\n\n/** The steps a post goes through, in board order: the team's own words.\n * Add, rename or drop steps; keep one with the id PUBLISHED, last. */\nexport const STATUSES: Status[] = [\n { id: 'idea', en: 'Idea', zh: '选题', color: 'zinc' },\n { id: 'in_progress', en: 'In progress', zh: '制作中', color: 'amber' },\n { id: 'ready', en: 'Ready', zh: '待发布', color: 'sky' },\n { id: PUBLISHED, en: 'Published', zh: '已发布', color: 'emerald' },\n];\n\n/** One post on one platform: a topic on the board until it has a day, on\n * the calendar once it has one. */\nexport interface Post {\n id: string;\n title: string;\n /** A Platform id; null while it is not decided. */\n platform: string | null;\n /** A Status id. */\n status: string;\n /** When it goes out. publish_at is an instant (ISO) when the time is\n * set; publish_date the day (YYYY-MM-DD) when only the day is; both are\n * null for a topic with no day yet. */\n publish_at: string | null;\n publish_date: string | null;\n owner_id: string | null;\n owner_name: string | null;\n /** The brief for this post: what it is about, the angle, the call to\n * action. */\n brief: string;\n /** Links, one per line: the draft, the assets, the published post. */\n links: string;\n /** The pasted brief it was split from (briefs_plan): who pasted it and\n * when; null for a post added by hand or imported. */\n brief_id: string | null;\n brief_by_name: string | null;\n brief_at: string | null;\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/** A post's fields as posts_save and briefs_plan take them. Every field is\n * written as given: one left out is cleared (no platform, no day, no\n * owner…). publish_at and publish_date are never both given. */\nexport interface PostFields {\n title: string;\n platform?: string;\n /** A Status id; briefs_plan starts a post at the first step without it. */\n status?: string;\n /** An ISO instant with its offset, as 2026-11-03T12:00:00-05:00. */\n publish_at?: string;\n /** YYYY-MM-DD, for a day with no time yet. */\n publish_date?: string;\n owner_id?: string;\n owner_name?: string;\n brief?: string;\n links?: string;\n}\n\n/** posts_save params: no id creates a post. */\nexport interface PostInput extends PostFields {\n id?: string;\n status: string;\n}\n\n/** posts_status params: moves a post to another step. */\nexport interface PostStatusInput {\n id: string;\n status: string;\n}\n\n/** posts_range params: the days a calendar view shows, as instants for\n * posts with a time and as local days for posts with only a day. */\nexport interface PostRange {\n from: string;\n to: string;\n from_date: string;\n to_date: string;\n}\n\n/** new: waiting for the agent; planned: split into posts. */\nexport type BriefStatus = 'new' | 'planned';\n\n/** A brief someone pasted into the app for the agent to split into posts. */\nexport interface Brief {\n id: string;\n body: string;\n status: BriefStatus;\n /** What the agent says about how it split it: what it assumed, what it\n * still needs. */\n note: string;\n planned_by_name: string;\n planned_at: string | null;\n created_by: string;\n created_by_name: string;\n created_at: string;\n /** How many posts it was split into that are still there. */\n post_count: number;\n /** Whether the caller may delete it: whoever pasted it or an org\n * owner/admin. */\n can_delete: boolean;\n}\n\n/** briefs_add params. */\nexport interface BriefInput {\n body: string;\n}\n\n/** briefs_plan params (the agent): the posts the brief is split into, and\n * a note for whoever pasted it. */\nexport interface BriefPlanInput {\n id: string;\n note: string;\n posts: PostFields[];\n}\n\n/** briefs_plan's answer: the brief, planned, and every post it has. */\nexport interface BriefPlan {\n brief: Brief;\n posts: Post[];\n}\n",
|
|
100
|
+
"src/components/post-badges.tsx": "import { PLATFORMS } from '@shared/content';\nimport { Badge } from '@/components/ui/badge';\nimport { locale } from '@/lib/i18n';\nimport { platformColors, platformName, statusColors, statusName } from '@/lib/content';\nimport { cn } from '@/lib/utils';\n\n/** A platform's color, as a dot. */\nexport function PlatformDot({\n platform,\n className,\n}: {\n platform: string | null;\n className?: string;\n}) {\n return (\n <span\n aria-hidden\n className={cn('size-2 shrink-0 rounded-full', platformColors(platform).dot, className)}\n />\n );\n}\n\n/** A platform's dot and name. */\nexport function PlatformBadge({\n platform,\n className,\n}: {\n platform: string | null;\n className?: string;\n}) {\n return (\n <span className={cn('inline-flex min-w-0 items-center gap-1.5 text-xs', className)}>\n <PlatformDot platform={platform} />\n <span className=\"truncate\">{platformName(platform)}</span>\n </span>\n );\n}\n\n/** A post's step, as a badge in the step's color. */\nexport function StatusBadge({ status, className }: { status: string; className?: string }) {\n return (\n <Badge variant=\"outline\" className={cn('gap-1.5 font-normal', className)}>\n <span aria-hidden className={cn('size-1.5 rounded-full', statusColors(status).dot)} />\n {statusName(status)}\n </Badge>\n );\n}\n\n/** Every platform with its color: the calendar's key. */\nexport function PlatformLegend({ className }: { className?: string }) {\n return (\n <ul className={cn('flex flex-wrap items-center gap-x-3 gap-y-1', className)}>\n {PLATFORMS.map((platform) => (\n <li key={platform.id} className=\"inline-flex items-center gap-1.5\">\n <PlatformDot platform={platform.id} />\n {platform[locale]}\n </li>\n ))}\n </ul>\n );\n}\n",
|
|
101
|
+
"src/components/post-dialog.tsx": "import { PLATFORMS, type Post, type PostInput, PUBLISHED, STATUSES } from '@shared/content';\nimport { Clock, Copy, Lock, Sparkles, Trash2 } from 'lucide-react';\nimport { useEffect, useId, useState } from 'react';\nimport { toast } from 'sonner';\nimport { ConfirmDialog } from '@/components/confirm-dialog';\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 { useCanEdit } from '@/hooks/use-host';\nimport {\n isLate,\n linkList,\n type Owner,\n ownersWith,\n platformColors,\n platformName,\n postDay,\n t as shared,\n statusName,\n} from '@/lib/content';\nimport { describeError } from '@/lib/errors';\nimport { formatRelative } from '@/lib/format';\nimport { locale } from '@/lib/i18n';\nimport { onEnter } from '@/lib/keys';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { t } from './post-messages';\n\nconst NONE = '__none__';\n\n/** What the dialog starts from: a post to open, or the day and step a new\n * one goes to. */\nexport type PostDraft =\n | { mode: 'edit'; post: Post }\n | { mode: 'create'; day?: string; status?: string };\n\n/** \"14:30\" of an instant, in the viewer's own time. */\nfunction localTime(at: string): string {\n const date = new Date(at);\n const pad = (n: number) => String(n).padStart(2, '0');\n return `${pad(date.getHours())}:${pad(date.getMinutes())}`;\n}\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/** Creates, edits or shows one post (posts_save, posts_delete): its\n * platform, day and time, owner, step, brief and links. For someone who\n * can only view the app it shows the post read-only. */\nexport function PostDialog({\n draft,\n owners,\n onClose,\n onSaved,\n onDeleted,\n}: {\n draft: PostDraft | null;\n owners: Owner[];\n onClose: () => void;\n onSaved: (post: Post) => void;\n onDeleted: (id: string) => void;\n}) {\n const formId = useId();\n const readOnly = !useCanEdit();\n const save = useMutation<Post, PostInput>('posts_save');\n const remove = useMutation<{ id: string }, { id: string }>('posts_delete');\n const resetSave = save.reset;\n const [title, setTitle] = useState('');\n const [platform, setPlatform] = useState(NONE);\n const [status, setStatus] = useState(STATUSES[0]?.id ?? '');\n const [day, setDay] = useState('');\n const [time, setTime] = useState('');\n const [owner, setOwner] = useState(NONE);\n const [brief, setBrief] = useState('');\n const [links, setLinks] = useState('');\n const [deleting, setDeleting] = useState(false);\n\n const post = draft?.mode === 'edit' ? draft.post : null;\n const ownerOptions = ownersWith(owners, post?.owner_id, post?.owner_name);\n\n useEffect(() => {\n if (!draft) return;\n const p = draft.mode === 'edit' ? draft.post : null;\n setTitle(p?.title ?? '');\n setPlatform(p ? (p.platform ?? NONE) : (PLATFORMS[0]?.id ?? NONE));\n setStatus(\n p?.status ?? (draft.mode === 'create' ? draft.status : undefined) ?? STATUSES[0]?.id ?? '',\n );\n setDay(p ? (postDay(p) ?? '') : draft.mode === 'create' ? (draft.day ?? '') : '');\n setTime(p?.publish_at ? localTime(p.publish_at) : '');\n setOwner(p?.owner_id ?? NONE);\n setBrief(p?.brief ?? '');\n setLinks(p?.links ?? '');\n resetSave();\n }, [draft, resetSave]);\n\n const ready = title.trim() !== '' && status !== '';\n\n async function submit() {\n if (readOnly || !ready || save.pending) return;\n const picked = ownerOptions.find((o) => o.id === owner);\n const at = day && time ? new Date(`${day}T${time}`) : null;\n try {\n const saved = await save.run({\n ...(post ? { id: post.id } : {}),\n title: title.trim(),\n status,\n ...(platform !== NONE ? { platform } : {}),\n ...(at && !Number.isNaN(at.getTime()) ? { publish_at: at.toISOString() } : {}),\n ...(day && !time ? { publish_date: day } : {}),\n ...(picked ? { owner_id: picked.id, owner_name: picked.name } : {}),\n brief: brief.trim(),\n links,\n });\n onSaved(saved);\n toast.success(t('saved'));\n onClose();\n } catch {\n // Shown under the form from save.error.\n }\n }\n\n async function confirmDelete() {\n if (!post) return;\n try {\n await remove.run({ id: post.id });\n onDeleted(post.id);\n toast.success(t('deleted'));\n setDeleting(false);\n onClose();\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n const field = (id: string) => `${formId}-${id}`;\n const shownLinks = linkList(links);\n const late = post ? isLate(post) : false;\n return (\n <>\n <ResponsiveDialog\n open={draft !== null}\n onOpenChange={(next) => !next && onClose()}\n title={readOnly ? t('postDetails') : post ? t('editPost') : t('newPost')}\n footer={\n readOnly ? (\n <Button variant=\"outline\" onClick={onClose}>\n {common('close')}\n </Button>\n ) : (\n <>\n {post?.can_delete ? (\n <Button\n variant=\"ghost\"\n className=\"text-destructive hover:text-destructive sm:mr-auto\"\n onClick={() => setDeleting(true)}\n disabled={save.pending}\n >\n <Trash2 />\n {common('delete')}\n </Button>\n ) : null}\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 {late ? (\n <p className=\"flex items-center gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-destructive text-sm\">\n <Clock className=\"size-4 shrink-0\" />\n {t('late', { status: statusName(PUBLISHED) })}\n </p>\n ) : null}\n <fieldset disabled={readOnly} className=\"flex min-w-0 flex-col gap-4\">\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 autoFocus={!post}\n onKeyDown={onEnter(submit)}\n />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"flex min-w-0 flex-col gap-2\">\n <Label htmlFor={field('platform')}>{t('fieldPlatform')}</Label>\n <Select value={platform} onValueChange={setPlatform}>\n <SelectTrigger id={field('platform')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {PLATFORMS.map((p) => (\n <SelectItem key={p.id} value={p.id}>\n <span className={cn('size-2 rounded-full', platformColors(p.id).dot)} />\n {p[locale]}\n </SelectItem>\n ))}\n <SelectItem value={NONE}>{platformName(null)}</SelectItem>\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex min-w-0 flex-col gap-2\">\n <Label htmlFor={field('status')}>{t('fieldStatus')}</Label>\n <Select value={status} onValueChange={setStatus}>\n <SelectTrigger id={field('status')} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {STATUSES.map((s) => (\n <SelectItem key={s.id} value={s.id}>\n {s[locale]}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"flex min-w-0 flex-col gap-2\">\n <Label htmlFor={field('day')}>{t('fieldDay')}</Label>\n <Input\n id={field('day')}\n type=\"date\"\n value={day}\n onChange={(e) => setDay(e.target.value)}\n />\n </div>\n <div className=\"flex min-w-0 flex-col gap-2\">\n <Label htmlFor={field('time')}>{t('fieldTime')}</Label>\n <Input\n id={field('time')}\n type=\"time\"\n value={time}\n disabled={!day}\n title={day ? undefined : t('dayFirst')}\n onChange={(e) => setTime(e.target.value)}\n />\n </div>\n </div>\n {readOnly ? null : (\n <p className=\"-mt-2 text-muted-foreground text-xs\">{t('timeHint')}</p>\n )}\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={NONE}>{shared('unassigned')}</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=\"flex flex-col gap-2\">\n <Label htmlFor={field('brief')}>{t('fieldBrief')}</Label>\n <Textarea\n id={field('brief')}\n value={brief}\n onChange={(e) => setBrief(e.target.value)}\n placeholder={t('briefPlaceholder')}\n rows={3}\n maxLength={5000}\n />\n </div>\n {readOnly ? null : (\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={field('links')}>{t('fieldLinks')}</Label>\n <Textarea\n id={field('links')}\n value={links}\n onChange={(e) => setLinks(e.target.value)}\n placeholder={t('linksPlaceholder')}\n rows={2}\n maxLength={2000}\n className=\"font-mono md:text-xs\"\n />\n <p className=\"text-muted-foreground text-xs\">{t('linksHint')}</p>\n </div>\n )}\n </fieldset>\n {/* Someone who can only view the app gets each link with a copy\n button: links do not open from inside the app. */}\n {readOnly && shownLinks.length > 0 ? (\n <div className=\"flex flex-col gap-1.5\">\n <p className=\"font-medium text-sm\">{t('fieldLinks')}</p>\n <ul className=\"flex flex-col gap-1\">\n {shownLinks.map((link) => (\n <li\n key={link}\n className=\"flex min-w-0 items-center gap-2 rounded-md bg-muted/60 py-1 pr-1 pl-2.5\"\n >\n <span className=\"min-w-0 flex-1 select-text truncate font-mono text-xs\">\n {link}\n </span>\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('copyLink', { link })}\n onClick={() => copy(link)}\n >\n <Copy />\n </Button>\n </li>\n ))}\n </ul>\n <p className=\"text-muted-foreground text-xs\">{t('linksHint')}</p>\n </div>\n ) : null}\n {post?.brief_id && post.brief_by_name ? (\n <p className=\"flex items-center gap-1.5 text-muted-foreground text-xs\">\n <Sparkles className=\"size-3.5 shrink-0\" />\n {t('fromBrief', {\n name: post.brief_by_name,\n when: post.brief_at ? formatRelative(post.brief_at) : '',\n })}\n </p>\n ) : null}\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 <ConfirmDialog\n open={deleting}\n onOpenChange={setDeleting}\n title={t('deleteTitle', { title: post?.title ?? '' })}\n description={t('deleteBody')}\n confirmText={common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </>\n );\n}\n",
|
|
102
|
+
"src/components/post-messages.ts": "import { defineMessages } from '@/lib/i18n';\n\n/** The texts of one post's dialog and its badges (src/components). */\nexport const t = defineMessages({\n en: {\n newPost: 'New post',\n editPost: 'Edit post',\n postDetails: 'Post',\n fieldTitle: 'Title',\n titlePlaceholder: 'What the post is',\n fieldPlatform: 'Platform',\n fieldStatus: 'Status',\n fieldDay: 'Day',\n fieldTime: 'Time',\n timeHint: 'Leave the time empty to pick it later.',\n dayFirst: 'Pick a day first.',\n fieldOwner: 'Owner',\n fieldBrief: 'Brief',\n briefPlaceholder: 'What it is about: the angle, the message, the call to action',\n fieldLinks: 'Links',\n linksPlaceholder: 'The draft, the assets, the published post — one per line',\n linksHint: 'Links do not open from inside the app: copy one to open it.',\n copy: 'Copy',\n copyLink: 'Copy {link}',\n copied: 'Copied',\n copyFailed: 'Could not copy here; select the text and copy it.',\n fromBrief: 'From the brief {name} pasted {when}',\n late: 'Its time has passed and it is not marked {status}.',\n deleteTitle: 'Delete “{title}”?',\n deleteBody: 'It is removed from the calendar and the board for everyone.',\n deleted: 'Deleted',\n saved: 'Saved',\n },\n zh: {\n newPost: '新建排期',\n editPost: '编辑排期',\n postDetails: '排期',\n fieldTitle: '标题',\n titlePlaceholder: '这条发什么',\n fieldPlatform: '平台',\n fieldStatus: '状态',\n fieldDay: '日期',\n fieldTime: '时间',\n timeHint: '时间可以先空着,之后再定。',\n dayFirst: '先选日期。',\n fieldOwner: '负责人',\n fieldBrief: 'Brief',\n briefPlaceholder: '讲什么:角度、要传达的信息、希望看的人做什么',\n fieldLinks: '链接',\n linksPlaceholder: '草稿、素材、发出去的帖子,一行一个',\n linksHint: '在应用里点不开链接:复制后在外面打开。',\n copy: '复制',\n copyLink: '复制 {link}',\n copied: '已复制',\n copyFailed: '这里复制不了,请选中文字手动复制。',\n fromBrief: '来自 {name} {when}贴的 brief',\n late: '已过发布时间,还没标为「{status}」。',\n deleteTitle: '删除“{title}”?',\n deleteBody: '所有人的日历和看板上都会去掉它。',\n deleted: '已删除',\n saved: '已保存',\n },\n});\n",
|
|
103
|
+
"src/lib/content.ts": "import {\n type ContentColor,\n PLATFORMS,\n type Platform,\n type Post,\n PUBLISHED,\n STATUSES,\n type Status,\n} from '@shared/content';\nimport { defineMessages, formatLocale, locale } from '@/lib/i18n';\n\n// What the content calendar's pages share: platform and status names and\n// colors, the day and time a post goes out, whether it is late, and the\n// people posts can be given to.\n\nexport const t = defineMessages({\n en: {\n noPlatform: 'Platform not decided',\n noDay: 'No day yet',\n anyTime: 'Any time',\n today: 'Today',\n tomorrow: 'Tomorrow',\n yesterday: 'Yesterday',\n late: 'Late',\n unassigned: 'No owner',\n all: 'All',\n },\n zh: {\n noPlatform: '平台未定',\n noDay: '还没定日子',\n anyTime: '时间未定',\n today: '今天',\n tomorrow: '明天',\n yesterday: '昨天',\n late: '已逾期',\n unassigned: '未分配',\n all: '全部',\n },\n});\n\nexport function platformOf(id: string | null): Platform | undefined {\n return id ? PLATFORMS.find((p) => p.id === id) : undefined;\n}\n\n/** The platform's name in the viewer's language; none decided, or an id no\n * longer listed, as such. */\nexport function platformName(id: string | null): string {\n if (!id) return t('noPlatform');\n return platformOf(id)?.[locale] ?? id;\n}\n\nexport function statusOf(id: string): Status | undefined {\n return STATUSES.find((s) => s.id === id);\n}\n\nexport function statusName(id: string): string {\n return statusOf(id)?.[locale] ?? id;\n}\n\n/** Tailwind classes per color, readable in both themes: a dot (also the\n * bar beside a listed post), a chip's background and text, and a card's\n * left edge. */\nexport interface ColorClasses {\n dot: string;\n chip: string;\n edge: string;\n}\n\nexport const COLORS: Record<ContentColor, ColorClasses> = {\n fuchsia: {\n dot: 'bg-fuchsia-500',\n chip: 'bg-fuchsia-500/12 text-fuchsia-900 hover:bg-fuchsia-500/20 dark:text-fuchsia-100',\n edge: 'border-l-fuchsia-500',\n },\n red: {\n dot: 'bg-red-500',\n chip: 'bg-red-500/12 text-red-900 hover:bg-red-500/20 dark:text-red-100',\n edge: 'border-l-red-500',\n },\n orange: {\n dot: 'bg-orange-500',\n chip: 'bg-orange-500/15 text-orange-900 hover:bg-orange-500/25 dark:text-orange-100',\n edge: 'border-l-orange-500',\n },\n amber: {\n dot: 'bg-amber-500',\n chip: 'bg-amber-500/15 text-amber-900 hover:bg-amber-500/25 dark:text-amber-100',\n edge: 'border-l-amber-500',\n },\n emerald: {\n dot: 'bg-emerald-500',\n chip: 'bg-emerald-500/12 text-emerald-900 hover:bg-emerald-500/20 dark:text-emerald-100',\n edge: 'border-l-emerald-500',\n },\n teal: {\n dot: 'bg-teal-500',\n chip: 'bg-teal-500/12 text-teal-900 hover:bg-teal-500/20 dark:text-teal-100',\n edge: 'border-l-teal-500',\n },\n sky: {\n dot: 'bg-sky-500',\n chip: 'bg-sky-500/12 text-sky-900 hover:bg-sky-500/20 dark:text-sky-100',\n edge: 'border-l-sky-500',\n },\n blue: {\n dot: 'bg-blue-600',\n chip: 'bg-blue-600/12 text-blue-900 hover:bg-blue-600/20 dark:text-blue-100',\n edge: 'border-l-blue-600',\n },\n violet: {\n dot: 'bg-violet-500',\n chip: 'bg-violet-500/12 text-violet-900 hover:bg-violet-500/20 dark:text-violet-100',\n edge: 'border-l-violet-500',\n },\n zinc: {\n dot: 'bg-zinc-800 dark:bg-zinc-300',\n chip: 'bg-zinc-500/12 text-zinc-900 hover:bg-zinc-500/20 dark:text-zinc-100',\n edge: 'border-l-zinc-800 dark:border-l-zinc-300',\n },\n};\n\nconst NO_PLATFORM: ColorClasses = {\n dot: 'bg-zinc-300 dark:bg-zinc-600',\n chip: 'bg-muted text-muted-foreground hover:bg-accent',\n edge: 'border-l-zinc-300 dark:border-l-zinc-600',\n};\n\n/** A platform's colors; gray while none is decided. */\nexport function platformColors(id: string | null): ColorClasses {\n const color = platformOf(id)?.color;\n return color ? COLORS[color] : NO_PLATFORM;\n}\n\nexport function statusColors(id: string) {\n return COLORS[statusOf(id)?.color ?? 'zinc'];\n}\n\nconst pad = (n: number) => String(n).padStart(2, '0');\n\n/** YYYY-MM-DD of a local date. */\nexport function isoDay(date: Date): string {\n return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;\n}\n\n/** The local midnight of a YYYY-MM-DD. */\nexport function parseDay(value: string): Date {\n const [y, m, d] = value.split('-').map(Number);\n return new Date(y ?? 1970, (m ?? 1) - 1, d ?? 1);\n}\n\n/** The viewer's local day a post goes out (YYYY-MM-DD), or null with no day. */\nexport function postDay(post: Pick<Post, 'publish_at' | 'publish_date'>): string | null {\n if (post.publish_at) {\n const at = new Date(post.publish_at);\n return Number.isNaN(at.getTime()) ? null : isoDay(at);\n }\n return post.publish_date;\n}\n\n/** When it goes out, for sorting: its time, or the start of its day. */\nexport function postTime(post: Pick<Post, 'publish_at' | 'publish_date'>): number {\n if (post.publish_at) return Date.parse(post.publish_at);\n return post.publish_date ? parseDay(post.publish_date).getTime() : Number.POSITIVE_INFINITY;\n}\n\n/** Posts in the order they go out: a day's posts with no time first. */\nexport function byTime(a: Post, b: Post): number {\n const day = (postDay(a) ?? '9999').localeCompare(postDay(b) ?? '9999');\n if (day !== 0) return day;\n if (!a.publish_at !== !b.publish_at) return a.publish_at ? 1 : -1;\n return postTime(a) - postTime(b) || a.title.localeCompare(b.title);\n}\n\n/** Whether a post's time has passed and it is not published: one with only\n * a day is late from the next day on. */\nexport function isLate(post: Post, now = new Date()): boolean {\n if (post.status === PUBLISHED) return false;\n if (post.publish_at) return Date.parse(post.publish_at) < now.getTime();\n return post.publish_date !== null && post.publish_date < isoDay(now);\n}\n\nconst time = new Intl.DateTimeFormat(formatLocale, { hour: 'numeric', minute: '2-digit' });\n\n/** \"12:00 PM\" / \"12:00\", or '' for a post with only a day. */\nexport function formatTime(post: Pick<Post, 'publish_at'>): string {\n return post.publish_at ? time.format(new Date(post.publish_at)) : '';\n}\n\n/** The time as a calendar chip fits it: \"12pm\", \"9:30am\" where the clock\n * has AM/PM, \"12:00\" where it does not; '' with only a day. */\nexport function formatShortTime(post: Pick<Post, 'publish_at'>): string {\n if (!post.publish_at) return '';\n const parts = time.formatToParts(new Date(post.publish_at));\n const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((p) => p.type === type)?.value;\n const period = part('dayPeriod');\n if (!period) return time.format(new Date(post.publish_at));\n const minute = part('minute');\n return `${part('hour')}${minute && minute !== '00' ? `:${minute}` : ''}${period.toLowerCase().replace(/[.\\s]/g, '')}`;\n}\n\nconst shortDay = new Intl.DateTimeFormat(formatLocale, { month: 'short', day: 'numeric' });\nconst weekday = new Intl.DateTimeFormat(formatLocale, { weekday: 'short' });\n\n/** \"Today\", \"Tomorrow\", \"Yesterday\" or \"Thu, Nov 6\" — with the time when\n * it has one; \"No day yet\" without a day. */\nexport function formatWhen(post: Pick<Post, 'publish_at' | 'publish_date'>): string {\n const day = postDay(post);\n if (!day) return t('noDay');\n const date = parseDay(day);\n const today = isoDay(new Date());\n const offset = Math.round((date.getTime() - parseDay(today).getTime()) / 86_400_000);\n const name =\n offset === 0\n ? t('today')\n : offset === 1\n ? t('tomorrow')\n : offset === -1\n ? t('yesterday')\n : `${weekday.format(date)} ${shortDay.format(date)}`;\n const at = formatTime(post);\n return at ? `${name} ${at}` : name;\n}\n\n/** The links of a post, one per line. */\nexport function linkList(links: string): string[] {\n return links\n .split('\\n')\n .map((line) => line.trim())\n .filter(Boolean);\n}\n\nexport interface Owner {\n id: string;\n name: string;\n}\n\n/** Everyone a post can be given to: the organization's members, and the\n * owners posts already have (an imported owner may have left it). */\nexport function ownersOf(people: Array<{ id: string; display_name: string }>, posts: Post[]) {\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 post of posts) {\n if (post.owner_id && !out.has(post.owner_id)) {\n out.set(post.owner_id, { id: post.owner_id, name: post.owner_name ?? post.owner_id });\n }\n }\n return [...out.values()];\n}\n\n/** `owners` plus the owner a post already has when it is not among them\n * (say, one who has left the organization): the dialog lists it and keeps\n * 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",
|
|
104
|
+
"src/pages/board/BoardPage.tsx": "import { PLATFORMS, type Post, type PostStatusInput, PUBLISHED, STATUSES } from '@shared/content';\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 { PageContainer, PageHeader } from '@/components/page';\nimport { PlatformDot } from '@/components/post-badges';\nimport { PostDialog, type PostDraft } from '@/components/post-dialog';\nimport { t as postText } from '@/components/post-messages';\nimport { EmptyState, ErrorState, LoadingState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';\nimport { useAction, useMutation } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { usePeople } from '@/hooks/use-people';\nimport { byTime, ownersOf, t as shared, statusColors, statusName } from '@/lib/content';\nimport { describeError } from '@/lib/errors';\nimport { locale } from '@/lib/i18n';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { PostCard } from './PostCard';\nimport { t } from './messages';\n\nconst NO_POSTS: Post[] = [];\nconst ALL = '__all__';\nconst NONE = '__none__';\n\n/**\n * The topic board: one column per step (shared/content.ts), each topic a\n * card in the order it goes out, read from posts_board — published ones\n * from the last 30 days only. Cards move between steps from their menu (the\n * same on phones) and open on a click; a row of platforms filters them. A\n * link prll://app_…#board/<post id> opens that post. Someone who can only\n * view the app sees no control that would write (useCanEdit); a card opens\n * read-only for them.\n */\nexport function BoardPage({ route }: PageProps) {\n const board = useAction<Post[]>('posts_board');\n const move = useMutation<Post, PostStatusInput>('posts_status');\n const remove = useMutation<{ id: string }, { id: string }>('posts_delete');\n const { people } = usePeople();\n const canEdit = useCanEdit();\n const [platform, setPlatform] = useState(ALL);\n const [draft, setDraft] = useState<PostDraft | null>(null);\n const [deleting, setDeleting] = useState<Post | null>(null);\n const [openedRoute, setOpenedRoute] = useState<string | null>(null);\n\n const posts = board.data ?? NO_POSTS;\n const owners = useMemo(() => ownersOf(people, posts), [people, posts]);\n const counts = useMemo(() => {\n const out: Record<string, number> = {};\n for (const post of posts) {\n const key = post.platform ?? NONE;\n out[key] = (out[key] ?? 0) + 1;\n }\n return out;\n }, [posts]);\n const columns = useMemo(() => {\n const shown = posts.filter((p) => platform === ALL || (p.platform ?? NONE) === platform);\n const out = new Map(STATUSES.map((s) => [s.id, [] as Post[]]));\n // A post in a step that is no longer listed shows in the first column.\n for (const post of [...shown].sort(byTime)) {\n (out.get(post.status) ?? out.get(STATUSES[0]?.id ?? ''))?.push(post);\n }\n // What went out last comes first; the other steps go by what is next.\n out.get(PUBLISHED)?.reverse();\n return out;\n }, [posts, platform]);\n const filtered = [...columns.values()].reduce((sum, list) => sum + list.length, 0);\n\n // Open the post a link points at, once it has loaded.\n useEffect(() => {\n if (!route) {\n setOpenedRoute(null);\n return;\n }\n const post = posts.find((p) => p.id === route);\n if (post && openedRoute !== route) {\n setOpenedRoute(route);\n setDraft({ mode: 'edit', post });\n }\n }, [route, posts, openedRoute]);\n\n function replace(post: Post) {\n board.setData((current = []) => [...current.filter((p) => p.id !== post.id), post]);\n }\n\n async function movePost(post: Post, status: string) {\n replace({ ...post, status });\n try {\n replace(await move.run({ id: post.id, status }));\n toast.success(t('moved', { 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((p) => p.id !== deleting.id));\n toast.success(postText('deleted'));\n setDeleting(null);\n } catch (err) {\n toast.error(describeError(err).message);\n }\n }\n\n const newTopic = canEdit ? (\n <Button onClick={() => setDraft({ mode: 'create', status: STATUSES[0]?.id })}>\n <Plus />\n {t('newTopic')}\n </Button>\n ) : undefined;\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 (posts.length === 0) {\n body = (\n <EmptyState\n icon={SquareKanban}\n title={t('emptyTitle')}\n description={canEdit ? t('emptyBody') : t('emptyBodyViewOnly')}\n action={newTopic}\n />\n );\n } else {\n body = (\n <>\n <ToggleGroup\n type=\"single\"\n variant=\"outline\"\n size=\"sm\"\n aria-label={t('platforms')}\n value={platform}\n onValueChange={(next) => next && setPlatform(next)}\n className=\"no-scrollbar mb-3 max-w-full justify-start overflow-x-auto\"\n >\n <ToggleGroupItem value={ALL} className=\"shrink-0 gap-1.5 px-3\">\n {shared('all')}\n <span className=\"text-muted-foreground text-xs tabular-nums\">{posts.length}</span>\n </ToggleGroupItem>\n {PLATFORMS.map((p) => (\n <ToggleGroupItem key={p.id} value={p.id} className=\"shrink-0 gap-1.5 px-3\">\n <PlatformDot platform={p.id} />\n {p[locale]}\n <span className=\"text-muted-foreground text-xs tabular-nums\">\n {counts[p.id] ?? 0}\n </span>\n </ToggleGroupItem>\n ))}\n {counts[NONE] ? (\n <ToggleGroupItem value={NONE} className=\"shrink-0 gap-1.5 px-3\">\n <PlatformDot platform={null} />\n {shared('noPlatform')}\n <span className=\"text-muted-foreground text-xs tabular-nums\">{counts[NONE]}</span>\n </ToggleGroupItem>\n ) : null}\n </ToggleGroup>\n {filtered === 0 ? (\n <EmptyState icon={SquareKanban} title={t('noMatch')} />\n ) : (\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 {STATUSES.map((status) => {\n const cards = columns.get(status.id) ?? NO_POSTS;\n return (\n <section\n key={status.id}\n aria-label={status[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', statusColors(status.id).dot)} />\n <h2 className=\"font-medium text-sm\">{status[locale]}</h2>\n <span className=\"text-muted-foreground text-xs tabular-nums\">\n {cards.length}\n </span>\n {status.id === PUBLISHED ? (\n <span className=\"ml-auto text-muted-foreground text-xs\">\n {t('recentOnly')}\n </span>\n ) : (\n <span className=\"ml-auto\" />\n )}\n {canEdit ? (\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('addToStatus', { status: status[locale] })}\n className=\"text-muted-foreground\"\n onClick={() => setDraft({ mode: 'create', status: status.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\">\n {t('emptyColumn')}\n </p>\n ) : (\n cards.map((post) => (\n <PostCard\n key={post.id}\n post={post}\n onOpen={(p) => setDraft({ mode: 'edit', post: p })}\n onMove={movePost}\n onDelete={setDeleting}\n />\n ))\n )}\n </div>\n </section>\n );\n })}\n </div>\n )}\n </>\n );\n }\n\n return (\n <PageContainer width=\"full\">\n <PageHeader title={t('title')} description={t('description')} actions={newTopic} />\n {body}\n <PostDialog\n draft={draft}\n owners={owners}\n onClose={() => setDraft(null)}\n onSaved={replace}\n onDeleted={(id) => board.setData((current = []) => current.filter((p) => p.id !== id))}\n />\n <ConfirmDialog\n open={deleting !== null}\n onOpenChange={(open) => !open && setDeleting(null)}\n title={postText('deleteTitle', { title: deleting?.title ?? '' })}\n description={postText('deleteBody')}\n confirmText={common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </PageContainer>\n );\n}\n",
|
|
105
|
+
"src/pages/board/PostCard.tsx": "import { type Post, PUBLISHED, STATUSES } from '@shared/content';\nimport { addDays } from 'date-fns';\nimport { ArrowRight, CalendarClock, Ellipsis, Pencil, Trash2 } from 'lucide-react';\nimport { PlatformBadge } from '@/components/post-badges';\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 { formatWhen, isLate, isoDay, postDay, statusColors } from '@/lib/content';\nimport { locale } from '@/lib/i18n';\nimport { t as common } from '@/lib/messages';\nimport { cn } from '@/lib/utils';\nimport { t } from './messages';\n\n/** One topic on the board: its platform, title, when it goes out and its\n * owner. A click (or Enter) opens it; the menu moves it to another step or\n * deletes it — no menu for someone who can only view the app. */\nexport function PostCard({\n post,\n onOpen,\n onMove,\n onDelete,\n}: {\n post: Post;\n onOpen: (post: Post) => void;\n onMove: (post: Post, status: string) => void;\n onDelete: (post: Post) => void;\n}) {\n const canEdit = useCanEdit();\n const late = isLate(post);\n // Not out yet and going out today or tomorrow.\n const day = postDay(post);\n const soon =\n !late &&\n post.status !== PUBLISHED &&\n day !== null &&\n day >= isoDay(new Date()) &&\n day <= isoDay(addDays(new Date(), 1));\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 post: one transparent button over it. */}\n <button\n type=\"button\"\n onClick={() => onOpen(post)}\n aria-label={post.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-center gap-2\">\n <PlatformBadge platform={post.platform} className=\"min-w-0 flex-1 text-muted-foreground\" />\n {canEdit ? (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('postActions', { title: post.title })}\n className=\"-my-1 -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(post)}>\n <Pencil />\n {common('edit')}\n </DropdownMenuItem>\n <DropdownMenuSeparator />\n <DropdownMenuLabel className=\"text-muted-foreground text-xs\">\n {t('moveTo')}\n </DropdownMenuLabel>\n {STATUSES.filter((s) => s.id !== post.status).map((s) => (\n <DropdownMenuItem key={s.id} onSelect={() => onMove(post, s.id)}>\n <span className={cn('size-2 rounded-full', statusColors(s.id).dot)} />\n {s[locale]}\n <ArrowRight className=\"ml-auto\" />\n </DropdownMenuItem>\n ))}\n {post.can_delete ? (\n <>\n <DropdownMenuSeparator />\n <DropdownMenuItem variant=\"destructive\" onSelect={() => onDelete(post)}>\n <Trash2 />\n {common('delete')}\n </DropdownMenuItem>\n </>\n ) : null}\n </DropdownMenuContent>\n </DropdownMenu>\n ) : null}\n </div>\n <p className=\"line-clamp-2 font-medium text-sm leading-snug\">{post.title}</p>\n {post.brief ? (\n <p className=\"line-clamp-2 text-muted-foreground text-xs leading-relaxed\">{post.brief}</p>\n ) : null}\n <div className=\"mt-0.5 flex items-center gap-2\">\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 late && 'bg-destructive/10 text-destructive',\n soon && '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\">{formatWhen(post)}</span>\n </span>\n {post.owner_name ? (\n <UserAvatar\n id={post.owner_id ?? post.owner_name}\n name={post.owner_name}\n size=\"sm\"\n className=\"ml-auto shrink-0\"\n title={post.owner_name}\n />\n ) : null}\n </div>\n </div>\n );\n}\n",
|
|
106
|
+
"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",
|
|
107
|
+
"src/pages/board/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n title: 'Topic board',\n tab: 'Topic board',\n description: 'Every topic by step, from the first idea to the published post.',\n newTopic: 'New topic',\n addToStatus: 'Add a topic to {status}',\n platforms: 'Platforms',\n emptyTitle: 'No topics yet',\n emptyBody:\n 'Add the first one, or paste a brief on the calendar and the agent splits it into posts.',\n emptyBodyViewOnly: 'Nothing has been added yet.',\n noMatch: 'No topics on this platform.',\n emptyColumn: 'Nothing here',\n recentOnly: 'Last 30 days',\n postActions: 'Actions for {title}',\n moveTo: 'Move to',\n moved: 'Moved to {status}',\n },\n zh: {\n title: '选题看板',\n tab: '选题看板',\n description: '每个选题走到哪一步:从想法到发出去。',\n newTopic: '新建选题',\n addToStatus: '在「{status}」新建选题',\n platforms: '平台',\n emptyTitle: '还没有选题',\n emptyBody: '新建第一个,或者在日历上贴一段 brief,agent 会拆成多条排期。',\n emptyBodyViewOnly: '还没有人添加。',\n noMatch: '这个平台还没有选题。',\n emptyColumn: '暂无',\n recentOnly: '最近 30 天',\n postActions: '{title} 的操作',\n moveTo: '移到',\n moved: '已移到「{status}」',\n },\n});\n",
|
|
108
|
+
"src/pages/calendar/BriefDialog.tsx": "import type { Brief, BriefInput } from '@shared/content';\nimport { CircleCheck, Hourglass, Trash2 } from 'lucide-react';\nimport { useEffect, useId, useState } from 'react';\nimport { toast } from 'sonner';\nimport { ConfirmDialog } from '@/components/confirm-dialog';\nimport { ResponsiveDialog } from '@/components/responsive-dialog';\nimport { Button } from '@/components/ui/button';\nimport { Label } from '@/components/ui/label';\nimport { Textarea } from '@/components/ui/textarea';\nimport { type ActionState, useMutation } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { describeError } from '@/lib/errors';\nimport { formatRelative } from '@/lib/format';\nimport { t as common } from '@/lib/messages';\nimport { t } from './brief-messages';\n\nconst SHOWN = 5;\n\n/**\n * \"Paste a brief\": the text goes into the app (briefs_add), which wakes the\n * agent that looks after it; the agent splits it into posts that show up on\n * the calendar by themselves, and marks the brief planned with a note. The\n * latest briefs are listed under the box with how each went. Someone who\n * can only view the app sees the list only.\n */\nexport function BriefDialog({\n open,\n briefs,\n onOpenChange,\n}: {\n open: boolean;\n /** briefs_list, read by the page. */\n briefs: ActionState<Brief[]>;\n onOpenChange: (open: boolean) => void;\n}) {\n const formId = useId();\n const canEdit = useCanEdit();\n const add = useMutation<Brief, BriefInput>('briefs_add');\n const remove = useMutation<{ id: string }, { id: string }>('briefs_delete');\n const resetAdd = add.reset;\n const [body, setBody] = useState('');\n const [deleting, setDeleting] = useState<Brief | null>(null);\n\n useEffect(() => {\n if (!open) return;\n setBody('');\n resetAdd();\n }, [open, resetAdd]);\n\n async function submit() {\n if (!canEdit || !body.trim() || add.pending) return;\n try {\n const added = await add.run({ body: body.trim() });\n briefs.setData((current = []) => [added, ...current.filter((b) => b.id !== added.id)]);\n setBody('');\n toast.success(t('added'));\n } catch {\n // Shown under the box from add.error.\n }\n }\n\n async function confirmDelete() {\n if (!deleting) return;\n try {\n await remove.run({ id: deleting.id });\n briefs.setData((current = []) => current.filter((b) => b.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 recent = (briefs.data ?? []).slice(0, SHOWN);\n return (\n <ResponsiveDialog\n open={open}\n onOpenChange={onOpenChange}\n title={t('title')}\n description={canEdit ? t('description') : t('descriptionViewOnly')}\n footer={\n canEdit ? (\n <>\n <Button variant=\"outline\" onClick={() => onOpenChange(false)} disabled={add.pending}>\n {common('close')}\n </Button>\n <Button onClick={submit} disabled={add.pending || !body.trim()}>\n {add.pending ? t('adding') : t('add')}\n </Button>\n </>\n ) : (\n <Button variant=\"outline\" onClick={() => onOpenChange(false)}>\n {common('close')}\n </Button>\n )\n }\n >\n <div className=\"flex flex-col gap-4\">\n {canEdit ? (\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor={`${formId}-body`} className=\"sr-only\">\n {t('title')}\n </Label>\n <Textarea\n id={`${formId}-body`}\n value={body}\n onChange={(e) => setBody(e.target.value)}\n placeholder={t('placeholder')}\n rows={7}\n maxLength={20000}\n autoFocus\n />\n {add.error ? (\n <p role=\"alert\" className=\"text-destructive text-sm\">\n {describeError(add.error).message}\n </p>\n ) : null}\n </div>\n ) : null}\n <section className=\"flex flex-col gap-2\">\n <h3 className=\"font-medium text-sm\">{t('recent')}</h3>\n {recent.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">\n {briefs.loading ? common('loading') : t('none')}\n </p>\n ) : (\n <ul className=\"flex flex-col divide-y rounded-xl border\">\n {recent.map((brief) => (\n <li key={brief.id} className=\"flex flex-col gap-1.5 p-3\">\n <div className=\"flex items-start gap-2\">\n <p className=\"line-clamp-2 min-w-0 flex-1 whitespace-pre-line text-sm\">\n {brief.body}\n </p>\n {canEdit && brief.can_delete ? (\n <Button\n variant=\"ghost\"\n size=\"icon-xs\"\n aria-label={t('delete')}\n className=\"-mt-0.5 shrink-0 text-muted-foreground\"\n onClick={() => setDeleting(brief)}\n >\n <Trash2 />\n </Button>\n ) : null}\n </div>\n <p className=\"text-muted-foreground text-xs\">\n {t('byLine', {\n name: brief.created_by_name,\n when: formatRelative(brief.created_at),\n })}\n </p>\n {brief.status === 'planned' ? (\n <div className=\"flex flex-col gap-1 rounded-lg bg-muted/60 p-2.5 text-xs\">\n <span className=\"flex items-center gap-1.5 font-medium text-emerald-700 dark:text-emerald-400\">\n <CircleCheck className=\"size-3.5 shrink-0\" />\n {brief.post_count === 1\n ? t('plannedOne', { name: brief.planned_by_name || '—' })\n : t('planned', {\n n: brief.post_count,\n name: brief.planned_by_name || '—',\n })}\n </span>\n {brief.note ? (\n <p className=\"whitespace-pre-line text-muted-foreground leading-relaxed\">\n {brief.note}\n </p>\n ) : null}\n </div>\n ) : (\n <span className=\"flex items-center gap-1.5 text-amber-700 text-xs dark:text-amber-400\">\n <Hourglass className=\"size-3.5 shrink-0\" />\n {t('waiting')}\n </span>\n )}\n </li>\n ))}\n </ul>\n )}\n </section>\n </div>\n <ConfirmDialog\n open={deleting !== null}\n onOpenChange={(next) => !next && setDeleting(null)}\n title={t('deleteTitle')}\n description={deleting?.status === 'new' ? t('deleteBodyWaiting') : t('deleteBody')}\n confirmText={common('delete')}\n destructive\n pending={remove.pending}\n onConfirm={confirmDelete}\n />\n </ResponsiveDialog>\n );\n}\n",
|
|
109
|
+
"src/pages/calendar/CalendarPage.tsx": "import type { Brief, Post } from '@shared/content';\nimport {\n addMonths,\n addWeeks,\n isSameMonth,\n isWithinInterval,\n startOfDay,\n startOfMonth,\n} from 'date-fns';\nimport { ChevronLeft, ChevronRight, ClipboardPaste, Hourglass, Plus } from 'lucide-react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { toast } from 'sonner';\nimport type { PageProps } from '@/components/app-shell';\nimport { PageContainer } from '@/components/page';\nimport { PlatformLegend } from '@/components/post-badges';\nimport { PostDialog, type PostDraft } from '@/components/post-dialog';\nimport { ErrorState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { Spinner } from '@/components/ui/spinner';\nimport { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';\nimport { useAction } from '@/hooks/use-action';\nimport { useCanEdit } from '@/hooks/use-host';\nimport { useIsMobile } from '@/hooks/use-media-query';\nimport { usePeople } from '@/hooks/use-people';\nimport { isoDay, ownersOf, parseDay, postDay } from '@/lib/content';\nimport { BriefDialog } from './BriefDialog';\nimport { type CalendarView, eachDay, rangeParams, viewTitle, visibleDays } from './dates';\nimport { ListView } from './ListView';\nimport { MonthView } from './MonthView';\nimport { t } from './messages';\nimport { WeekView } from './WeekView';\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst NO_POSTS: Post[] = [];\n\n/**\n * The calendar: month, week and list views of the posts, colored by\n * platform, over posts_range; \"Paste a brief\" hands a brief to the agent\n * (BriefDialog). A link prll://app_…#calendar/2026-11-03 opens at that day,\n * and prll://app_…#calendar/<post id> opens that post. Someone who can only\n * view the app gets no way to add posts or briefs and opens posts\n * read-only.\n */\nexport function CalendarPage({ route }: PageProps) {\n const compact = useIsMobile();\n const canEdit = useCanEdit();\n const [view, setView] = useState<CalendarView>('month');\n const [cursor, setCursor] = useState(() =>\n DAY.test(route) ? parseDay(route) : startOfDay(new Date()),\n );\n const [selected, setSelected] = useState(cursor);\n const [draft, setDraft] = useState<PostDraft | null>(null);\n const [briefOpen, setBriefOpen] = useState(false);\n const [openedRoute, setOpenedRoute] = useState<string | null>(null);\n const { people } = usePeople();\n\n const { start, end } = useMemo(() => visibleDays(view, cursor), [view, cursor]);\n const days = useMemo(() => eachDay(start, end), [start, end]);\n const query = useAction<Post[]>('posts_range', rangeParams(start, end));\n const briefs = useAction<Brief[]>('briefs_list');\n const linked = useAction<Post>('post_get', { id: route }, { enabled: UUID.test(route) });\n const posts = query.data ?? NO_POSTS;\n const owners = useMemo(() => ownersOf(people, posts), [people, posts]);\n const waiting = (briefs.data ?? []).filter((b) => b.status === 'new').length;\n\n // A link to a day (#calendar/2026-11-03) while the calendar is open goes there.\n useEffect(() => {\n if (!DAY.test(route)) return;\n const day = parseDay(route);\n setCursor(day);\n setSelected(day);\n }, [route]);\n\n // A link to a post (#calendar/<id>) goes to its day and opens it, once.\n useEffect(() => {\n if (!UUID.test(route)) {\n setOpenedRoute(null);\n return;\n }\n if (openedRoute === route) return;\n const post = linked.data;\n if (post?.id === route) {\n setOpenedRoute(route);\n const day = postDay(post);\n if (day) {\n setCursor(parseDay(day));\n setSelected(parseDay(day));\n }\n setDraft({ mode: 'edit', post });\n } else if (linked.error) {\n setOpenedRoute(route);\n toast.error(t('notFound'));\n }\n }, [route, linked.data, linked.error, openedRoute]);\n\n function move(step: 1 | -1) {\n const next = view === 'week' ? addWeeks(cursor, step) : addMonths(cursor, step);\n setCursor(next);\n // Keep the selected day inside what is shown: today if it is there.\n const today = startOfDay(new Date());\n if (view === 'week') setSelected(addWeeks(selected, step));\n else setSelected(isSameMonth(today, next) ? today : startOfMonth(next));\n }\n\n function goToday() {\n const today = startOfDay(new Date());\n setCursor(today);\n setSelected(today);\n }\n\n function createOn(day: Date) {\n setDraft({ mode: 'create', day: isoDay(day) });\n }\n\n function replace(post: Post) {\n query.setData((rows = []) => [...rows.filter((p) => p.id !== post.id), post]);\n }\n\n const open = (post: Post) => setDraft({ mode: 'edit', post });\n const newOn = isWithinInterval(selected, { start, end }) ? selected : cursor;\n const emptyAction = canEdit ? (\n <Button onClick={() => setBriefOpen(true)}>\n <ClipboardPaste />\n {t('pasteBrief')}\n </Button>\n ) : undefined;\n\n return (\n <PageContainer width=\"wide\" className=\"gap-4\">\n <div className=\"flex flex-col gap-3\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h1 className=\"min-w-0 flex-1 truncate font-semibold text-xl tracking-tight md:flex-none md:text-2xl\">\n {viewTitle(view, cursor)}\n </h1>\n {query.loading || query.refreshing ? <Spinner className=\"text-muted-foreground\" /> : null}\n <div className=\"flex items-center gap-1 md:ml-2\">\n <Button variant=\"outline\" size=\"sm\" onClick={goToday}>\n {t('today')}\n </Button>\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n aria-label={t('previous')}\n onClick={() => move(-1)}\n >\n <ChevronLeft />\n </Button>\n <Button variant=\"ghost\" size=\"icon-sm\" aria-label={t('next')} onClick={() => move(1)}>\n <ChevronRight />\n </Button>\n </div>\n {/* Phones: the views on a row of their own, then the two buttons\n side by side; from md on, all of it beside the title. */}\n <div className=\"flex w-full min-w-0 flex-wrap items-center gap-2 md:ml-auto md:w-auto\">\n <ToggleGroup\n type=\"single\"\n variant=\"outline\"\n size=\"sm\"\n aria-label={t('views')}\n value={view}\n onValueChange={(value) => {\n if (!value) return;\n // The new view opens around the selected day.\n setView(value as CalendarView);\n setCursor(selected);\n }}\n className=\"w-full sm:w-auto\"\n >\n {(['month', 'week', 'list'] as const).map((key) => (\n <ToggleGroupItem key={key} value={key} className=\"flex-1 sm:flex-none sm:px-3\">\n {t(key)}\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n {canEdit ? (\n <div className=\"flex w-full gap-2 sm:w-auto\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"flex-1 sm:flex-none\"\n onClick={() => setBriefOpen(true)}\n >\n <ClipboardPaste />\n {t('pasteBrief')}\n </Button>\n <Button size=\"sm\" className=\"flex-1 sm:flex-none\" onClick={() => createOn(newOn)}>\n <Plus />\n {t('newPost')}\n </Button>\n </div>\n ) : null}\n </div>\n </div>\n <div className=\"flex flex-wrap items-center gap-x-4 gap-y-1.5 text-muted-foreground text-xs\">\n <PlatformLegend />\n {waiting > 0 ? (\n <button\n type=\"button\"\n onClick={() => setBriefOpen(true)}\n className=\"inline-flex items-center gap-1.5 rounded-full bg-amber-500/15 px-2 py-0.5 text-amber-800 hover:bg-amber-500/25 dark:text-amber-300\"\n >\n <Hourglass className=\"size-3\" />\n {t(waiting === 1 ? 'waiting' : 'waitingMany', { n: waiting })}\n </button>\n ) : null}\n </div>\n {/* An empty month or week still shows its days; this says how to fill them. */}\n {view !== 'list' && query.data && posts.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">\n {canEdit ? t('nothingHereEdit') : t('nothingHere')}\n </p>\n ) : null}\n </div>\n\n {query.error && !query.data ? (\n <ErrorState error={query.error} onRetry={query.reload} />\n ) : view === 'month' ? (\n <MonthView\n days={days}\n cursor={cursor}\n posts={posts}\n selected={selected}\n compact={compact}\n loading={query.loading}\n onSelectDay={setSelected}\n onCreate={canEdit ? createOn : undefined}\n onOpen={open}\n />\n ) : view === 'week' ? (\n <WeekView\n days={days}\n posts={posts}\n selected={selected}\n compact={compact}\n loading={query.loading}\n onSelectDay={setSelected}\n onCreate={canEdit ? createOn : undefined}\n onOpen={open}\n />\n ) : (\n <ListView\n // Another month starts at its first day, or at today, again.\n key={start.toISOString()}\n days={days}\n posts={posts}\n loading={query.loading}\n empty={{\n description: canEdit ? t('noPostsBodyEdit') : t('noPostsBody'),\n action: emptyAction,\n }}\n onOpen={open}\n />\n )}\n\n <PostDialog\n draft={draft}\n owners={owners}\n onClose={() => setDraft(null)}\n onSaved={replace}\n onDeleted={(id) => query.setData((rows = []) => rows.filter((p) => p.id !== id))}\n />\n <BriefDialog open={briefOpen} briefs={briefs} onOpenChange={setBriefOpen} />\n </PageContainer>\n );\n}\n",
|
|
110
|
+
"src/pages/calendar/ListView.tsx": "import { type Post, PUBLISHED } from '@shared/content';\nimport { isToday, startOfDay } from 'date-fns';\nimport { CalendarDays, ChevronUp, CircleCheck, Clock } from 'lucide-react';\nimport { type ReactNode, useState } from 'react';\nimport { PlatformBadge, StatusBadge } from '@/components/post-badges';\nimport { EmptyState, LoadingState } from '@/components/states';\nimport { Button } from '@/components/ui/button';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { formatTime, isLate, platformColors, t as shared } from '@/lib/content';\nimport { cn } from '@/lib/utils';\nimport { formatLongDay, postsOn } from './dates';\nimport { t } from './messages';\n\n/** The month's posts as a list, one group per day that has any. In the\n * current month it starts at today, with the earlier days a click away.\n * Until the first answer for these days arrives (`loading`) it shows a\n * skeleton, not \"nothing scheduled\". */\nexport function ListView({\n days,\n posts,\n loading,\n empty,\n onOpen,\n}: {\n days: Date[];\n posts: Post[];\n loading: boolean;\n /** What to say, and offer, when nothing goes out. */\n empty: { description: string; action?: ReactNode };\n onOpen: (post: Post) => void;\n}) {\n const [showEarlier, setShowEarlier] = useState(false);\n const groups = days\n .map((day) => ({ day, posts: postsOn(posts, day) }))\n .filter((group) => group.posts.length > 0);\n if (groups.length === 0 && loading) return <LoadingState rows={4} />;\n if (groups.length === 0) {\n return (\n <EmptyState\n icon={CalendarDays}\n title={t('noPosts')}\n description={empty.description}\n action={empty.action}\n />\n );\n }\n const today = startOfDay(new Date());\n const earlier = days.some((day) => isToday(day))\n ? groups.filter((group) => group.day < today)\n : [];\n const hidden = showEarlier ? 0 : earlier.reduce((sum, group) => sum + group.posts.length, 0);\n const shown = hidden > 0 ? groups.filter((group) => group.day >= today) : groups;\n return (\n <div className=\"flex flex-col gap-5\">\n {hidden > 0 ? (\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"self-start\"\n onClick={() => setShowEarlier(true)}\n >\n <ChevronUp />\n {hidden === 1 ? t('earlierOne') : t('earlier', { n: hidden })}\n </Button>\n ) : null}\n {shown.length === 0 ? (\n <p className=\"text-muted-foreground text-sm\">{t('nothingLeft')}</p>\n ) : null}\n {shown.map(({ day, posts: dayPosts }) => (\n <section key={day.toISOString()} className=\"flex flex-col gap-2\">\n <h2 className={cn('font-medium text-sm', isToday(day) && 'text-primary')}>\n {formatLongDay(day)}\n {isToday(day) ? <span className=\"text-muted-foreground\"> · {t('today')}</span> : null}\n </h2>\n <PostList posts={dayPosts} onOpen={onOpen} />\n </section>\n ))}\n </div>\n );\n}\n\n/** One day's posts: time, platform, title, owner and step. */\nexport function PostList({\n posts,\n onOpen,\n loading = false,\n}: {\n posts: Post[];\n onOpen: (post: Post) => void;\n /** No answer yet: a skeleton instead of \"nothing on this day\". */\n loading?: boolean;\n}) {\n if (posts.length === 0 && loading) return <LoadingState rows={2} />;\n if (posts.length === 0) {\n return (\n <p className=\"rounded-xl border border-dashed px-4 py-6 text-center text-muted-foreground text-sm\">\n {t('noPostsDay')}\n </p>\n );\n }\n return (\n <ul className=\"flex flex-col divide-y overflow-hidden rounded-xl border bg-card\">\n {posts.map((post) => {\n const late = isLate(post);\n return (\n <li key={post.id}>\n <button\n type=\"button\"\n onClick={() => onOpen(post)}\n className=\"flex w-full items-start gap-3 px-3 py-3 text-left transition-colors hover:bg-accent/60 sm:px-4\"\n >\n <span\n aria-hidden\n className={cn(\n 'mt-0.5 h-9 w-1 shrink-0 rounded-full',\n platformColors(post.platform).dot,\n )}\n />\n <span className=\"flex min-w-0 flex-1 flex-col gap-1\">\n <span className=\"flex min-w-0 items-center gap-1.5\">\n {post.status === PUBLISHED ? (\n <CircleCheck\n className=\"size-3.5 shrink-0 text-emerald-600 dark:text-emerald-400\"\n aria-label={t('published')}\n />\n ) : null}\n <span className=\"truncate font-medium text-sm\">{post.title}</span>\n </span>\n <span className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-muted-foreground text-xs\">\n <span className=\"tabular-nums\">{formatTime(post) || shared('anyTime')}</span>\n <PlatformBadge platform={post.platform} />\n {post.owner_name ? <span className=\"truncate\">{post.owner_name}</span> : null}\n {late ? (\n <span className=\"inline-flex items-center gap-1 text-destructive\">\n <Clock className=\"size-3\" />\n {t('late')}\n </span>\n ) : null}\n </span>\n </span>\n <span className=\"flex shrink-0 flex-col items-end gap-1.5\">\n <StatusBadge status={post.status} className=\"hidden sm:inline-flex\" />\n {post.owner_name ? (\n <UserAvatar\n id={post.owner_id ?? post.owner_name}\n name={post.owner_name}\n size=\"sm\"\n className=\"sm:hidden\"\n title={post.owner_name}\n />\n ) : null}\n </span>\n </button>\n </li>\n );\n })}\n </ul>\n );\n}\n",
|
|
111
|
+
"src/pages/calendar/MonthView.tsx": "import { type Post, PUBLISHED } from '@shared/content';\nimport { isSameDay, isSameMonth, isToday } from 'date-fns';\nimport { CircleCheck, Plus } from 'lucide-react';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { formatShortTime, isLate, platformColors, platformName } from '@/lib/content';\nimport { cn } from '@/lib/utils';\nimport { formatLongDay, postsOn, weekdayNames } from './dates';\nimport { PostList } from './ListView';\nimport { t } from './messages';\n\nconst MAX_CHIPS = 3;\n\n/** A month grid. Wide: each day's posts as chips in the platform's color,\n * \"+N more\" opens the rest. Narrow (`compact`): a dot per post under each\n * day, and the selected day's posts listed below the grid. */\nexport function MonthView({\n days,\n cursor,\n posts,\n selected,\n compact,\n loading,\n onSelectDay,\n onCreate,\n onOpen,\n}: {\n days: Date[];\n cursor: Date;\n posts: Post[];\n selected: Date;\n compact: boolean;\n /** No answer yet for these days. */\n loading: boolean;\n onSelectDay: (day: Date) => void;\n /** Starts a post on a day; left out for someone who can only view. */\n onCreate?: (day: Date) => void;\n onOpen: (post: Post) => void;\n}) {\n const names = weekdayNames();\n if (compact) {\n return (\n <div className=\"flex flex-col gap-4\">\n <div className=\"rounded-xl border bg-card p-2\">\n <div className=\"grid grid-cols-7 pb-1 text-center text-muted-foreground text-xs\">\n {names.map((name) => (\n <div key={name} className=\"py-1\">\n {name}\n </div>\n ))}\n </div>\n <div className=\"grid grid-cols-7 gap-y-1\">\n {days.map((day) => {\n const dayPosts = postsOn(posts, day);\n const isSelected = isSameDay(day, selected);\n return (\n <button\n key={day.toISOString()}\n type=\"button\"\n aria-pressed={isSelected}\n aria-label={formatLongDay(day)}\n onClick={() => onSelectDay(day)}\n className=\"flex h-12 min-w-0 flex-col items-center justify-start gap-1 rounded-lg pt-1\"\n >\n <span\n className={cn(\n 'flex size-8 items-center justify-center rounded-full text-sm tabular-nums',\n !isSameMonth(day, cursor) && 'text-muted-foreground/50',\n isToday(day) &&\n !isSelected &&\n 'font-semibold text-primary ring-1 ring-primary/40',\n isSelected && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n <span className=\"flex h-1.5 gap-0.5\">\n {dayPosts.slice(0, 4).map((post) => (\n <span\n key={post.id}\n className={cn('size-1.5 rounded-full', platformColors(post.platform).dot)}\n />\n ))}\n </span>\n </button>\n );\n })}\n </div>\n </div>\n <section className=\"flex flex-col gap-2\">\n <h2 className=\"font-medium text-sm\">{formatLongDay(selected)}</h2>\n <PostList posts={postsOn(posts, selected)} onOpen={onOpen} loading={loading} />\n </section>\n </div>\n );\n }\n\n return (\n <div className=\"overflow-hidden rounded-xl border bg-card\">\n <div className=\"grid grid-cols-7 border-b bg-muted/40\">\n {names.map((name) => (\n <div key={name} className=\"px-2 py-2 font-medium text-muted-foreground text-xs\">\n {name}\n </div>\n ))}\n </div>\n <div className=\"grid auto-rows-fr grid-cols-7\">\n {days.map((day, index) => {\n const dayPosts = postsOn(posts, day);\n const extra = dayPosts.length - MAX_CHIPS;\n const inMonth = isSameMonth(day, cursor);\n return (\n <div\n key={day.toISOString()}\n className={cn(\n 'group flex min-h-28 min-w-0 flex-col gap-1 border-b p-1.5',\n index % 7 !== 6 && 'border-r',\n index >= days.length - 7 && 'border-b-0',\n !inMonth && 'bg-muted/30',\n )}\n >\n <div className=\"flex items-center justify-between\">\n <span\n className={cn(\n 'flex size-6 items-center justify-center rounded-full text-xs tabular-nums',\n !inMonth && 'text-muted-foreground',\n isToday(day) && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n {onCreate ? (\n <button\n type=\"button\"\n aria-label={t('newPostOn', { day: formatLongDay(day) })}\n onClick={() => onCreate(day)}\n className=\"flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100\"\n >\n <Plus className=\"size-3.5\" />\n </button>\n ) : null}\n </div>\n {dayPosts.slice(0, MAX_CHIPS).map((post) => (\n <PostChip key={post.id} post={post} onOpen={onOpen} />\n ))}\n {extra > 0 ? (\n <Popover>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n className=\"self-start rounded px-1.5 text-muted-foreground text-xs hover:bg-accent hover:text-foreground\"\n >\n {t('more', { n: extra })}\n </button>\n </PopoverTrigger>\n <PopoverContent align=\"start\" className=\"flex w-64 flex-col gap-1 p-2\">\n <p className=\"px-1 pb-1 font-medium text-sm\">{formatLongDay(day)}</p>\n {dayPosts.map((post) => (\n <PostChip key={post.id} post={post} onOpen={onOpen} />\n ))}\n </PopoverContent>\n </Popover>\n ) : null}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\n/** One post in a day: its time and title in its platform's color; a\n * published one has a check, a late one a red edge. */\nexport function PostChip({ post, onOpen }: { post: Post; onOpen: (post: Post) => void }) {\n const late = isLate(post);\n return (\n <button\n type=\"button\"\n onClick={() => onOpen(post)}\n title={`${platformName(post.platform)} · ${post.title}`}\n className={cn(\n 'flex w-full min-w-0 items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-xs transition-colors',\n platformColors(post.platform).chip,\n late && 'ring-1 ring-destructive/60 ring-inset',\n )}\n >\n {post.status === PUBLISHED ? (\n <CircleCheck className=\"size-3 shrink-0 opacity-70\" aria-label={t('published')} />\n ) : null}\n {/* Narrower days give the title the room; the time is in the post. */}\n {post.publish_at ? (\n <span className=\"hidden shrink-0 tabular-nums opacity-70 lg:inline\">\n {formatShortTime(post)}\n </span>\n ) : null}\n <span className=\"min-w-0 truncate font-medium\">{post.title}</span>\n </button>\n );\n}\n",
|
|
112
|
+
"src/pages/calendar/WeekView.tsx": "import { type Post, PUBLISHED } from '@shared/content';\nimport { isSameDay, isToday } from 'date-fns';\nimport { CircleCheck, Plus } from 'lucide-react';\nimport { PlatformBadge } from '@/components/post-badges';\nimport { UserAvatar } from '@/components/user-avatar';\nimport { formatShortTime, isLate, platformColors, statusColors, statusName } from '@/lib/content';\nimport { cn } from '@/lib/utils';\nimport { formatLongDay, postsOn, weekdayNames } from './dates';\nimport { PostList } from './ListView';\nimport { t } from './messages';\n\n/** A week. Wide: the seven days side by side, each day's posts as cards in\n * the order they go out. Narrow (`compact`): a strip to pick a day, and\n * that day's posts. */\nexport function WeekView({\n days,\n posts,\n selected,\n compact,\n loading,\n onSelectDay,\n onCreate,\n onOpen,\n}: {\n days: Date[];\n posts: Post[];\n selected: Date;\n compact: boolean;\n loading: boolean;\n onSelectDay: (day: Date) => void;\n /** Starts a post on a day; left out for someone who can only view. */\n onCreate?: (day: Date) => void;\n onOpen: (post: Post) => void;\n}) {\n const names = weekdayNames();\n if (compact) {\n return (\n <div className=\"flex flex-col gap-4\">\n <div className=\"grid grid-cols-7 gap-1 rounded-xl border bg-card p-2\">\n {days.map((day, i) => {\n const isSelected = isSameDay(day, selected);\n return (\n <button\n key={day.toISOString()}\n type=\"button\"\n aria-pressed={isSelected}\n aria-label={formatLongDay(day)}\n onClick={() => onSelectDay(day)}\n className=\"flex min-w-0 flex-col items-center gap-1 rounded-lg py-1 text-xs\"\n >\n <span className=\"text-muted-foreground\">{names[i]}</span>\n <span\n className={cn(\n 'flex size-8 items-center justify-center rounded-full text-sm tabular-nums',\n isToday(day) &&\n !isSelected &&\n 'font-semibold text-primary ring-1 ring-primary/40',\n isSelected && 'bg-primary font-semibold text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n <span className=\"flex h-1.5 gap-0.5\">\n {postsOn(posts, day)\n .slice(0, 4)\n .map((post) => (\n <span\n key={post.id}\n className={cn('size-1.5 rounded-full', platformColors(post.platform).dot)}\n />\n ))}\n </span>\n </button>\n );\n })}\n </div>\n <section className=\"flex flex-col gap-2\">\n <h2 className=\"font-medium text-sm\">{formatLongDay(selected)}</h2>\n <PostList posts={postsOn(posts, selected)} onOpen={onOpen} loading={loading} />\n </section>\n </div>\n );\n }\n\n return (\n <div className=\"grid grid-cols-7 overflow-hidden rounded-xl border bg-card\">\n {days.map((day, i) => {\n const dayPosts = postsOn(posts, day);\n return (\n <section\n key={day.toISOString()}\n aria-label={formatLongDay(day)}\n className={cn('group flex min-h-96 min-w-0 flex-col', i % 7 !== 6 && 'border-r')}\n >\n <header className=\"flex items-center gap-1.5 border-b bg-muted/40 px-2 py-2\">\n <span className=\"text-muted-foreground text-xs\">{names[i]}</span>\n <span\n className={cn(\n 'flex size-6 items-center justify-center rounded-full font-medium text-sm tabular-nums',\n isToday(day) && 'bg-primary text-primary-foreground',\n )}\n >\n {day.getDate()}\n </span>\n {onCreate ? (\n <button\n type=\"button\"\n aria-label={t('newPostOn', { day: formatLongDay(day) })}\n onClick={() => onCreate(day)}\n className=\"ml-auto flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100\"\n >\n <Plus className=\"size-3.5\" />\n </button>\n ) : null}\n </header>\n <div className=\"flex flex-col gap-1.5 p-1.5\">\n {dayPosts.map((post) => (\n <WeekCard key={post.id} post={post} onOpen={onOpen} />\n ))}\n </div>\n </section>\n );\n })}\n </div>\n );\n}\n\n/** One post in a week's day: time, platform, title, step and owner. */\nfunction WeekCard({ post, onOpen }: { post: Post; onOpen: (post: Post) => void }) {\n const late = isLate(post);\n return (\n <button\n type=\"button\"\n onClick={() => onOpen(post)}\n className={cn(\n 'flex w-full min-w-0 flex-col gap-1 rounded-lg border border-l-[3px] bg-background p-2 text-left text-xs shadow-xs transition-colors hover:bg-accent/50',\n platformColors(post.platform).edge,\n )}\n >\n <span className=\"flex min-w-0 items-center gap-1.5 text-muted-foreground\">\n {post.publish_at ? (\n <span className=\"shrink-0 tabular-nums\">{formatShortTime(post)}</span>\n ) : null}\n <PlatformBadge platform={post.platform} className=\"min-w-0\" />\n </span>\n <span className=\"line-clamp-2 font-medium text-foreground text-xs leading-snug\">\n {post.title}\n </span>\n <span className=\"flex min-w-0 items-center gap-1.5\">\n {post.status === PUBLISHED ? (\n <CircleCheck className=\"size-3 shrink-0 text-emerald-600 dark:text-emerald-400\" />\n ) : (\n <span\n aria-hidden\n className={cn(\n 'size-1.5 shrink-0 rounded-full',\n late ? 'bg-destructive' : statusColors(post.status).dot,\n )}\n />\n )}\n <span className={cn('truncate text-muted-foreground', late && 'text-destructive')}>\n {late ? t('late') : statusName(post.status)}\n </span>\n {post.owner_name ? (\n <UserAvatar\n id={post.owner_id ?? post.owner_name}\n name={post.owner_name}\n size=\"sm\"\n className=\"ml-auto shrink-0\"\n title={post.owner_name}\n />\n ) : null}\n </span>\n </button>\n );\n}\n",
|
|
113
|
+
"src/pages/calendar/brief-messages.ts": "import { defineMessages } from '@/lib/i18n';\n\n/** The texts of \"Paste a brief\" (BriefDialog). */\nexport const t = defineMessages({\n en: {\n title: 'Paste a brief',\n description:\n 'The agent that looks after this app splits it into posts — platform, day and time, owner — and puts them on the calendar, usually within a minute or two.',\n descriptionViewOnly: 'The briefs pasted here, and the posts the agent split them into.',\n placeholder:\n 'Paste the brief: what it is for, the platforms, the dates, who does what, links to the assets…',\n add: 'Send to the agent',\n adding: 'Sending…',\n added: 'Sent: the agent will split it into posts',\n recent: 'Recent briefs',\n none: 'No briefs yet.',\n byLine: '{name} · {when}',\n waiting: 'Waiting for the agent',\n planned: 'Split into {n} posts by {name}',\n plannedOne: 'Split into 1 post by {name}',\n delete: 'Delete this brief',\n deleteTitle: 'Delete this brief?',\n deleteBody: 'It is removed for everyone. The posts split from it stay on the calendar.',\n deleteBodyWaiting: 'It is removed for everyone, and the agent will not split it into posts.',\n deleted: 'Deleted; its posts stay on the calendar',\n },\n zh: {\n title: '贴 brief',\n description:\n '负责这个应用的 agent 会把它拆成多条排期(平台、日期时间、负责人)放进日历,一般一两分钟就好。',\n descriptionViewOnly: '贴在这里的 brief,以及 agent 拆出来的排期。',\n placeholder: '把 brief 贴在这里:做什么、发哪些平台、什么时候、谁负责、素材链接……',\n add: '交给 agent',\n adding: '发送中…',\n added: '已交给 agent,它会拆成排期',\n recent: '最近的 brief',\n none: '还没有 brief。',\n byLine: '{name} · {when}',\n waiting: '等 agent 处理',\n planned: '{name} 拆成了 {n} 条排期',\n plannedOne: '{name} 拆成了 1 条排期',\n delete: '删除这段 brief',\n deleteTitle: '删除这段 brief?',\n deleteBody: '所有人都将看不到它;拆出来的排期还留在日历上。',\n deleteBodyWaiting: '所有人都将看不到它,agent 也不会再拆它。',\n deleted: '已删除,拆出来的排期还在日历上',\n },\n});\n",
|
|
114
|
+
"src/pages/calendar/dates.ts": "import type { Post, PostRange } from '@shared/content';\nimport {\n addDays,\n endOfMonth,\n endOfWeek,\n isBefore,\n startOfDay,\n startOfMonth,\n startOfWeek,\n} from 'date-fns';\nimport { byTime, isoDay, postDay } from '@/lib/content';\nimport { browserLocale, formatLocale } from '@/lib/i18n';\n\n// Date math for the calendar page, after the calendar block's\n// (`parall app add calendar`): which days a view shows, the range it asks\n// posts_range for, and the names of days and weeks.\n\nexport type CalendarView = 'month' | 'week' | 'list';\n\n/** The first day of the week where the viewer is (by the browser's\n * language and region): 0 Sunday … 6 Saturday. */\nconst regionLocale = browserLocale ?? formatLocale;\nexport const weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6 = (() => {\n try {\n const loc = new Intl.Locale(regionLocale) as Intl.Locale & {\n getWeekInfo?: () => { firstDay: number };\n weekInfo?: { firstDay: number };\n };\n const first = loc.getWeekInfo?.().firstDay ?? loc.weekInfo?.firstDay;\n if (first) return (first % 7) as 0 | 1 | 2 | 3 | 4 | 5 | 6;\n } catch {\n // Older engines: decide by region below.\n }\n return /-(US|CA|JP|BR|MX|IL|PH)\\b/i.test(regionLocale) ? 0 : 1;\n})();\n\n/** The days a view shows, [start, end): whole weeks around the month, one\n * week, or the month for the list. */\nexport function visibleDays(view: CalendarView, cursor: Date): { start: Date; end: Date } {\n if (view === 'week') {\n const start = startOfWeek(cursor, { weekStartsOn });\n return { start, end: addDays(start, 7) };\n }\n // endOfMonth / endOfWeek are the last millisecond; the range ends at the\n // following midnight.\n if (view === 'list') {\n return { start: startOfMonth(cursor), end: startOfDay(addDays(endOfMonth(cursor), 1)) };\n }\n const start = startOfWeek(startOfMonth(cursor), { weekStartsOn });\n const end = startOfDay(addDays(endOfWeek(endOfMonth(cursor), { weekStartsOn }), 1));\n return { start, end };\n}\n\n/** posts_range params for [start, end). */\nexport function rangeParams(start: Date, end: Date): PostRange {\n return {\n from: start.toISOString(),\n to: end.toISOString(),\n from_date: isoDay(start),\n to_date: isoDay(addDays(end, -1)),\n };\n}\n\nexport function eachDay(start: Date, end: Date): Date[] {\n const days: Date[] = [];\n for (let d = startOfDay(start); isBefore(d, end); d = addDays(d, 1)) days.push(d);\n return days;\n}\n\n/** The posts going out on a local day, in order: those with no time first. */\nexport function postsOn(posts: Post[], day: Date): Post[] {\n const key = isoDay(day);\n return posts.filter((post) => postDay(post) === key).sort(byTime);\n}\n\nconst weekdayFormat = new Intl.DateTimeFormat(formatLocale, { weekday: 'short' });\n/** Short weekday names in display order, starting at weekStartsOn. */\nexport function weekdayNames(): string[] {\n const base = startOfWeek(new Date(2024, 0, 10), { weekStartsOn });\n return Array.from({ length: 7 }, (_, i) => weekdayFormat.format(addDays(base, i)));\n}\n\nconst monthFormat = new Intl.DateTimeFormat(formatLocale, { year: 'numeric', month: 'long' });\nconst dayFormat = new Intl.DateTimeFormat(formatLocale, { month: 'short', day: 'numeric' });\nconst dayOfMonthFormat = new Intl.DateTimeFormat(formatLocale, { day: 'numeric' });\nconst longDayFormat = new Intl.DateTimeFormat(formatLocale, {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n});\n\n/** The page's title: \"November 2026\", or the week's dates. */\nexport function viewTitle(view: CalendarView, cursor: Date): string {\n if (view !== 'week') return monthFormat.format(cursor);\n const { start, end } = visibleDays('week', cursor);\n const last = addDays(end, -1);\n // \"Nov 2 – 8\" / \"11月2日 – 8日\"; the month again when it changes.\n const tail =\n last.getMonth() === start.getMonth() ? dayOfMonthFormat.format(last) : dayFormat.format(last);\n return `${dayFormat.format(start)} – ${tail}`;\n}\n\nexport function formatLongDay(day: Date): string {\n return longDayFormat.format(day);\n}\n",
|
|
115
|
+
"src/pages/calendar/index.ts": "import { CalendarDays } from 'lucide-react';\nimport type { AppPage } from '@/components/app-shell';\nimport { CalendarPage } from './CalendarPage';\nimport { t } from './messages';\n\nexport const calendarPage: AppPage = {\n id: 'calendar',\n title: t('tab'),\n icon: CalendarDays,\n component: CalendarPage,\n};\n",
|
|
116
|
+
"src/pages/calendar/messages.ts": "import { defineMessages } from '@/lib/i18n';\n\nexport const t = defineMessages({\n en: {\n tab: 'Calendar',\n today: 'Today',\n previous: 'Previous',\n next: 'Next',\n month: 'Month',\n week: 'Week',\n list: 'List',\n views: 'View',\n newPost: 'New post',\n newPostOn: 'New post on {day}',\n pasteBrief: 'Paste a brief',\n more: '+{n} more',\n noPosts: 'Nothing scheduled',\n noPostsBody: 'Nothing goes out this month yet.',\n noPostsBodyEdit: 'Add a post, or paste a brief and the agent splits it into posts.',\n noPostsDay: 'Nothing goes out on this day.',\n nothingHere: 'Nothing scheduled in these days yet.',\n nothingHereEdit:\n 'Nothing scheduled in these days yet: paste a brief and the agent splits it into posts.',\n earlier: 'Show {n} earlier posts this month',\n earlierOne: 'Show 1 earlier post this month',\n nothingLeft: 'Nothing else goes out this month.',\n published: 'Published',\n late: 'Late',\n waiting: '{n} brief waiting for the agent',\n waitingMany: '{n} briefs waiting for the agent',\n notFound: 'This post does not exist any more.',\n },\n zh: {\n tab: '日历',\n today: '今天',\n previous: '上一页',\n next: '下一页',\n month: '月',\n week: '周',\n list: '列表',\n views: '看法',\n newPost: '新建排期',\n newPostOn: '在 {day} 新建排期',\n pasteBrief: '贴 brief',\n more: '还有 {n} 条',\n noPosts: '还没有排期',\n noPostsBody: '这个月还没有要发的。',\n noPostsBodyEdit: '新建一条,或者贴一段 brief,agent 会拆成多条排期。',\n noPostsDay: '这一天没有要发的。',\n nothingHere: '这段时间还没有排期。',\n nothingHereEdit: '这段时间还没有排期:贴一段 brief,agent 会拆成多条排期。',\n earlier: '显示这个月更早的 {n} 条',\n earlierOne: '显示这个月更早的 1 条',\n nothingLeft: '这个月剩下的日子没有要发的。',\n published: '已发布',\n late: '已逾期',\n waiting: '{n} 段 brief 等 agent 处理',\n waitingMany: '{n} 段 brief 等 agent 处理',\n notFound: '这条排期已经不在了。',\n },\n});\n",
|
|
117
|
+
"src/pages.tsx": "import type { AppPage } from '@/components/app-shell';\nimport { boardPage } from '@/pages/board';\nimport { calendarPage } from '@/pages/calendar';\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 calendarPage,\n boardPage,\n // parall:pages — `parall app add` puts block pages above this line.\n];\n"
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
"id": "pipeline",
|
|
122
|
+
"intro": {
|
|
123
|
+
"id": "pipeline",
|
|
124
|
+
"cli": "1.80.0",
|
|
125
|
+
"name": "Customer / partner pipeline",
|
|
126
|
+
"summary": "Customers, brand deals or creator partnerships: where each one stands and what happens next, on one board.",
|
|
127
|
+
"short": "Where each customer or partner deal stands",
|
|
128
|
+
"agent": "Tells you who to follow up each day and drafts the message",
|
|
129
|
+
"pages": [
|
|
130
|
+
{
|
|
131
|
+
"id": "board",
|
|
132
|
+
"icon": "square-kanban",
|
|
133
|
+
"name": "Pipeline board",
|
|
134
|
+
"description": "A card for each deal, laid out by stage. The stages are your own words — for brand deals, say, Inquiry → Quote → Contract → Delivery → Payment."
|
|
73
135
|
},
|
|
74
136
|
{
|
|
75
|
-
"
|
|
76
|
-
"
|
|
137
|
+
"id": "followups",
|
|
138
|
+
"icon": "list-todo",
|
|
139
|
+
"name": "Follow up today",
|
|
140
|
+
"description": "The agent lays out each day who to follow up and why, with a message drafted for you."
|
|
77
141
|
},
|
|
78
142
|
{
|
|
79
|
-
"
|
|
80
|
-
"
|
|
143
|
+
"id": "partners",
|
|
144
|
+
"icon": "building-2",
|
|
145
|
+
"name": "Partner details",
|
|
146
|
+
"description": "Contacts, the history with them, the next step and its date."
|
|
81
147
|
}
|
|
82
148
|
],
|
|
149
|
+
"questions": [
|
|
150
|
+
"Are you following customers, brand deals or creator partnerships? The stages will be named the way you name them.",
|
|
151
|
+
"Where is this kept today — a spreadsheet, a channel, email?",
|
|
152
|
+
"Who follows up? Should each person get their own view?",
|
|
153
|
+
"Should amounts go in, and in which currency?",
|
|
154
|
+
"What time each day should it go through the pipeline?",
|
|
155
|
+
"Who should see the app? By default everyone in the organization can."
|
|
156
|
+
],
|
|
83
157
|
"data": [
|
|
84
158
|
{
|
|
85
159
|
"kind": "channels",
|
|
86
|
-
"name":
|
|
87
|
-
|
|
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
|
-
}
|
|
160
|
+
"name": "Channels",
|
|
161
|
+
"text": "Past messages in a channel such as #deals. The agent must be in the channel to read it."
|
|
94
162
|
},
|
|
95
163
|
{
|
|
96
164
|
"kind": "tasks",
|
|
97
|
-
"name":
|
|
98
|
-
|
|
99
|
-
"zh": "任务"
|
|
100
|
-
},
|
|
101
|
-
"text": {
|
|
102
|
-
"en": "Tasks about your partners.",
|
|
103
|
-
"zh": "和合作方有关的任务。"
|
|
104
|
-
}
|
|
165
|
+
"name": "Tasks",
|
|
166
|
+
"text": "Tasks about your partners."
|
|
105
167
|
},
|
|
106
168
|
{
|
|
107
169
|
"kind": "wiki",
|
|
108
|
-
"name":
|
|
109
|
-
|
|
110
|
-
"zh": "知识库"
|
|
111
|
-
},
|
|
112
|
-
"text": {
|
|
113
|
-
"en": "Documents such as price lists and how deals are run.",
|
|
114
|
-
"zh": "报价单、合作流程这类文档。"
|
|
115
|
-
}
|
|
170
|
+
"name": "Wiki",
|
|
171
|
+
"text": "Documents such as price lists and how deals are run."
|
|
116
172
|
},
|
|
117
173
|
{
|
|
118
174
|
"kind": "connections",
|
|
119
|
-
"name":
|
|
120
|
-
|
|
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
|
-
}
|
|
175
|
+
"name": "Connections",
|
|
176
|
+
"text": "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."
|
|
127
177
|
}
|
|
128
178
|
],
|
|
129
|
-
"data_note":
|
|
130
|
-
|
|
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
|
-
},
|
|
179
|
+
"data_note": "Exactly what it reads, and how far back, it agrees with you in the DM first.",
|
|
180
|
+
"visibility": "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 “Can’t view” in the app’s Access and add those people one by one.",
|
|
137
181
|
"routine": [
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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
|
-
}
|
|
182
|
+
"Goes through the pipeline each day, lays out who to follow up today and drafts the message for each owner.",
|
|
183
|
+
"Tells the owner when a deal has sat in one stage too long.",
|
|
184
|
+
"When someone moves a deal or adds to the history, takes a look and fills in the next step and its date."
|
|
150
185
|
],
|
|
151
186
|
"wake": [
|
|
152
187
|
{
|
|
153
188
|
"kind": "data_changed",
|
|
154
|
-
"name":
|
|
155
|
-
|
|
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
|
-
}
|
|
189
|
+
"name": "When someone writes in the app",
|
|
190
|
+
"text": "Moving a deal or adding to the history wakes it to take a look."
|
|
162
191
|
},
|
|
163
192
|
{
|
|
164
193
|
"kind": "daily",
|
|
165
|
-
"name":
|
|
166
|
-
|
|
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
|
-
}
|
|
194
|
+
"name": "Once a day",
|
|
195
|
+
"text": "At a time you agree with it in the DM, such as 9:00 every day."
|
|
173
196
|
}
|
|
174
197
|
],
|
|
175
198
|
"limits": [
|
|
176
199
|
{
|
|
177
200
|
"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
|
-
}
|
|
201
|
+
"text": "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 “Can’t view” in the app’s Access and add those people one by one."
|
|
182
202
|
},
|
|
183
203
|
{
|
|
184
204
|
"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
|
-
}
|
|
205
|
+
"text": "The pages cannot take file uploads. Send contracts, price lists and receipts to the agent instead."
|
|
189
206
|
},
|
|
190
207
|
{
|
|
191
208
|
"kind": "links",
|
|
192
|
-
"text":
|
|
193
|
-
"en": "Links to Parall (channels, tasks, documents) do not open from inside the app.",
|
|
194
|
-
"zh": "app 里点不开 Parall 的链接(频道、任务、文档)。"
|
|
195
|
-
}
|
|
209
|
+
"text": "Links to Parall (channels, tasks, documents) do not open from inside the app."
|
|
196
210
|
}
|
|
197
211
|
]
|
|
198
212
|
},
|
|
199
|
-
"skill": "#
|
|
213
|
+
"skill": "# App template: Customer / partner pipeline (pipeline)\n\nWhen someone wants an app to follow customers, brand deals or creator partnerships, follow this skill: first agree on the details with the person who asked and tell them which data you will read; once they agree, build the app from the template's source and the organization's real data, set up the wake-ups, and from then on, each time you are woken, do what \"Day to day\" says. How to build an app in general, how to write PostgreSQL and how to subscribe to data changes are in your Mini App instructions and the scaffold's `AGENTS.md`; this skill covers only what is particular to this template.\n\nTalk to the person in their language; the stage names and copy in the app use their team's own words too.\n\n## 1. Agree first\n\nIn the DM, ask all of the following in one message, each with its default; whatever they leave unanswered takes the default:\n\n1. What they follow (customers, brand deals, creator partnerships…) and what the stages are called. Default: the template's Inquiry → Quote → Contract → Delivery → Payment.\n2. Where this is kept today: a spreadsheet, a channel, email, tasks or the wiki. Default: only what they send you in the DM.\n3. Who follows up, and whether each person should get their own view. Default: the person who asked owns every deal; the board can be filtered by owner.\n4. Whether amounts go in (if they do, everyone who can open the app sees them), and in which currency. Default: no amounts; amounts with no currency named are US dollars.\n5. What time each day to go through the pipeline, and in which time zone. Default: 9:00 every day, in the person's time zone.\n6. Who should see the app. Once something is written into the app, everyone in the organization can see it by default; to keep it to a few people, set the app's \"Everyone else in the organization\" to \"Can't view\" (in the app's Access) and add those people one by one. Default: everyone in the organization.\n\n## 2. Explain the data\n\nIn the same message, before you read any data, say:\n\n- What you will read: which channel, which tasks, which wiki pages, which of the organization's connections, and how far back.\n- What of it goes into the app: partners, contacts, stages, amounts (if they go in), next steps and a summary of the history.\n- The parameters of write calls are kept in the app's call records, which only its authors, org owners / admins and the person who made the call can see.\n- What you cannot read: ask them to add you to the channel, or request the connection through the approval card; no detours.\n\nUntil they agree, do not read this data and do not create the app.\n\nAnything you would read that the person who asked cannot see themselves (a channel they are not in — public channels too, since non-members cannot read its messages; tasks or wiki pages they have no access to; someone else's personal connection): first ask your manager in a DM, or an org admin if you have no manager — say who wants to build what, which content you would read, and who will see it once it is in the app (everyone in the organization by default). Read that part only once they agree; if they do not, use only what the person can see. When you are not sure whether the person can see something, treat it as something they cannot. A channel's members: `parall chats members list <chat>`.\n\n## 3. Build\n\n1. `parall app create --name \"<name>\"`, and note the `app_…`. If only a few people should see it, add `--members none` when you create it (an app created open and changed later has already shown its name in everyone's list), then add each of them with `parall app access add <app_…> <usr_…> --level read`, or `--level write` for those who should be able to change it.\n2. `parall app init <dir> --template pipeline --app <app_…>` writes the template's source and this skill (`SKILL.md` at the project root). It refuses when the app's Database is on TiDB: tell the person what it says; do not rewrite the template for MySQL yourself.\n3. Adapt it to the answers: the stages are `STAGES` in `shared/pipeline.ts` (to rename one, change its `en` and `zh`; `id` is the value stored in the data); with no amounts, set `AMOUNTS` to `false`; the currency is `CURRENCY`, `USD` in the template — if the team works in another currency, set its ISO 4217 code (`EUR`, `CNY`…); the copy is in `src/pages/*/messages.ts`; for a field they want to keep as well, add a column in `db/schema.sql` (`ALTER TABLE … ADD COLUMN IF NOT EXISTS`), then change `actions/` and the pages.\n4. Create the tables: `parall app db exec --app <app_…> --file db/schema.sql`.\n5. Import the real data, from the sources they agreed to only: partners into `partners` (one per `lower(name)`), each deal into `deals`, the history into `activities` (`source` says where it came from, such as `#deals` or `Gmail`; what you wrote up yourself has `by_agent = true`). Owners are members: their `usr_…` and name. Leave empty what you cannot read: do not guess amounts, dates or contact details, and do not make up partners or history. One exec takes at most 256 KiB; split a large import.\n6. `pnpm install && pnpm build` → `parall app check dist` → `parall app publish dist --app <app_…> --source .`.\n\n## 4. Wake-ups\n\n- Subscribe to this app's data changes, watching `deals` and `activities` only: `parall triggers create --source-kind platform_event --event-types app.data.changed --name \"Writes to <app name>\" --target-ids <your usr_…> --filter '…' --template '…'`. The filter names this app (`\"<app_…>\" in entity.app_ids`) and the two tables (`entity.tables != null && (\"deals\" in entity.tables || \"activities\" in entity.tables)`; filters do not support loop macros such as `exists`). `--template` is what you are told when it wakes you (Liquid): say which app and what to do, such as `\"<app name>\" prll://<app_…> has new writes: tables {{ entity.tables | json }}, by {{ entity.actor_ids | json }}. Handle them as \"Day to day\" in <dir>/SKILL.md says.`\n- Then a daily schedule at the time they gave: `parall schedules create --name \"…\" --description \"…\" --target-ids <your usr_…> --cron-expr \"0 9 * * *\" --timezone <their time zone>`; `--description` says which app's daily pass this is and to follow \"Day to day\" in `SKILL.md`.\n- Your own writes do not wake you. Read data with `parall app db query`: a query run with `parall app db exec` counts as a write, with its tables recorded as unknown, so filtering by table no longer works.\n\n## 5. Hand over\n\nReply in the DM with the app's link (`prll://app_…`), say what you imported (how many partners, deals and history entries, and where each came from) and when you will be woken (when someone moves a deal or adds to the history in the app, and at what time each day), and ask whether to post it in a channel.\n\n## 6. Day to day\n\n- The daily pass: read the open deals (`parall app db query`). For each one whose next step is due today or overdue, write down why to follow up, then draft a follow-up message for its owner: `parall app action run <app_…> followups_draft --params '{\"id\": \"<deal id>\", \"reason\": \"…\", \"draft\": \"…\"}'`, and the app's \"Follow up today\" page lists it. When a deal has sat in one stage too long (by default, no change in 14 days), tell its owner in a DM.\n- When someone writes in the app: look at what changed. Where a next step is now empty, fill in the next step and its date from the history; when unsure, ask the owner.\n- Read only the sources the person agreed to. To read a new one, first ask again as \"Explain the data\" says.\n- Before changing the app, if you have no local project, fetch the current version's source with `parall app pull <app_…> --out <dir>`.\n- Ask about what a person has to decide, and do not decide it for them: changing an amount or an owner, marking a deal done or not happening, deleting a partner or a deal.\n",
|
|
200
214
|
"overlay": {
|
|
201
215
|
"_overlay.json": "{\n \"remove\": [\"public/manifest.json\", \"src/pages/items\", \"actions/items.ts\", \"shared/items.ts\"],\n \"blocks\": []\n}\n",
|
|
202
216
|
"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';\
|
|
217
|
+
"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';\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 { rows } = await ctx.db.exec(\n `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 [\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 return readDeal(ctx, rows[0]?.id as string);\n }\n\n const { rows_affected } = await ctx.db.exec(\n `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 [partnerId, title, stageId, value, ownerId, ownerName, nextStep, due, id],\n );\n if (!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 { rows_affected } = await ctx.db.exec(\n `UPDATE deals\n SET stage = COALESCE($1, stage), status = COALESCE($2, status), updated_at = now()\n WHERE id = $3`,\n [stageId, input.status ?? null, id],\n );\n if (!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 {\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[1]?.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 { rows_affected } = await ctx.db.exec(\n `UPDATE deals SET next_step_due = $1, updated_at = now()\n WHERE id = $2 AND status = 'open'`,\n [until, id],\n );\n if (!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 { rows_affected } = await ctx.db.exec(\n `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 [input.reason.trim(), input.draft.trim(), ctx.viewer.display_name, due, id],\n );\n if (!rows_affected) throw new ActionError('This deal is closed or was deleted.');\n return readDeal(ctx, id);\n },\n};\n",
|
|
204
218
|
"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';\
|
|
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
|
|
219
|
+
"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';\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 { rows } = await ctx.db.exec(\n `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 [...fields, ctx.viewer.id, ctx.viewer.display_name],\n );\n return readPartner(ctx, rows[0]?.id as string);\n }\n const { rows_affected } = await ctx.db.exec(\n `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 [...fields, id],\n );\n if (!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 { rows } = await ctx.db.exec(\n `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 [\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 const row = 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",
|
|
220
|
+
"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-- The organization's members are not a table here: actions/people.ts lists\n-- them with ctx.parall.members(), and pages offer them as owners. Tables\n-- keep a member's id (usr_…). ctx.viewer is the only trustworthy identity.\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
221
|
"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 = '
|
|
222
|
+
"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: set the team's own (EUR,\n * CNY…). */\nexport const CURRENCY = 'USD';\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
223
|
"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 \"
|
|
224
|
+
"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.6K\", \"US$5.5万\"). */\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 organization's members and the\n * owners the deals already have (an imported owner may have left 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, one who has left the organization): 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
225
|
"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
226
|
"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
227
|
"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",
|