@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
package/src/account.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { isOpenLead } from './leads.ts';
|
|
2
|
+
import { addMoney, type MoneyTotals } from './money.ts';
|
|
3
|
+
import { dealOutcome, isDealWith } from './pipeline.ts';
|
|
4
|
+
import { outstandingTotals, overdueTotals, paymentsReceived } from './invoices.ts';
|
|
5
|
+
import { withPayments } from './sales.ts';
|
|
6
|
+
import type { Deal, Invoice, InvoiceParty, Lead, Pipeline, Remittance } from './types.ts';
|
|
7
|
+
|
|
8
|
+
/** Everything a CRM knows about one customer company, for its account page. */
|
|
9
|
+
export interface CompanyAccount {
|
|
10
|
+
company: string;
|
|
11
|
+
leads: Lead[];
|
|
12
|
+
openLeads: Lead[];
|
|
13
|
+
deals: Deal[];
|
|
14
|
+
openDeals: Deal[];
|
|
15
|
+
/** Open deals' target values. */
|
|
16
|
+
openValue: MoneyTotals;
|
|
17
|
+
/** Won deals' target values. */
|
|
18
|
+
wonValue: MoneyTotals;
|
|
19
|
+
/** Invoices to or paid by the company. */
|
|
20
|
+
invoices: Invoice[];
|
|
21
|
+
outstanding: MoneyTotals;
|
|
22
|
+
overdue: MoneyTotals;
|
|
23
|
+
/** Payments against the company's invoices, newest first. */
|
|
24
|
+
payments: Remittance[];
|
|
25
|
+
/** Received less refunded. */
|
|
26
|
+
received: MoneyTotals;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface AccountData {
|
|
30
|
+
leads: readonly Lead[];
|
|
31
|
+
deals: readonly Deal[];
|
|
32
|
+
pipelines: readonly Pipeline[];
|
|
33
|
+
invoices: readonly Invoice[];
|
|
34
|
+
remittances: readonly Remittance[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const isParty = (party: InvoiceParty | null | undefined, company: string) => party?.company?.urn === company;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One company's account, from a CRM owner's records: the company's leads and deals, the invoices it was sent or pays,
|
|
41
|
+
* and the payments against them. People and tasks about the company come from the identity search and
|
|
42
|
+
* baack-ts-tasks, which the host already has.
|
|
43
|
+
*/
|
|
44
|
+
export function companyAccount(company: string, data: AccountData, now = new Date()): CompanyAccount {
|
|
45
|
+
const leads = data.leads.filter((lead) => lead.contactCompany?.urn === company);
|
|
46
|
+
const deals = data.deals.filter((deal) => isDealWith(deal, company));
|
|
47
|
+
let openValue: MoneyTotals = {};
|
|
48
|
+
let wonValue: MoneyTotals = {};
|
|
49
|
+
const openDeals: Deal[] = [];
|
|
50
|
+
for (const deal of deals) {
|
|
51
|
+
const outcome = dealOutcome(deal);
|
|
52
|
+
if (outcome === 'OPEN') {
|
|
53
|
+
openDeals.push(deal);
|
|
54
|
+
openValue = addMoney(openValue, deal.targetValue);
|
|
55
|
+
} else if (outcome === 'WON') wonValue = addMoney(wonValue, deal.targetValue);
|
|
56
|
+
}
|
|
57
|
+
// Paid amounts follow the payments, so one just recorded shows on its invoice.
|
|
58
|
+
const invoices = withPayments(data.invoices, data.remittances).filter(
|
|
59
|
+
(invoice) => isParty(invoice.recipient, company) || isParty(invoice.remitter, company),
|
|
60
|
+
);
|
|
61
|
+
const invoiceUrns = new Set(invoices.map((invoice) => invoice.urn));
|
|
62
|
+
const payments = data.remittances
|
|
63
|
+
.filter((remittance) => invoiceUrns.has(remittance.paymentInvoice.urn))
|
|
64
|
+
.toSorted((a, b) => b.receivedTimestamp.localeCompare(a.receivedTimestamp));
|
|
65
|
+
return {
|
|
66
|
+
company,
|
|
67
|
+
leads,
|
|
68
|
+
openLeads: leads.filter(isOpenLead),
|
|
69
|
+
deals,
|
|
70
|
+
openDeals,
|
|
71
|
+
openValue,
|
|
72
|
+
wonValue,
|
|
73
|
+
invoices,
|
|
74
|
+
outstanding: outstandingTotals(invoices),
|
|
75
|
+
overdue: overdueTotals(invoices, now),
|
|
76
|
+
payments,
|
|
77
|
+
received: paymentsReceived(payments),
|
|
78
|
+
};
|
|
79
|
+
}
|
package/src/backend.ts
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Endpoint,
|
|
3
|
+
type BaackClient,
|
|
4
|
+
type Company,
|
|
5
|
+
type IncludeScope,
|
|
6
|
+
type Search,
|
|
7
|
+
type Workflow,
|
|
8
|
+
} from '@baack-software/baack-ts-client';
|
|
9
|
+
import { toTimestamp, urnOf, type Ref, type RefLike } from '@baack-software/baack-ts-tasks';
|
|
10
|
+
import { CrmNotFoundError, CrmSearchTimeoutError } from './errors.ts';
|
|
11
|
+
import type { CrmConcept, Deal, Invoice, InvoiceLine, InvoiceParty, Lead, Pipeline, Remittance } from './types.ts';
|
|
12
|
+
|
|
13
|
+
/** Fields of a new record: everything but what the server sets. */
|
|
14
|
+
export type RecordInput<T> = Omit<T, 'urn' | 'url' | 'createdTimestamp' | 'updatedTimestamp'>;
|
|
15
|
+
|
|
16
|
+
export type LeadInput = RecordInput<Lead>;
|
|
17
|
+
export type DealInput = RecordInput<Deal>;
|
|
18
|
+
/** A new invoice: its lines and remittances are made on their own endpoints, once it exists. */
|
|
19
|
+
export type InvoiceInput = Omit<RecordInput<Invoice>, 'lines' | 'remittances'>;
|
|
20
|
+
export type RemittanceInput = RecordInput<Remittance>;
|
|
21
|
+
/** A new line on an existing invoice. */
|
|
22
|
+
export type InvoiceLineInput = Omit<InvoiceLine, 'urn'> & { paymentInvoice: Ref };
|
|
23
|
+
|
|
24
|
+
/** A concept that can only be read. */
|
|
25
|
+
export interface ReadApi<T> {
|
|
26
|
+
/** Every record a company owns. */
|
|
27
|
+
list(owner: RefLike): Promise<T[]>;
|
|
28
|
+
get(record: RefLike): Promise<T>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A concept with full create, read, update and delete. */
|
|
32
|
+
export interface RecordApi<T, TInput> extends ReadApi<T> {
|
|
33
|
+
create(input: TInput): Promise<T>;
|
|
34
|
+
/** Applies `changes` and returns the record as stored. */
|
|
35
|
+
update(record: RefLike, changes: Partial<TInput>): Promise<T>;
|
|
36
|
+
delete(record: RefLike): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Making client companies (baack-ts-client's `Company`): a company owned by the CRM's company, named. */
|
|
40
|
+
export interface CompanyApi {
|
|
41
|
+
create(input: { owner: RefLike; name: string }): Promise<Company>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Where each CRM concept is read and written. */
|
|
45
|
+
export interface CrmBackend {
|
|
46
|
+
/** Client companies, made when a lead is created or converted with a business name. */
|
|
47
|
+
companies: CompanyApi;
|
|
48
|
+
leads: RecordApi<Lead, LeadInput>;
|
|
49
|
+
deals: RecordApi<Deal, DealInput>;
|
|
50
|
+
pipelines: ReadApi<Pipeline>;
|
|
51
|
+
invoices: RecordApi<Invoice, InvoiceInput>;
|
|
52
|
+
/** An invoice's lines are made on their own, once the invoice exists; they're read with it. */
|
|
53
|
+
invoiceLines: { create(input: InvoiceLineInput): Promise<InvoiceLine> };
|
|
54
|
+
remittances: RecordApi<Remittance, RemittanceInput>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ==========================================
|
|
58
|
+
// THE BAACK API
|
|
59
|
+
// ==========================================
|
|
60
|
+
|
|
61
|
+
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
62
|
+
|
|
63
|
+
/** The URNs of everything a company owns in one search scope: created, read again until full, pages followed. */
|
|
64
|
+
async function searchUrns(
|
|
65
|
+
client: BaackClient,
|
|
66
|
+
owner: string,
|
|
67
|
+
scope: IncludeScope,
|
|
68
|
+
timeoutMs = 15_000,
|
|
69
|
+
): Promise<string[]> {
|
|
70
|
+
let search: Search = await client.search({ owner: { urn: owner, url: '' }, includeScopes: [scope], order: 'NAME' });
|
|
71
|
+
const urn = search.urn;
|
|
72
|
+
if (!urn) throw new Error('The API created a search without a URN');
|
|
73
|
+
const started = Date.now();
|
|
74
|
+
for (let delay = 250; search.status !== 'FULL_RESULT'; delay = Math.min(delay * 1.5, 2000)) {
|
|
75
|
+
if (Date.now() - started > timeoutMs) throw new CrmSearchTimeoutError();
|
|
76
|
+
await wait(delay);
|
|
77
|
+
search = await client.searchResult(urn);
|
|
78
|
+
}
|
|
79
|
+
const urns = (search.items ?? []).map((item) => item.urn);
|
|
80
|
+
for (let page = search; page.pagination?.isMorePages && page.pagination.after;) {
|
|
81
|
+
page = await client.searchResult(urn, page.pagination.after);
|
|
82
|
+
urns.push(...(page.items ?? []).map((item) => item.urn));
|
|
83
|
+
}
|
|
84
|
+
return urns;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The API is rate limited (10 requests a second): records found by search are read a few at a time. */
|
|
88
|
+
const READS_AT_ONCE = 4;
|
|
89
|
+
|
|
90
|
+
async function readEach<T>(urns: readonly string[], read: (urn: string) => Promise<T>): Promise<T[]> {
|
|
91
|
+
const records: T[] = new Array(urns.length);
|
|
92
|
+
let next = 0;
|
|
93
|
+
const worker = async () => {
|
|
94
|
+
for (let index = next++; index < urns.length; index = next++) records[index] = await read(urns[index]!);
|
|
95
|
+
};
|
|
96
|
+
await Promise.all(Array.from({ length: Math.min(READS_AT_ONCE, urns.length) }, worker));
|
|
97
|
+
return records;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Any of the API's links, which are the same type with only a URN (and URL) set. */
|
|
101
|
+
type Linked = { urn?: string | null } | null | undefined;
|
|
102
|
+
|
|
103
|
+
/** A link as a ref, or null when it's absent or empty (the API has answered a missing link as `{ urn: "" }`). */
|
|
104
|
+
const link = (value: Linked): Ref | null => (value?.urn ? { urn: value.urn } : null);
|
|
105
|
+
const links = (values: readonly Linked[] | null | undefined): Ref[] =>
|
|
106
|
+
(values ?? []).flatMap((value) => (value?.urn ? [{ urn: value.urn }] : []));
|
|
107
|
+
const party = (value: { company?: Linked; identity?: Linked } | null | undefined): InvoiceParty | null => {
|
|
108
|
+
const company = link(value?.company);
|
|
109
|
+
const identity = link(value?.identity);
|
|
110
|
+
return company || identity ? { company, identity } : null;
|
|
111
|
+
};
|
|
112
|
+
/** An empty text as absent: the API answers an unset reason as "". */
|
|
113
|
+
const text = (value: string | null | undefined) => value || null;
|
|
114
|
+
|
|
115
|
+
/** The fields of the API's representations that are turned into the package's: links as refs, lists present. */
|
|
116
|
+
interface Raw {
|
|
117
|
+
urn: string;
|
|
118
|
+
owner?: Linked;
|
|
119
|
+
assignee?: Linked;
|
|
120
|
+
entity?: Linked;
|
|
121
|
+
contactIdentity?: Linked;
|
|
122
|
+
contactCompany?: Linked;
|
|
123
|
+
contactCompanies?: Linked[] | null;
|
|
124
|
+
contactIdentities?: Linked[] | null;
|
|
125
|
+
workflowStage?: Linked;
|
|
126
|
+
leadSource?: Linked;
|
|
127
|
+
invoices?: Linked[] | null;
|
|
128
|
+
closedReason?: string | null;
|
|
129
|
+
lostReason?: string | null;
|
|
130
|
+
remitter?: { company?: Linked; identity?: Linked } | null;
|
|
131
|
+
recipient?: { company?: Linked; identity?: Linked } | null;
|
|
132
|
+
lines?: unknown[] | null;
|
|
133
|
+
remittances?: Raw[] | null;
|
|
134
|
+
paymentInvoice?: Linked;
|
|
135
|
+
remittingCompany?: Linked;
|
|
136
|
+
remittingIdentity?: Linked;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// The API's representations as the package's: links as refs, lists always present.
|
|
140
|
+
|
|
141
|
+
const asLead = (raw: Raw): Lead =>
|
|
142
|
+
({
|
|
143
|
+
...raw,
|
|
144
|
+
owner: link(raw.owner)!,
|
|
145
|
+
contactIdentity: link(raw.contactIdentity),
|
|
146
|
+
contactCompany: link(raw.contactCompany),
|
|
147
|
+
assignee: link(raw.assignee),
|
|
148
|
+
entity: link(raw.entity),
|
|
149
|
+
closedReason: text(raw.closedReason),
|
|
150
|
+
}) as unknown as Lead;
|
|
151
|
+
|
|
152
|
+
const asDeal = (raw: Raw): Deal =>
|
|
153
|
+
({
|
|
154
|
+
...raw,
|
|
155
|
+
owner: link(raw.owner)!,
|
|
156
|
+
contactCompanies: links(raw.contactCompanies),
|
|
157
|
+
contactIdentities: links(raw.contactIdentities),
|
|
158
|
+
workflowStage: link(raw.workflowStage),
|
|
159
|
+
leadSource: link(raw.leadSource),
|
|
160
|
+
assignee: link(raw.assignee),
|
|
161
|
+
invoices: links(raw.invoices),
|
|
162
|
+
entity: link(raw.entity),
|
|
163
|
+
lostReason: text(raw.lostReason),
|
|
164
|
+
}) as unknown as Deal;
|
|
165
|
+
|
|
166
|
+
const asRemittance = (raw: Raw, invoice?: string): Remittance =>
|
|
167
|
+
({
|
|
168
|
+
...raw,
|
|
169
|
+
// On its invoice, a remittance's own link to the invoice can be absent: it's the invoice it's listed on.
|
|
170
|
+
paymentInvoice: link(raw.paymentInvoice) ?? { urn: invoice ?? '' },
|
|
171
|
+
remittingCompany: link(raw.remittingCompany),
|
|
172
|
+
remittingIdentity: link(raw.remittingIdentity),
|
|
173
|
+
}) as unknown as Remittance;
|
|
174
|
+
|
|
175
|
+
const asInvoice = (raw: Raw): Invoice =>
|
|
176
|
+
({
|
|
177
|
+
...raw,
|
|
178
|
+
owner: link(raw.owner)!,
|
|
179
|
+
remitter: party(raw.remitter),
|
|
180
|
+
recipient: party(raw.recipient),
|
|
181
|
+
lines: raw.lines ?? [],
|
|
182
|
+
remittances: (raw.remittances ?? []).map((remittance) => asRemittance(remittance, raw.urn)),
|
|
183
|
+
}) as unknown as Invoice;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* One concept on the API: listed by search in `scope` then read a few at a time, read by URN, created, updated (the
|
|
187
|
+
* record is read, the changes merged in, and the whole of it sent, as the API replaces on update; then read back) and
|
|
188
|
+
* deleted. `as` turns the API's representation into the package's.
|
|
189
|
+
*/
|
|
190
|
+
function onApi<T, TInput>(
|
|
191
|
+
client: BaackClient,
|
|
192
|
+
endpoint: string,
|
|
193
|
+
scope: IncludeScope,
|
|
194
|
+
as: (raw: Raw) => T,
|
|
195
|
+
omit: readonly string[] = [],
|
|
196
|
+
): RecordApi<T, TInput> {
|
|
197
|
+
const read = async (urn: string) => as(await client.read<Raw>(endpoint, urn));
|
|
198
|
+
const body = (record: object) =>
|
|
199
|
+
Object.fromEntries(Object.entries(record).filter(([field]) => !omit.includes(field)));
|
|
200
|
+
return {
|
|
201
|
+
list: async (owner) => readEach(await searchUrns(client, urnOf(owner), scope), read),
|
|
202
|
+
get: (record) => read(urnOf(record)),
|
|
203
|
+
create: async (input) => as(await client.create<Raw>(endpoint, body(input as object))),
|
|
204
|
+
async update(record, changes) {
|
|
205
|
+
const urn = urnOf(record);
|
|
206
|
+
const current = await client.read<Raw>(endpoint, urn);
|
|
207
|
+
await client.update(endpoint, urn, body({ ...current, ...changes }));
|
|
208
|
+
return read(urn);
|
|
209
|
+
},
|
|
210
|
+
delete: async (record) => {
|
|
211
|
+
await client.delete(endpoint, urnOf(record));
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Every CRM concept on the Baack API: leads, deals and payment invoices found by search; remittances, which have no
|
|
218
|
+
* owner, through their invoices; pipelines are the company's workflows.
|
|
219
|
+
*/
|
|
220
|
+
export function apiBackend(client: BaackClient): CrmBackend {
|
|
221
|
+
const invoices = onApi<Invoice, InvoiceInput>(client, Endpoint.PAYMENT_INVOICE, 'PAYMENT_INVOICE', asInvoice, [
|
|
222
|
+
// Ignored on update, and made on their own endpoints.
|
|
223
|
+
'lines',
|
|
224
|
+
'remittances',
|
|
225
|
+
]);
|
|
226
|
+
const remittance = async (urn: string) => asRemittance(await client.read<Raw>(Endpoint.INVOICE_REMITTANCE, urn));
|
|
227
|
+
return {
|
|
228
|
+
companies: {
|
|
229
|
+
create: ({ owner, name }) => client.create<Company>(Endpoint.COMPANY, { owner: { urn: urnOf(owner) }, name }),
|
|
230
|
+
},
|
|
231
|
+
leads: onApi(client, Endpoint.LEAD, 'LEAD', asLead),
|
|
232
|
+
deals: onApi(client, Endpoint.DEAL, 'DEAL', asDeal),
|
|
233
|
+
invoices,
|
|
234
|
+
invoiceLines: { create: (input) => client.create<InvoiceLine>(Endpoint.INVOICE_LINE, input) },
|
|
235
|
+
remittances: {
|
|
236
|
+
list: async (owner) => (await invoices.list(owner)).flatMap((invoice) => invoice.remittances ?? []),
|
|
237
|
+
get: (record) => remittance(urnOf(record)),
|
|
238
|
+
create: async (input) => asRemittance(await client.create<Raw>(Endpoint.INVOICE_REMITTANCE, input)),
|
|
239
|
+
async update(record, changes) {
|
|
240
|
+
const urn = urnOf(record);
|
|
241
|
+
const current = await client.read<Raw>(Endpoint.INVOICE_REMITTANCE, urn);
|
|
242
|
+
await client.update(Endpoint.INVOICE_REMITTANCE, urn, { ...current, ...changes });
|
|
243
|
+
return remittance(urn);
|
|
244
|
+
},
|
|
245
|
+
delete: async (record) => {
|
|
246
|
+
await client.delete(Endpoint.INVOICE_REMITTANCE, urnOf(record));
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
pipelines: {
|
|
250
|
+
list: async (owner) =>
|
|
251
|
+
readEach(await searchUrns(client, urnOf(owner), 'WORKFLOW'), (urn) =>
|
|
252
|
+
client.read<Workflow>(Endpoint.WORKFLOW, urn),
|
|
253
|
+
),
|
|
254
|
+
get: (record) => client.read<Workflow>(Endpoint.WORKFLOW, urnOf(record)),
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ==========================================
|
|
260
|
+
// IN MEMORY (sample data, tests, demos)
|
|
261
|
+
// ==========================================
|
|
262
|
+
|
|
263
|
+
/** The records an in-memory backend starts with. */
|
|
264
|
+
export interface CrmData {
|
|
265
|
+
leads: Lead[];
|
|
266
|
+
deals: Deal[];
|
|
267
|
+
pipelines: Pipeline[];
|
|
268
|
+
invoices: Invoice[];
|
|
269
|
+
/** Kept apart from their invoices here; the API lists them on the invoice. */
|
|
270
|
+
remittances: Remittance[];
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export interface MemoryOptions {
|
|
274
|
+
/** Delay before each answer, to show loading states in demos. Default 0. */
|
|
275
|
+
latencyMs?: number;
|
|
276
|
+
/** New records' URNs. Default `crypto.randomUUID()`. */
|
|
277
|
+
newUrn?: () => string;
|
|
278
|
+
/** The time new and changed records are stamped with. Default now. */
|
|
279
|
+
now?: () => Date;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Every CRM concept held in memory, starting from `data` (copied, so the caller's arrays aren't changed). Writes
|
|
284
|
+
* behave as the API's would: create stamps a URN and times, update merges the changes, delete removes.
|
|
285
|
+
*/
|
|
286
|
+
export function memoryBackend(data: CrmData, options: MemoryOptions = {}): CrmBackend {
|
|
287
|
+
const { latencyMs = 0, newUrn = () => crypto.randomUUID(), now = () => new Date() } = options;
|
|
288
|
+
const answer = async <T>(value: T): Promise<T> => {
|
|
289
|
+
if (latencyMs > 0) await wait(latencyMs);
|
|
290
|
+
return structuredClone(value);
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
function collection<T extends { urn: string }, TInput>(
|
|
294
|
+
concept: CrmConcept,
|
|
295
|
+
records: T[],
|
|
296
|
+
url: string,
|
|
297
|
+
stamped: boolean,
|
|
298
|
+
ownerOf: (record: T) => string | undefined,
|
|
299
|
+
): RecordApi<T, TInput> {
|
|
300
|
+
const find = (record: RefLike) => {
|
|
301
|
+
const index = records.findIndex((candidate) => candidate.urn === urnOf(record));
|
|
302
|
+
if (index < 0) throw new CrmNotFoundError(concept, urnOf(record));
|
|
303
|
+
return index;
|
|
304
|
+
};
|
|
305
|
+
return {
|
|
306
|
+
list: async (owner) => answer(records.filter((record) => ownerOf(record) === urnOf(owner))),
|
|
307
|
+
get: async (record) => answer(records[find(record)]!),
|
|
308
|
+
async create(input) {
|
|
309
|
+
const urn = newUrn();
|
|
310
|
+
const time = toTimestamp(now());
|
|
311
|
+
const created = {
|
|
312
|
+
...structuredClone(input),
|
|
313
|
+
urn,
|
|
314
|
+
url: `${url}${urn}`,
|
|
315
|
+
...(stamped ? { createdTimestamp: time, updatedTimestamp: time } : {}),
|
|
316
|
+
} as unknown as T;
|
|
317
|
+
records.push(created);
|
|
318
|
+
return answer(created);
|
|
319
|
+
},
|
|
320
|
+
async update(record, changes) {
|
|
321
|
+
const index = find(record);
|
|
322
|
+
const updated = {
|
|
323
|
+
...records[index]!,
|
|
324
|
+
...structuredClone(changes),
|
|
325
|
+
...(stamped ? { updatedTimestamp: toTimestamp(now()) } : {}),
|
|
326
|
+
};
|
|
327
|
+
records[index] = updated;
|
|
328
|
+
return answer(updated);
|
|
329
|
+
},
|
|
330
|
+
async delete(record) {
|
|
331
|
+
records.splice(find(record), 1);
|
|
332
|
+
await answer(undefined);
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const copy = structuredClone(data);
|
|
338
|
+
const owned = (record: { owner?: { urn: string } | null }) => record.owner?.urn;
|
|
339
|
+
// A remittance has no owner: it's its invoice's owner's.
|
|
340
|
+
const invoiceOwner = (remittance: Remittance) =>
|
|
341
|
+
copy.invoices.find((invoice) => invoice.urn === remittance.paymentInvoice.urn)?.owner.urn;
|
|
342
|
+
return {
|
|
343
|
+
// Sample companies live only in memory: converting a sample lead never makes a real company.
|
|
344
|
+
companies: {
|
|
345
|
+
async create({ owner, name }) {
|
|
346
|
+
const urn = newUrn();
|
|
347
|
+
const company: Company = {
|
|
348
|
+
urn,
|
|
349
|
+
url: `/n/v1/company/${urn}`,
|
|
350
|
+
name,
|
|
351
|
+
owner: { urn: urnOf(owner), url: `/n/v1/company/${urnOf(owner)}` },
|
|
352
|
+
};
|
|
353
|
+
return answer(company);
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
leads: collection('leads', copy.leads, '/n/v1/lead/', true, owned),
|
|
357
|
+
deals: collection('deals', copy.deals, '/n/v1/deal/', true, owned),
|
|
358
|
+
invoiceLines: {
|
|
359
|
+
async create({ paymentInvoice, ...fields }) {
|
|
360
|
+
const invoice = copy.invoices.find((candidate) => candidate.urn === paymentInvoice.urn);
|
|
361
|
+
if (!invoice) throw new CrmNotFoundError('invoices', paymentInvoice.urn);
|
|
362
|
+
const line: InvoiceLine = { ...structuredClone(fields), urn: newUrn() };
|
|
363
|
+
invoice.lines = [...(invoice.lines ?? []), line];
|
|
364
|
+
return answer(line);
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
remittances: collection('remittances', copy.remittances, '/n/v1/invoiceremittance/', false, invoiceOwner),
|
|
368
|
+
pipelines: collection('pipelines', copy.pipelines, '', false, owned),
|
|
369
|
+
invoices: collection('invoices', copy.invoices, '/n/v1/paymentinvoice/', false, owned),
|
|
370
|
+
};
|
|
371
|
+
}
|