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

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/index.js ADDED
@@ -0,0 +1,388 @@
1
+ // Deals: the first shipped extension (stage 4, ADR 0026). Pipelines of ordered, typed stages; deals
2
+ // that move through them under stage rules; and the people on each deal. Everything here is the
3
+ // public contract: the stage behaviour (ADR 0100) makes the host enforce stage rules, keep the
4
+ // probability, status and won/lost date, record stage history and post "Moved to <stage>" on the
5
+ // deal and its organisation, for every actor. It runs through the same runtime as AI-written
6
+ // extensions.
7
+ import { defineExtension } from "@composable-os/sdk";
8
+ import { dealAutomations } from "./automations.js";
9
+ import { pipelineHealth, salesOverview } from "./dashboards.js";
10
+ import { stageMetrics } from "./tools.js";
11
+ const DEAL_COLUMNS = [
12
+ "name",
13
+ "stage",
14
+ "value",
15
+ "probability",
16
+ "expectedClose",
17
+ "owner",
18
+ "organisation",
19
+ ];
20
+ /** Deal fields a stage can require (the stage's `requiredFields` options). */
21
+ const REQUIRABLE = [
22
+ { value: "value", label: "Value" },
23
+ { value: "expectedClose", label: "Expected close" },
24
+ { value: "owner", label: "Owner" },
25
+ { value: "organisation", label: "Organisation" },
26
+ { value: "source", label: "Source" },
27
+ { value: "nextStep", label: "Next step" },
28
+ { value: "nextStepDate", label: "Next step date" },
29
+ { value: "lostReason", label: "Lost reason" },
30
+ ];
31
+ const stage = (pipeline, name, position, type, probability, requiredFields = []) => ({
32
+ name,
33
+ pipeline: { seed: pipeline },
34
+ position,
35
+ type,
36
+ probability,
37
+ requiredFields,
38
+ });
39
+ export default defineExtension({
40
+ id: "deals",
41
+ version: "1.2.0",
42
+ contractVersion: 1,
43
+ label: "Deals",
44
+ description: "Deals moving through pipelines of stages, with stage rules, probabilities, stage history " +
45
+ "and the people involved.",
46
+ permissions: {
47
+ read: ["organisation", "person", "activity"],
48
+ write: ["task"],
49
+ operations: ["query.sql", "notification.send"],
50
+ modules: ["ops", "log"],
51
+ },
52
+ objects: {
53
+ pipeline: {
54
+ label: "Pipeline",
55
+ plural: "Pipelines",
56
+ icon: "kanban",
57
+ titleField: "name",
58
+ description: "A sales process: an ordered set of stages deals move through.",
59
+ navigation: "settings",
60
+ fields: {
61
+ name: { type: "text", label: "Name", required: true },
62
+ position: { type: "number", label: "Order" },
63
+ description: { type: "longText", label: "Description" },
64
+ },
65
+ indexes: [["position"]],
66
+ seed: {
67
+ newBusiness: { name: "New business", position: 1 },
68
+ renewals: { name: "Renewals", position: 2 },
69
+ },
70
+ },
71
+ stage: {
72
+ label: "Stage",
73
+ plural: "Stages",
74
+ icon: "list-ordered",
75
+ titleField: "name",
76
+ description: "One step of a pipeline: its order, whether deals in it are open, won or lost, the " +
77
+ "default probability, and the deal fields required to enter it (stage rules).",
78
+ navigation: "settings",
79
+ fields: {
80
+ name: { type: "text", label: "Name", required: true },
81
+ pipeline: { type: "relation", label: "Pipeline", to: "deals.pipeline", required: true },
82
+ position: { type: "number", label: "Order", required: true },
83
+ type: {
84
+ type: "select",
85
+ label: "Type",
86
+ required: true,
87
+ options: [
88
+ { value: "open", label: "Open" },
89
+ { value: "won", label: "Won", color: "green" },
90
+ { value: "lost", label: "Lost", color: "red" },
91
+ ],
92
+ },
93
+ probability: { type: "percent", label: "Default probability" },
94
+ requiredFields: {
95
+ type: "multiSelect",
96
+ label: "Required fields",
97
+ description: "Deal fields that must have a value to enter this stage.",
98
+ options: REQUIRABLE,
99
+ },
100
+ },
101
+ indexes: [["pipeline", "position"]],
102
+ seed: {
103
+ nbLead: stage("newBusiness", "Lead", 1, "open", 10),
104
+ nbQualified: stage("newBusiness", "Qualified", 2, "open", 25, ["owner"]),
105
+ nbProposal: stage("newBusiness", "Proposal", 3, "open", 50, ["value", "expectedClose"]),
106
+ nbNegotiation: stage("newBusiness", "Negotiation", 4, "open", 75, [
107
+ "value",
108
+ "expectedClose",
109
+ "organisation",
110
+ ]),
111
+ nbWon: stage("newBusiness", "Won", 5, "won", 100, ["value"]),
112
+ nbLost: stage("newBusiness", "Lost", 6, "lost", 0),
113
+ rnUpcoming: stage("renewals", "Upcoming renewal", 1, "open", 60, ["organisation"]),
114
+ rnInDiscussion: stage("renewals", "Renewal in discussion", 2, "open", 75, ["value"]),
115
+ rnCommitted: stage("renewals", "Renewal committed", 3, "open", 90, [
116
+ "value",
117
+ "expectedClose",
118
+ ]),
119
+ rnRenewed: stage("renewals", "Renewed", 4, "won", 100, ["value"]),
120
+ rnChurned: stage("renewals", "Churned", 5, "lost", 0),
121
+ },
122
+ },
123
+ deal: {
124
+ label: "Deal",
125
+ plural: "Deals",
126
+ icon: "handshake",
127
+ titleField: "name",
128
+ description: "A potential sale moving through a pipeline.",
129
+ // The deal's owner, which assignment rules set for deals created without one (ADR 0246).
130
+ owner: "owner",
131
+ navigationOrder: 20,
132
+ fields: {
133
+ name: { type: "text", label: "Name", required: true },
134
+ value: {
135
+ type: "currency",
136
+ label: "Value",
137
+ description: "In the deployment's base currency (Settings → General).",
138
+ },
139
+ pipeline: {
140
+ type: "relation",
141
+ label: "Pipeline",
142
+ to: "deals.pipeline",
143
+ description: "Defaults to the Default pipeline setting (New business).",
144
+ },
145
+ stage: {
146
+ type: "relation",
147
+ label: "Stage",
148
+ to: "deals.stage",
149
+ track: "timeline",
150
+ description: "Defaults to the pipeline's first stage. Stage rules apply on entering it.",
151
+ },
152
+ status: {
153
+ type: "select",
154
+ label: "Status",
155
+ readOnly: true,
156
+ description: "Open, won or lost: the type of the deal's stage.",
157
+ options: [
158
+ { value: "open", label: "Open" },
159
+ { value: "won", label: "Won", color: "green" },
160
+ { value: "lost", label: "Lost", color: "red" },
161
+ ],
162
+ },
163
+ expectedClose: { type: "date", label: "Expected close" },
164
+ probability: {
165
+ type: "percent",
166
+ label: "Probability",
167
+ description: "Follows the stage's default unless set by hand.",
168
+ },
169
+ probabilityOverridden: {
170
+ type: "boolean",
171
+ label: "Probability set by hand",
172
+ description: "Clear it to go back to the stage's default probability.",
173
+ },
174
+ weightedValue: {
175
+ type: "formula",
176
+ label: "Weighted value",
177
+ expression: "round(coalesce(value, 0) * coalesce(probability, 0) / 100, 2)",
178
+ },
179
+ owner: { type: "user", label: "Owner" },
180
+ organisation: { type: "relation", label: "Organisation", to: "organisation" },
181
+ source: {
182
+ type: "select",
183
+ label: "Source",
184
+ options: [
185
+ { value: "inbound", label: "Inbound" },
186
+ { value: "outbound", label: "Outbound" },
187
+ { value: "referral", label: "Referral" },
188
+ { value: "partner", label: "Partner" },
189
+ { value: "event", label: "Event" },
190
+ { value: "existing", label: "Existing customer" },
191
+ { value: "other", label: "Other" },
192
+ ],
193
+ },
194
+ lostReason: {
195
+ type: "select",
196
+ label: "Lost reason",
197
+ description: "Required to move a deal to a lost stage.",
198
+ options: [
199
+ { value: "price", label: "Price" },
200
+ { value: "competitor", label: "Went with a competitor" },
201
+ { value: "noBudget", label: "No budget" },
202
+ { value: "noDecision", label: "No decision" },
203
+ { value: "timing", label: "Timing" },
204
+ { value: "productFit", label: "Product fit" },
205
+ { value: "other", label: "Other" },
206
+ ],
207
+ },
208
+ nextStep: { type: "text", label: "Next step" },
209
+ nextStepDate: { type: "date", label: "Next step date" },
210
+ closedAt: {
211
+ type: "datetime",
212
+ label: "Won/lost date",
213
+ readOnly: true,
214
+ description: "Set when the deal enters a won or lost stage; cleared when it reopens.",
215
+ },
216
+ },
217
+ stages: {
218
+ field: "stage",
219
+ stage: {
220
+ type: "type",
221
+ order: "position",
222
+ requiredFields: "requiredFields",
223
+ probability: "probability",
224
+ group: "pipeline",
225
+ },
226
+ group: "pipeline",
227
+ probability: { field: "probability", overridden: "probabilityOverridden" },
228
+ closedDate: "closedAt",
229
+ status: "status",
230
+ requiredByType: { lost: ["lostReason"] },
231
+ defaultGroupSetting: "defaultPipeline",
232
+ },
233
+ timelineLinks: ["organisation"],
234
+ // Hot queries: board columns (stage), open pipeline (status, close month), an
235
+ // organisation's deals, an owner's deals, won-this-quarter and slipped close dates.
236
+ indexes: [
237
+ ["stage"],
238
+ ["pipeline", "status"],
239
+ ["status", "expectedClose"],
240
+ ["status", "closedAt"],
241
+ ["organisation"],
242
+ ["owner", "status"],
243
+ // The daily stalled-deal scan: open deals not changed since a date.
244
+ ["status", "updatedAt"],
245
+ ],
246
+ },
247
+ participant: {
248
+ label: "Deal participant",
249
+ plural: "Deal participants",
250
+ icon: "users",
251
+ titleField: "role",
252
+ description: "A person involved in a deal, and their role in it.",
253
+ navigation: "none",
254
+ fields: {
255
+ role: {
256
+ type: "select",
257
+ label: "Role",
258
+ required: true,
259
+ options: [
260
+ { value: "decisionMaker", label: "Decision maker" },
261
+ { value: "champion", label: "Champion" },
262
+ { value: "influencer", label: "Influencer" },
263
+ { value: "user", label: "User" },
264
+ { value: "other", label: "Other" },
265
+ ],
266
+ },
267
+ deal: { type: "relation", label: "Deal", to: "deals.deal", required: true },
268
+ person: { type: "relation", label: "Person", to: "person", required: true },
269
+ note: { type: "text", label: "Note" },
270
+ },
271
+ indexes: [["deal"], ["person"]],
272
+ },
273
+ },
274
+ // Shipped saved views: shared and read-only in the Deals views menu. Relative values resolve
275
+ // for whoever opens them, when they do (ADR 0103).
276
+ views: {
277
+ myOpenDeals: {
278
+ label: "My open deals",
279
+ object: "deals.deal",
280
+ filter: {
281
+ and: [
282
+ { field: "status", op: "eq", value: "open" },
283
+ { field: "owner", op: "eq", value: { $relative: "me" } },
284
+ ],
285
+ },
286
+ sort: { field: "expectedClose", direction: "asc" },
287
+ columns: DEAL_COLUMNS,
288
+ },
289
+ closingThisMonth: {
290
+ label: "Closing this month",
291
+ object: "deals.deal",
292
+ filter: {
293
+ and: [
294
+ { field: "status", op: "eq", value: "open" },
295
+ { field: "expectedClose", op: "gte", value: { $relative: "startOfMonth" } },
296
+ { field: "expectedClose", op: "lt", value: { $relative: "startOfNextMonth" } },
297
+ ],
298
+ },
299
+ sort: { field: "expectedClose", direction: "asc" },
300
+ columns: DEAL_COLUMNS,
301
+ },
302
+ wonThisQuarter: {
303
+ label: "Won this quarter",
304
+ object: "deals.deal",
305
+ filter: {
306
+ and: [
307
+ { field: "status", op: "eq", value: "won" },
308
+ { field: "closedAt", op: "gte", value: { $relative: "startOfQuarter" } },
309
+ { field: "closedAt", op: "lt", value: { $relative: "startOfNextQuarter" } },
310
+ ],
311
+ },
312
+ sort: { field: "closedAt", direction: "desc" },
313
+ columns: ["name", "value", "closedAt", "owner", "organisation", "pipeline"],
314
+ },
315
+ pipelineBoard: {
316
+ label: "Pipeline board",
317
+ type: "board",
318
+ object: "deals.deal",
319
+ groupBy: "stage",
320
+ sumField: "value",
321
+ cardFields: ["value", "organisation", "expectedClose", "owner"],
322
+ sort: { field: "expectedClose", direction: "asc" },
323
+ },
324
+ },
325
+ // A Deals tab on organisation and person pages, People on a deal, and an organisation's open
326
+ // deals in its side panel (ADR 0058).
327
+ recordTabs: {
328
+ organisationDeals: {
329
+ label: "Deals",
330
+ on: "organisation",
331
+ view: {
332
+ type: "table",
333
+ object: "deals.deal",
334
+ relation: "organisation",
335
+ columns: ["name", "stage", "value", "expectedClose", "owner", "status"],
336
+ sort: { field: "expectedClose", direction: "desc" },
337
+ },
338
+ order: 20,
339
+ },
340
+ personDeals: {
341
+ label: "Deals",
342
+ on: "person",
343
+ view: {
344
+ type: "table",
345
+ object: "deals.participant",
346
+ relation: "person",
347
+ columns: ["deal", "role", "note"],
348
+ },
349
+ order: 20,
350
+ },
351
+ dealPeople: {
352
+ label: "People",
353
+ on: "deals.deal",
354
+ view: {
355
+ type: "table",
356
+ object: "deals.participant",
357
+ relation: "deal",
358
+ columns: ["person", "role", "note"],
359
+ },
360
+ order: 10,
361
+ },
362
+ },
363
+ recordPanels: {
364
+ organisationOpenDeals: {
365
+ label: "Open deals",
366
+ on: "organisation",
367
+ view: {
368
+ type: "table",
369
+ object: "deals.deal",
370
+ relation: "organisation",
371
+ filter: { field: "status", op: "eq", value: "open" },
372
+ columns: ["name", "stage", "value"],
373
+ sort: { field: "expectedClose", direction: "asc" },
374
+ },
375
+ },
376
+ },
377
+ settings: {
378
+ defaultPipeline: {
379
+ type: "text",
380
+ label: "Default pipeline",
381
+ description: "The pipeline (by name or id) a new deal goes in when none is chosen.",
382
+ default: "New business",
383
+ },
384
+ },
385
+ dashboards: { salesOverview, pipelineHealth },
386
+ tools: { stageMetrics },
387
+ automations: dealAutomations,
388
+ });
@@ -0,0 +1,21 @@
1
+ import { z } from "@composable-os/sdk";
2
+ export declare const stageMetrics: import("@composable-os/sdk").ToolSpec<z.ZodObject<{
3
+ pipelineId: z.ZodString;
4
+ since: z.ZodOptional<z.ZodString>;
5
+ }, z.core.$strip>, z.ZodObject<{
6
+ pipelineId: z.ZodString;
7
+ stages: z.ZodArray<z.ZodObject<{
8
+ stageId: z.ZodString;
9
+ stage: z.ZodString;
10
+ type: z.ZodString;
11
+ entered: z.ZodNumber;
12
+ current: z.ZodNumber;
13
+ avgDaysInStage: z.ZodNullable<z.ZodNumber>;
14
+ avgDaysBeforeMovingOn: z.ZodNullable<z.ZodNumber>;
15
+ }, z.core.$strip>>;
16
+ velocity: z.ZodObject<{
17
+ won: z.ZodNumber;
18
+ avgDaysToWin: z.ZodNullable<z.ZodNumber>;
19
+ wonValue: z.ZodNumber;
20
+ }, z.core.$strip>;
21
+ }, z.core.$strip>>;
package/dist/tools.js ADDED
@@ -0,0 +1,90 @@
1
+ // The Deals tools. They become operations x.deals.<tool>, run in the sandbox, and call the CRM
2
+ // only through ctx.ops (here read-only SQL over the rec_* views and stage history).
3
+ import { defineTool, z } from "@composable-os/sdk";
4
+ const num = (value) => typeof value === "number" ? value : value == null ? null : Number(value);
5
+ /** Per-stage time in stage and counts, from stage history. */
6
+ const STAGE_SQL = `
7
+ SELECT h.stage_id AS stage_id, s.name AS stage, s.position AS position, s.type AS type,
8
+ count(*) AS entered,
9
+ sum(CASE WHEN h.left_at IS NULL THEN 1 ELSE 0 END) AS current,
10
+ sum(CASE WHEN h.left_at IS NOT NULL THEN 1 ELSE 0 END) AS moved_on,
11
+ avg(CASE WHEN h.left_at IS NOT NULL THEN h.days_in_stage END) AS avg_days_completed,
12
+ avg(h.days_in_stage) AS avg_days
13
+ FROM rec_stage_history h
14
+ JOIN rec_x_deals_stage s ON s.id = h.stage_id
15
+ JOIN rec_x_deals_deal d ON d.id = h.record_id
16
+ WHERE h.object_type = 'deals.deal'
17
+ AND s.pipeline = ?
18
+ AND (? IS NULL OR h.entered_at >= ?)
19
+ GROUP BY h.stage_id, s.name, s.position, s.type
20
+ ORDER BY s.position, s.name`;
21
+ /** Won deals of the pipeline: how many, how long from first stage to won, and their value. */
22
+ const VELOCITY_SQL = `
23
+ SELECT count(*) AS won, avg(julianday(w.entered_at) - julianday(f.first_entered)) AS avg_days_to_win,
24
+ coalesce(sum(d.value), 0) AS won_value
25
+ FROM rec_stage_history w
26
+ JOIN (
27
+ SELECT record_id, min(entered_at) AS first_entered FROM rec_stage_history
28
+ WHERE object_type = 'deals.deal' GROUP BY record_id
29
+ ) f ON f.record_id = w.record_id
30
+ JOIN rec_x_deals_deal d ON d.id = w.record_id
31
+ WHERE w.object_type = 'deals.deal' AND w.stage_type = 'won' AND w.left_at IS NULL
32
+ AND d.pipeline = ?
33
+ AND (? IS NULL OR w.entered_at >= ?)`;
34
+ const round = (value) => (value === null ? null : Math.round(value * 100) / 100);
35
+ export const stageMetrics = defineTool({
36
+ description: "Time in stage and velocity for a deal pipeline, from stage history: for each stage how many " +
37
+ "deals entered it, how many are in it now, and the average days deals spent in it; and for " +
38
+ "won deals how many were won, the average days from entering the pipeline to being won, and " +
39
+ "their total value. Optionally only stage entries since a date. Read-only.",
40
+ risk: "read",
41
+ input: z.object({
42
+ pipelineId: z.string().min(1).describe("The pipeline (deals.pipeline record id)"),
43
+ since: z
44
+ .string()
45
+ .regex(/^\d{4}-\d{2}-\d{2}/)
46
+ .optional()
47
+ .describe("Only count stage entries on or after this date (YYYY-MM-DD)"),
48
+ }),
49
+ output: z.object({
50
+ pipelineId: z.string(),
51
+ stages: z.array(z.object({
52
+ stageId: z.string(),
53
+ stage: z.string(),
54
+ type: z.string(),
55
+ entered: z.number(),
56
+ current: z.number(),
57
+ avgDaysInStage: z.number().nullable(),
58
+ avgDaysBeforeMovingOn: z.number().nullable(),
59
+ })),
60
+ velocity: z.object({
61
+ won: z.number(),
62
+ avgDaysToWin: z.number().nullable(),
63
+ wonValue: z.number(),
64
+ }),
65
+ }),
66
+ async handler({ pipelineId, since }, ctx) {
67
+ const params = [pipelineId, since ?? null, since ?? null];
68
+ const stages = await ctx.ops.call("query.sql", { sql: STAGE_SQL, params });
69
+ const velocity = await ctx.ops.call("query.sql", { sql: VELOCITY_SQL, params });
70
+ const v = velocity.rows[0] ?? {};
71
+ ctx.log.info("stage metrics", { pipelineId, stages: stages.rows.length });
72
+ return {
73
+ pipelineId,
74
+ stages: stages.rows.map((row) => ({
75
+ stageId: String(row.stage_id),
76
+ stage: String(row.stage),
77
+ type: String(row.type),
78
+ entered: num(row.entered) ?? 0,
79
+ current: num(row.current) ?? 0,
80
+ avgDaysInStage: round(num(row.avg_days)),
81
+ avgDaysBeforeMovingOn: round(num(row.avg_days_completed)),
82
+ })),
83
+ velocity: {
84
+ won: num(v.won) ?? 0,
85
+ avgDaysToWin: round(num(v.avg_days_to_win)),
86
+ wonValue: num(v.won_value) ?? 0,
87
+ },
88
+ };
89
+ },
90
+ });
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@composable-os/pack-deals",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.8",
4
+ "license": "FSL-1.1-ALv2",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/timoconnellaus/composable-os.git"
9
+ },
10
+ "homepage": "https://composableos.dev",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "provenance": true
14
+ },
15
+ "description": "Deals, pipelines and stages: the first shipped extension (stage 4, ADR 0026). Bundled as source into cos-runner.",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./client": {
22
+ "types": "./dist/client/index.d.ts",
23
+ "default": "./dist/client/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "dependencies": {
30
+ "@composable-os/sdk": "0.1.0-beta.8"
31
+ }
32
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.