@baack-software/baack-ts-crm 0.0.7 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/leads.d.ts +25 -1
  2. package/dist/leads.d.ts.map +1 -1
  3. package/dist/leads.js +25 -0
  4. package/dist/leads.js.map +1 -1
  5. package/dist/pipeline.d.ts +25 -4
  6. package/dist/pipeline.d.ts.map +1 -1
  7. package/dist/pipeline.js +43 -4
  8. package/dist/pipeline.js.map +1 -1
  9. package/dist/react/DashboardCards.d.ts +14 -1
  10. package/dist/react/DashboardCards.d.ts.map +1 -1
  11. package/dist/react/DashboardCards.js +15 -3
  12. package/dist/react/DashboardCards.js.map +1 -1
  13. package/dist/react/Details.d.ts +3 -1
  14. package/dist/react/Details.d.ts.map +1 -1
  15. package/dist/react/Details.js +13 -5
  16. package/dist/react/Details.js.map +1 -1
  17. package/dist/react/LeadsTable.d.ts +6 -3
  18. package/dist/react/LeadsTable.d.ts.map +1 -1
  19. package/dist/react/LeadsTable.js +39 -7
  20. package/dist/react/LeadsTable.js.map +1 -1
  21. package/dist/react/format.d.ts +6 -0
  22. package/dist/react/format.d.ts.map +1 -1
  23. package/dist/react/format.js +9 -0
  24. package/dist/react/format.js.map +1 -1
  25. package/dist/react/text.d.ts +19 -0
  26. package/dist/react/text.d.ts.map +1 -1
  27. package/dist/react/text.js +19 -0
  28. package/dist/react/text.js.map +1 -1
  29. package/dist/react/views.d.ts +13 -4
  30. package/dist/react/views.d.ts.map +1 -1
  31. package/dist/react/views.js +42 -11
  32. package/dist/react/views.js.map +1 -1
  33. package/dist/store.d.ts +2 -0
  34. package/dist/store.d.ts.map +1 -1
  35. package/dist/store.js +6 -1
  36. package/dist/store.js.map +1 -1
  37. package/package.json +1 -1
  38. package/src/leads.ts +48 -1
  39. package/src/pipeline.ts +53 -6
  40. package/src/react/DashboardCards.tsx +65 -4
  41. package/src/react/Details.tsx +51 -1
  42. package/src/react/LeadsTable.tsx +42 -6
  43. package/src/react/format.ts +11 -0
  44. package/src/react/text.ts +20 -0
  45. package/src/react/views.tsx +96 -7
  46. package/src/store.ts +7 -1
@@ -1,5 +1,5 @@
1
1
  import { Download, Search } from 'lucide-react';
