@baack-software/baack-ts-crm 0.0.0-stage → 0.0.3
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 +201 -0
- package/README.md +74 -2
- package/dist/account.d.ts +36 -0
- package/dist/account.d.ts.map +1 -0
- package/dist/account.js +48 -0
- package/dist/account.js.map +1 -0
- package/dist/backend.d.ts +104 -0
- package/dist/backend.d.ts.map +1 -0
- package/dist/backend.js +328 -0
- package/dist/backend.js.map +1 -0
- package/dist/crm-client.d.ts +164 -0
- package/dist/crm-client.d.ts.map +1 -0
- package/dist/crm-client.js +252 -0
- package/dist/crm-client.js.map +1 -0
- package/dist/deal-order.d.ts +42 -0
- package/dist/deal-order.d.ts.map +1 -0
- package/dist/deal-order.js +80 -0
- package/dist/deal-order.js.map +1 -0
- package/dist/errors.d.ts +21 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +33 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/invoices.d.ts +53 -0
- package/dist/invoices.d.ts.map +1 -0
- package/dist/invoices.js +155 -0
- package/dist/invoices.js.map +1 -0
- package/dist/leads.d.ts +29 -0
- package/dist/leads.d.ts.map +1 -0
- package/dist/leads.js +56 -0
- package/dist/leads.js.map +1 -0
- package/dist/mock/index.d.ts +43 -0
- package/dist/mock/index.d.ts.map +1 -0
- package/dist/mock/index.js +303 -0
- package/dist/mock/index.js.map +1 -0
- package/dist/money.d.ts +29 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +82 -0
- package/dist/money.js.map +1 -0
- package/dist/period.d.ts +30 -0
- package/dist/period.d.ts.map +1 -0
- package/dist/period.js +49 -0
- package/dist/period.js.map +1 -0
- package/dist/pipeline.d.ts +36 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +58 -0
- package/dist/pipeline.js.map +1 -0
- package/dist/react/Charts.d.ts +19 -0
- package/dist/react/Charts.d.ts.map +1 -0
- package/dist/react/Charts.js +38 -0
- package/dist/react/Charts.js.map +1 -0
- package/dist/react/ChoiceCombobox.d.ts +36 -0
- package/dist/react/ChoiceCombobox.d.ts.map +1 -0
- package/dist/react/ChoiceCombobox.js +105 -0
- package/dist/react/ChoiceCombobox.js.map +1 -0
- package/dist/react/CompanyAccountView.d.ts +21 -0
- package/dist/react/CompanyAccountView.d.ts.map +1 -0
- package/dist/react/CompanyAccountView.js +27 -0
- package/dist/react/CompanyAccountView.js.map +1 -0
- package/dist/react/DashboardCards.d.ts +32 -0
- package/dist/react/DashboardCards.d.ts.map +1 -0
- package/dist/react/DashboardCards.js +38 -0
- package/dist/react/DashboardCards.js.map +1 -0
- package/dist/react/DealsBoard.d.ts +49 -0
- package/dist/react/DealsBoard.d.ts.map +1 -0
- package/dist/react/DealsBoard.js +82 -0
- package/dist/react/DealsBoard.js.map +1 -0
- package/dist/react/Details.d.ts +85 -0
- package/dist/react/Details.d.ts.map +1 -0
- package/dist/react/Details.js +268 -0
- package/dist/react/Details.js.map +1 -0
- package/dist/react/Forms.d.ts +190 -0
- package/dist/react/Forms.d.ts.map +1 -0
- package/dist/react/Forms.js +494 -0
- package/dist/react/Forms.js.map +1 -0
- package/dist/react/LeadsTable.d.ts +22 -0
- package/dist/react/LeadsTable.d.ts.map +1 -0
- package/dist/react/LeadsTable.js +79 -0
- package/dist/react/LeadsTable.js.map +1 -0
- package/dist/react/Sales.d.ts +68 -0
- package/dist/react/Sales.d.ts.map +1 -0
- package/dist/react/Sales.js +270 -0
- package/dist/react/Sales.js.map +1 -0
- package/dist/react/SidePanel.d.ts +31 -0
- package/dist/react/SidePanel.d.ts.map +1 -0
- package/dist/react/SidePanel.js +49 -0
- package/dist/react/SidePanel.js.map +1 -0
- package/dist/react/format.d.ts +28 -0
- package/dist/react/format.d.ts.map +1 -0
- package/dist/react/format.js +30 -0
- package/dist/react/format.js.map +1 -0
- package/dist/react/index.d.ts +15 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +15 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/parts.d.ts +55 -0
- package/dist/react/parts.d.ts.map +1 -0
- package/dist/react/parts.js +82 -0
- package/dist/react/parts.js.map +1 -0
- package/dist/react/pipeline-choice.d.ts +19 -0
- package/dist/react/pipeline-choice.d.ts.map +1 -0
- package/dist/react/pipeline-choice.js +39 -0
- package/dist/react/pipeline-choice.js.map +1 -0
- package/dist/react/text.d.ts +232 -0
- package/dist/react/text.d.ts.map +1 -0
- package/dist/react/text.js +229 -0
- package/dist/react/text.js.map +1 -0
- package/dist/react/ui/alert.d.ts +11 -0
- package/dist/react/ui/alert.d.ts.map +1 -0
- package/dist/react/ui/alert.js +29 -0
- package/dist/react/ui/alert.js.map +1 -0
- package/dist/react/ui/badge.d.ts +10 -0
- package/dist/react/ui/badge.d.ts.map +1 -0
- package/dist/react/ui/badge.js +26 -0
- package/dist/react/ui/badge.js.map +1 -0
- package/dist/react/ui/button.d.ts +11 -0
- package/dist/react/ui/button.d.ts.map +1 -0
- package/dist/react/ui/button.js +37 -0
- package/dist/react/ui/button.js.map +1 -0
- package/dist/react/ui/card.d.ts +12 -0
- package/dist/react/ui/card.d.ts.map +1 -0
- package/dist/react/ui/card.js +26 -0
- package/dist/react/ui/card.js.map +1 -0
- package/dist/react/ui/chart.d.ts +45 -0
- package/dist/react/ui/chart.d.ts.map +1 -0
- package/dist/react/ui/chart.js +116 -0
- package/dist/react/ui/chart.js.map +1 -0
- package/dist/react/ui/input.d.ts +4 -0
- package/dist/react/ui/input.d.ts.map +1 -0
- package/dist/react/ui/input.js +8 -0
- package/dist/react/ui/input.js.map +1 -0
- package/dist/react/ui/label.d.ts +5 -0
- package/dist/react/ui/label.d.ts.map +1 -0
- package/dist/react/ui/label.js +10 -0
- package/dist/react/ui/label.js.map +1 -0
- package/dist/react/ui/progress.d.ts +5 -0
- package/dist/react/ui/progress.d.ts.map +1 -0
- package/dist/react/ui/progress.js +10 -0
- package/dist/react/ui/progress.js.map +1 -0
- package/dist/react/ui/select.d.ts +16 -0
- package/dist/react/ui/select.d.ts.map +1 -0
- package/dist/react/ui/select.js +37 -0
- package/dist/react/ui/select.js.map +1 -0
- package/dist/react/ui/separator.d.ts +5 -0
- package/dist/react/ui/separator.d.ts.map +1 -0
- package/dist/react/ui/separator.js +10 -0
- package/dist/react/ui/separator.js.map +1 -0
- package/dist/react/ui/sheet.d.ts +15 -0
- package/dist/react/ui/sheet.d.ts.map +1 -0
- package/dist/react/ui/sheet.js +38 -0
- package/dist/react/ui/sheet.js.map +1 -0
- package/dist/react/ui/skeleton.d.ts +3 -0
- package/dist/react/ui/skeleton.d.ts.map +1 -0
- package/dist/react/ui/skeleton.js +7 -0
- package/dist/react/ui/skeleton.js.map +1 -0
- package/dist/react/ui/table.d.ts +11 -0
- package/dist/react/ui/table.d.ts.map +1 -0
- package/dist/react/ui/table.js +29 -0
- package/dist/react/ui/table.js.map +1 -0
- package/dist/react/ui/tabs.d.ts +12 -0
- package/dist/react/ui/tabs.d.ts.map +1 -0
- package/dist/react/ui/tabs.js +31 -0
- package/dist/react/ui/tabs.js.map +1 -0
- package/dist/react/views.d.ts +82 -0
- package/dist/react/views.d.ts.map +1 -0
- package/dist/react/views.js +241 -0
- package/dist/react/views.js.map +1 -0
- package/dist/sales.d.ts +82 -0
- package/dist/sales.d.ts.map +1 -0
- package/dist/sales.js +87 -0
- package/dist/sales.js.map +1 -0
- package/dist/store.d.ts +159 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +305 -0
- package/dist/store.js.map +1 -0
- package/dist/target.d.ts +22 -0
- package/dist/target.d.ts.map +1 -0
- package/dist/target.js +40 -0
- package/dist/target.js.map +1 -0
- package/dist/types.d.ts +204 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +100 -4
- package/src/account.ts +79 -0
- package/src/backend.ts +501 -0
- package/src/crm-client.ts +393 -0
- package/src/deal-order.ts +116 -0
- package/src/errors.ts +34 -0
- package/src/index.ts +13 -0
- package/src/invoices.ts +177 -0
- package/src/leads.ts +78 -0
- package/src/mock/index.ts +398 -0
- package/src/money.ts +104 -0
- package/src/period.ts +71 -0
- package/src/pipeline.ts +82 -0
- package/src/react/Charts.tsx +143 -0
- package/src/react/ChoiceCombobox.tsx +227 -0
- package/src/react/CompanyAccountView.tsx +198 -0
- package/src/react/DashboardCards.tsx +171 -0
- package/src/react/DealsBoard.tsx +344 -0
- package/src/react/Details.tsx +870 -0
- package/src/react/Forms.tsx +1486 -0
- package/src/react/LeadsTable.tsx +234 -0
- package/src/react/Sales.tsx +827 -0
- package/src/react/SidePanel.tsx +104 -0
- package/src/react/format.ts +53 -0
- package/src/react/index.ts +14 -0
- package/src/react/parts.tsx +183 -0
- package/src/react/pipeline-choice.ts +54 -0
- package/src/react/text.ts +232 -0
- package/src/react/ui/README.md +6 -0
- package/src/react/ui/alert.tsx +75 -0
- package/src/react/ui/badge.tsx +48 -0
- package/src/react/ui/button.tsx +66 -0
- package/src/react/ui/card.tsx +102 -0
- package/src/react/ui/chart.tsx +304 -0
- package/src/react/ui/input.tsx +18 -0
- package/src/react/ui/label.tsx +23 -0
- package/src/react/ui/progress.tsx +30 -0
- package/src/react/ui/select.tsx +189 -0
- package/src/react/ui/separator.tsx +27 -0
- package/src/react/ui/sheet.tsx +145 -0
- package/src/react/ui/skeleton.tsx +13 -0
- package/src/react/ui/table.tsx +113 -0
- package/src/react/ui/tabs.tsx +89 -0
- package/src/react/views.tsx +633 -0
- package/src/sales.ts +167 -0
- package/src/store.ts +528 -0
- package/src/target.ts +54 -0
- package/src/types.ts +230 -0
package/src/sales.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { addMoney, type MoneyTotals } from './money.ts';
|
|
2
|
+
import { inRange, periodChange, previousRange, type DateRange } from './period.ts';
|
|
3
|
+
import {
|
|
4
|
+
invoiceFromRemittances,
|
|
5
|
+
isCostInvoice,
|
|
6
|
+
outstandingByAge,
|
|
7
|
+
outstandingTotals,
|
|
8
|
+
overdueTotals,
|
|
9
|
+
paymentsByDay,
|
|
10
|
+
paymentsReceived,
|
|
11
|
+
type AgeBucket,
|
|
12
|
+
} from './invoices.ts';
|
|
13
|
+
import type { Invoice, Money, Remittance, RemittanceMethod } from './types.ts';
|
|
14
|
+
|
|
15
|
+
/** Totals now and in the period before, with the change in the main currency (undefined with nothing before). */
|
|
16
|
+
export interface ComparedTotals {
|
|
17
|
+
current: MoneyTotals;
|
|
18
|
+
previous: MoneyTotals;
|
|
19
|
+
change: number | undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Invoices the business pays (see `isCostInvoice`), kept out of the sales figures. */
|
|
23
|
+
export interface CostsSummary {
|
|
24
|
+
/** Cost invoices issued in the period. */
|
|
25
|
+
invoiced: ComparedTotals;
|
|
26
|
+
/** Paid on cost invoices in the period, less refunds. */
|
|
27
|
+
paid: MoneyTotals;
|
|
28
|
+
/** Still to pay now on cost invoices, and how much of it is overdue. */
|
|
29
|
+
outstanding: MoneyTotals;
|
|
30
|
+
overdue: MoneyTotals;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface SalesSummary {
|
|
34
|
+
range: DateRange;
|
|
35
|
+
/** The currency with the most money in the period, which charts and changes use. */
|
|
36
|
+
currencyCode: string | undefined;
|
|
37
|
+
/** Invoices issued in the period (not drafts or void). */
|
|
38
|
+
invoiced: ComparedTotals;
|
|
39
|
+
/** Payments received less refunds. */
|
|
40
|
+
received: ComparedTotals;
|
|
41
|
+
/** Sales tax on the invoices issued in the period. */
|
|
42
|
+
tax: ComparedTotals;
|
|
43
|
+
/** Still to pay now, and how much of it is overdue. */
|
|
44
|
+
outstanding: MoneyTotals;
|
|
45
|
+
overdue: MoneyTotals;
|
|
46
|
+
/** Draft invoices now, whenever drafted: not yet sent, so not in the other figures. */
|
|
47
|
+
drafts: { count: number; totals: MoneyTotals };
|
|
48
|
+
byDay: { day: string; totals: MoneyTotals }[];
|
|
49
|
+
byAge: { bucket: AgeBucket; totals: MoneyTotals }[];
|
|
50
|
+
byMethod: { method: RemittanceMethod; totals: MoneyTotals }[];
|
|
51
|
+
/** Invoices the business pays, apart from the sales figures above. */
|
|
52
|
+
costs: CostsSummary;
|
|
53
|
+
/** Every invoice, sales and costs, newest first, with its payment fields worked out from its remittances. */
|
|
54
|
+
invoices: Invoice[];
|
|
55
|
+
/** Every remittance, newest first. */
|
|
56
|
+
payments: Remittance[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const ISSUED = (invoice: Invoice) => invoice.status !== 'DRAFT' && invoice.status !== 'VOIDED';
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Invoices with `paid`, `refunded`, `status` and `fullyPaidTimestamp` worked out from their remittances
|
|
63
|
+
* (`invoiceFromRemittances`), so recording a payment shows on its invoice at once. Invoices without remittances
|
|
64
|
+
* keep what the API gave.
|
|
65
|
+
*/
|
|
66
|
+
export function withPayments(invoices: readonly Invoice[], remittances: readonly Remittance[]): Invoice[] {
|
|
67
|
+
const paidFor = new Set(remittances.map((remittance) => remittance.paymentInvoice.urn));
|
|
68
|
+
return invoices.map((invoice) =>
|
|
69
|
+
paidFor.has(invoice.urn) ? { ...invoice, ...invoiceFromRemittances(invoice, remittances) } : invoice,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Money received per payment method, refunds taken off, in a range. */
|
|
74
|
+
export function paymentsByMethod(
|
|
75
|
+
remittances: readonly Remittance[],
|
|
76
|
+
range?: DateRange,
|
|
77
|
+
): { method: RemittanceMethod; totals: MoneyTotals }[] {
|
|
78
|
+
const byMethod = new Map<RemittanceMethod, Remittance[]>();
|
|
79
|
+
for (const remittance of remittances) {
|
|
80
|
+
const method = remittance.remittanceMethod;
|
|
81
|
+
byMethod.set(method, [...(byMethod.get(method) ?? []), remittance]);
|
|
82
|
+
}
|
|
83
|
+
return [...byMethod].map(([method, list]) => ({ method, totals: paymentsReceived(list, range) }));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The currency with the most money across some totals. */
|
|
87
|
+
const largest = (...sets: MoneyTotals[]): string | undefined => {
|
|
88
|
+
const all: Record<string, number> = {};
|
|
89
|
+
for (const set of sets)
|
|
90
|
+
for (const [currency, minor] of Object.entries(set)) all[currency] = (all[currency] ?? 0) + Math.abs(minor);
|
|
91
|
+
return Object.entries(all).sort(([, a], [, b]) => b - a)[0]?.[0];
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** Remittances against sales invoices only, leaving out payments the business made on its costs. */
|
|
95
|
+
export function salesRemittances(
|
|
96
|
+
data: { invoices: readonly Invoice[]; remittances: readonly Remittance[] },
|
|
97
|
+
own?: ReadonlySet<string>,
|
|
98
|
+
): Remittance[] {
|
|
99
|
+
const costs = new Set(data.invoices.filter((invoice) => isCostInvoice(invoice, own)).map((invoice) => invoice.urn));
|
|
100
|
+
return data.remittances.filter((remittance) => !costs.has(remittance.paymentInvoice.urn));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Sales for a period from invoices and remittances, compared with the period before. Invoices the business pays (see
|
|
105
|
+
* `isCostInvoice`; `own` is the companies it counts as itself) are costs: summed apart, not counted as sales.
|
|
106
|
+
*/
|
|
107
|
+
export function salesSummary(
|
|
108
|
+
data: { invoices: readonly Invoice[]; remittances: readonly Remittance[] },
|
|
109
|
+
range: DateRange,
|
|
110
|
+
now = new Date(),
|
|
111
|
+
own?: ReadonlySet<string>,
|
|
112
|
+
): SalesSummary {
|
|
113
|
+
const before = previousRange(range);
|
|
114
|
+
const all = withPayments(data.invoices, data.remittances).toSorted((a, b) =>
|
|
115
|
+
(b.issuedTimestamp ?? '').localeCompare(a.issuedTimestamp ?? ''),
|
|
116
|
+
);
|
|
117
|
+
const costInvoices = all.filter((invoice) => isCostInvoice(invoice, own));
|
|
118
|
+
const invoices = all.filter((invoice) => !isCostInvoice(invoice, own));
|
|
119
|
+
const costUrns = new Set(costInvoices.map((invoice) => invoice.urn));
|
|
120
|
+
const costPayments = data.remittances.filter((remittance) => costUrns.has(remittance.paymentInvoice.urn));
|
|
121
|
+
const remittances = data.remittances.filter((remittance) => !costUrns.has(remittance.paymentInvoice.urn));
|
|
122
|
+
const issuedIn = (period: DateRange, list = invoices) =>
|
|
123
|
+
list.filter((invoice) => ISSUED(invoice) && inRange(invoice.issuedTimestamp, period));
|
|
124
|
+
const sum = (list: Invoice[], amount: (invoice: Invoice) => Money | null | undefined) =>
|
|
125
|
+
list.reduce<MoneyTotals>((totals, invoice) => addMoney(totals, amount(invoice)), {});
|
|
126
|
+
|
|
127
|
+
const invoicedNow = sum(issuedIn(range), (invoice) => invoice.total);
|
|
128
|
+
const invoicedBefore = sum(issuedIn(before), (invoice) => invoice.total);
|
|
129
|
+
const receivedNow = paymentsReceived(remittances, range);
|
|
130
|
+
const receivedBefore = paymentsReceived(remittances, before);
|
|
131
|
+
const taxNow = sum(issuedIn(range), (invoice) => invoice.tax);
|
|
132
|
+
const taxBefore = sum(issuedIn(before), (invoice) => invoice.tax);
|
|
133
|
+
const currencyCode = largest(invoicedNow, receivedNow, invoicedBefore, receivedBefore);
|
|
134
|
+
const compared = (current: MoneyTotals, previous: MoneyTotals): ComparedTotals => ({
|
|
135
|
+
current,
|
|
136
|
+
previous,
|
|
137
|
+
change: currencyCode ? periodChange(current[currencyCode] ?? 0, previous[currencyCode] ?? 0) : undefined,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
range,
|
|
142
|
+
currencyCode,
|
|
143
|
+
invoiced: compared(invoicedNow, invoicedBefore),
|
|
144
|
+
received: compared(receivedNow, receivedBefore),
|
|
145
|
+
tax: compared(taxNow, taxBefore),
|
|
146
|
+
outstanding: outstandingTotals(invoices),
|
|
147
|
+
overdue: overdueTotals(invoices, now),
|
|
148
|
+
drafts: (() => {
|
|
149
|
+
const drafts = invoices.filter((invoice) => invoice.status === 'DRAFT');
|
|
150
|
+
return { count: drafts.length, totals: sum(drafts, (invoice) => invoice.total) };
|
|
151
|
+
})(),
|
|
152
|
+
byDay: paymentsByDay(remittances, range),
|
|
153
|
+
byAge: outstandingByAge(invoices, now),
|
|
154
|
+
byMethod: paymentsByMethod(remittances, range),
|
|
155
|
+
costs: {
|
|
156
|
+
invoiced: compared(
|
|
157
|
+
sum(issuedIn(range, costInvoices), (invoice) => invoice.total),
|
|
158
|
+
sum(issuedIn(before, costInvoices), (invoice) => invoice.total),
|
|
159
|
+
),
|
|
160
|
+
paid: paymentsReceived(costPayments, range),
|
|
161
|
+
outstanding: outstandingTotals(costInvoices),
|
|
162
|
+
overdue: overdueTotals(costInvoices, now),
|
|
163
|
+
},
|
|
164
|
+
invoices: all,
|
|
165
|
+
payments: data.remittances.toSorted((a, b) => b.receivedTimestamp.localeCompare(a.receivedTimestamp)),
|
|
166
|
+
};
|
|
167
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
import type { Company } from '@baack-software/baack-ts-client';
|
|
2
|
+
import { urnOf, type RefLike } from '@baack-software/baack-ts-tasks';
|
|
3
|
+
import { companyAccount, type CompanyAccount } from './account.ts';
|
|
4
|
+
import type { DealInput, InvoiceInput, LeadInput, RemittanceInput } from './backend.ts';
|
|
5
|
+
import type {
|
|
6
|
+
ConvertOptions,
|
|
7
|
+
CrmClient,
|
|
8
|
+
InvoicePartyOptions,
|
|
9
|
+
InvoiceSaved,
|
|
10
|
+
NewInvoiceOptions,
|
|
11
|
+
NewLeadOptions,
|
|
12
|
+
} from './crm-client.ts';
|
|
13
|
+
import { CrmUnavailableError } from './errors.ts';
|
|
14
|
+
import { leadsBySource, type SourceCount } from './leads.ts';
|
|
15
|
+
import { addMoney, type MoneyTotals } from './money.ts';
|
|
16
|
+
import { inRange, periodChange, previousRange, type DateRange } from './period.ts';
|
|
17
|
+
import { dealCompany, dealOutcome, defaultPipeline, pipelineByStage, type StageSummary } from './pipeline.ts';
|
|
18
|
+
import { paymentsByDay, paymentsReceived } from './invoices.ts';
|
|
19
|
+
import { salesRemittances, salesSummary, type SalesSummary } from './sales.ts';
|
|
20
|
+
import { salesTarget, type SalesTarget } from './target.ts';
|
|
21
|
+
import {
|
|
22
|
+
CRM_CONCEPTS,
|
|
23
|
+
type ContactDetails,
|
|
24
|
+
type CrmConcept,
|
|
25
|
+
type CrmPerson,
|
|
26
|
+
type Deal,
|
|
27
|
+
type DealOutcome,
|
|
28
|
+
type Invoice,
|
|
29
|
+
type Lead,
|
|
30
|
+
type LeadOutcome,
|
|
31
|
+
type NewContact,
|
|
32
|
+
type Pipeline,
|
|
33
|
+
type PipelineStage,
|
|
34
|
+
type Remittance,
|
|
35
|
+
} from './types.ts';
|
|
36
|
+
|
|
37
|
+
export interface CrmStoreOptions {
|
|
38
|
+
/** The company whose CRM the store holds. */
|
|
39
|
+
owner: RefLike;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type LoadStatus = 'idle' | 'loading' | 'ready' | 'error';
|
|
43
|
+
|
|
44
|
+
/** How one concept loaded. `unavailable`: the API doesn't have it yet and it isn't served from sample data. */
|
|
45
|
+
export interface ConceptState {
|
|
46
|
+
status: LoadStatus | 'unavailable';
|
|
47
|
+
error?: unknown;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A snapshot of the store. Each change replaces it, so it can be compared by reference. */
|
|
51
|
+
export interface CrmStoreState {
|
|
52
|
+
/** `ready` once every concept has loaded or been found unavailable; `error` if any failed otherwise. */
|
|
53
|
+
status: LoadStatus;
|
|
54
|
+
concepts: Readonly<Record<CrmConcept, ConceptState>>;
|
|
55
|
+
leads: readonly Lead[];
|
|
56
|
+
deals: readonly Deal[];
|
|
57
|
+
pipelines: readonly Pipeline[];
|
|
58
|
+
invoices: readonly Invoice[];
|
|
59
|
+
remittances: readonly Remittance[];
|
|
60
|
+
/** Client companies made while the store was open, such as a converted lead's prospect, with their names. */
|
|
61
|
+
companies: readonly Company[];
|
|
62
|
+
/** People made while the store was open, such as a lead's new contact, with their names. */
|
|
63
|
+
people: readonly CrmPerson[];
|
|
64
|
+
/** URNs of records with a write in flight. */
|
|
65
|
+
saving: ReadonlySet<string>;
|
|
66
|
+
/** The last write the server refused, until the next write. */
|
|
67
|
+
writeError?: unknown;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type Records = Pick<CrmStoreState, CrmConcept | 'companies' | 'people'>;
|
|
71
|
+
|
|
72
|
+
const idle = Object.fromEntries(CRM_CONCEPTS.map((concept) => [concept, { status: 'idle' }])) as Record<
|
|
73
|
+
CrmConcept,
|
|
74
|
+
ConceptState
|
|
75
|
+
>;
|
|
76
|
+
|
|
77
|
+
const EMPTY: CrmStoreState = {
|
|
78
|
+
status: 'idle',
|
|
79
|
+
concepts: idle,
|
|
80
|
+
leads: [],
|
|
81
|
+
deals: [],
|
|
82
|
+
pipelines: [],
|
|
83
|
+
invoices: [],
|
|
84
|
+
remittances: [],
|
|
85
|
+
companies: [],
|
|
86
|
+
people: [],
|
|
87
|
+
saving: new Set(),
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
let pendingCount = 0;
|
|
91
|
+
|
|
92
|
+
/** The companies and people saving an invoice made, added to those held. */
|
|
93
|
+
const madeForInvoice = ({ companies, people }: Records, result: Omit<InvoiceSaved, 'invoice'>): Partial<Records> => ({
|
|
94
|
+
...(result.companies.length ? { companies: [...companies, ...result.companies] } : {}),
|
|
95
|
+
...(result.people.length ? { people: [...people, ...result.people] } : {}),
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
/** The company and person a lead's save made, added to those the store holds. */
|
|
99
|
+
const made = (
|
|
100
|
+
{ companies, people }: Records,
|
|
101
|
+
result: { company?: Company | undefined; person?: CrmPerson | undefined },
|
|
102
|
+
): Partial<Records> => ({
|
|
103
|
+
...(result.company ? { companies: [...companies, result.company] } : {}),
|
|
104
|
+
...(result.person ? { people: [...people, result.person] } : {}),
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Holds a company's CRM records for a UI: loads every concept, applies changes straight away and rolls them back if
|
|
109
|
+
* the server refuses, and notifies subscribers. `subscribe` and `getState` fit React's `useSyncExternalStore`.
|
|
110
|
+
*
|
|
111
|
+
* ```ts
|
|
112
|
+
* const store = new CrmStore(crm, { owner });
|
|
113
|
+
* store.subscribe(() => render(selectDashboard(store.getState(), lastDays(28))));
|
|
114
|
+
* await store.load();
|
|
115
|
+
* await store.moveDeal(dealUrn, stage);
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
export class CrmStore {
|
|
119
|
+
#state: CrmStoreState = EMPTY;
|
|
120
|
+
readonly #listeners = new Set<() => void>();
|
|
121
|
+
#disposed = false;
|
|
122
|
+
|
|
123
|
+
constructor(
|
|
124
|
+
readonly client: CrmClient,
|
|
125
|
+
readonly options: CrmStoreOptions,
|
|
126
|
+
) {}
|
|
127
|
+
|
|
128
|
+
getState = (): CrmStoreState => this.#state;
|
|
129
|
+
|
|
130
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
131
|
+
this.#listeners.add(listener);
|
|
132
|
+
return () => this.#listeners.delete(listener);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** Drops subscribers; answers still arriving are ignored. */
|
|
136
|
+
dispose(): void {
|
|
137
|
+
this.#disposed = true;
|
|
138
|
+
this.#listeners.clear();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
#set(next: Partial<CrmStoreState>): void {
|
|
142
|
+
if (this.#disposed) return;
|
|
143
|
+
this.#state = { ...this.#state, ...next };
|
|
144
|
+
for (const listener of this.#listeners) listener();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ==========================================
|
|
148
|
+
// LOADING
|
|
149
|
+
// ==========================================
|
|
150
|
+
|
|
151
|
+
/** Loads (or reloads) every concept at once. A concept that fails doesn't stop the others. */
|
|
152
|
+
async load(): Promise<void> {
|
|
153
|
+
const owner = urnOf(this.options.owner);
|
|
154
|
+
const loading = Object.fromEntries(CRM_CONCEPTS.map((concept) => [concept, { status: 'loading' }])) as Record<
|
|
155
|
+
CrmConcept,
|
|
156
|
+
ConceptState
|
|
157
|
+
>;
|
|
158
|
+
this.#set({ status: 'loading', concepts: loading });
|
|
159
|
+
await Promise.all(
|
|
160
|
+
CRM_CONCEPTS.map(async (concept) => {
|
|
161
|
+
try {
|
|
162
|
+
const records = await this.client[concept].list(owner);
|
|
163
|
+
this.#set({ [concept]: records, concepts: { ...this.#state.concepts, [concept]: { status: 'ready' } } });
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const status = error instanceof CrmUnavailableError ? 'unavailable' : 'error';
|
|
166
|
+
this.#set({ concepts: { ...this.#state.concepts, [concept]: { status, error } } });
|
|
167
|
+
}
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
const failed = Object.values(this.#state.concepts).some((state) => state.status === 'error');
|
|
171
|
+
this.#set({ status: failed ? 'error' : 'ready' });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ==========================================
|
|
175
|
+
// WRITES
|
|
176
|
+
// ==========================================
|
|
177
|
+
|
|
178
|
+
/** Shows `optimistic` at once, runs `write`, then shows what the server stored, or rolls back if it refuses. */
|
|
179
|
+
async #write<T>(
|
|
180
|
+
urns: string[],
|
|
181
|
+
optimistic: (records: Records) => Partial<Records>,
|
|
182
|
+
write: () => Promise<T>,
|
|
183
|
+
stored: (records: Records, result: T) => Partial<Records>,
|
|
184
|
+
): Promise<T> {
|
|
185
|
+
const before: Records = this.#records();
|
|
186
|
+
this.#set({ ...optimistic(before), saving: new Set([...this.#state.saving, ...urns]), writeError: undefined });
|
|
187
|
+
const saved = () => new Set([...this.#state.saving].filter((urn) => !urns.includes(urn)));
|
|
188
|
+
try {
|
|
189
|
+
const result = await write();
|
|
190
|
+
this.#set({ ...stored(this.#records(), result), saving: saved() });
|
|
191
|
+
return result;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
this.#set({ ...before, saving: saved(), writeError: error });
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
#records(): Records {
|
|
199
|
+
const { leads, deals, pipelines, invoices, remittances, companies, people } = this.#state;
|
|
200
|
+
return { leads, deals, pipelines, invoices, remittances, companies, people };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Creates a lead, shown at the top straight away. With `companyName` or `contact`, the prospect's company or contact
|
|
205
|
+
* is made first and linked (see `CrmClient.createLead`).
|
|
206
|
+
*/
|
|
207
|
+
async createLead(input: LeadInput, options: NewLeadOptions = {}): Promise<Lead> {
|
|
208
|
+
const temporary = `pending-${++pendingCount}`;
|
|
209
|
+
const placeholder: Lead = { ...input, urn: temporary, createdTimestamp: '' };
|
|
210
|
+
const { lead } = await this.#write(
|
|
211
|
+
[temporary],
|
|
212
|
+
({ leads }) => ({ leads: [placeholder, ...leads] }),
|
|
213
|
+
() => this.client.createLead(input, options),
|
|
214
|
+
(records, result) => ({
|
|
215
|
+
leads: records.leads.map((candidate) => (candidate.urn === temporary ? result.lead : candidate)),
|
|
216
|
+
...made(records, result),
|
|
217
|
+
}),
|
|
218
|
+
);
|
|
219
|
+
return lead;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Changes a lead, shown at once. With `companyName` or `contact`, its new company or contact is made first, as for
|
|
224
|
+
* a new lead (see `CrmClient.updateLead`).
|
|
225
|
+
*/
|
|
226
|
+
async updateLead(lead: RefLike, changes: Partial<LeadInput>, options: NewLeadOptions = {}): Promise<Lead> {
|
|
227
|
+
const urn = urnOf(lead);
|
|
228
|
+
const current = this.#state.leads.find((candidate) => candidate.urn === urn);
|
|
229
|
+
if (!current) throw new Error(`No lead ${urn} in the store`);
|
|
230
|
+
const result = await this.#write(
|
|
231
|
+
[urn],
|
|
232
|
+
({ leads }) => ({ leads: replace(leads, urn, (shown) => ({ ...shown, ...changes })) }),
|
|
233
|
+
() => this.client.updateLead(current, changes, options),
|
|
234
|
+
(records, saved) => ({ leads: replace(records.leads, urn, () => saved.lead), ...made(records, saved) }),
|
|
235
|
+
);
|
|
236
|
+
return result.lead;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A person's email and telephone, read when asked for: they aren't held in the store's state. */
|
|
240
|
+
contactDetails(identity: RefLike): Promise<ContactDetails> {
|
|
241
|
+
return this.client.contactDetails(identity);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Sets a person's email and telephone; fields left out are kept. */
|
|
245
|
+
setContactDetails(identity: RefLike, details: Partial<ContactDetails>): Promise<ContactDetails> {
|
|
246
|
+
return this.client.setContactDetails(identity, details);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Makes a person owned by the store's company: a customer's person when `company` is given. */
|
|
250
|
+
createContact(contact: NewContact, company?: RefLike | null): Promise<CrmPerson> {
|
|
251
|
+
return this.#write(
|
|
252
|
+
[],
|
|
253
|
+
() => ({}),
|
|
254
|
+
() => this.client.createContact(this.options.owner, contact, company),
|
|
255
|
+
({ people }, person) => ({ people: [...people, person] }),
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Qualifies a lead into a deal (see `CrmClient.convertLead`). Shown once the server has made the deal. */
|
|
260
|
+
async convertLead(lead: RefLike, options: ConvertOptions): Promise<{ lead: Lead; deal: Deal; company?: Company }> {
|
|
261
|
+
const urn = urnOf(lead);
|
|
262
|
+
const current = this.#state.leads.find((candidate) => candidate.urn === urn);
|
|
263
|
+
if (!current) throw new Error(`No lead ${urn} in the store`);
|
|
264
|
+
return this.#write(
|
|
265
|
+
[urn],
|
|
266
|
+
() => ({}),
|
|
267
|
+
() => this.client.convertLead(current, options),
|
|
268
|
+
({ leads, deals, companies }, result) => ({
|
|
269
|
+
leads: replace(leads, urn, () => result.lead),
|
|
270
|
+
deals: [result.deal, ...deals],
|
|
271
|
+
...(result.company ? { companies: [...companies, result.company] } : {}),
|
|
272
|
+
}),
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Moves a deal to a stage, shown at once (see `CrmClient.moveDeal`). */
|
|
277
|
+
moveDeal(deal: RefLike, stage: PipelineStage): Promise<Deal> {
|
|
278
|
+
const urn = urnOf(deal);
|
|
279
|
+
return this.#write(
|
|
280
|
+
[urn],
|
|
281
|
+
({ deals }) => ({ deals: replace(deals, urn, (current) => ({ ...current, workflowStage: { urn: stage.urn } })) }),
|
|
282
|
+
() => this.client.moveDeal(urn, stage),
|
|
283
|
+
({ deals }, moved) => ({ deals: replace(deals, urn, () => moved) }),
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Changes a deal's fields, shown at once. Moving it between stages is `moveDeal`; its outcome, `setOutcome`. */
|
|
288
|
+
updateDeal(deal: RefLike, changes: Partial<DealInput>): Promise<Deal> {
|
|
289
|
+
const urn = urnOf(deal);
|
|
290
|
+
return this.#write(
|
|
291
|
+
[urn],
|
|
292
|
+
({ deals }) => ({ deals: replace(deals, urn, (current) => ({ ...current, ...changes })) }),
|
|
293
|
+
() => this.client.deals.update(urn, changes),
|
|
294
|
+
({ deals }, stored) => ({ deals: replace(deals, urn, () => stored) }),
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Changes an invoice's own fields (status, parties, dates), shown at once, making a party's new company and person
|
|
300
|
+
* first when `options` asks (see `CrmClient.updateInvoice`). Its lines and payments aren't changed by an update, so
|
|
301
|
+
* they're kept as they were when the server's answer leaves them out or has none.
|
|
302
|
+
*/
|
|
303
|
+
async updateInvoice(
|
|
304
|
+
invoice: RefLike,
|
|
305
|
+
changes: Partial<InvoiceInput>,
|
|
306
|
+
options: InvoicePartyOptions = {},
|
|
307
|
+
): Promise<Invoice> {
|
|
308
|
+
const urn = urnOf(invoice);
|
|
309
|
+
const current = this.#state.invoices.find((candidate) => candidate.urn === urn);
|
|
310
|
+
if (!current) throw new Error(`No invoice ${urn} in the store`);
|
|
311
|
+
const result = await this.#write(
|
|
312
|
+
[urn],
|
|
313
|
+
({ invoices }) => ({ invoices: replace(invoices, urn, (shown) => ({ ...shown, ...changes })) }),
|
|
314
|
+
() => this.client.updateInvoice(current, changes, options),
|
|
315
|
+
(records, saved) => ({
|
|
316
|
+
invoices: replace(records.invoices, urn, (shown) => {
|
|
317
|
+
const lines = saved.invoice.lines?.length ? saved.invoice.lines : shown.lines;
|
|
318
|
+
const remittances = saved.invoice.remittances?.length ? saved.invoice.remittances : shown.remittances;
|
|
319
|
+
return { ...saved.invoice, ...(lines ? { lines } : {}), ...(remittances ? { remittances } : {}) };
|
|
320
|
+
}),
|
|
321
|
+
...madeForInvoice(records, saved),
|
|
322
|
+
}),
|
|
323
|
+
);
|
|
324
|
+
return result.invoice;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Wins, loses or reopens a deal, shown at once (see `CrmClient.setOutcome`). */
|
|
328
|
+
setOutcome(deal: RefLike, outcome: DealOutcome, options: { lostReason?: string } = {}): Promise<Deal> {
|
|
329
|
+
const urn = urnOf(deal);
|
|
330
|
+
return this.#write(
|
|
331
|
+
[urn],
|
|
332
|
+
({ deals }) => ({ deals: replace(deals, urn, (current) => ({ ...current, outcome })) }),
|
|
333
|
+
() => this.client.setOutcome(urn, outcome, options),
|
|
334
|
+
({ deals }, stored) => ({ deals: replace(deals, urn, () => stored) }),
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Closes a lead as unqualified or reopens it, shown at once (see `CrmClient.setLeadOutcome`). */
|
|
339
|
+
setLeadOutcome(
|
|
340
|
+
lead: RefLike,
|
|
341
|
+
outcome: Exclude<LeadOutcome, 'CONVERTED'>,
|
|
342
|
+
options: { closedReason?: string } = {},
|
|
343
|
+
): Promise<Lead> {
|
|
344
|
+
const urn = urnOf(lead);
|
|
345
|
+
return this.#write(
|
|
346
|
+
[urn],
|
|
347
|
+
({ leads }) => ({ leads: replace(leads, urn, (current) => ({ ...current, outcome })) }),
|
|
348
|
+
() => this.client.setLeadOutcome(urn, outcome, options),
|
|
349
|
+
({ leads }, stored) => ({ leads: replace(leads, urn, () => stored) }),
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Creates a deal, shown on the board straight away. */
|
|
354
|
+
createDeal(input: DealInput): Promise<Deal> {
|
|
355
|
+
const temporary = `pending-${++pendingCount}`;
|
|
356
|
+
const placeholder: Deal = { ...input, urn: temporary, createdTimestamp: '' };
|
|
357
|
+
return this.#write(
|
|
358
|
+
[temporary],
|
|
359
|
+
({ deals }) => ({ deals: [placeholder, ...deals] }),
|
|
360
|
+
() => this.client.createDeal(input),
|
|
361
|
+
({ deals }, made) => ({ deals: deals.map((candidate) => (candidate.urn === temporary ? made : candidate)) }),
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Creates an invoice with its lines, linked to `deal` when given (see `CrmClient.createInvoice`). Shown once the
|
|
367
|
+
* server has made it, as its lines are made one by one.
|
|
368
|
+
*/
|
|
369
|
+
async createInvoice(
|
|
370
|
+
input: InvoiceInput,
|
|
371
|
+
lines: Parameters<CrmClient['createInvoice']>[1] = [],
|
|
372
|
+
options: NewInvoiceOptions = {},
|
|
373
|
+
): Promise<Invoice> {
|
|
374
|
+
const { invoice } = await this.#write(
|
|
375
|
+
options.deal ? [options.deal.urn] : [],
|
|
376
|
+
() => ({}),
|
|
377
|
+
() => this.client.createInvoice(input, lines, options),
|
|
378
|
+
(records, result) => ({
|
|
379
|
+
invoices: [result.invoice, ...records.invoices],
|
|
380
|
+
...(result.deal ? { deals: replace(records.deals, result.deal.urn, () => result.deal!) } : {}),
|
|
381
|
+
...madeForInvoice(records, result),
|
|
382
|
+
}),
|
|
383
|
+
);
|
|
384
|
+
return invoice;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Records a payment or refund against an invoice. */
|
|
388
|
+
recordPayment(input: RemittanceInput): Promise<Remittance> {
|
|
389
|
+
const temporary = `pending-${++pendingCount}`;
|
|
390
|
+
return this.#write(
|
|
391
|
+
[temporary],
|
|
392
|
+
({ remittances }) => ({ remittances: [{ ...input, urn: temporary }, ...remittances] }),
|
|
393
|
+
() => this.client.recordPayment(input),
|
|
394
|
+
({ remittances }, made) => ({
|
|
395
|
+
remittances: remittances.map((candidate) => (candidate.urn === temporary ? made : candidate)),
|
|
396
|
+
}),
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function replace<T extends { urn: string }>(records: readonly T[], urn: string, change: (record: T) => T): T[] {
|
|
402
|
+
return records.map((record) => (record.urn === urn ? change(record) : record));
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// ==========================================
|
|
406
|
+
// SELECTORS
|
|
407
|
+
// ==========================================
|
|
408
|
+
|
|
409
|
+
/** A number now and in the period before, with the change between them (undefined with nothing before). */
|
|
410
|
+
export interface Compared<T> {
|
|
411
|
+
current: T;
|
|
412
|
+
previous: T;
|
|
413
|
+
change: number | undefined;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
export interface Dashboard {
|
|
417
|
+
range: DateRange;
|
|
418
|
+
/** Companies with a won deal; compared: companies whose first won deal closed in each period. */
|
|
419
|
+
customers: { total: number; added: Compared<number> };
|
|
420
|
+
/** Open deals and their value; compared: deals created in each period. */
|
|
421
|
+
openDeals: { count: number; value: MoneyTotals; created: Compared<number> };
|
|
422
|
+
/** Payments received less refunds, in each period. */
|
|
423
|
+
revenue: Compared<MoneyTotals> & { currencyCode: string | undefined };
|
|
424
|
+
/** Payments received less refunds on each day of the period. */
|
|
425
|
+
revenueByDay: { day: string; totals: MoneyTotals }[];
|
|
426
|
+
/** Leads created in each period. */
|
|
427
|
+
newLeads: Compared<number>;
|
|
428
|
+
target: SalesTarget;
|
|
429
|
+
leadsBySource: SourceCount[];
|
|
430
|
+
/** The first pipeline's stages. */
|
|
431
|
+
pipeline: StageSummary[];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const compare = (current: number, previous: number): Compared<number> => ({
|
|
435
|
+
current,
|
|
436
|
+
previous,
|
|
437
|
+
change: periodChange(current, previous),
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
/** The largest currency in a set of totals. */
|
|
441
|
+
export const mainCurrency = (totals: MoneyTotals): string | undefined =>
|
|
442
|
+
Object.entries(totals).sort(([, a], [, b]) => b - a)[0]?.[0];
|
|
443
|
+
|
|
444
|
+
/** Everything a CRM dashboard shows for a period, compared with the period before. */
|
|
445
|
+
export function selectDashboard(
|
|
446
|
+
state: CrmStoreState,
|
|
447
|
+
range: DateRange,
|
|
448
|
+
own?: ReadonlySet<string>,
|
|
449
|
+
/** The user's chosen pipeline, for the pipeline card (see `defaultPipeline`). */
|
|
450
|
+
chosenPipeline?: string,
|
|
451
|
+
): Dashboard {
|
|
452
|
+
const before = previousRange(range);
|
|
453
|
+
const { leads, deals, pipelines } = state;
|
|
454
|
+
const shownPipeline = defaultPipeline(pipelines, deals, chosenPipeline);
|
|
455
|
+
// Revenue is what customers paid: payments the business made on its costs aren't counted.
|
|
456
|
+
const remittances = salesRemittances(state, own);
|
|
457
|
+
|
|
458
|
+
const firstWins = new Map<string, string>();
|
|
459
|
+
let openValue: MoneyTotals = {};
|
|
460
|
+
let openCount = 0;
|
|
461
|
+
for (const deal of deals) {
|
|
462
|
+
const outcome = dealOutcome(deal);
|
|
463
|
+
if (outcome === 'OPEN') {
|
|
464
|
+
openCount += 1;
|
|
465
|
+
openValue = addMoney(openValue, deal.targetValue);
|
|
466
|
+
}
|
|
467
|
+
const company = dealCompany(deal)?.urn;
|
|
468
|
+
if (outcome === 'WON' && company) {
|
|
469
|
+
const closed = deal.closeTimestamp ?? deal.updatedTimestamp ?? deal.createdTimestamp;
|
|
470
|
+
const known = firstWins.get(company);
|
|
471
|
+
if (!known || closed < known) firstWins.set(company, closed);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
const count = <T>(records: Iterable<T>, when: (record: T) => string | null | undefined, period: DateRange) =>
|
|
475
|
+
[...records].filter((record) => inRange(when(record), period)).length;
|
|
476
|
+
const wins = [...firstWins.values()];
|
|
477
|
+
const current = paymentsReceived(remittances, range);
|
|
478
|
+
const previous = paymentsReceived(remittances, before);
|
|
479
|
+
const revenueCurrency = mainCurrency(current) ?? mainCurrency(previous);
|
|
480
|
+
|
|
481
|
+
return {
|
|
482
|
+
range,
|
|
483
|
+
customers: {
|
|
484
|
+
total: firstWins.size,
|
|
485
|
+
added: compare(
|
|
486
|
+
count(wins, (when) => when, range),
|
|
487
|
+
count(wins, (when) => when, before),
|
|
488
|
+
),
|
|
489
|
+
},
|
|
490
|
+
openDeals: {
|
|
491
|
+
count: openCount,
|
|
492
|
+
value: openValue,
|
|
493
|
+
created: compare(
|
|
494
|
+
count(deals, (deal) => deal.createdTimestamp, range),
|
|
495
|
+
count(deals, (deal) => deal.createdTimestamp, before),
|
|
496
|
+
),
|
|
497
|
+
},
|
|
498
|
+
revenue: {
|
|
499
|
+
current,
|
|
500
|
+
previous,
|
|
501
|
+
currencyCode: revenueCurrency,
|
|
502
|
+
change: revenueCurrency ? periodChange(current[revenueCurrency] ?? 0, previous[revenueCurrency] ?? 0) : undefined,
|
|
503
|
+
},
|
|
504
|
+
revenueByDay: paymentsByDay(remittances, range),
|
|
505
|
+
newLeads: compare(
|
|
506
|
+
count(leads, (lead) => lead.createdTimestamp, range),
|
|
507
|
+
count(leads, (lead) => lead.createdTimestamp, before),
|
|
508
|
+
),
|
|
509
|
+
target: salesTarget(leads, deals, remittances),
|
|
510
|
+
leadsBySource: leadsBySource(leads),
|
|
511
|
+
pipeline: shownPipeline ? pipelineByStage(deals, shownPipeline) : [],
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** One customer company's account from the store's records. */
|
|
516
|
+
export function selectAccount(state: CrmStoreState, company: RefLike, now = new Date()): CompanyAccount {
|
|
517
|
+
return companyAccount(urnOf(company), state, now);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** Sales for a period from the store's invoices and payments, costs apart (see `salesSummary`). */
|
|
521
|
+
export function selectSales(
|
|
522
|
+
state: CrmStoreState,
|
|
523
|
+
range: DateRange,
|
|
524
|
+
now = new Date(),
|
|
525
|
+
own?: ReadonlySet<string>,
|
|
526
|
+
): SalesSummary {
|
|
527
|
+
return salesSummary(state, range, now, own);
|
|
528
|
+
}
|