@composable-os/pack-deals 0.0.0-stage → 0.1.0-beta.11

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/LICENSE ADDED
@@ -0,0 +1,109 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ > This licence covers the repository except the directories listed in NOTICE. In particular, the
4
+ > assistant packages `packages/agent-*` (agent-core, agent-a2ui, agent-voice, agent-plugins) are
5
+ > licensed under the MIT License; see the LICENSE file in each of those directories (ADR 0350).
6
+
7
+ ## Abbreviation
8
+
9
+ FSL-1.1-ALv2
10
+
11
+ ## Notice
12
+
13
+ Copyright 2026 Tim O'Connell
14
+
15
+ ## Terms and Conditions
16
+
17
+ ### Licensor ("We")
18
+
19
+ The party offering the Software under these Terms and Conditions.
20
+
21
+ ### The Software
22
+
23
+ The "Software" is each version of the software that we make available under
24
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
25
+ Conditions with the Software.
26
+
27
+ ### License Grant
28
+
29
+ Subject to your compliance with this License Grant and the Patents,
30
+ Redistribution and Trademark clauses below, we hereby grant you the right to
31
+ use, copy, modify, create derivative works, publicly perform, publicly display
32
+ and redistribute the Software for any Permitted Purpose identified below.
33
+
34
+ ### Permitted Purpose
35
+
36
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
37
+ means making the Software available to others in a commercial product or
38
+ service that:
39
+
40
+ 1. substitutes for the Software;
41
+
42
+ 2. substitutes for any other product or service we offer using the Software
43
+ that exists as of the date we make the Software available; or
44
+
45
+ 3. offers the same or substantially similar functionality as the Software.
46
+
47
+ Permitted Purposes specifically include using the Software:
48
+
49
+ 1. for your internal use and access;
50
+
51
+ 2. for non-commercial education;
52
+
53
+ 3. for non-commercial research; and
54
+
55
+ 4. in connection with professional services that you provide to a licensee
56
+ using the Software in accordance with these Terms and Conditions.
57
+
58
+ ### Patents
59
+
60
+ To the extent your use for a Permitted Purpose would necessarily infringe our
61
+ patents, the license grant above includes a license under our patents. If you
62
+ make a claim against any party that the Software infringes or contributes to
63
+ the infringement of any patent, then your patent license to the Software ends
64
+ immediately.
65
+
66
+ ### Redistribution
67
+
68
+ The Terms and Conditions apply to all copies, modifications and derivatives of
69
+ the Software.
70
+
71
+ If you redistribute any copies, modifications or derivatives of the Software,
72
+ you must include a copy of or a link to these Terms and Conditions and not
73
+ remove any copyright notices provided in or with the Software.
74
+
75
+ ### Disclaimer
76
+
77
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
78
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
79
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
80
+
81
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
82
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
83
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
84
+
85
+ ### Trademarks
86
+
87
+ Except for displaying the License Details and identifying us as the origin of
88
+ the Software, you have no right under these Terms and Conditions to use our
89
+ trademarks, trade names, service marks or product names.
90
+
91
+ ## Grant of Future License
92
+
93
+ We hereby irrevocably grant you an additional license to use the Software under
94
+ the Apache License, Version 2.0 that is effective on the second anniversary of
95
+ the date we make the Software available. On or after that date, you may use the
96
+ Software under the Apache License, Version 2.0, in which case the following
97
+ will apply:
98
+
99
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
100
+ this file except in compliance with the License.
101
+
102
+ You may obtain a copy of the License at
103
+
104
+ http://www.apache.org/licenses/LICENSE-2.0
105
+
106
+ Unless required by applicable law or agreed to in writing, software distributed
107
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
108
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
109
+ specific language governing permissions and limitations under the License.
@@ -0,0 +1,49 @@
1
+ export declare const STALLED_DAYS = 14;
2
+ export declare const FOLLOW_UP_PREFIX = "Follow up:";
3
+ /** Stalled deals handled per daily run (oldest first); the rest wait for the next day. */
4
+ export declare const STALLED_BATCH = 100;
5
+ export declare const ONBOARDING_TASKS: readonly ["Kick-off call", "Send welcome pack", "Set up account"];
6
+ /**
7
+ * Open deals with no change and no timeline activity for STALLED_DAYS days, that do not already
8
+ * have an open follow-up task. Indexed: deals by (status, updatedAt); activity and task links by
9
+ * (object_type, record_id).
10
+ */
11
+ export declare const STALLED_SQL = "\nSELECT d.id AS id, d.name AS name, d.owner AS owner\nFROM rec_x_deals_deal d\nWHERE d.status = 'open' AND d.updated_at < ?1\n AND NOT EXISTS (\n SELECT 1 FROM rec_activity_link l JOIN rec_activity a ON a.id = l.activity_id\n WHERE l.object_type = 'deals.deal' AND l.record_id = d.id AND a.occurred_at >= ?1)\n AND NOT EXISTS (\n SELECT 1 FROM rec_task_link tl JOIN rec_task t ON t.id = tl.task_id\n WHERE tl.object_type = 'deals.deal' AND tl.record_id = d.id AND t.status = 'open'\n AND t.title LIKE 'Follow up:%')\nORDER BY d.updated_at\nLIMIT 100";
12
+ export declare const stalledDeal: import("@composable-os/sdk").AutomationSpec<{
13
+ readonly type: "schedule";
14
+ readonly cron: "0 8 * * *";
15
+ }>;
16
+ export declare const wonOnboarding: import("@composable-os/sdk").AutomationSpec<{
17
+ readonly type: "fieldChanged";
18
+ readonly object: "deals.deal";
19
+ readonly field: "stage";
20
+ readonly to: {
21
+ readonly stageType: "won";
22
+ };
23
+ }>;
24
+ export declare const closeDatePassed: import("@composable-os/sdk").AutomationSpec<{
25
+ readonly type: "dateRelative";
26
+ readonly object: "deals.deal";
27
+ readonly field: "expectedClose";
28
+ readonly offsetDays: 1;
29
+ }>;
30
+ export declare const dealAutomations: {
31
+ stalledDeal: import("@composable-os/sdk").AutomationSpec<{
32
+ readonly type: "schedule";
33
+ readonly cron: "0 8 * * *";
34
+ }>;
35
+ wonOnboarding: import("@composable-os/sdk").AutomationSpec<{
36
+ readonly type: "fieldChanged";
37
+ readonly object: "deals.deal";
38
+ readonly field: "stage";
39
+ readonly to: {
40
+ readonly stageType: "won";
41
+ };
42
+ }>;
43
+ closeDatePassed: import("@composable-os/sdk").AutomationSpec<{
44
+ readonly type: "dateRelative";
45
+ readonly object: "deals.deal";
46
+ readonly field: "expectedClose";
47
+ readonly offsetDays: 1;
48
+ }>;
49
+ };
@@ -0,0 +1,173 @@
1
+ // The Deals automations (stage 5, ADR 0028). Each is listed under Automations and can be turned
2
+ // off with automation.disable (or the Pause button). They declare their steps and intents, so
3
+ // the host renders the summary and step diagram from them; `run` only takes declared steps.
4
+ import { defineAutomation, OpsCallError } from "@composable-os/sdk";
5
+ export const STALLED_DAYS = 14;
6
+ export const FOLLOW_UP_PREFIX = "Follow up:";
7
+ /** Stalled deals handled per daily run (oldest first); the rest wait for the next day. */
8
+ export const STALLED_BATCH = 100;
9
+ export const ONBOARDING_TASKS = ["Kick-off call", "Send welcome pack", "Set up account"];
10
+ /**
11
+ * Open deals with no change and no timeline activity for STALLED_DAYS days, that do not already
12
+ * have an open follow-up task. Indexed: deals by (status, updatedAt); activity and task links by
13
+ * (object_type, record_id).
14
+ */
15
+ export const STALLED_SQL = `
16
+ SELECT d.id AS id, d.name AS name, d.owner AS owner
17
+ FROM rec_x_deals_deal d
18
+ WHERE d.status = 'open' AND d.updated_at < ?1
19
+ AND NOT EXISTS (
20
+ SELECT 1 FROM rec_activity_link l JOIN rec_activity a ON a.id = l.activity_id
21
+ WHERE l.object_type = 'deals.deal' AND l.record_id = d.id AND a.occurred_at >= ?1)
22
+ AND NOT EXISTS (
23
+ SELECT 1 FROM rec_task_link tl JOIN rec_task t ON t.id = tl.task_id
24
+ WHERE tl.object_type = 'deals.deal' AND tl.record_id = d.id AND t.status = 'open'
25
+ AND t.title LIKE '${FOLLOW_UP_PREFIX}%')
26
+ ORDER BY d.updated_at
27
+ LIMIT ${STALLED_BATCH}`;
28
+ const DAY_MS = 86_400_000;
29
+ const isoDate = (ms) => new Date(ms).toISOString().slice(0, 10);
30
+ /** The period a schedule run is for (`2026-11-05` or `2026-11-05T08:00`) as epoch ms. */
31
+ function periodMs(period) {
32
+ const parsed = period ? Date.parse(period.length === 10 ? `${period}T00:00:00Z` : period) : NaN;
33
+ return Number.isNaN(parsed) ? Date.now() : parsed;
34
+ }
35
+ export const stalledDeal = defineAutomation({
36
+ label: "Stalled deal follow-up",
37
+ description: `Every morning, an open deal with no changes or activity for ${STALLED_DAYS} days gets a ` +
38
+ "follow-up task for its owner, unless it already has an open one.",
39
+ trigger: { type: "schedule", cron: "0 8 * * *" },
40
+ steps: [
41
+ {
42
+ name: "createFollowUps",
43
+ label: "Create follow-up tasks for stalled deals",
44
+ reads: ["deals.deal", "activity", "task"],
45
+ calls: ["query.sql"],
46
+ writes: [{ object: "task", titles: [`${FOLLOW_UP_PREFIX} <deal name>`] }],
47
+ },
48
+ ],
49
+ async run(event, step, ctx) {
50
+ // One step: a retry re-reads, so deals that already got their task are skipped.
51
+ return step.do("createFollowUps", async () => {
52
+ const since = new Date(periodMs(event.period) - STALLED_DAYS * DAY_MS).toISOString();
53
+ const { rows } = await ctx.ops.call("query.sql", { sql: STALLED_SQL, params: [since], maxRows: STALLED_BATCH });
54
+ const created = [];
55
+ for (const deal of rows) {
56
+ const task = await ctx.ops.call("task.create", {
57
+ title: `${FOLLOW_UP_PREFIX} ${deal.name}`,
58
+ notes: `No changes or activity on this deal for ${STALLED_DAYS} days.`,
59
+ dueAt: isoDate(periodMs(event.period)),
60
+ assigneeId: deal.owner,
61
+ links: [{ object: "deals.deal", id: deal.id }],
62
+ });
63
+ if (task.id)
64
+ created.push(task.id);
65
+ }
66
+ return { stalled: rows.length, created };
67
+ });
68
+ },
69
+ });
70
+ export const wonOnboarding = defineAutomation({
71
+ label: "Won deal → onboarding",
72
+ description: "When a deal is won, creates three onboarding tasks for its owner and tells them. Three days " +
73
+ "later, if any are still open, tells the owner's manager (the admins, as users have no " +
74
+ "manager field).",
75
+ trigger: { type: "fieldChanged", object: "deals.deal", field: "stage", to: { stageType: "won" } },
76
+ steps: [
77
+ {
78
+ name: "createTasks",
79
+ label: "Create onboarding tasks",
80
+ writes: [
81
+ {
82
+ object: "task",
83
+ count: ONBOARDING_TASKS.length,
84
+ titles: [...ONBOARDING_TASKS],
85
+ assignTo: { field: "owner" },
86
+ linkedToTrigger: true,
87
+ },
88
+ ],
89
+ },
90
+ {
91
+ name: "notifyOwner",
92
+ notifies: [{ to: { field: "owner" }, message: "Deal won 🎉 onboarding tasks created" }],
93
+ },
94
+ { name: "wait", kind: "sleep", duration: "3 days" },
95
+ {
96
+ name: "anyOpen",
97
+ kind: "condition",
98
+ label: "Any onboarding task still open?",
99
+ clause: "any of those tasks are still open",
100
+ },
101
+ {
102
+ name: "notifyManager",
103
+ reads: ["task"],
104
+ notifies: [{ to: { managerOf: "owner" }, message: "Onboarding not started for {record}" }],
105
+ },
106
+ ],
107
+ async run(event, step, ctx) {
108
+ const deal = event.record;
109
+ if (!deal)
110
+ return { skipped: "no deal" };
111
+ const owner = typeof deal.data?.owner === "string" ? deal.data.owner : null;
112
+ const taskIds = await step.do("createTasks", async () => {
113
+ const ids = [];
114
+ for (const title of ONBOARDING_TASKS) {
115
+ // A task queued for approval comes back pending, without an id.
116
+ const task = await ctx.ops.call("task.create", {
117
+ title,
118
+ assigneeId: owner,
119
+ links: [{ object: deal.object, id: deal.id }],
120
+ });
121
+ if (task.id)
122
+ ids.push(task.id);
123
+ }
124
+ return ids;
125
+ });
126
+ await step.do("notifyOwner", () => ctx.notify({ field: "owner" }, { title: "Deal won 🎉 onboarding tasks created" }));
127
+ await step.sleep("wait", "3 days");
128
+ return step.do("notifyManager", async () => {
129
+ let open = 0;
130
+ for (const id of taskIds) {
131
+ try {
132
+ const task = await ctx.ops.call("task.get", { id });
133
+ if (task.status === "open")
134
+ open += 1;
135
+ }
136
+ catch (error) {
137
+ // A deleted task no longer counts.
138
+ if (!(error instanceof OpsCallError && error.code === "not_found"))
139
+ throw error;
140
+ }
141
+ }
142
+ if (open === 0)
143
+ return { open, notified: false };
144
+ await ctx.notify({ managerOf: "owner" }, {
145
+ title: "Onboarding not started for {record}",
146
+ body: `${open} of ${taskIds.length} onboarding tasks are still open.`,
147
+ });
148
+ return { open, notified: true };
149
+ });
150
+ },
151
+ });
152
+ export const closeDatePassed = defineAutomation({
153
+ label: "Close date passed",
154
+ description: "The day after an open deal's expected close date, reminds its owner to update the date or " +
155
+ "close the deal.",
156
+ trigger: { type: "dateRelative", object: "deals.deal", field: "expectedClose", offsetDays: 1 },
157
+ conditions: { field: "status", op: "eq", value: "open" },
158
+ steps: [
159
+ {
160
+ name: "notifyOwner",
161
+ notifies: [
162
+ { to: { field: "owner" }, message: "{record}: the expected close date has passed" },
163
+ ],
164
+ },
165
+ ],
166
+ async run(_event, step, ctx) {
167
+ return step.do("notifyOwner", () => ctx.notify({ field: "owner" }, {
168
+ title: "{record}: the expected close date has passed",
169
+ body: "Update the expected close date, or move the deal to won or lost.",
170
+ }));
171
+ },
172
+ });
173
+ export const dealAutomations = { stalledDeal, wonOnboarding, closeDatePassed };
@@ -0,0 +1,87 @@
1
+ import type { z } from "@composable-os/sdk";
2
+ import type { stageMetrics } from "../tools.ts";
3
+ /** The operations this entry calls, as the generated client types them. */
4
+ export type DealsOperations = {
5
+ "x.deals.stageMetrics": {
6
+ kind: "query";
7
+ input: z.input<typeof stageMetrics.input>;
8
+ output: z.output<typeof stageMetrics.output>;
9
+ };
10
+ };
11
+ export type StageMetrics = DealsOperations["x.deals.stageMetrics"]["output"];
12
+ /** The part of a generated staff client this entry needs. A product's staff client fits it. */
13
+ export interface DealsClient {
14
+ query<N extends keyof DealsOperations & string>(name: N, input: DealsOperations[N]["input"]): {
15
+ queryKey: readonly unknown[];
16
+ queryFn: () => Promise<DealsOperations[N]["output"]>;
17
+ };
18
+ }
19
+ /** `queryOptions` for a pipeline's stage metrics, optionally from a date (YYYY-MM-DD). */
20
+ export declare function stageMetricsQuery(api: DealsClient, pipelineId: string, since?: string): {
21
+ queryKey: readonly unknown[];
22
+ queryFn: () => Promise<{
23
+ pipelineId: string;
24
+ stages: {
25
+ stageId: string;
26
+ stage: string;
27
+ type: string;
28
+ entered: number;
29
+ current: number;
30
+ avgDaysInStage: number | null;
31
+ avgDaysBeforeMovingOn: number | null;
32
+ }[];
33
+ velocity: {
34
+ won: number;
35
+ avgDaysToWin: number | null;
36
+ wonValue: number;
37
+ };
38
+ }>;
39
+ };
40
+ /** One line per stage for a funnel: share of deals that entered it, in pipeline order. */
41
+ export declare function funnel(metrics: StageMetrics): {
42
+ stage: string;
43
+ entered: number;
44
+ share: number;
45
+ }[];
46
+ /** The app's `useQuery`, as far as these hooks use it. */
47
+ export type UseQuery = <T>(options: {
48
+ queryKey: readonly unknown[];
49
+ queryFn: () => Promise<T>;
50
+ }) => {
51
+ data: T | undefined;
52
+ isPending: boolean;
53
+ error: unknown;
54
+ };
55
+ /** Hooks for a React or React Native app: `const deals = createDealsHooks(useQuery, api)`. */
56
+ export declare function createDealsHooks(useQuery: UseQuery, api: DealsClient): {
57
+ useStageMetrics(pipelineId: string, since?: string): {
58
+ data: {
59
+ pipelineId: string;
60
+ stages: {
61
+ stageId: string;
62
+ stage: string;
63
+ type: string;
64
+ entered: number;
65
+ current: number;
66
+ avgDaysInStage: number | null;
67
+ avgDaysBeforeMovingOn: number | null;
68
+ }[];
69
+ velocity: {
70
+ won: number;
71
+ avgDaysToWin: number | null;
72
+ wonValue: number;
73
+ };
74
+ } | undefined;
75
+ isPending: boolean;
76
+ error: unknown;
77
+ };
78
+ useFunnel(pipelineId: string, since?: string): {
79
+ data: {
80
+ stage: string;
81
+ entered: number;
82
+ share: number;
83
+ }[] | undefined;
84
+ isPending: boolean;
85
+ error: unknown;
86
+ };
87
+ };
@@ -0,0 +1,25 @@
1
+ /** `queryOptions` for a pipeline's stage metrics, optionally from a date (YYYY-MM-DD). */
2
+ export function stageMetricsQuery(api, pipelineId, since) {
3
+ return api.query("x.deals.stageMetrics", since ? { pipelineId, since } : { pipelineId });
4
+ }
5
+ /** One line per stage for a funnel: share of deals that entered it, in pipeline order. */
6
+ export function funnel(metrics) {
7
+ const top = Math.max(1, ...metrics.stages.map((s) => s.entered));
8
+ return metrics.stages.map((s) => ({
9
+ stage: s.stage,
10
+ entered: s.entered,
11
+ share: Math.round((s.entered / top) * 1000) / 1000,
12
+ }));
13
+ }
14
+ /** Hooks for a React or React Native app: `const deals = createDealsHooks(useQuery, api)`. */
15
+ export function createDealsHooks(useQuery, api) {
16
+ return {
17
+ useStageMetrics(pipelineId, since) {
18
+ return useQuery(stageMetricsQuery(api, pipelineId, since));
19
+ },
20
+ useFunnel(pipelineId, since) {
21
+ const result = useQuery(stageMetricsQuery(api, pipelineId, since));
22
+ return { ...result, data: result.data ? funnel(result.data) : undefined };
23
+ },
24
+ };
25
+ }
@@ -0,0 +1,3 @@
1
+ import type { DashboardDeclaration } from "@composable-os/sdk";
2
+ export declare const salesOverview: DashboardDeclaration;
3
+ export declare const pipelineHealth: DashboardDeclaration;