@baack-software/baack-ts-crm 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend.d.ts +29 -1
- package/dist/backend.d.ts.map +1 -1
- package/dist/backend.js +95 -0
- package/dist/backend.js.map +1 -1
- package/dist/crm-client.d.ts +55 -13
- package/dist/crm-client.d.ts.map +1 -1
- package/dist/crm-client.js +99 -15
- package/dist/crm-client.js.map +1 -1
- 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/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/invoices.d.ts +7 -0
- package/dist/invoices.d.ts.map +1 -1
- package/dist/invoices.js +20 -2
- package/dist/invoices.js.map +1 -1
- package/dist/period.d.ts +15 -2
- package/dist/period.d.ts.map +1 -1
- package/dist/period.js +27 -1
- package/dist/period.js.map +1 -1
- package/dist/pipeline.d.ts +6 -0
- package/dist/pipeline.d.ts.map +1 -1
- package/dist/pipeline.js +18 -0
- package/dist/pipeline.js.map +1 -1
- 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/DealsBoard.d.ts +22 -3
- package/dist/react/DealsBoard.d.ts.map +1 -1
- package/dist/react/DealsBoard.js +53 -4
- package/dist/react/DealsBoard.js.map +1 -1
- package/dist/react/Details.d.ts +40 -7
- package/dist/react/Details.d.ts.map +1 -1
- package/dist/react/Details.js +180 -23
- package/dist/react/Details.js.map +1 -1
- package/dist/react/Forms.d.ts +148 -17
- package/dist/react/Forms.d.ts.map +1 -1
- package/dist/react/Forms.js +365 -75
- package/dist/react/Forms.js.map +1 -1
- package/dist/react/Sales.d.ts +25 -6
- package/dist/react/Sales.d.ts.map +1 -1
- package/dist/react/Sales.js +114 -30
- package/dist/react/Sales.js.map +1 -1
- package/dist/react/SidePanel.d.ts +10 -0
- package/dist/react/SidePanel.d.ts.map +1 -1
- package/dist/react/SidePanel.js +18 -3
- package/dist/react/SidePanel.js.map +1 -1
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -0
- package/dist/react/index.js.map +1 -1
- package/dist/react/parts.d.ts +12 -2
- package/dist/react/parts.d.ts.map +1 -1
- package/dist/react/parts.js +25 -2
- package/dist/react/parts.js.map +1 -1
- 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 +89 -2
- package/dist/react/text.d.ts.map +1 -1
- package/dist/react/text.js +89 -2
- package/dist/react/text.js.map +1 -1
- package/dist/react/ui/badge.d.ts +1 -1
- package/dist/react/ui/button.d.ts +2 -2
- package/dist/react/views.d.ts +33 -11
- package/dist/react/views.d.ts.map +1 -1
- package/dist/react/views.js +96 -27
- package/dist/react/views.js.map +1 -1
- package/dist/sales.d.ts +28 -3
- package/dist/sales.d.ts.map +1 -1
- package/dist/sales.js +33 -10
- package/dist/sales.js.map +1 -1
- package/dist/store.d.ts +31 -12
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +82 -21
- package/dist/store.js.map +1 -1
- package/dist/target.d.ts +2 -1
- package/dist/target.d.ts.map +1 -1
- package/dist/target.js +6 -2
- package/dist/target.js.map +1 -1
- package/dist/types.d.ts +24 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/backend.ts +131 -1
- package/src/crm-client.ts +162 -19
- package/src/deal-order.ts +116 -0
- package/src/index.ts +1 -0
- package/src/invoices.ts +22 -2
- package/src/period.ts +41 -2
- package/src/pipeline.ts +21 -0
- package/src/react/ChoiceCombobox.tsx +227 -0
- package/src/react/DealsBoard.tsx +171 -4
- package/src/react/Details.tsx +608 -31
- package/src/react/Forms.tsx +1006 -139
- package/src/react/Sales.tsx +332 -44
- package/src/react/SidePanel.tsx +22 -11
- package/src/react/index.ts +1 -0
- package/src/react/parts.tsx +56 -4
- package/src/react/pipeline-choice.ts +54 -0
- package/src/react/text.ts +90 -2
- package/src/react/views.tsx +222 -32
- package/src/sales.ts +57 -10
- package/src/store.ts +136 -27
- package/src/target.ts +5 -2
- package/src/types.ts +28 -0
package/src/backend.ts
CHANGED
|
@@ -8,7 +8,19 @@ import {
|
|
|
8
8
|
} from '@baack-software/baack-ts-client';
|
|
9
9
|
import { toTimestamp, urnOf, type Ref, type RefLike } from '@baack-software/baack-ts-tasks';
|
|
10
10
|
import { CrmNotFoundError, CrmSearchTimeoutError } from './errors.ts';
|
|
11
|
-
import type {
|
|
11
|
+
import type {
|
|
12
|
+
ContactDetails,
|
|
13
|
+
CrmConcept,
|
|
14
|
+
CrmPerson,
|
|
15
|
+
Deal,
|
|
16
|
+
Invoice,
|
|
17
|
+
InvoiceLine,
|
|
18
|
+
InvoiceParty,
|
|
19
|
+
Lead,
|
|
20
|
+
NewContact,
|
|
21
|
+
Pipeline,
|
|
22
|
+
Remittance,
|
|
23
|
+
} from './types.ts';
|
|
12
24
|
|
|
13
25
|
/** Fields of a new record: everything but what the server sets. */
|
|
14
26
|
export type RecordInput<T> = Omit<T, 'urn' | 'url' | 'createdTimestamp' | 'updatedTimestamp'>;
|
|
@@ -41,10 +53,43 @@ export interface CompanyApi {
|
|
|
41
53
|
create(input: { owner: RefLike; name: string }): Promise<Company>;
|
|
42
54
|
}
|
|
43
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Making people: an identity owned by the CRM's company, linked to `company` (a customer) when given, with a person,
|
|
58
|
+
* the person's name, an email address and a telephone number. A person's email and telephone can be read and changed
|
|
59
|
+
* later, each kept as one record on their identity.
|
|
60
|
+
*/
|
|
61
|
+
export interface PeopleApi {
|
|
62
|
+
createContact(input: { owner: RefLike; contact: NewContact; company?: RefLike | null }): Promise<CrmPerson>;
|
|
63
|
+
/** A person's email and telephone: the first of each on their identity. */
|
|
64
|
+
contactDetails(identity: RefLike): Promise<ContactDetails>;
|
|
65
|
+
/**
|
|
66
|
+
* Sets a person's email and telephone: the first of each on their identity is changed, made when there's none, and
|
|
67
|
+
* deleted when emptied. Fields left out are kept.
|
|
68
|
+
*/
|
|
69
|
+
setContactDetails(identity: RefLike, details: Partial<ContactDetails>): Promise<ContactDetails>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A contact's name, as shown: given and family name. */
|
|
73
|
+
export const contactName = ({ givenName, familyName }: NewContact): string =>
|
|
74
|
+
[givenName.trim(), familyName?.trim()].filter(Boolean).join(' ');
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* A contact's identity label: their initials, such as "J.S.". A label isn't held securely, so it never carries a
|
|
78
|
+
* person's name, which goes in the person name instead.
|
|
79
|
+
*/
|
|
80
|
+
export const contactLabel = ({ givenName, familyName }: NewContact): string =>
|
|
81
|
+
[givenName, familyName ?? '']
|
|
82
|
+
.map((name) => name.trim().charAt(0).toUpperCase())
|
|
83
|
+
.filter(Boolean)
|
|
84
|
+
.map((initial) => `${initial}.`)
|
|
85
|
+
.join('');
|
|
86
|
+
|
|
44
87
|
/** Where each CRM concept is read and written. */
|
|
45
88
|
export interface CrmBackend {
|
|
46
89
|
/** Client companies, made when a lead is created or converted with a business name. */
|
|
47
90
|
companies: CompanyApi;
|
|
91
|
+
/** People, made as a lead's contact or a customer's person. */
|
|
92
|
+
people: PeopleApi;
|
|
48
93
|
leads: RecordApi<Lead, LeadInput>;
|
|
49
94
|
deals: RecordApi<Deal, DealInput>;
|
|
50
95
|
pipelines: ReadApi<Pipeline>;
|
|
@@ -224,10 +269,75 @@ export function apiBackend(client: BaackClient): CrmBackend {
|
|
|
224
269
|
'remittances',
|
|
225
270
|
]);
|
|
226
271
|
const remittance = async (urn: string) => asRemittance(await client.read<Raw>(Endpoint.INVOICE_REMITTANCE, urn));
|
|
272
|
+
// An identity's emails and telephones, which the API returns with the identity.
|
|
273
|
+
const reachable = (urn: string) =>
|
|
274
|
+
client.read<{ emails?: { urn: string; email: string }[]; telephones?: { urn: string; number: string }[] }>(
|
|
275
|
+
Endpoint.IDENTITY,
|
|
276
|
+
urn,
|
|
277
|
+
);
|
|
278
|
+
const detailsOf = (identity: Awaited<ReturnType<typeof reachable>>): ContactDetails => ({
|
|
279
|
+
email: identity.emails?.[0]?.email ?? '',
|
|
280
|
+
telephone: identity.telephones?.[0]?.number ?? '',
|
|
281
|
+
});
|
|
282
|
+
// An identity's first email or telephone set to `value`: changed (read, merged and sent whole, as other updates
|
|
283
|
+
// are), made when there's none, deleted when emptied, and left alone when `value` is undefined or unchanged.
|
|
284
|
+
const setFirst = async (
|
|
285
|
+
endpoint: string,
|
|
286
|
+
existing: { urn: string; email?: string; number?: string } | undefined,
|
|
287
|
+
field: 'email' | 'number',
|
|
288
|
+
value: string | undefined,
|
|
289
|
+
identity: string,
|
|
290
|
+
) => {
|
|
291
|
+
if (value === undefined) return;
|
|
292
|
+
const next = value.trim();
|
|
293
|
+
if (existing?.[field] === next) return;
|
|
294
|
+
if (existing && !next) return void (await client.delete(endpoint, existing.urn));
|
|
295
|
+
if (existing) {
|
|
296
|
+
const stored = await client.read<Raw>(endpoint, existing.urn);
|
|
297
|
+
return void (await client.update(endpoint, existing.urn, { ...stored, [field]: next }));
|
|
298
|
+
}
|
|
299
|
+
if (next) await client.create(endpoint, { identity: { urn: identity }, [field]: next });
|
|
300
|
+
};
|
|
227
301
|
return {
|
|
228
302
|
companies: {
|
|
229
303
|
create: ({ owner, name }) => client.create<Company>(Endpoint.COMPANY, { owner: { urn: urnOf(owner) }, name }),
|
|
230
304
|
},
|
|
305
|
+
people: {
|
|
306
|
+
// An identity, then its person, the person's name and the email, each on its own endpoint. If any of those is
|
|
307
|
+
// refused (an email the API doesn't accept, say), the identity is deleted, which takes what was made with it,
|
|
308
|
+
// so trying again doesn't leave a half-made contact behind.
|
|
309
|
+
async createContact({ owner, contact, company }) {
|
|
310
|
+
const identity = await client.create<{ urn: string }>(Endpoint.IDENTITY, {
|
|
311
|
+
owner: { urn: urnOf(owner) },
|
|
312
|
+
label: contactLabel(contact),
|
|
313
|
+
companies: company ? [{ urn: urnOf(company) }] : [],
|
|
314
|
+
});
|
|
315
|
+
try {
|
|
316
|
+
const person = await client.create<{ urn: string }>(Endpoint.PERSON, { identity: { urn: identity.urn } });
|
|
317
|
+
await client.create(Endpoint.PERSON_NAME, {
|
|
318
|
+
person: { urn: person.urn },
|
|
319
|
+
givenName: contact.givenName.trim(),
|
|
320
|
+
familyName: contact.familyName?.trim() || null,
|
|
321
|
+
});
|
|
322
|
+
const email = contact.email?.trim();
|
|
323
|
+
if (email) await client.create(Endpoint.EMAIL, { identity: { urn: identity.urn }, email });
|
|
324
|
+
const number = contact.telephone?.trim();
|
|
325
|
+
if (number) await client.create(Endpoint.TELEPHONE, { identity: { urn: identity.urn }, number });
|
|
326
|
+
} catch (error) {
|
|
327
|
+
await client.delete(Endpoint.IDENTITY, identity.urn).catch(() => undefined);
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
return { urn: identity.urn, name: contactName(contact), company: company ? { urn: urnOf(company) } : null };
|
|
331
|
+
},
|
|
332
|
+
contactDetails: async (identity) => detailsOf(await reachable(urnOf(identity))),
|
|
333
|
+
async setContactDetails(identity, details) {
|
|
334
|
+
const urn = urnOf(identity);
|
|
335
|
+
const current = await reachable(urn);
|
|
336
|
+
await setFirst(Endpoint.EMAIL, current.emails?.[0], 'email', details.email, urn);
|
|
337
|
+
await setFirst(Endpoint.TELEPHONE, current.telephones?.[0], 'number', details.telephone, urn);
|
|
338
|
+
return detailsOf(await reachable(urn));
|
|
339
|
+
},
|
|
340
|
+
},
|
|
231
341
|
leads: onApi(client, Endpoint.LEAD, 'LEAD', asLead),
|
|
232
342
|
deals: onApi(client, Endpoint.DEAL, 'DEAL', asDeal),
|
|
233
343
|
invoices,
|
|
@@ -339,6 +449,9 @@ export function memoryBackend(data: CrmData, options: MemoryOptions = {}): CrmBa
|
|
|
339
449
|
// A remittance has no owner: it's its invoice's owner's.
|
|
340
450
|
const invoiceOwner = (remittance: Remittance) =>
|
|
341
451
|
copy.invoices.find((invoice) => invoice.urn === remittance.paymentInvoice.urn)?.owner.urn;
|
|
452
|
+
// Sample people's email and telephone, by identity URN; anyone else has none until they're set.
|
|
453
|
+
const details = new Map<string, ContactDetails>();
|
|
454
|
+
const detailsFor = (urn: string): ContactDetails => details.get(urn) ?? { email: '', telephone: '' };
|
|
342
455
|
return {
|
|
343
456
|
// Sample companies live only in memory: converting a sample lead never makes a real company.
|
|
344
457
|
companies: {
|
|
@@ -353,6 +466,23 @@ export function memoryBackend(data: CrmData, options: MemoryOptions = {}): CrmBa
|
|
|
353
466
|
return answer(company);
|
|
354
467
|
},
|
|
355
468
|
},
|
|
469
|
+
// Sample people too: a sample lead's contact is never a real identity.
|
|
470
|
+
people: {
|
|
471
|
+
async createContact({ contact, company }) {
|
|
472
|
+
const urn = newUrn();
|
|
473
|
+
details.set(urn, { email: contact.email?.trim() ?? '', telephone: contact.telephone?.trim() ?? '' });
|
|
474
|
+
return answer({ urn, name: contactName(contact), company: company ? { urn: urnOf(company) } : null });
|
|
475
|
+
},
|
|
476
|
+
contactDetails: async (identity) => answer({ ...detailsFor(urnOf(identity)) }),
|
|
477
|
+
async setContactDetails(identity, changes) {
|
|
478
|
+
const urn = urnOf(identity);
|
|
479
|
+
const next = { ...detailsFor(urn) };
|
|
480
|
+
if (changes.email !== undefined) next.email = changes.email.trim();
|
|
481
|
+
if (changes.telephone !== undefined) next.telephone = changes.telephone.trim();
|
|
482
|
+
details.set(urn, next);
|
|
483
|
+
return answer({ ...next });
|
|
484
|
+
},
|
|
485
|
+
},
|
|
356
486
|
leads: collection('leads', copy.leads, '/n/v1/lead/', true, owned),
|
|
357
487
|
deals: collection('deals', copy.deals, '/n/v1/deal/', true, owned),
|
|
358
488
|
invoiceLines: {
|
package/src/crm-client.ts
CHANGED
|
@@ -13,12 +13,15 @@ import {
|
|
|
13
13
|
import { orderedStages, pipelineOf } from './pipeline.ts';
|
|
14
14
|
import {
|
|
15
15
|
CRM_CONCEPTS,
|
|
16
|
+
type ContactDetails,
|
|
16
17
|
type CrmConcept,
|
|
18
|
+
type CrmPerson,
|
|
17
19
|
type Deal,
|
|
18
20
|
type DealOutcome,
|
|
19
21
|
type Invoice,
|
|
20
22
|
type Lead,
|
|
21
23
|
type LeadOutcome,
|
|
24
|
+
type NewContact,
|
|
22
25
|
type Pipeline,
|
|
23
26
|
type PipelineStage,
|
|
24
27
|
} from './types.ts';
|
|
@@ -49,12 +52,47 @@ export interface ConvertOptions {
|
|
|
49
52
|
companyName?: string;
|
|
50
53
|
}
|
|
51
54
|
|
|
55
|
+
/**
|
|
56
|
+
* What an invoice's parties also need made: a company that isn't in Baack yet, by name, and a new person, made after
|
|
57
|
+
* that party's company (so they're its customer's person).
|
|
58
|
+
*/
|
|
59
|
+
export interface InvoicePartyOptions {
|
|
60
|
+
remitterCompanyName?: string | undefined;
|
|
61
|
+
recipientCompanyName?: string | undefined;
|
|
62
|
+
remitterContact?: NewContact | undefined;
|
|
63
|
+
recipientContact?: NewContact | undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What a new invoice also needs: the deal it's for, and its parties' new companies and people. */
|
|
67
|
+
export interface NewInvoiceOptions extends InvoicePartyOptions {
|
|
68
|
+
deal?: Deal;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** What saving an invoice made along the way: its parties' new companies and people. */
|
|
72
|
+
export interface InvoiceSaved {
|
|
73
|
+
invoice: Invoice;
|
|
74
|
+
companies: Company[];
|
|
75
|
+
people: CrmPerson[];
|
|
76
|
+
}
|
|
77
|
+
|
|
52
78
|
export interface NewLeadOptions {
|
|
53
79
|
/**
|
|
54
80
|
* 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
81
|
* owner, and linked as the lead's contact company, since a lead holds a business by its company.
|
|
56
82
|
*/
|
|
57
83
|
companyName?: string;
|
|
84
|
+
/**
|
|
85
|
+
* A new person to be the lead's contact: made after the company (so they're linked to it, as its customer's person),
|
|
86
|
+
* and linked as the lead's contact identity.
|
|
87
|
+
*/
|
|
88
|
+
contact?: NewContact;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What saving a lead made along the way: the prospect's company and the contact, when they were new. */
|
|
92
|
+
export interface LeadSaved {
|
|
93
|
+
lead: Lead;
|
|
94
|
+
company?: Company;
|
|
95
|
+
person?: CrmPerson;
|
|
58
96
|
}
|
|
59
97
|
|
|
60
98
|
/**
|
|
@@ -69,6 +107,7 @@ export interface NewLeadOptions {
|
|
|
69
107
|
*/
|
|
70
108
|
export class CrmClient {
|
|
71
109
|
readonly companies: CrmBackend['companies'];
|
|
110
|
+
readonly people: CrmBackend['people'];
|
|
72
111
|
readonly leads: CrmBackend['leads'];
|
|
73
112
|
readonly deals: CrmBackend['deals'];
|
|
74
113
|
readonly pipelines: CrmBackend['pipelines'];
|
|
@@ -82,6 +121,7 @@ export class CrmClient {
|
|
|
82
121
|
readonly sources: Readonly<Record<CrmConcept, CrmSource>>,
|
|
83
122
|
) {
|
|
84
123
|
this.companies = backend.companies;
|
|
124
|
+
this.people = backend.people;
|
|
85
125
|
this.leads = backend.leads;
|
|
86
126
|
this.deals = backend.deals;
|
|
87
127
|
this.pipelines = backend.pipelines;
|
|
@@ -156,10 +196,7 @@ export class CrmClient {
|
|
|
156
196
|
options: { closedReason?: string } = {},
|
|
157
197
|
): Promise<Lead> {
|
|
158
198
|
const closed = outcome === 'CLOSED';
|
|
159
|
-
return this.leads.update(lead, {
|
|
160
|
-
outcome,
|
|
161
|
-
closedReason: closed ? options.closedReason?.trim() || null : null,
|
|
162
|
-
});
|
|
199
|
+
return this.leads.update(lead, { outcome, closedReason: closed ? options.closedReason?.trim() || null : null });
|
|
163
200
|
}
|
|
164
201
|
|
|
165
202
|
/** Creates a deal, for example one that didn't start as a lead. */
|
|
@@ -169,15 +206,18 @@ export class CrmClient {
|
|
|
169
206
|
|
|
170
207
|
/**
|
|
171
208
|
* Creates an invoice, then its lines (numbered in order), then links it to `deal` when given, as deals hold their
|
|
172
|
-
* invoices.
|
|
173
|
-
*
|
|
209
|
+
* invoices. A party's new company (`remitterCompanyName`, `recipientCompanyName`) is made first, owned by the
|
|
210
|
+
* invoice's owner, then its new person (`remitterContact`, `recipientContact`). The invoice's amounts are as given:
|
|
211
|
+
* the API doesn't add them up from the lines. Returns it read back, with its lines, the deal as updated and the
|
|
212
|
+
* companies and people made.
|
|
174
213
|
*/
|
|
175
214
|
async createInvoice(
|
|
176
215
|
input: InvoiceInput,
|
|
177
216
|
lines: readonly Omit<InvoiceLineInput, 'paymentInvoice' | 'lineNumber'>[] = [],
|
|
178
|
-
options:
|
|
179
|
-
): Promise<
|
|
180
|
-
const
|
|
217
|
+
options: NewInvoiceOptions = {},
|
|
218
|
+
): Promise<InvoiceSaved & { deal?: Deal }> {
|
|
219
|
+
const { links, companies, people } = await this.#parties(input.owner, input, options);
|
|
220
|
+
const created = await this.invoices.create({ ...input, ...links });
|
|
181
221
|
for (const [index, line] of lines.entries()) {
|
|
182
222
|
await this.invoiceLines.create({ ...line, lineNumber: index + 1, paymentInvoice: ref(created) });
|
|
183
223
|
}
|
|
@@ -185,7 +225,64 @@ export class CrmClient {
|
|
|
185
225
|
? await this.deals.update(options.deal, { invoices: [...options.deal.invoices, ref(created)] })
|
|
186
226
|
: undefined;
|
|
187
227
|
const invoice = await this.invoices.get(created);
|
|
188
|
-
return { invoice, ...(deal ? { deal } : {}) };
|
|
228
|
+
return { invoice, ...(deal ? { deal } : {}), companies, people };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Changes an invoice's own fields (status, parties, dates), making a party's new company and person first, as for a
|
|
233
|
+
* new invoice. Its lines aren't changed.
|
|
234
|
+
*/
|
|
235
|
+
async updateInvoice(
|
|
236
|
+
invoice: Invoice,
|
|
237
|
+
changes: Partial<InvoiceInput>,
|
|
238
|
+
options: InvoicePartyOptions = {},
|
|
239
|
+
): Promise<InvoiceSaved> {
|
|
240
|
+
const parties = {
|
|
241
|
+
remitter: changes.remitter === undefined ? (invoice.remitter ?? null) : changes.remitter,
|
|
242
|
+
recipient: changes.recipient === undefined ? (invoice.recipient ?? null) : changes.recipient,
|
|
243
|
+
};
|
|
244
|
+
const { links, companies, people } = await this.#parties(invoice.owner, parties, options);
|
|
245
|
+
const updated = await this.invoices.update(invoice, { ...changes, ...links });
|
|
246
|
+
return { invoice: updated, companies, people };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* An invoice's parties with their new companies and people made and linked: each party's company from its
|
|
251
|
+
* `...CompanyName`, then its person from its `...Contact`, linked to that party's company. Only parties that changed
|
|
252
|
+
* are returned in `links`.
|
|
253
|
+
*/
|
|
254
|
+
async #parties(
|
|
255
|
+
owner: RefLike,
|
|
256
|
+
parties: Pick<Partial<InvoiceInput>, 'remitter' | 'recipient'>,
|
|
257
|
+
options: InvoicePartyOptions,
|
|
258
|
+
): Promise<{
|
|
259
|
+
links: Pick<Partial<InvoiceInput>, 'remitter' | 'recipient'>;
|
|
260
|
+
companies: Company[];
|
|
261
|
+
people: CrmPerson[];
|
|
262
|
+
}> {
|
|
263
|
+
const companies: Company[] = [];
|
|
264
|
+
const people: CrmPerson[] = [];
|
|
265
|
+
const links: Pick<Partial<InvoiceInput>, 'remitter' | 'recipient'> = {};
|
|
266
|
+
for (const which of ['remitter', 'recipient'] as const) {
|
|
267
|
+
const name = options[`${which}CompanyName`]?.trim();
|
|
268
|
+
const contact = options[`${which}Contact`];
|
|
269
|
+
if (!name && !contact) continue;
|
|
270
|
+
const given = parties[which];
|
|
271
|
+
let company = given?.company ?? null;
|
|
272
|
+
if (name) {
|
|
273
|
+
const made = await this.companies.create({ owner, name });
|
|
274
|
+
companies.push(made);
|
|
275
|
+
company = ref(made);
|
|
276
|
+
}
|
|
277
|
+
let identity = given?.identity ?? null;
|
|
278
|
+
if (contact) {
|
|
279
|
+
const person = await this.createContact(owner, contact, company);
|
|
280
|
+
people.push(person);
|
|
281
|
+
identity = { urn: person.urn };
|
|
282
|
+
}
|
|
283
|
+
links[which] = { ...given, company, identity };
|
|
284
|
+
}
|
|
285
|
+
return { links, companies, people };
|
|
189
286
|
}
|
|
190
287
|
|
|
191
288
|
/** Records a payment (or refund) received against an invoice. */
|
|
@@ -193,16 +290,60 @@ export class CrmClient {
|
|
|
193
290
|
return this.remittances.create(input);
|
|
194
291
|
}
|
|
195
292
|
|
|
293
|
+
/** A person's email and telephone (see `PeopleApi.contactDetails`). */
|
|
294
|
+
contactDetails(identity: RefLike): Promise<ContactDetails> {
|
|
295
|
+
return this.people.contactDetails(identity);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Sets a person's email and telephone; fields left out are kept (see `PeopleApi.setContactDetails`). */
|
|
299
|
+
setContactDetails(identity: RefLike, details: Partial<ContactDetails>): Promise<ContactDetails> {
|
|
300
|
+
return this.people.setContactDetails(identity, details);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Makes a person owned by `owner`: a customer's person when `company` is given (see `PeopleApi`). */
|
|
304
|
+
createContact(owner: RefLike, contact: NewContact, company?: RefLike | null): Promise<CrmPerson> {
|
|
305
|
+
return this.people.createContact({ owner, contact, company: company ?? null });
|
|
306
|
+
}
|
|
307
|
+
|
|
196
308
|
/**
|
|
197
|
-
*
|
|
198
|
-
*
|
|
309
|
+
* A lead's company and contact links, making them first when `options` asks: the company from `companyName` when
|
|
310
|
+
* the lead has none, then the contact from `contact`, linked to that company.
|
|
199
311
|
*/
|
|
200
|
-
async
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
312
|
+
async #prospect(
|
|
313
|
+
owner: RefLike,
|
|
314
|
+
company: Lead['contactCompany'],
|
|
315
|
+
options: NewLeadOptions,
|
|
316
|
+
): Promise<{ links: Partial<LeadInput>; company?: Company; person?: CrmPerson }> {
|
|
317
|
+
const name = options.companyName?.trim();
|
|
318
|
+
const made = !company && name ? await this.companies.create({ owner, name }) : undefined;
|
|
319
|
+
const companyRef = made ? ref(made) : (company ?? null);
|
|
320
|
+
const person = options.contact ? await this.createContact(owner, options.contact, companyRef) : undefined;
|
|
321
|
+
return {
|
|
322
|
+
links: {
|
|
323
|
+
...(made ? { contactCompany: companyRef } : {}),
|
|
324
|
+
...(person ? { contactIdentity: { urn: person.urn } } : {}),
|
|
325
|
+
},
|
|
326
|
+
...(made ? { company: made } : {}),
|
|
327
|
+
...(person ? { person } : {}),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Creates a lead. With `companyName` and no contact company, the prospect's company is made first and linked; with
|
|
333
|
+
* `contact`, so is the contact. Both are returned with the lead.
|
|
334
|
+
*/
|
|
335
|
+
async createLead(input: LeadInput, options: NewLeadOptions = {}): Promise<LeadSaved> {
|
|
336
|
+
const { links, ...made } = await this.#prospect(input.owner, input.contactCompany, options);
|
|
337
|
+
const lead = await this.leads.create({ ...input, ...links });
|
|
338
|
+
return { lead, ...made };
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Changes a lead, making its new company or contact first as `createLead` does. */
|
|
342
|
+
async updateLead(lead: Lead, changes: Partial<LeadInput>, options: NewLeadOptions = {}): Promise<LeadSaved> {
|
|
343
|
+
const company = changes.contactCompany === undefined ? lead.contactCompany : changes.contactCompany;
|
|
344
|
+
const { links, ...made } = await this.#prospect(lead.owner, company, options);
|
|
345
|
+
const updated = await this.leads.update(lead, { ...changes, ...links });
|
|
346
|
+
return { lead: updated, ...made };
|
|
206
347
|
}
|
|
207
348
|
|
|
208
349
|
/** Everything the CRM holds about one customer company of `owner`. */
|
|
@@ -230,13 +371,15 @@ export function createCrmClient({ client, sample }: CrmClientOptions): CrmClient
|
|
|
230
371
|
sample !== undefined && (sample.concepts === 'all' || sample.concepts.includes(concept));
|
|
231
372
|
const pick = <K extends CrmConcept>(concept: K): CrmBackend[K] =>
|
|
232
373
|
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
|
|
374
|
+
// Companies and people are made for leads, so they come from wherever the leads do: sample leads never make real
|
|
375
|
+
// companies or people.
|
|
234
376
|
const sources = Object.fromEntries(
|
|
235
377
|
CRM_CONCEPTS.map((concept) => [concept, fromSample(concept) ? 'sample' : 'api']),
|
|
236
378
|
) as Record<CrmConcept, CrmSource>;
|
|
237
379
|
return new CrmClient(
|
|
238
380
|
{
|
|
239
381
|
companies: fromSample('leads') ? sample!.backend.companies : api.companies,
|
|
382
|
+
people: fromSample('leads') ? sample!.backend.people : api.people,
|
|
240
383
|
leads: pick('leads'),
|
|
241
384
|
deals: pick('deals'),
|
|
242
385
|
pipelines: pick('pipelines'),
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { minorOf } from './money.ts';
|
|
2
|
+
import { dealOutcome } from './pipeline.ts';
|
|
3
|
+
import type { Deal, DealOutcome } from './types.ts';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* How a board's columns order their deals:
|
|
7
|
+
* - `weighted`: value times chance of winning, sooner closes first (see `weightedScore`), highest first;
|
|
8
|
+
* - `size`: the target value, largest first;
|
|
9
|
+
* - `urgency`: the expected close, soonest (or most overdue) first, deals without one last.
|
|
10
|
+
*/
|
|
11
|
+
export type DealOrder = 'weighted' | 'size' | 'urgency';
|
|
12
|
+
|
|
13
|
+
export const DEAL_ORDERS: readonly DealOrder[] = ['weighted', 'size', 'urgency'];
|
|
14
|
+
|
|
15
|
+
const DAY_MS = 86_400_000;
|
|
16
|
+
/** Days to close assumed for a deal without an expected close. */
|
|
17
|
+
export const DEFAULT_DAYS_TO_CLOSE = 30;
|
|
18
|
+
/** The chance of winning assumed when no deal has a probability. */
|
|
19
|
+
export const DEFAULT_PROBABILITY = 10;
|
|
20
|
+
|
|
21
|
+
const average = (values: readonly number[]): number | undefined =>
|
|
22
|
+
values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : undefined;
|
|
23
|
+
|
|
24
|
+
/** Whole days from `now` until a deal's expected close, negative once past; undefined without one. */
|
|
25
|
+
export function daysToClose(deal: Deal, now: Date): number | undefined {
|
|
26
|
+
if (!deal.targetCloseTimestamp) return undefined;
|
|
27
|
+
const close = Date.parse(
|
|
28
|
+
deal.targetCloseTimestamp.endsWith('Z') ? deal.targetCloseTimestamp : `${deal.targetCloseTimestamp}Z`,
|
|
29
|
+
);
|
|
30
|
+
return Number.isNaN(close) ? undefined : Math.ceil((close - now.getTime()) / DAY_MS);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** What the weighted order assumes for deals missing a value or probability: the averages of those that have one. */
|
|
34
|
+
export interface WeightDefaults {
|
|
35
|
+
/** In minor units; at least 1. */
|
|
36
|
+
value: number;
|
|
37
|
+
/** 0 to 100. */
|
|
38
|
+
probability: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function weightDefaults(deals: readonly Deal[]): WeightDefaults {
|
|
42
|
+
const values = deals.flatMap((deal) => (deal.targetValue ? [minorOf(deal.targetValue)] : []));
|
|
43
|
+
const chances = deals.flatMap((deal) => (typeof deal.probability === 'number' ? [deal.probability] : []));
|
|
44
|
+
return { value: Math.max(1, average(values) ?? 1), probability: average(chances) ?? DEFAULT_PROBABILITY };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A deal's weighted score: its value (the average when it has none, and at least 1) times its chance of winning (the
|
|
49
|
+
* average probability when it has none, or 10%), divided by the days until its expected close (30 when it has none,
|
|
50
|
+
* and at least 1, so overdue deals count as due now). Values are compared in minor units, whatever the currency.
|
|
51
|
+
*/
|
|
52
|
+
export function weightedScore(deal: Deal, defaults: WeightDefaults, now: Date): number {
|
|
53
|
+
const value = Math.max(1, deal.targetValue ? minorOf(deal.targetValue) : defaults.value);
|
|
54
|
+
const probability = typeof deal.probability === 'number' ? deal.probability : defaults.probability;
|
|
55
|
+
const days = Math.max(1, daysToClose(deal, now) ?? DEFAULT_DAYS_TO_CLOSE);
|
|
56
|
+
return (value * probability) / 100 / days;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Deals in `order`, ties by title. Averages for the weighted order come from all of `deals`. */
|
|
60
|
+
export function sortDeals(deals: readonly Deal[], order: DealOrder, now = new Date()): Deal[] {
|
|
61
|
+
const byTitle = (a: Deal, b: Deal) => a.title.localeCompare(b.title, 'en-GB');
|
|
62
|
+
switch (order) {
|
|
63
|
+
case 'weighted': {
|
|
64
|
+
const defaults = weightDefaults(deals);
|
|
65
|
+
const scores = new Map(deals.map((deal) => [deal.urn, weightedScore(deal, defaults, now)]));
|
|
66
|
+
return deals.toSorted((a, b) => scores.get(b.urn)! - scores.get(a.urn)! || byTitle(a, b));
|
|
67
|
+
}
|
|
68
|
+
case 'size':
|
|
69
|
+
return deals.toSorted((a, b) => minorOf(b.targetValue) - minorOf(a.targetValue) || byTitle(a, b));
|
|
70
|
+
case 'urgency':
|
|
71
|
+
return deals.toSorted((a, b) => {
|
|
72
|
+
const da = daysToClose(a, now) ?? Number.POSITIVE_INFINITY;
|
|
73
|
+
const db = daysToClose(b, now) ?? Number.POSITIVE_INFINITY;
|
|
74
|
+
return da === db ? byTitle(a, b) : da - db;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** What a deals board shows. Absent fields don't filter; `null` assignee or company means "none". */
|
|
80
|
+
export interface DealFilter {
|
|
81
|
+
/** Words to find in the title, or the names of its companies, contacts and assignee. */
|
|
82
|
+
text?: string | undefined;
|
|
83
|
+
outcome?: DealOutcome | undefined;
|
|
84
|
+
assignee?: string | null | undefined;
|
|
85
|
+
company?: string | null | undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Deals matching `filter`. `name` names a company or person, for the text search. */
|
|
89
|
+
export function filterDeals(
|
|
90
|
+
deals: readonly Deal[],
|
|
91
|
+
filter: DealFilter,
|
|
92
|
+
name: (urn: string) => string | undefined = () => undefined,
|
|
93
|
+
): Deal[] {
|
|
94
|
+
const words = (filter.text ?? '').toLocaleLowerCase('en-GB').split(/\s+/).filter(Boolean);
|
|
95
|
+
return deals.filter((deal) => {
|
|
96
|
+
if (filter.outcome && dealOutcome(deal) !== filter.outcome) return false;
|
|
97
|
+
if (filter.assignee !== undefined && (deal.assignee?.urn ?? null) !== filter.assignee) return false;
|
|
98
|
+
if (filter.company !== undefined) {
|
|
99
|
+
const companies = deal.contactCompanies ?? [];
|
|
100
|
+
if (filter.company === null ? companies.length > 0 : !companies.some((c) => c.urn === filter.company))
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (words.length === 0) return true;
|
|
104
|
+
const haystack = [
|
|
105
|
+
deal.title,
|
|
106
|
+
...[
|
|
107
|
+
...(deal.contactCompanies ?? []),
|
|
108
|
+
...(deal.contactIdentities ?? []),
|
|
109
|
+
...(deal.assignee ? [deal.assignee] : []),
|
|
110
|
+
].map((ref) => name(ref.urn) ?? ''),
|
|
111
|
+
]
|
|
112
|
+
.join(' ')
|
|
113
|
+
.toLocaleLowerCase('en-GB');
|
|
114
|
+
return words.every((word) => haystack.includes(word));
|
|
115
|
+
});
|
|
116
|
+
}
|
package/src/index.ts
CHANGED
package/src/invoices.ts
CHANGED
|
@@ -6,11 +6,31 @@ import type { Invoice, InvoiceStatus, Money, Remittance } from './types.ts';
|
|
|
6
6
|
/** Statuses of an invoice that has been sent and is waiting to be paid. */
|
|
7
7
|
export const AWAITING_PAYMENT: readonly InvoiceStatus[] = ['AUTHORISED', 'PENDING'];
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* Whether an invoice is a cost: paid by the business (one of `own`, the companies it counts as itself, such as the
|
|
11
|
+
* owner and its child companies) rather than paid to it. Without `own`, only the invoice's owner counts.
|
|
12
|
+
*/
|
|
13
|
+
export function isCostInvoice(invoice: Invoice, own?: ReadonlySet<string>): boolean {
|
|
14
|
+
const payer = invoice.remitter?.company?.urn;
|
|
15
|
+
return payer !== undefined && (own ? own.has(payer) : payer === invoice.owner.urn);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Every invoice status the API has, in the order an invoice usually moves through them. */
|
|
19
|
+
export const INVOICE_STATUSES: readonly InvoiceStatus[] = [
|
|
20
|
+
'DRAFT',
|
|
21
|
+
'IN_REVIEW',
|
|
22
|
+
'AUTHORISED',
|
|
23
|
+
'PENDING',
|
|
24
|
+
'PAID',
|
|
25
|
+
'REFUNDED',
|
|
26
|
+
'VOIDED',
|
|
27
|
+
];
|
|
28
|
+
|
|
9
29
|
export const INVOICE_STATUS_LABELS: Readonly<Record<InvoiceStatus, string>> = {
|
|
10
30
|
DRAFT: 'Draft',
|
|
11
31
|
IN_REVIEW: 'In review',
|
|
12
|
-
AUTHORISED: '
|
|
13
|
-
PENDING: '
|
|
32
|
+
AUTHORISED: 'Authorised',
|
|
33
|
+
PENDING: 'Pending payment',
|
|
14
34
|
VOIDED: 'Void',
|
|
15
35
|
PAID: 'Paid',
|
|
16
36
|
REFUNDED: 'Refunded',
|
package/src/period.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { parseTimestamp } from '@baack-software/baack-ts-tasks';
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* A span of time: from `start` (included) to `end` (excluded). `previous` is what it's compared with, when that isn't
|
|
5
|
+
* the same length of time just before it (see `previousRange`).
|
|
6
|
+
*/
|
|
4
7
|
export interface DateRange {
|
|
5
8
|
start: Date;
|
|
6
9
|
end: Date;
|
|
10
|
+
previous?: DateRange | undefined;
|
|
7
11
|
}
|
|
8
12
|
|
|
9
13
|
/** The `days` up to `now`, for "last 28 days" views. */
|
|
@@ -11,8 +15,9 @@ export function lastDays(days: number, now = new Date()): DateRange {
|
|
|
11
15
|
return { start: new Date(now.getTime() - days * 86_400_000), end: now };
|
|
12
16
|
}
|
|
13
17
|
|
|
14
|
-
/**
|
|
18
|
+
/** What `range` is compared with: its own `previous`, else the same length of time just before it. */
|
|
15
19
|
export function previousRange(range: DateRange): DateRange {
|
|
20
|
+
if (range.previous) return range.previous;
|
|
16
21
|
const length = range.end.getTime() - range.start.getTime();
|
|
17
22
|
return { start: new Date(range.start.getTime() - length), end: range.start };
|
|
18
23
|
}
|
|
@@ -30,3 +35,37 @@ export function inRange(timestamp: string | null | undefined, range: DateRange):
|
|
|
30
35
|
export function periodChange(current: number, previous: number): number | undefined {
|
|
31
36
|
return previous === 0 ? undefined : (current - previous) / previous;
|
|
32
37
|
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The reporting periods views offer: the last 30 days against the 30 before, or the calendar quarter or year so far
|
|
41
|
+
* against the same span of the one before. TODO: a company's own reporting year (most don't follow the calendar),
|
|
42
|
+
* once companies can record when theirs starts.
|
|
43
|
+
*/
|
|
44
|
+
export type ReportingPeriod = 'last30' | 'quarter' | 'year';
|
|
45
|
+
|
|
46
|
+
export const REPORTING_PERIODS: readonly ReportingPeriod[] = ['last30', 'quarter', 'year'];
|
|
47
|
+
|
|
48
|
+
/** The span so far of the period that started at `start`, against the same span from `before` (that period's start). */
|
|
49
|
+
function soFar(start: Date, before: Date, now: Date): DateRange {
|
|
50
|
+
const elapsed = now.getTime() - start.getTime();
|
|
51
|
+
return {
|
|
52
|
+
start,
|
|
53
|
+
end: now,
|
|
54
|
+
previous: { start: before, end: new Date(Math.min(before.getTime() + elapsed, start.getTime())) },
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A reporting period's range at `now`, in UTC, with what it's compared with. */
|
|
59
|
+
export function periodRange(period: ReportingPeriod, now = new Date()): DateRange {
|
|
60
|
+
const year = now.getUTCFullYear();
|
|
61
|
+
switch (period) {
|
|
62
|
+
case 'last30':
|
|
63
|
+
return lastDays(30, now);
|
|
64
|
+
case 'quarter': {
|
|
65
|
+
const month = now.getUTCMonth() - (now.getUTCMonth() % 3);
|
|
66
|
+
return soFar(new Date(Date.UTC(year, month, 1)), new Date(Date.UTC(year, month - 3, 1)), now);
|
|
67
|
+
}
|
|
68
|
+
case 'year':
|
|
69
|
+
return soFar(new Date(Date.UTC(year, 0, 1)), new Date(Date.UTC(year - 1, 0, 1)), now);
|
|
70
|
+
}
|
|
71
|
+
}
|