2
- import { useMemo, useState } from 'react';
2
+ import { useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react';
3
3
  import { toDecimal } from '../money.ts';
4
4
  import {
5
5
  LEAD_OUTCOME_LABELS,
@@ -8,6 +8,7 @@ import {
8
8
  LEAD_STATE_LABELS,
9
9
  LEAD_STATUS_LABELS,
10
10
  SOURCE_LABELS,
11
+ byLeadPriority,
11
12
  leadOutcome,
12
13
  leadState,
13
14
  type LeadState,
@@ -54,16 +55,47 @@ function download(name: string, csv: string) {
54
55
  URL.revokeObjectURL(url);
55
56
  }
56
57
 
58
+ /** Space kept below the rows for the paging line and the card's padding, in pixels. */
59
+ const ROOM_BELOW = 96;
60
+
61
+ /**
62
+ * How many rows fit between the table's top and the bottom of the window, never fewer than `minimum`: the rows on
63
+ * screen are measured for their height, and it's measured again when the window is resized. Without `fill`, or before
64
+ * there are rows to measure, it's `minimum`.
65
+ */
66
+ function useRowsThatFit(table: RefObject<HTMLTableElement | null>, minimum: number, fill: boolean, rows: number) {
67
+ const [fit, setFit] = useState(minimum);
68
+ useLayoutEffect(() => {
69
+ if (!fill) return;
70
+ const measure = () => {
71
+ const element = table.current;
72
+ const shown = Array.from(element?.tBodies[0]?.rows ?? []);
73
+ const height = shown.reduce((sum, row) => sum + row.getBoundingClientRect().height, 0) / (shown.length || 1);
74
+ if (!element || !height) return;
75
+ // From where the table starts on the page, whatever is scrolled, to the bottom of the window.
76
+ const head = element.tHead?.getBoundingClientRect().height ?? 0;
77
+ const top = element.getBoundingClientRect().top + window.scrollY + head;
78
+ setFit(Math.max(minimum, Math.floor((window.innerHeight - top - ROOM_BELOW) / height)));
79
+ };
80
+ measure();
81
+ window.addEventListener('resize', measure);
82
+ return () => window.removeEventListener('resize', measure);
83
+ }, [table, minimum, fill, rows]);
84
+ return fill ? fit : minimum;
85
+ }
86
+
57
87
  /**
58
- * Leads, newest first, filtered by words, status and source, a page at a time, with an export of the rows filtered.
59
- * `onOpen` makes each lead's title a button.
88
+ * Leads, in the order to work them (byLeadPriority), filtered by words, status and source, a page at a time, with an export of the rows filtered.
89
+ * `onOpen` makes each lead's title a button. With `fill`, a page is as many leads as fit the window's height, and
90
+ * never fewer than `pageSize`.
60
91
  */
61
92
  export function LeadsTable({
62
93
  leads,
63
94
  names,
64
95
  onOpen,
65
96
  selected,
66
- pageSize = 10,
97
+ pageSize: minimumPageSize = 10,
98
+ fill = false,
67
99
  sample,
68
100
  text,
69
101
  }: {
@@ -73,6 +105,8 @@ export function LeadsTable({
73
105
  /** The open lead, highlighted. */
74
106
  selected?: string | undefined;
75
107
  pageSize?: number;
108
+ /** Show as many leads as fit the window's height, for a page that is mostly this table. */
109
+ fill?: boolean | undefined;
76
110
  sample?: boolean | undefined;
77
111
  text?: Partial<CrmText> | undefined;
78
112
  }) {
@@ -81,6 +115,7 @@ export function LeadsTable({
81
115
  const [status, setStatus] = useState<LeadState | typeof ALL>(ALL);
82
116
  const [source, setSource] = useState<LeadSource | typeof ALL>(ALL);
83
117
  const [page, setPage] = useState(0);
118
+ const table = useRef<HTMLTableElement>(null);
84
119
 
85
120
  const filtered = useMemo(() => {
86
121
  const needle = query.trim().toLowerCase();
@@ -95,9 +130,10 @@ export function LeadsTable({
95
130
  .toLowerCase()
96
131
  .includes(needle),
97
132
  )
98
- .toSorted((a, b) => b.createdTimestamp.localeCompare(a.createdTimestamp));
133
+ .toSorted(byLeadPriority);
99
134
  }, [leads, names, query, status, source]);
100
135
 
136
+ const pageSize = useRowsThatFit(table, minimumPageSize, fill, Math.min(filtered.length, minimumPageSize));
101
137
  const pages = Math.max(1, Math.ceil(filtered.length / pageSize));
102
138
  const current = Math.min(page, pages - 1);
103
139
  const shown = filtered.slice(current * pageSize, (current + 1) * pageSize);
@@ -161,7 +197,7 @@ export function LeadsTable({
161
197
  </SelectContent>
162
198
  </Select>
163
199
  </div>
164
- <Table>
200
+ <Table ref={table}>
165
201
  <caption className="sr-only">{words.leads}</caption>
166
202
  <TableHeader>
167
203
  <TableRow>
@@ -32,6 +32,17 @@ export const formatMaybeMoney = (money: Money | null | undefined, locale = 'en-G
32
32
  money ? formatMoney(money, locale) : '-';
33
33
 
34
34
  /** A short date such as "24 Oct 2026", or a dash. */
35
+ /** A length of time in whole days, such as "12 days", for averages in a table; "-" when unknown. */
36
+ export function formatDays(
37
+ milliseconds: number | undefined,
38
+ words: { day: string; days: string; underADay: string },
39
+ ): string {
40
+ if (milliseconds === undefined) return '-';
41
+ const days = Math.round(milliseconds / 86_400_000);
42
+ if (days < 1) return words.underADay;
43
+ return `${days} ${days === 1 ? words.day : words.days}`;
44
+ }
45
+
35
46
  export function formatDate(timestamp: string | null | undefined, locale = 'en-GB'): string {
36
47
  const date = parseTimestamp(timestamp);
37
48
  return date
package/src/react/text.ts CHANGED
@@ -35,6 +35,17 @@ export const CRM_TEXT = {
35
35
  week: 'Week',
36
36
  weekOf: 'Week of',
37
37
  pipeline: 'Sales pipeline',
38
+ leadsPipeline: 'Leads pipeline',
39
+ leadsPipelineHint: 'Every lead by status: new, contacted and qualified ones still need action.',
40
+ waitingSince: 'Oldest waiting',
41
+ toNextStage: 'To next stage',
42
+ dropOff: 'Drop-off',
43
+ averageTime: 'Average time',
44
+ pipelineHint: 'Conversion assumes a deal passed every stage before its own. Average time runs from creation to now, or to close.',
45
+ leadsPipelineAgeHint: 'Average time runs from creation to now, to conversion, or to closing.',
46
+ day: 'day',
47
+ days: 'days',
48
+ underADay: 'Under a day',
38
49
  stage: 'Stage',
39
50
  workflow: 'Workflow',
40
51
  deals: 'Deals',
@@ -81,6 +92,14 @@ export const CRM_TEXT = {
81
92
  convertedTo: 'Converted to',
82
93
  created: 'Created',
83
94
  noDeals: 'No deals here.',
95
+ noDealsYet: 'No deals yet. Deals start here, or from a lead you convert.',
96
+ noPipeline: 'Deals move through the stages of a sales workflow, and this company has none yet.',
97
+ createPipeline: 'Create a sales workflow',
98
+ createPipelineHint:
99
+ 'Makes a workflow called Sales with the stages Lead, Qualified, Proposal, Negotiation and Closed. You can rename it and change its stages in Workflows.',
100
+ creatingPipeline: 'Creating...',
101
+ createPipelineFailed: "The workflow couldn't be created. Try again, or create one in Workflows.",
102
+ noPipelineAsk: 'Ask an administrator to create a sales workflow in Workflows, then add deals here.',
84
103
  account: 'Account',
85
104
  openValue: 'Open deals',
86
105
  wonValue: 'Won',
@@ -130,6 +149,7 @@ export const CRM_TEXT = {
130
149
  newCompany: 'New company',
131
150
  newCompanyHint: 'Makes the client company, owned by yours, when the lead is saved.',
132
151
  addCompany: 'Add a new company',
152
+ openCompany: 'Open company',
133
153
  companyNameRequired: 'Enter the company name.',
134
154
  noContact: 'No contact',
135
155
  newContact: 'New contact',
@@ -3,11 +3,12 @@ import { useEffect, useId, useMemo, useState, useSyncExternalStore, type ReactNo
3
3
  import { ref } from '@baack-software/baack-ts-tasks';
4
4
  import { DEAL_ORDERS, filterDeals, type DealFilter, type DealOrder } from '../deal-order.ts';
5
5
  import { periodRange, type DateRange, type ReportingPeriod } from '../period.ts';
6
- import { pipelineOf } from '../pipeline.ts';
6
+ import { leadsByState } from '../leads.ts';
7
+ import { DEFAULT_SALES_PIPELINE, pipelineOf } from '../pipeline.ts';
7
8
  import { selectAccount, selectDashboard, selectSales, type CrmStore, type CrmStoreState } from '../store.ts';
8
9
  import type { CrmConcept, Deal, DealOutcome, Invoice, Lead, PipelineStage } from '../types.ts';
9
10
  import { LeadsBySourceCard, RevenueChart, TimelineCard } from './Charts.tsx';
10
- import { MetricCards, PipelineCard, TargetCard } from './DashboardCards.tsx';
11
+ import { LeadsPipelineCard, MetricCards, PipelineCard, TargetCard } from './DashboardCards.tsx';
11
12
  import { DealFilters, DealsBoard } from './DealsBoard.tsx';
12
13
  import { DealDetail, LeadDetail, type ContactDetailsAccess } from './Details.tsx';
13
14
  import { CompanyAccountView } from './CompanyAccountView.tsx';
@@ -31,7 +32,7 @@ import {
31
32
  } from './Forms.tsx';
32
33
  import { recallDeals, rememberDeals, usePipeline } from './pipeline-choice.ts';
33
34
  import { SidePanelLayout, recordItemId } from './SidePanel.tsx';
34
- import { PeriodSelect, SampleDataNotice, periodText } from './parts.tsx';
35
+ import { CrmCard, PeriodSelect, SampleDataNotice, periodText } from './parts.tsx';
35
36
  import { withText, type CrmText } from './text.ts';
36
37
  import { Alert, AlertDescription, AlertTitle } from './ui/alert.tsx';
37
38
  import { Label } from './ui/label.tsx';
@@ -141,6 +142,55 @@ const currencyOf = (state: CrmStoreState): string =>
141
142
  [...state.deals, ...state.leads].find((record) => record.targetValue)?.targetValue?.currencyCode ??
142
143
  'GBP';
143
144
 
145
+ /**
146
+ * The first step of a new deal for a company with no sales workflow: why it needs one, and a button to create the
147
+ * default one (`onCreate`), after which the panel goes on to the new deal's form. Without `onCreate`, who to ask.
148
+ */
149
+ function NoPipelineStep({
150
+ onCreate,
151
+ text,
152
+ }: {
153
+ onCreate?: (() => Promise<void>) | undefined;
154
+ text?: Partial<CrmText> | undefined;
155
+ }) {
156
+ const words = withText(text);
157
+ const [pending, setPending] = useState(false);
158
+ const [failed, setFailed] = useState(false);
159
+ const create = async () => {
160
+ setPending(true);
161
+ setFailed(false);
162
+ try {
163
+ await onCreate?.();
164
+ } catch {
165
+ setFailed(true);
166
+ } finally {
167
+ setPending(false);
168
+ }
169
+ };
170
+ return (
171
+ <div className="grid gap-3 text-sm">
172
+ <p>{words.noPipeline}</p>
173
+ {onCreate ? (
174
+ <>
175
+ <p className="text-muted-foreground">{words.createPipelineHint}</p>
176
+ <div>
177
+ <Button onClick={() => void create()} disabled={pending}>
178
+ {pending ? words.creatingPipeline : words.createPipeline}
179
+ </Button>
180
+ </div>
181
+ {failed && (
182
+ <p role="alert" className="text-destructive">
183
+ {words.createPipelineFailed}
184
+ </p>
185
+ )}
186
+ </>
187
+ ) : (
188
+ <p className="text-muted-foreground">{words.noPipelineAsk}</p>
189
+ )}
190
+ </div>
191
+ );
192
+ }
193
+
144
194
  /**
145
195
  * "New ...": opens the form in the side panel, in place of a record. Its id is the panel's, so closing the form
146
196
  * returns focus to it.
@@ -160,7 +210,7 @@ function NewButton({ panel, label, onClick }: { panel: string; label: string; on
160
210
  * The CRM dashboard for a period: `range`, else the one picked (the last 30 days to start with), with figures against
161
211
  * the period before, then from realised revenue back up the funnel: revenue over time with what's overdue, the target
162
212
  * with the new deals that make it up, the pipeline, leads by source and over time beside the host's tasks panel, and
163
- * the leads table. Cards in a row share its height.
213
+ * the leads pipeline: every lead by status, with those still to action first. Cards in a row share its height.
164
214
  */
165
215
  export function CrmDashboard({
166
216
  store,
@@ -169,18 +219,19 @@ export function CrmDashboard({
169
219
  range,
170
220
  ownCompanies,
171
221
  tasks,
172
- onOpenLead,
173
222
  }: ViewProps & {
174
223
  range?: DateRange | undefined;
175
224
  /** The companies the business counts as itself (the owner and its child companies), to leave its costs out. */
176
225
  ownCompanies?: readonly string[] | undefined;
177
226
  /** The host's tasks panel, such as baack-ts-tasks' TasksAbout. */
178
227
  tasks?: ReactNode;
228
+ /** @deprecated The dashboard no longer lists leads (the leads pipeline replaced the table): not called. */
179
229
  onOpenLead?: ((lead: Lead) => void) | undefined;
180
230
  }) {
181
231
  const state = useCrmStore(store);
182
232
  names = useCrmNames(names, state);
183
233
  const words = withText(text);
234
+ const leadStates = useMemo(() => leadsByState(state.leads, state.deals), [state.leads, state.deals]);
184
235
  const [picked, setPicked] = useState<ReportingPeriod>('last30');
185
236
  const period = useMemo(() => range ?? periodRange(picked), [range, picked]);
186
237
  const ownKey = ownCompanies?.join(',');
@@ -242,7 +293,7 @@ export function CrmDashboard({
242
293
  ) : (
243
294
  <div className="grid gap-6 lg:grid-cols-2">{leadCharts}</div>
244
295
  )}
245
- <LeadsTable leads={state.leads} names={names} onOpen={onOpenLead} text={text} />
296
+ <LeadsPipelineCard states={leadStates} text={text} />
246
297
  </div>
247
298
  );
248
299
  }
@@ -258,6 +309,7 @@ export function CrmLeadsView({
258
309
  selected,
259
310
  onSelect,
260
311
  onConverted,
312
+ onOpenCompany,
261
313
  }: ViewProps & {
262
314
  /** People a lead's contact can be chosen from: the host's customers' people. */
263
315
  people?: readonly CrmPersonChoice[] | undefined;
@@ -267,6 +319,8 @@ export function CrmLeadsView({
267
319
  onSelect?: ((lead: Lead | undefined) => void) | undefined;
268
320
  /** After a lead becomes a deal, for example to open the deal. */
269
321
  onConverted?: ((deal: Deal) => void) | undefined;
322
+ /** Opens a lead's company's own page in the host: the open lead's company is then a link. */
323
+ onOpenCompany?: ((company: string) => void) | undefined;
270
324
  }) {
271
325
  const state = useCrmStore(store);
272
326
  names = useCrmNames(names, state);
@@ -322,6 +376,7 @@ export function CrmLeadsView({
322
376
  text={text}
323
377
  converting={state.saving.has(lead.urn)}
324
378
  contactDetails={contactDetails}
379
+ onOpenCompany={onOpenCompany}
325
380
  onSetOutcome={(closing, outcome, closedReason) =>
326
381
  void store
327
382
  .setLeadOutcome(closing, outcome, closedReason === undefined ? {} : { closedReason })
@@ -341,7 +396,7 @@ export function CrmLeadsView({
341
396
  )
342
397
  }
343
398
  >
344
- <LeadsTable leads={state.leads} names={names} onOpen={select} selected={lead?.urn} text={text} />
399
+ <LeadsTable leads={state.leads} names={names} onOpen={select} selected={lead?.urn} text={text} fill />
345
400
  </SidePanelLayout>
346
401
  </div>
347
402
  );
@@ -372,6 +427,7 @@ export function CrmDealsView({
372
427
  team = [],
373
428
  selected,
374
429
  onSelect,
430
+ onCreatePipeline,
375
431
  }: ViewProps & {
376
432
  /** People a deal's contact can be chosen from: the host's customers' people. */
377
433
  people?: readonly CrmPersonChoice[] | undefined;
@@ -379,6 +435,11 @@ export function CrmDealsView({
379
435
  team?: readonly CrmPersonChoice[] | undefined;
380
436
  selected?: string | undefined;
381
437
  onSelect?: ((deal: Deal | undefined) => void) | undefined;
438
+ /**
439
+ * Creates the company's sales workflow (DEFAULT_SALES_PIPELINE), for a company with none, as the host makes
440
+ * workflows. The pipelines are read again after it. Without it, a company with no workflow is asked to make one.
441
+ */
442
+ onCreatePipeline?: ((pipeline: typeof DEFAULT_SALES_PIPELINE) => Promise<unknown>) | undefined;
382
443
  }) {
383
444
  const state = useCrmStore(store);
384
445
  names = useCrmNames(names, state);
@@ -429,6 +490,34 @@ export function CrmDealsView({
429
490
  <div className="grid gap-6">
430
491
  <Sample store={store} concepts={['deals', 'pipelines']} text={text} />
431
492
  <Problems state={state} concepts={['deals', 'pipelines']} text={words} />
493
+ {!pipeline && (
494
+ // No workflow yet: the same page as with one, empty, and "New deal" first makes the sales workflow.
495
+ <>
496
+ <NewButton panel="new-deal" label={words.newDeal} onClick={() => setCreating(true)} />
497
+ <SidePanelLayout
498
+ open={creating ? 'new-deal' : undefined}
499
+ title={words.newDeal}
500
+ onClose={() => setCreating(false)}
501
+ text={text}
502
+ panel={
503
+ <NoPipelineStep
504
+ onCreate={
505
+ onCreatePipeline &&
506
+ (async () => {
507
+ await onCreatePipeline(DEFAULT_SALES_PIPELINE);
508
+ await store.reloadPipelines();
509
+ })
510
+ }
511
+ text={text}
512
+ />
513
+ }
514
+ >
515
+ <CrmCard title={words.deals} text={text}>
516
+ <p className="text-muted-foreground text-sm">{words.noDealsYet}</p>
517
+ </CrmCard>
518
+ </SidePanelLayout>
519
+ </>
520
+ )}
432
521
  {pipeline && (
433
522
  <div className="flex flex-wrap items-end justify-between gap-3">
434
523
  {state.pipelines.length > 1 ? (
package/src/store.ts CHANGED
@@ -149,6 +149,12 @@ export class CrmStore {
149
149
  // LOADING
150
150
  // ==========================================
151
151
 
152
+ /** Reads the pipelines again, such as after the host creates a workflow, leaving the other concepts as they are. */
153
+ async reloadPipelines(): Promise<void> {
154
+ const pipelines = await this.client.pipelines.list(urnOf(this.options.owner));
155
+ this.#set({ pipelines, concepts: { ...this.#state.concepts, pipelines: { status: 'ready' } } });
156
+ }
157
+
152
158
  /** Loads (or reloads) every concept at once. A concept that fails doesn't stop the others. */
153
159
  async load(): Promise<void> {
154
160
  const owner = urnOf(this.options.owner);
@@ -525,7 +531,7 @@ export function selectDashboard(
525
531
  (deal) => deal.targetValue,
526
532
  ),
527
533
  leadsBySource: leadsBySource(leads),
528
- pipeline: shownPipeline ? pipelineByStage(deals, shownPipeline) : [],
534
+ pipeline: shownPipeline ? pipelineByStage(deals, shownPipeline, now) : [],
529
535
  };
530
536
  }
531
537