@baack-software/baack-ts-crm 0.0.0-stage → 0.0.2
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 +76 -0
- package/dist/backend.d.ts.map +1 -0
- package/dist/backend.js +233 -0
- package/dist/backend.js.map +1 -0
- package/dist/crm-client.d.ts +122 -0
- package/dist/crm-client.d.ts.map +1 -0
- package/dist/crm-client.js +168 -0
- package/dist/crm-client.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 +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/invoices.d.ts +46 -0
- package/dist/invoices.d.ts.map +1 -0
- package/dist/invoices.js +137 -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 +17 -0
- package/dist/period.d.ts.map +1 -0
- package/dist/period.js +23 -0
- package/dist/period.js.map +1 -0
- package/dist/pipeline.d.ts +30 -0
- package/dist/pipeline.d.ts.map +1 -0
- package/dist/pipeline.js +40 -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/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 +30 -0
- package/dist/react/DealsBoard.d.ts.map +1 -0
- package/dist/react/DealsBoard.js +33 -0
- package/dist/react/DealsBoard.js.map +1 -0
- package/dist/react/Details.d.ts +52 -0
- package/dist/react/Details.d.ts.map +1 -0
- package/dist/react/Details.js +111 -0
- package/dist/react/Details.js.map +1 -0
- package/dist/react/Forms.d.ts +59 -0
- package/dist/react/Forms.d.ts.map +1 -0
- package/dist/react/Forms.js +204 -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 +49 -0
- package/dist/react/Sales.d.ts.map +1 -0
- package/dist/react/Sales.js +186 -0
- package/dist/react/Sales.js.map +1 -0
- package/dist/react/SidePanel.d.ts +21 -0
- package/dist/react/SidePanel.d.ts.map +1 -0
- package/dist/react/SidePanel.js +37 -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 +14 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +14 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/parts.d.ts +45 -0
- package/dist/react/parts.d.ts.map +1 -0
- package/dist/react/parts.js +59 -0
- package/dist/react/parts.js.map +1 -0
- package/dist/react/text.d.ts +145 -0
- package/dist/react/text.d.ts.map +1 -0
- package/dist/react/text.js +142 -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 +60 -0
- package/dist/react/views.d.ts.map +1 -0
- package/dist/react/views.js +172 -0
- package/dist/react/views.js.map +1 -0
- package/dist/sales.d.ts +57 -0
- package/dist/sales.d.ts.map +1 -0
- package/dist/sales.js +64 -0
- package/dist/sales.js.map +1 -0
- package/dist/store.d.ts +140 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +244 -0
- package/dist/store.js.map +1 -0
- package/dist/target.d.ts +21 -0
- package/dist/target.d.ts.map +1 -0
- package/dist/target.js +36 -0
- package/dist/target.js.map +1 -0
- package/dist/types.d.ts +180 -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 +371 -0
- package/src/crm-client.ts +250 -0
- package/src/errors.ts +34 -0
- package/src/index.ts +12 -0
- package/src/invoices.ts +157 -0
- package/src/leads.ts +78 -0
- package/src/mock/index.ts +398 -0
- package/src/money.ts +104 -0
- package/src/period.ts +32 -0
- package/src/pipeline.ts +61 -0
- package/src/react/Charts.tsx +143 -0
- package/src/react/CompanyAccountView.tsx +198 -0
- package/src/react/DashboardCards.tsx +171 -0
- package/src/react/DealsBoard.tsx +177 -0
- package/src/react/Details.tsx +293 -0
- package/src/react/Forms.tsx +619 -0
- package/src/react/LeadsTable.tsx +234 -0
- package/src/react/Sales.tsx +539 -0
- package/src/react/SidePanel.tsx +95 -0
- package/src/react/format.ts +53 -0
- package/src/react/index.ts +13 -0
- package/src/react/parts.tsx +131 -0
- package/src/react/text.ts +144 -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 +443 -0
- package/src/sales.ts +120 -0
- package/src/store.ts +419 -0
- package/src/target.ts +51 -0
- package/src/types.ts +202 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import type { BaackClient, Company } from '@baack-software/baack-ts-client';
|
|
2
|
+
import { ref, toTimestamp, urnOf, type RefLike } from '@baack-software/baack-ts-tasks';
|
|
3
|
+
import { companyAccount, type CompanyAccount } from './account.ts';
|
|
4
|
+
import {
|
|
5
|
+
apiBackend,
|
|
6
|
+
type CrmBackend,
|
|
7
|
+
type DealInput,
|
|
8
|
+
type InvoiceInput,
|
|
9
|
+
type InvoiceLineInput,
|
|
10
|
+
type LeadInput,
|
|
11
|
+
type RemittanceInput,
|
|
12
|
+
} from './backend.ts';
|
|
13
|
+
import { orderedStages, pipelineOf } from './pipeline.ts';
|
|
14
|
+
import {
|
|
15
|
+
CRM_CONCEPTS,
|
|
16
|
+
type CrmConcept,
|
|
17
|
+
type Deal,
|
|
18
|
+
type DealOutcome,
|
|
19
|
+
type Invoice,
|
|
20
|
+
type Lead,
|
|
21
|
+
type LeadOutcome,
|
|
22
|
+
type Pipeline,
|
|
23
|
+
type PipelineStage,
|
|
24
|
+
} from './types.ts';
|
|
25
|
+
|
|
26
|
+
/** Where a concept's records come from: the Baack API, or sample data while the API doesn't have it. */
|
|
27
|
+
export type CrmSource = 'api' | 'sample';
|
|
28
|
+
|
|
29
|
+
export interface CrmClientOptions {
|
|
30
|
+
client: BaackClient;
|
|
31
|
+
/**
|
|
32
|
+
* Concepts served from sample data, with the backend holding it (usually `memoryBackend(sampleCrm(...))` from
|
|
33
|
+
* `@baack-software/baack-ts-crm/mock`). The rest come from the API.
|
|
34
|
+
*/
|
|
35
|
+
sample?: { backend: CrmBackend; concepts: readonly CrmConcept[] | 'all' };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ConvertOptions {
|
|
39
|
+
/** The new deal's pipeline. It starts at the first open stage. */
|
|
40
|
+
pipeline: Pipeline;
|
|
41
|
+
/** Defaults to the lead's title. */
|
|
42
|
+
title?: string;
|
|
43
|
+
/** Defaults to the lead's target value. */
|
|
44
|
+
targetValue?: Deal['targetValue'];
|
|
45
|
+
/**
|
|
46
|
+
* The client company's name when the lead has no contact company yet, as confirmed on qualifying: the company is
|
|
47
|
+
* made and linked to the lead and the deal. Empty or absent converts without a company, as for a consumer.
|
|
48
|
+
*/
|
|
49
|
+
companyName?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface NewLeadOptions {
|
|
53
|
+
/**
|
|
54
|
+
* The prospect's business name when it isn't a company in Baack yet: the company is made first, owned by the lead's
|
|
55
|
+
* owner, and linked as the lead's contact company, since a lead holds a business by its company.
|
|
56
|
+
*/
|
|
57
|
+
companyName?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* CRM records for a company, each concept from the API or from sample data (see `CrmClientOptions.sample`), so views
|
|
62
|
+
* can be built and reviewed before the API has every concept. Moving a concept to the API changes the options, not
|
|
63
|
+
* the code using this client.
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* const crm = createCrmClient({ client, sample: { backend: memoryBackend(sampleCrm({ owner })), concepts: 'all' } });
|
|
67
|
+
* const leads = await crm.leads.list(owner);
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export class CrmClient {
|
|
71
|
+
readonly companies: CrmBackend['companies'];
|
|
72
|
+
readonly leads: CrmBackend['leads'];
|
|
73
|
+
readonly deals: CrmBackend['deals'];
|
|
74
|
+
readonly pipelines: CrmBackend['pipelines'];
|
|
75
|
+
readonly invoices: CrmBackend['invoices'];
|
|
76
|
+
readonly invoiceLines: CrmBackend['invoiceLines'];
|
|
77
|
+
readonly remittances: CrmBackend['remittances'];
|
|
78
|
+
|
|
79
|
+
constructor(
|
|
80
|
+
backend: CrmBackend,
|
|
81
|
+
/** Where each concept comes from, so views can mark sample data. */
|
|
82
|
+
readonly sources: Readonly<Record<CrmConcept, CrmSource>>,
|
|
83
|
+
) {
|
|
84
|
+
this.companies = backend.companies;
|
|
85
|
+
this.leads = backend.leads;
|
|
86
|
+
this.deals = backend.deals;
|
|
87
|
+
this.pipelines = backend.pipelines;
|
|
88
|
+
this.invoices = backend.invoices;
|
|
89
|
+
this.invoiceLines = backend.invoiceLines;
|
|
90
|
+
this.remittances = backend.remittances;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Whether any of these concepts come from sample data. */
|
|
94
|
+
isSample(...concepts: CrmConcept[]): boolean {
|
|
95
|
+
return concepts.some((concept) => this.sources[concept] === 'sample');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Qualifies a lead into a deal: creates the deal (open, with the lead's company, contact and target value, at the
|
|
100
|
+
* pipeline's first stage, with the lead as its `leadSource`), then marks the lead converted. A lead without a contact
|
|
101
|
+
* company gets one first when `companyName` is given, owned by the lead's owner and linked to the lead too, so the
|
|
102
|
+
* deal shows on the customer's page. A consumer's lead (a person, no business) converts without a company.
|
|
103
|
+
*/
|
|
104
|
+
async convertLead(lead: Lead, options: ConvertOptions): Promise<{ lead: Lead; deal: Deal; company?: Company }> {
|
|
105
|
+
const first = orderedStages(options.pipeline)[0];
|
|
106
|
+
const name = options.companyName?.trim();
|
|
107
|
+
// TODO: search the owner's companies first so people can pick one rather than make a duplicate (TODO.md).
|
|
108
|
+
const company = !lead.contactCompany && name ? await this.companies.create({ owner: lead.owner, name }) : undefined;
|
|
109
|
+
const companyRef = lead.contactCompany ? ref(lead.contactCompany) : company ? ref(company) : null;
|
|
110
|
+
const input: DealInput = {
|
|
111
|
+
owner: ref(lead.owner),
|
|
112
|
+
title: options.title ?? lead.title,
|
|
113
|
+
contactCompanies: companyRef ? [companyRef] : [],
|
|
114
|
+
contactIdentities: lead.contactIdentity ? [ref(lead.contactIdentity)] : [],
|
|
115
|
+
workflowStage: first ? ref(first) : null,
|
|
116
|
+
outcome: 'OPEN',
|
|
117
|
+
targetValue: options.targetValue ?? lead.targetValue ?? null,
|
|
118
|
+
assignee: lead.assignee ? ref(lead.assignee) : null,
|
|
119
|
+
leadSource: ref(lead),
|
|
120
|
+
invoices: [],
|
|
121
|
+
};
|
|
122
|
+
const deal = await this.deals.create(input);
|
|
123
|
+
const converted = await this.leads.update(lead, {
|
|
124
|
+
status: 'QUALIFIED',
|
|
125
|
+
outcome: 'CONVERTED',
|
|
126
|
+
...(company ? { contactCompany: ref(company) } : {}),
|
|
127
|
+
});
|
|
128
|
+
return { lead: converted, deal, ...(company ? { company } : {}) };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Moves a deal to a stage of its pipeline. Stages are only progress: winning or losing is `setOutcome`. */
|
|
132
|
+
moveDeal(deal: RefLike, stage: PipelineStage): Promise<Deal> {
|
|
133
|
+
return this.deals.update(deal, { workflowStage: ref(stage) });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Wins, loses or reopens a deal. Won or lost closes it now (`closeTimestamp`); reopening clears the close time and
|
|
138
|
+
* reason. `lostReason` is kept only when the deal is lost.
|
|
139
|
+
*/
|
|
140
|
+
setOutcome(deal: RefLike, outcome: DealOutcome, options: { lostReason?: string; now?: Date } = {}): Promise<Deal> {
|
|
141
|
+
const closed = outcome !== 'OPEN';
|
|
142
|
+
return this.deals.update(deal, {
|
|
143
|
+
outcome,
|
|
144
|
+
closeTimestamp: closed ? toTimestamp(options.now ?? new Date()) : null,
|
|
145
|
+
lostReason: outcome === 'LOST' ? options.lostReason?.trim() || null : null,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Closes a lead as unqualified (with why), or reopens it, as `setOutcome` does for deals. Converting is
|
|
151
|
+
* `convertLead`, which also makes the deal. A lead has no close time of its own: its `updatedTimestamp` says when.
|
|
152
|
+
*/
|
|
153
|
+
setLeadOutcome(
|
|
154
|
+
lead: RefLike,
|
|
155
|
+
outcome: Exclude<LeadOutcome, 'CONVERTED'>,
|
|
156
|
+
options: { closedReason?: string } = {},
|
|
157
|
+
): Promise<Lead> {
|
|
158
|
+
const closed = outcome === 'CLOSED';
|
|
159
|
+
return this.leads.update(lead, {
|
|
160
|
+
outcome,
|
|
161
|
+
closedReason: closed ? options.closedReason?.trim() || null : null,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Creates a deal, for example one that didn't start as a lead. */
|
|
166
|
+
createDeal(input: DealInput): Promise<Deal> {
|
|
167
|
+
return this.deals.create(input);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Creates an invoice, then its lines (numbered in order), then links it to `deal` when given, as deals hold their
|
|
172
|
+
* invoices. The invoice's amounts are as given: the API doesn't add them up from the lines. Returns it read back, with
|
|
173
|
+
* its lines, and the deal as updated.
|
|
174
|
+
*/
|
|
175
|
+
async createInvoice(
|
|
176
|
+
input: InvoiceInput,
|
|
177
|
+
lines: readonly Omit<InvoiceLineInput, 'paymentInvoice' | 'lineNumber'>[] = [],
|
|
178
|
+
options: { deal?: Deal } = {},
|
|
179
|
+
): Promise<{ invoice: Invoice; deal?: Deal }> {
|
|
180
|
+
const created = await this.invoices.create(input);
|
|
181
|
+
for (const [index, line] of lines.entries()) {
|
|
182
|
+
await this.invoiceLines.create({ ...line, lineNumber: index + 1, paymentInvoice: ref(created) });
|
|
183
|
+
}
|
|
184
|
+
const deal = options.deal
|
|
185
|
+
? await this.deals.update(options.deal, { invoices: [...options.deal.invoices, ref(created)] })
|
|
186
|
+
: undefined;
|
|
187
|
+
const invoice = await this.invoices.get(created);
|
|
188
|
+
return { invoice, ...(deal ? { deal } : {}) };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Records a payment (or refund) received against an invoice. */
|
|
192
|
+
recordPayment(input: RemittanceInput) {
|
|
193
|
+
return this.remittances.create(input);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Creates a lead. With `companyName` and no contact company, the prospect's company is made first and linked, and
|
|
198
|
+
* returned with the lead.
|
|
199
|
+
*/
|
|
200
|
+
async createLead(input: LeadInput, options: NewLeadOptions = {}): Promise<{ lead: Lead; company?: Company }> {
|
|
201
|
+
const name = options.companyName?.trim()
|
|
202
|
+
const company =
|
|
203
|
+
!input.contactCompany && name ? await this.companies.create({ owner: input.owner, name }) : undefined;
|
|
204
|
+
const lead = await this.leads.create(company ? { ...input, contactCompany: ref(company) } : input);
|
|
205
|
+
return { lead, ...(company ? { company } : {}) };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Everything the CRM holds about one customer company of `owner`. */
|
|
209
|
+
async companyAccount(owner: RefLike, company: RefLike, now = new Date()): Promise<CompanyAccount> {
|
|
210
|
+
const [leads, deals, pipelines, invoices, remittances] = await Promise.all([
|
|
211
|
+
this.leads.list(owner),
|
|
212
|
+
this.deals.list(owner),
|
|
213
|
+
this.pipelines.list(owner),
|
|
214
|
+
this.invoices.list(owner),
|
|
215
|
+
this.remittances.list(owner),
|
|
216
|
+
]);
|
|
217
|
+
return companyAccount(urnOf(company), { leads, deals, pipelines, invoices, remittances }, now);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The pipeline a deal is in, among the owner's. */
|
|
221
|
+
async pipelineFor(deal: Deal): Promise<Pipeline | undefined> {
|
|
222
|
+
return pipelineOf(deal, await this.pipelines.list(deal.owner));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** A CrmClient over the Baack API, with the concepts named in `sample` served from sample data instead. */
|
|
227
|
+
export function createCrmClient({ client, sample }: CrmClientOptions): CrmClient {
|
|
228
|
+
const api = apiBackend(client);
|
|
229
|
+
const fromSample = (concept: CrmConcept) =>
|
|
230
|
+
sample !== undefined && (sample.concepts === 'all' || sample.concepts.includes(concept));
|
|
231
|
+
const pick = <K extends CrmConcept>(concept: K): CrmBackend[K] =>
|
|
232
|
+
fromSample(concept) ? sample!.backend[concept] : api[concept];
|
|
233
|
+
// Companies are made for leads, so they come from wherever the leads do: sample leads never make real companies.
|
|
234
|
+
const sources = Object.fromEntries(
|
|
235
|
+
CRM_CONCEPTS.map((concept) => [concept, fromSample(concept) ? 'sample' : 'api']),
|
|
236
|
+
) as Record<CrmConcept, CrmSource>;
|
|
237
|
+
return new CrmClient(
|
|
238
|
+
{
|
|
239
|
+
companies: fromSample('leads') ? sample!.backend.companies : api.companies,
|
|
240
|
+
leads: pick('leads'),
|
|
241
|
+
deals: pick('deals'),
|
|
242
|
+
pipelines: pick('pipelines'),
|
|
243
|
+
invoices: pick('invoices'),
|
|
244
|
+
// Lines are made with their invoices, so they come from wherever the invoices do.
|
|
245
|
+
invoiceLines: fromSample('invoices') ? sample!.backend.invoiceLines : api.invoiceLines,
|
|
246
|
+
remittances: pick('remittances'),
|
|
247
|
+
},
|
|
248
|
+
sources,
|
|
249
|
+
);
|
|
250
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { CrmConcept } from './types.ts';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The Baack API doesn't offer this yet (leads, deals, remittances, listing invoices). Serve the concept from sample
|
|
5
|
+
* data (see `createCrmClient`) until it does.
|
|
6
|
+
*/
|
|
7
|
+
export class CrmUnavailableError extends Error {
|
|
8
|
+
constructor(
|
|
9
|
+
readonly concept: CrmConcept,
|
|
10
|
+
readonly operation: string,
|
|
11
|
+
) {
|
|
12
|
+
super(`The Baack API can't ${operation} ${concept} yet: serve them from sample data`);
|
|
13
|
+
this.name = 'CrmUnavailableError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A record asked for by URN isn't there. */
|
|
18
|
+
export class CrmNotFoundError extends Error {
|
|
19
|
+
constructor(
|
|
20
|
+
readonly concept: CrmConcept,
|
|
21
|
+
readonly urn: string,
|
|
22
|
+
) {
|
|
23
|
+
super(`No ${concept} record ${urn}`);
|
|
24
|
+
this.name = 'CrmNotFoundError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A search didn't finish in time. */
|
|
29
|
+
export class CrmSearchTimeoutError extends Error {
|
|
30
|
+
constructor() {
|
|
31
|
+
super("The search didn't finish in time");
|
|
32
|
+
this.name = 'CrmSearchTimeoutError';
|
|
33
|
+
}
|
|
34
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export * from './types.ts';
|
|
2
|
+
export * from './money.ts';
|
|
3
|
+
export * from './period.ts';
|
|
4
|
+
export * from './leads.ts';
|
|
5
|
+
export * from './pipeline.ts';
|
|
6
|
+
export * from './target.ts';
|
|
7
|
+
export * from './invoices.ts';
|
|
8
|
+
export * from './account.ts';
|
|
9
|
+
export * from './sales.ts';
|
|
10
|
+
export * from './errors.ts';
|
|
11
|
+
export * from './backend.ts';
|
|
12
|
+
export * from './crm-client.ts';
|
package/src/invoices.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { parseTimestamp, toTimestamp } from '@baack-software/baack-ts-tasks';
|
|
2
|
+
import { addMoney, fromMinor, minorOf, type MoneyTotals } from './money.ts';
|
|
3
|
+
import { inRange, type DateRange } from './period.ts';
|
|
4
|
+
import type { Invoice, InvoiceStatus, Money, Remittance } from './types.ts';
|
|
5
|
+
|
|
6
|
+
/** Statuses of an invoice that has been sent and is waiting to be paid. */
|
|
7
|
+
export const AWAITING_PAYMENT: readonly InvoiceStatus[] = ['AUTHORISED', 'PENDING'];
|
|
8
|
+
|
|
9
|
+
export const INVOICE_STATUS_LABELS: Readonly<Record<InvoiceStatus, string>> = {
|
|
10
|
+
DRAFT: 'Draft',
|
|
11
|
+
IN_REVIEW: 'In review',
|
|
12
|
+
AUTHORISED: 'Awaiting payment',
|
|
13
|
+
PENDING: 'Awaiting payment',
|
|
14
|
+
VOIDED: 'Void',
|
|
15
|
+
PAID: 'Paid',
|
|
16
|
+
REFUNDED: 'Refunded',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** What's still to pay on an invoice awaiting payment: its total less what's been paid. Undefined otherwise. */
|
|
20
|
+
export function outstanding(invoice: Invoice): Money | undefined {
|
|
21
|
+
if (!AWAITING_PAYMENT.includes(invoice.status)) return undefined;
|
|
22
|
+
const { currencyCode } = invoice;
|
|
23
|
+
const due = minorOf(invoice.total) - minorOf(invoice.paid);
|
|
24
|
+
return due > 0 ? fromMinor(due, currencyCode) : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Whether an invoice is past its due date with something still to pay. */
|
|
28
|
+
export function isOverdueInvoice(invoice: Invoice, now = new Date()): boolean {
|
|
29
|
+
const due = parseTimestamp(invoice.dueTimestamp);
|
|
30
|
+
return due !== undefined && due < now && outstanding(invoice) !== undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What's still to pay across invoices, per currency. */
|
|
34
|
+
export function outstandingTotals(invoices: readonly Invoice[]): MoneyTotals {
|
|
35
|
+
return invoices.reduce<MoneyTotals>((totals, invoice) => addMoney(totals, outstanding(invoice)), {});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What's overdue across invoices, per currency. */
|
|
39
|
+
export function overdueTotals(invoices: readonly Invoice[], now = new Date()): MoneyTotals {
|
|
40
|
+
return invoices
|
|
41
|
+
.filter((invoice) => isOverdueInvoice(invoice, now))
|
|
42
|
+
.reduce<MoneyTotals>((totals, invoice) => addMoney(totals, outstanding(invoice)), {});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type AgeBucket = 'CURRENT' | 'DAYS_1_30' | 'DAYS_31_60' | 'DAYS_61_90' | 'DAYS_OVER_90';
|
|
46
|
+
|
|
47
|
+
export const AGE_BUCKETS: readonly AgeBucket[] = ['CURRENT', 'DAYS_1_30', 'DAYS_31_60', 'DAYS_61_90', 'DAYS_OVER_90'];
|
|
48
|
+
|
|
49
|
+
export const AGE_BUCKET_LABELS: Readonly<Record<AgeBucket, string>> = {
|
|
50
|
+
CURRENT: 'Not yet due',
|
|
51
|
+
DAYS_1_30: '1 to 30 days overdue',
|
|
52
|
+
DAYS_31_60: '31 to 60 days overdue',
|
|
53
|
+
DAYS_61_90: '61 to 90 days overdue',
|
|
54
|
+
DAYS_OVER_90: 'Over 90 days overdue',
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** How long an invoice has been overdue, as a bucket for an aged debt view. */
|
|
58
|
+
export function ageBucket(invoice: Invoice, now = new Date()): AgeBucket {
|
|
59
|
+
const due = parseTimestamp(invoice.dueTimestamp);
|
|
60
|
+
const days = due ? Math.floor((now.getTime() - due.getTime()) / 86_400_000) : 0;
|
|
61
|
+
if (days <= 0) return 'CURRENT';
|
|
62
|
+
if (days <= 30) return 'DAYS_1_30';
|
|
63
|
+
if (days <= 60) return 'DAYS_31_60';
|
|
64
|
+
if (days <= 90) return 'DAYS_61_90';
|
|
65
|
+
return 'DAYS_OVER_90';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** What's still to pay, per age bucket and currency, every bucket in order. */
|
|
69
|
+
export function outstandingByAge(
|
|
70
|
+
invoices: readonly Invoice[],
|
|
71
|
+
now = new Date(),
|
|
72
|
+
): { bucket: AgeBucket; totals: MoneyTotals }[] {
|
|
73
|
+
const byBucket = new Map<AgeBucket, MoneyTotals>();
|
|
74
|
+
for (const invoice of invoices) {
|
|
75
|
+
const due = outstanding(invoice);
|
|
76
|
+
if (!due) continue;
|
|
77
|
+
const bucket = ageBucket(invoice, now);
|
|
78
|
+
byBucket.set(bucket, addMoney(byBucket.get(bucket) ?? {}, due));
|
|
79
|
+
}
|
|
80
|
+
return AGE_BUCKETS.map((bucket) => ({ bucket, totals: byBucket.get(bucket) ?? {} }));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const counts = (remittance: Remittance) => remittance.remittanceStatus === 'RECEIVED';
|
|
84
|
+
|
|
85
|
+
/** Money received less refunds paid, per currency, optionally only within a date range. */
|
|
86
|
+
export function paymentsReceived(remittances: readonly Remittance[], range?: DateRange): MoneyTotals {
|
|
87
|
+
let totals: MoneyTotals = {};
|
|
88
|
+
for (const remittance of remittances) {
|
|
89
|
+
if (!counts(remittance) || (range && !inRange(remittance.receivedTimestamp, range))) continue;
|
|
90
|
+
totals = addMoney(totals, remittance.value, remittance.remittanceDirection === 'REFUND' ? -1 : 1);
|
|
91
|
+
}
|
|
92
|
+
return totals;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Payments received per UTC day in a range, every day included, for a chart. */
|
|
96
|
+
export function paymentsByDay(
|
|
97
|
+
remittances: readonly Remittance[],
|
|
98
|
+
range: DateRange,
|
|
99
|
+
): { day: string; totals: MoneyTotals }[] {
|
|
100
|
+
const days: { day: string; totals: MoneyTotals }[] = [];
|
|
101
|
+
const start = new Date(Date.UTC(range.start.getUTCFullYear(), range.start.getUTCMonth(), range.start.getUTCDate()));
|
|
102
|
+
for (let day = start; day < range.end; day = new Date(day.getTime() + 86_400_000)) {
|
|
103
|
+
const next = new Date(day.getTime() + 86_400_000);
|
|
104
|
+
days.push({
|
|
105
|
+
day: day.toISOString().slice(0, 10),
|
|
106
|
+
totals: paymentsReceived(remittances, { start: day, end: next }),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return days;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** An invoice's payment fields as they follow from its remittances. */
|
|
113
|
+
export interface InvoicePayments {
|
|
114
|
+
paid: Money;
|
|
115
|
+
refunded: Money;
|
|
116
|
+
status: InvoiceStatus;
|
|
117
|
+
fullyPaidTimestamp: string | null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* An invoice's `paid`, `refunded`, `status` and `fullyPaidTimestamp` worked out from its remittances, which the API
|
|
122
|
+
* lists on the invoice but doesn't total. An invoice's own amounts (`total`, `tax`) are as it was given: the API
|
|
123
|
+
* doesn't add them up from its lines, so an invoice can total something other than its lines' sum. Only received remittances count. An invoice is paid once payments reach its total (fully paid when the
|
|
124
|
+
* payment that got there arrived), and refunded once refunds match the payments; otherwise its status is kept.
|
|
125
|
+
*/
|
|
126
|
+
export function invoiceFromRemittances(invoice: Invoice, remittances: readonly Remittance[]): InvoicePayments {
|
|
127
|
+
const total = minorOf(invoice.total);
|
|
128
|
+
const mine = remittances
|
|
129
|
+
.filter((remittance) => remittance.paymentInvoice.urn === invoice.urn && counts(remittance))
|
|
130
|
+
.toSorted((a, b) => a.receivedTimestamp.localeCompare(b.receivedTimestamp));
|
|
131
|
+
let paid = 0;
|
|
132
|
+
let refunded = 0;
|
|
133
|
+
let fullyPaid: string | null = null;
|
|
134
|
+
for (const remittance of mine) {
|
|
135
|
+
const minor = remittance.value.unitValue;
|
|
136
|
+
if (remittance.remittanceDirection === 'REFUND') refunded += minor;
|
|
137
|
+
else {
|
|
138
|
+
paid += minor;
|
|
139
|
+
if (fullyPaid === null && paid >= total) fullyPaid = normalise(remittance.receivedTimestamp);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
let status = invoice.status;
|
|
143
|
+
if (paid > 0 && refunded >= paid) status = 'REFUNDED';
|
|
144
|
+
else if (fullyPaid) status = 'PAID';
|
|
145
|
+
return {
|
|
146
|
+
paid: fromMinor(paid, invoice.currencyCode),
|
|
147
|
+
refunded: fromMinor(refunded, invoice.currencyCode),
|
|
148
|
+
status,
|
|
149
|
+
fullyPaidTimestamp: fullyPaid,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A Baack timestamp written the one way, with milliseconds. */
|
|
154
|
+
function normalise(timestamp: string): string {
|
|
155
|
+
const date = parseTimestamp(timestamp);
|
|
156
|
+
return date ? toTimestamp(date) : timestamp;
|
|
157
|
+
}
|
package/src/leads.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { Lead, LeadOutcome, LeadSource, LeadStatus } from './types.ts';
|
|
2
|
+
|
|
3
|
+
export const LEAD_SOURCES: readonly LeadSource[] = [
|
|
4
|
+
'WEBSITE',
|
|
5
|
+
'REFERRAL',
|
|
6
|
+
'SOCIAL',
|
|
7
|
+
'EMAIL',
|
|
8
|
+
'CALL',
|
|
9
|
+
'ADS',
|
|
10
|
+
'EVENT',
|
|
11
|
+
'UNKNOWN',
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
export const SOURCE_LABELS: Readonly<Record<LeadSource, string>> = {
|
|
15
|
+
WEBSITE: 'Website',
|
|
16
|
+
REFERRAL: 'Referral',
|
|
17
|
+
SOCIAL: 'Social',
|
|
18
|
+
EMAIL: 'Email',
|
|
19
|
+
CALL: 'Call',
|
|
20
|
+
ADS: 'Ads',
|
|
21
|
+
EVENT: 'Event',
|
|
22
|
+
UNKNOWN: 'Other',
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Lead statuses in the order a lead moves through them. */
|
|
26
|
+
export const LEAD_STATUSES: readonly LeadStatus[] = ['NEW', 'CONTACTED', 'QUALIFIED'];
|
|
27
|
+
|
|
28
|
+
export const LEAD_STATUS_LABELS: Readonly<Record<LeadStatus, string>> = {
|
|
29
|
+
NEW: 'New',
|
|
30
|
+
CONTACTED: 'Contacted',
|
|
31
|
+
QUALIFIED: 'Qualified',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export const LEAD_OUTCOME_LABELS: Readonly<Record<LeadOutcome, string>> = {
|
|
35
|
+
IN_PROGRESS: 'In progress',
|
|
36
|
+
CONVERTED: 'Converted',
|
|
37
|
+
CLOSED: 'Closed',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** How a lead ended: its own outcome, in progress when it has none. */
|
|
41
|
+
export const leadOutcome = (lead: Lead): LeadOutcome => lead.outcome ?? 'IN_PROGRESS';
|
|
42
|
+
|
|
43
|
+
/** Whether a lead still needs work: not yet converted into a deal or closed as unqualified. */
|
|
44
|
+
export const isOpenLead = (lead: Lead): boolean => leadOutcome(lead) === 'IN_PROGRESS';
|
|
45
|
+
|
|
46
|
+
/** Where a lead stands, in one word for tables and filters: its outcome once closed, otherwise its status. */
|
|
47
|
+
export type LeadState = LeadStatus | Exclude<LeadOutcome, 'IN_PROGRESS'>;
|
|
48
|
+
|
|
49
|
+
export const LEAD_STATES: readonly LeadState[] = [...LEAD_STATUSES, 'CONVERTED', 'CLOSED'];
|
|
50
|
+
|
|
51
|
+
export const LEAD_STATE_LABELS: Readonly<Record<LeadState, string>> = {
|
|
52
|
+
...LEAD_STATUS_LABELS,
|
|
53
|
+
CONVERTED: LEAD_OUTCOME_LABELS.CONVERTED,
|
|
54
|
+
CLOSED: LEAD_OUTCOME_LABELS.CLOSED,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export function leadState(lead: Lead): LeadState {
|
|
58
|
+
const outcome = leadOutcome(lead);
|
|
59
|
+
return outcome === 'IN_PROGRESS' ? lead.status : outcome;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The deal a lead was converted into: the deal whose `leadSource` is the lead. */
|
|
63
|
+
export const dealFromLead = <D extends { leadSource?: { urn: string } | null }>(
|
|
64
|
+
lead: Pick<Lead, 'urn'>,
|
|
65
|
+
deals: readonly D[],
|
|
66
|
+
): D | undefined => deals.find((deal) => deal.leadSource?.urn === lead.urn);
|
|
67
|
+
|
|
68
|
+
export interface SourceCount {
|
|
69
|
+
source: LeadSource;
|
|
70
|
+
count: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** How many leads came from each source, every source in order, including those with none. */
|
|
74
|
+
export function leadsBySource(leads: readonly Lead[]): SourceCount[] {
|
|
75
|
+
const counts = new Map<LeadSource, number>();
|
|
76
|
+
for (const lead of leads) counts.set(lead.source, (counts.get(lead.source) ?? 0) + 1);
|
|
77
|
+
return LEAD_SOURCES.map((source) => ({ source, count: counts.get(source) ?? 0 }));
|
|
78
|
+
}
|