@baack-software/baack-ts-crm 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/backend.d.ts +29 -1
  2. package/dist/backend.d.ts.map +1 -1
  3. package/dist/backend.js +95 -0
  4. package/dist/backend.js.map +1 -1
  5. package/dist/crm-client.d.ts +55 -13
  6. package/dist/crm-client.d.ts.map +1 -1
  7. package/dist/crm-client.js +99 -15
  8. package/dist/crm-client.js.map +1 -1
  9. package/dist/deal-order.d.ts +42 -0
  10. package/dist/deal-order.d.ts.map +1 -0
  11. package/dist/deal-order.js +80 -0
  12. package/dist/deal-order.js.map +1 -0
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/invoices.d.ts +7 -0
  18. package/dist/invoices.d.ts.map +1 -1
  19. package/dist/invoices.js +20 -2
  20. package/dist/invoices.js.map +1 -1
  21. package/dist/period.d.ts +15 -2
  22. package/dist/period.d.ts.map +1 -1
  23. package/dist/period.js +27 -1
  24. package/dist/period.js.map +1 -1
  25. package/dist/pipeline.d.ts +6 -0
  26. package/dist/pipeline.d.ts.map +1 -1
  27. package/dist/pipeline.js +18 -0
  28. package/dist/pipeline.js.map +1 -1
  29. package/dist/react/ChoiceCombobox.d.ts +36 -0
  30. package/dist/react/ChoiceCombobox.d.ts.map +1 -0
  31. package/dist/react/ChoiceCombobox.js +105 -0
  32. package/dist/react/ChoiceCombobox.js.map +1 -0
  33. package/dist/react/DealsBoard.d.ts +22 -3
  34. package/dist/react/DealsBoard.d.ts.map +1 -1
  35. package/dist/react/DealsBoard.js +53 -4
  36. package/dist/react/DealsBoard.js.map +1 -1
  37. package/dist/react/Details.d.ts +40 -7
  38. package/dist/react/Details.d.ts.map +1 -1
  39. package/dist/react/Details.js +180 -23
  40. package/dist/react/Details.js.map +1 -1
  41. package/dist/react/Forms.d.ts +148 -17
  42. package/dist/react/Forms.d.ts.map +1 -1
  43. package/dist/react/Forms.js +365 -75
  44. package/dist/react/Forms.js.map +1 -1
  45. package/dist/react/Sales.d.ts +25 -6
  46. package/dist/react/Sales.d.ts.map +1 -1
  47. package/dist/react/Sales.js +114 -30
  48. package/dist/react/Sales.js.map +1 -1
  49. package/dist/react/SidePanel.d.ts +10 -0
  50. package/dist/react/SidePanel.d.ts.map +1 -1
  51. package/dist/react/SidePanel.js +14 -2
  52. package/dist/react/SidePanel.js.map +1 -1
  53. package/dist/react/index.d.ts +1 -0
  54. package/dist/react/index.d.ts.map +1 -1
  55. package/dist/react/index.js +1 -0
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/react/parts.d.ts +12 -2
  58. package/dist/react/parts.d.ts.map +1 -1
  59. package/dist/react/parts.js +25 -2
  60. package/dist/react/parts.js.map +1 -1
  61. package/dist/react/pipeline-choice.d.ts +19 -0
  62. package/dist/react/pipeline-choice.d.ts.map +1 -0
  63. package/dist/react/pipeline-choice.js +39 -0
  64. package/dist/react/pipeline-choice.js.map +1 -0
  65. package/dist/react/text.d.ts +89 -2
  66. package/dist/react/text.d.ts.map +1 -1
  67. package/dist/react/text.js +89 -2
  68. package/dist/react/text.js.map +1 -1
  69. package/dist/react/ui/badge.d.ts +1 -1
  70. package/dist/react/ui/button.d.ts +2 -2
  71. package/dist/react/views.d.ts +33 -11
  72. package/dist/react/views.d.ts.map +1 -1
  73. package/dist/react/views.js +96 -27
  74. package/dist/react/views.js.map +1 -1
  75. package/dist/sales.d.ts +28 -3
  76. package/dist/sales.d.ts.map +1 -1
  77. package/dist/sales.js +33 -10
  78. package/dist/sales.js.map +1 -1
  79. package/dist/store.d.ts +31 -12
  80. package/dist/store.d.ts.map +1 -1
  81. package/dist/store.js +82 -21
  82. package/dist/store.js.map +1 -1
  83. package/dist/target.d.ts +2 -1
  84. package/dist/target.d.ts.map +1 -1
  85. package/dist/target.js +6 -2
  86. package/dist/target.js.map +1 -1
  87. package/dist/types.d.ts +24 -0
  88. package/dist/types.d.ts.map +1 -1
  89. package/dist/types.js.map +1 -1
  90. package/package.json +1 -1
  91. package/src/backend.ts +131 -1
  92. package/src/crm-client.ts +162 -19
  93. package/src/deal-order.ts +116 -0
  94. package/src/index.ts +1 -0
  95. package/src/invoices.ts +22 -2
  96. package/src/period.ts +41 -2
  97. package/src/pipeline.ts +21 -0
  98. package/src/react/ChoiceCombobox.tsx +227 -0
  99. package/src/react/DealsBoard.tsx +171 -4
  100. package/src/react/Details.tsx +608 -31
  101. package/src/react/Forms.tsx +1006 -139
  102. package/src/react/Sales.tsx +332 -44
  103. package/src/react/SidePanel.tsx +19 -10
  104. package/src/react/index.ts +1 -0
  105. package/src/react/parts.tsx +56 -4
  106. package/src/react/pipeline-choice.ts +54 -0
  107. package/src/react/text.ts +90 -2
  108. package/src/react/views.tsx +222 -32
  109. package/src/sales.ts +57 -10
  110. package/src/store.ts +136 -27
  111. package/src/target.ts +5 -2
  112. package/src/types.ts +28 -0
@@ -1,22 +1,30 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { ref } from '@baack-software/baack-ts-tasks';
3
- import { Plus, X } from 'lucide-react';
3
+ import { ChevronRight, Plus, X } from 'lucide-react';
4
4
  import { useId, useState } from 'react';
5
+ import { INVOICE_STATUSES, INVOICE_STATUS_LABELS } from "../invoices.js";
5
6
  import { LEAD_SOURCES, SOURCE_LABELS } from "../leads.js";
6
- import { fractionDigits, fromMinor, toMinor } from "../money.js";
7
+ import { formatMoney, fractionDigits, fromMinor, toMinor } from "../money.js";
7
8
  import { orderedStages } from "../pipeline.js";
9
+ import { ChoiceCombobox } from "./ChoiceCombobox.js";
10
+ import { PanelCloseButton } from "./SidePanel.js";
8
11
  import { withText } from "./text.js";
9
12
  import { Button } from "./ui/button.js";
13
+ import { Card, CardAction, CardContent, CardHeader, CardTitle } from "./ui/card.js";
10
14
  import { Input } from "./ui/input.js";
11
15
  import { Label } from "./ui/label.js";
12
16
  import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select.js";
13
17
  /** Radix's select keeps "" for "no value", so "none" is chosen with this instead. */
14
18
  const NONE = '__none__';
19
+ /** "Add a new ..." in a choice select. */
20
+ const ADD = '__add__';
21
+ /** A new record, made when the form is saved, shown as chosen. */
22
+ const PENDING = '__pending__';
15
23
  /**
16
24
  * An amount typed in major units (120.00, or 1,500.00 with separators) as minor units, or undefined when it isn't a
17
25
  * number of at least zero.
18
26
  */
19
- function minorOrUndefined(amount, currencyCode) {
27
+ export function minorOrUndefined(amount, currencyCode) {
20
28
  try {
21
29
  const minor = toMinor(amount.replaceAll(',', '').trim(), currencyCode);
22
30
  return minor >= 0 ? minor : undefined;
@@ -29,21 +37,121 @@ function minorOrUndefined(amount, currencyCode) {
29
37
  const dayTimestamp = (day) => (day ? `${day}T00:00:00` : null);
30
38
  const today = (now) => now.toISOString().slice(0, 10);
31
39
  const inDays = (now, days) => today(new Date(now.getTime() + days * 86_400_000));
32
- /** A form's frame: its heading, fields, problem and submit button, as the record payment form is laid out. */
33
- function FormFrame({ title, submit, submitting, saving, error, onSubmit, children, }) {
40
+ /**
41
+ * A form's frame: a card, as an open record's is, with its heading (and the side panel's close button), fields,
42
+ * problem and submit button. `back` adds a way back beside the submit button, for a step of a larger form.
43
+ */
44
+ function FormFrame({ title, submit, submitting, saving, error, onSubmit, back, framed = true, children, }) {
34
45
  const id = useId();
35
46
  const errorId = error ? `${id}-error` : undefined;
36
- return (_jsxs("form", { className: "grid gap-3", "aria-labelledby": `${id}-title`, noValidate: true, onSubmit: (event) => {
47
+ const heading = (_jsx("h2", { id: `${id}-title`, className: "text-base font-semibold", children: title }));
48
+ const form = (_jsxs("form", { className: "grid gap-3", "aria-labelledby": `${id}-title`, noValidate: true, onSubmit: (event) => {
37
49
  event.preventDefault();
38
50
  void onSubmit();
39
- }, children: [_jsx("h2", { id: `${id}-title`, className: "text-base font-semibold", children: title }), children({ error: errorId }), error && (_jsx("p", { id: errorId, role: "alert", className: "text-destructive text-sm", children: error })), _jsx("div", { children: _jsx(Button, { type: "submit", disabled: saving, children: saving ? submitting : submit }) })] }));
51
+ }, children: [!framed && (_jsxs("div", { className: "flex items-center justify-between gap-2", children: [heading, _jsx(PanelCloseButton, {})] })), children({ error: errorId }), error && (_jsx("p", { id: errorId, role: "alert", className: "text-destructive text-sm", children: error })), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { type: "submit", disabled: saving, children: saving ? submitting : submit }), back && (_jsx(Button, { type: "button", variant: "ghost", onClick: back.onBack, children: back.label }))] })] }));
52
+ if (!framed)
53
+ return form;
54
+ return (_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: heading }), _jsx(CardAction, { children: _jsx(PanelCloseButton, {}) })] }), _jsx(CardContent, { children: form })] }));
40
55
  }
41
- function Field({ id, label, hint, children }) {
56
+ export function Field({ id, label, hint, children, }) {
42
57
  return (_jsxs("div", { className: "grid gap-1.5", children: [_jsx(Label, { htmlFor: id, children: label }), children, hint && (_jsx("p", { id: `${id}-hint`, className: "text-muted-foreground text-xs", children: hint }))] }));
43
58
  }
44
- function CompanySelect({ id, value, onChange, companies, none, }) {
45
- return (_jsxs(Select, { value: value || NONE, onValueChange: (next) => onChange(next === NONE ? '' : next), children: [_jsx(SelectTrigger, { id: id, className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: NONE, children: none }), companies.map((company) => (_jsx(SelectItem, { value: company.urn, children: company.name }, company.urn)))] })] }));
59
+ /**
60
+ * A record to link: none, one of `choices`, or, with `add`, a new one made by the step `add` opens. A new one waiting
61
+ * to be made shows as chosen (`pending`, its name). A linked record missing from `choices` is still shown, named by
62
+ * `named` or by the end of its URN.
63
+ */
64
+ export function ChoiceSelect({ id, value, onChange, choices, none, add, pending, named, disabled, describedBy, text, }) {
65
+ const words = withText(text);
66
+ const missing = value && !choices.some((choice) => choice.urn === value) ? value : undefined;
67
+ return (_jsxs(Select, { value: pending ? PENDING : value || NONE, disabled: disabled ?? false, onValueChange: (next) => {
68
+ if (next === ADD)
69
+ add?.onAdd();
70
+ else if (next !== PENDING)
71
+ onChange(next === NONE ? '' : next);
72
+ }, children: [_jsx(SelectTrigger, { id: id, className: "w-full", "aria-describedby": describedBy, children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: NONE, children: none }), pending && _jsx(SelectItem, { value: PENDING, children: `${pending} (${words.toBeCreated})` }), missing && _jsx(SelectItem, { value: missing, children: named?.(missing) ?? `...${missing.slice(-6)}` }), choices.map((choice) => (_jsxs(SelectItem, { value: choice.urn, children: [choice.name, choice.detail && (_jsxs(_Fragment, { children: [' ', _jsx("span", { className: "text-muted-foreground", children: choice.detail })] }))] }, choice.urn))), add && _jsx(SelectItem, { value: ADD, children: add.label })] })] }));
73
+ }
74
+ /** The currencies offered for an amount, with the one it's already in when that's another. */
75
+ export const CURRENCIES = ['GBP', 'EUR', 'USD'];
76
+ /**
77
+ * An amount of money: a currency select joined to the amount, typed in major units (1,500.00). The amount's input
78
+ * has `id`, so a field's label names it; the currency select is named by `currencyLabel`.
79
+ */
80
+ export function MoneyInput({ id, amount, currencyCode, onAmount, onCurrency, onCommit, describedBy, text, }) {
81
+ const words = withText(text);
82
+ const currencies = CURRENCIES.includes(currencyCode) ? CURRENCIES : [currencyCode, ...CURRENCIES];
83
+ return (_jsxs("div", { className: "flex", children: [_jsxs(Select, { value: currencyCode, onValueChange: onCurrency, children: [_jsx(SelectTrigger, { "aria-label": words.currency, className: "w-24 shrink-0 rounded-e-none border-e-0", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: currencies.map((code) => (_jsx(SelectItem, { value: code, children: code }, code))) })] }), _jsx(Input, { id: id, inputMode: "decimal", className: "rounded-s-none", value: amount, onChange: (event) => onAmount(event.target.value), onBlur: onCommit, onKeyDown: (event) => {
84
+ if (event.key === 'Enter')
85
+ onCommit?.();
86
+ }, "aria-describedby": describedBy })] }));
87
+ }
88
+ /**
89
+ * Money typed into a `MoneyInput`, for saving: the money, null for no amount, or undefined when the amount isn't a
90
+ * number of at least zero.
91
+ */
92
+ export function moneyOf(amount, currencyCode) {
93
+ if (!amount.trim())
94
+ return null;
95
+ const minor = minorOrUndefined(amount, currencyCode);
96
+ if (minor === undefined)
97
+ return undefined;
98
+ return minor ? fromMinor(minor, currencyCode) : null;
99
+ }
100
+ /**
101
+ * A new client company, as a step of a lead's form: its name, made when the lead is saved. `Use this` goes back to
102
+ * the lead with it chosen.
103
+ */
104
+ export function NewCompanyStep({ initial = '', onUse, onBack, framed, text, }) {
105
+ const words = withText(text);
106
+ const id = useId();
107
+ const [name, setName] = useState(initial);
108
+ const { saving, error, setError, run } = useSave();
109
+ return (_jsx(FormFrame, { title: words.newCompany, submit: words.useThis, submitting: words.saving, saving: saving, error: error, back: { label: words.back, onBack }, framed: framed, onSubmit: async () => {
110
+ if (!name.trim())
111
+ return setError(words.companyNameRequired);
112
+ await run(async () => onUse(name.trim()));
113
+ }, children: ({ error: errorId }) => (_jsx(Field, { id: `${id}-name`, label: words.companyName, hint: words.newCompanyHint, children: _jsx(Input, { id: `${id}-name`, value: name, onChange: (event) => setName(event.target.value), "aria-describedby": [`${id}-name-hint`, errorId].filter(Boolean).join(' ') }) })) }));
114
+ }
115
+ /**
116
+ * A new person to be a lead's contact, as a step of the lead's form: their given and family name and email, made
117
+ * when the lead is saved. `Use this` goes back to the lead with them chosen.
118
+ */
119
+ export function NewContactStep({ initial, onUse, onBack, framed, text, }) {
120
+ const words = withText(text);
121
+ return (_jsx(ContactForm, { initial: initial, title: words.newContact, hint: words.newContactHint, submit: words.useThis, submitting: words.saving, back: { label: words.back, onBack }, framed: framed, onSave: onUse, text: text }));
122
+ }
123
+ /**
124
+ * A new person, such as one of a customer company's people: their given and family name and email. `onCreate` makes
125
+ * them (`CrmStore.createContact`); the form stays as it was if that fails, so it can be sent again.
126
+ */
127
+ export function NewContactForm({ onCreate, text, }) {
128
+ const words = withText(text);
129
+ return (_jsx(ContactForm, { title: words.addPerson, submit: words.addPerson, submitting: words.creating,
130
+ // Shown in the host's card, such as a customer's people.
131
+ framed: false, onSave: onCreate, text: text }));
132
+ }
133
+ function ContactForm({ initial, title, hint, submit, submitting, back, framed, onSave, text, }) {
134
+ const words = withText(text);
135
+ const id = useId();
136
+ const [givenName, setGivenName] = useState(initial?.givenName ?? '');
137
+ const [familyName, setFamilyName] = useState(initial?.familyName ?? '');
138
+ const [email, setEmail] = useState(initial?.email ?? '');
139
+ const [telephone, setTelephone] = useState(initial?.telephone ?? '');
140
+ const { saving, error, setError, run } = useSave();
141
+ return (_jsx(FormFrame, { title: title, submit: submit, submitting: submitting, saving: saving, error: error, back: back, framed: framed, onSubmit: async () => {
142
+ if (!givenName.trim())
143
+ return setError(words.givenNameRequired);
144
+ const contact = {
145
+ givenName: givenName.trim(),
146
+ ...(familyName.trim() ? { familyName: familyName.trim() } : {}),
147
+ ...(email.trim() ? { email: email.trim() } : {}),
148
+ ...(telephone.trim() ? { telephone: telephone.trim() } : {}),
149
+ };
150
+ await run(async () => onSave(contact));
151
+ }, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [hint && _jsx("p", { className: "text-muted-foreground text-sm", children: hint }), _jsx(Field, { id: `${id}-given`, label: words.givenName, children: _jsx(Input, { id: `${id}-given`, autoComplete: "off", value: givenName, onChange: (event) => setGivenName(event.target.value), "aria-describedby": errorId }) }), _jsx(Field, { id: `${id}-family`, label: words.familyName, children: _jsx(Input, { id: `${id}-family`, autoComplete: "off", value: familyName, onChange: (event) => setFamilyName(event.target.value) }) }), _jsx(Field, { id: `${id}-email`, label: words.email, children: _jsx(Input, { id: `${id}-email`, type: "email", autoComplete: "off", value: email, onChange: (event) => setEmail(event.target.value) }) }), _jsx(Field, { id: `${id}-telephone`, label: words.telephone, children: _jsx(Input, { id: `${id}-telephone`, type: "tel", autoComplete: "off", value: telephone, onChange: (event) => setTelephone(event.target.value) }) })] })) }));
46
152
  }
153
+ /** A contact's name for showing while they're waiting to be made. */
154
+ export const draftName = (contact) => [contact.givenName, contact.familyName].filter(Boolean).join(' ');
47
155
  /** Runs a form's save: the problem in words when it fails, the form left as it was so it can be sent again. */
48
156
  function useSave() {
49
157
  const [saving, setSaving] = useState(false);
@@ -64,25 +172,30 @@ function useSave() {
64
172
  return { saving, error, setError, run };
65
173
  }
66
174
  /**
67
- * A new lead: its title, source, value, and its company, chosen from the host's companies or made from a new name (a
68
- * lead holds its business by its company).
175
+ * A new lead: its title, source, value, assignee, and its company and contact person (a lead holds its business by
176
+ * its company). Each is chosen from the host's, or added: "Add a new ..." opens a step for its details in the same
177
+ * form, and it's made when the lead is saved.
69
178
  */
70
- export function NewLeadForm({ owner, companies = [], currencyCode = 'GBP', onCreate, text, }) {
179
+ export function NewLeadForm({ owner, companies = [], people = [], team = [], currencyCode = 'GBP', onCreate, text, }) {
71
180
  const words = withText(text);
72
181
  const id = useId();
182
+ const [step, setStep] = useState('lead');
73
183
  const [title, setTitle] = useState('');
74
184
  const [source, setSource] = useState('WEBSITE');
75
185
  const [value, setValue] = useState('');
186
+ const [currency, setCurrency] = useState(currencyCode);
76
187
  const [company, setCompany] = useState('');
77
- const [newCompany, setNewCompany] = useState('');
188
+ const [newCompany, setNewCompany] = useState();
189
+ const [contact, setContact] = useState('');
190
+ const [newContact, setNewContact] = useState();
191
+ const [assignee, setAssignee] = useState('');
78
192
  const { saving, error, setError, run } = useSave();
79
193
  const submit = async () => {
80
- const minor = value.trim() ? minorOrUndefined(value, currencyCode) : 0;
194
+ const targetValue = moneyOf(value, currency);
81
195
  if (!title.trim())
82
196
  return setError(words.titleRequired);
83
- if (minor === undefined)
197
+ if (targetValue === undefined)
84
198
  return setError(words.invalidAmount);
85
- const named = company ? '' : newCompany.trim();
86
199
  await run(() => onCreate({
87
200
  owner: ref(owner),
88
201
  title: title.trim(),
@@ -90,115 +203,292 @@ export function NewLeadForm({ owner, companies = [], currencyCode = 'GBP', onCre
90
203
  status: 'NEW',
91
204
  outcome: 'IN_PROGRESS',
92
205
  contactCompany: company ? { urn: company } : null,
93
- targetValue: minor ? fromMinor(minor, currencyCode) : null,
94
- }, named ? { companyName: named } : {}));
206
+ contactIdentity: contact ? { urn: contact } : null,
207
+ assignee: assignee ? { urn: assignee } : null,
208
+ targetValue,
209
+ }, { ...(newCompany ? { companyName: newCompany } : {}), ...(newContact ? { contact: newContact } : {}) }));
95
210
  };
96
- return (_jsx(FormFrame, { title: words.newLead, submit: words.createLead, submitting: words.creating, saving: saving, error: error, onSubmit: submit, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [_jsx(Field, { id: `${id}-title`, label: words.title, children: _jsx(Input, { id: `${id}-title`, value: title, onChange: (event) => setTitle(event.target.value), "aria-describedby": errorId }) }), _jsx(Field, { id: `${id}-source`, label: words.source, children: _jsxs(Select, { value: source, onValueChange: (next) => setSource(next), children: [_jsx(SelectTrigger, { id: `${id}-source`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: LEAD_SOURCES.map((option) => (_jsx(SelectItem, { value: option, children: SOURCE_LABELS[option] }, option))) })] }) }), _jsx(Field, { id: `${id}-value`, label: `${words.value} (${currencyCode})`, children: _jsx(Input, { id: `${id}-value`, inputMode: "decimal", value: value, onChange: (event) => setValue(event.target.value) }) }), _jsx(Field, { id: `${id}-company`, label: words.company, children: _jsx(CompanySelect, { id: `${id}-company`, value: company, onChange: setCompany, companies: companies, none: words.noCompany }) }), !company && (_jsx(Field, { id: `${id}-new-company`, label: words.newCompany, hint: words.newCompanyHint, children: _jsx(Input, { id: `${id}-new-company`, value: newCompany, onChange: (event) => setNewCompany(event.target.value), "aria-describedby": `${id}-new-company-hint` }) }))] })) }));
211
+ if (step === 'company')
212
+ return (_jsx(NewCompanyStep, { initial: newCompany, text: text, onBack: () => setStep('lead'), onUse: (name) => {
213
+ setCompany('');
214
+ setNewCompany(name);
215
+ setStep('lead');
216
+ } }));
217
+ if (step === 'contact')
218
+ return (_jsx(NewContactStep, { initial: newContact, text: text, onBack: () => setStep('lead'), onUse: (made) => {
219
+ setContact('');
220
+ setNewContact(made);
221
+ setStep('lead');
222
+ } }));
223
+ return (_jsx(FormFrame, { title: words.newLead, submit: words.createLead, submitting: words.creating, saving: saving, error: error, onSubmit: submit, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [_jsx(Field, { id: `${id}-title`, label: words.title, children: _jsx(Input, { id: `${id}-title`, value: title, onChange: (event) => setTitle(event.target.value), "aria-describedby": errorId }) }), _jsx(Field, { id: `${id}-source`, label: words.source, children: _jsxs(Select, { value: source, onValueChange: (next) => setSource(next), children: [_jsx(SelectTrigger, { id: `${id}-source`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: LEAD_SOURCES.map((option) => (_jsx(SelectItem, { value: option, children: SOURCE_LABELS[option] }, option))) })] }) }), _jsx(Field, { id: `${id}-value`, label: words.value, children: _jsx(MoneyInput, { id: `${id}-value`, amount: value, currencyCode: currency, onAmount: setValue, onCurrency: setCurrency, text: text }) }), _jsx(Field, { id: `${id}-company`, label: words.company, children: _jsx(ChoiceSelect, { id: `${id}-company`, value: company, onChange: (urn) => {
224
+ setCompany(urn);
225
+ setNewCompany(undefined);
226
+ }, choices: companies, none: words.noCompany, add: { label: words.addCompany, onAdd: () => setStep('company') }, pending: newCompany, text: text }) }), _jsx(Field, { id: `${id}-contact`, label: words.contact, children: _jsx(ChoiceSelect, { id: `${id}-contact`, value: contact, onChange: (urn) => {
227
+ setContact(urn);
228
+ setNewContact(undefined);
229
+ }, choices: people, none: words.noContact, add: { label: words.addContact, onAdd: () => setStep('contact') }, pending: newContact && draftName(newContact), text: text }) }), _jsx(Field, { id: `${id}-assignee`, label: words.assignee, children: _jsx(ChoiceSelect, { id: `${id}-assignee`, value: assignee, onChange: setAssignee, choices: team, none: words.unassigned, text: text }) })] })) }));
97
230
  }
98
231
  /**
99
- * A new deal that didn't start as a lead: its title, company, value, stage in the pipeline (the first, to start with),
100
- * expected close and probability.
232
+ * Where a deal is: its workflow (any workflow can be a pipeline) and its stage in it. Choosing a workflow moves the
233
+ * deal to that workflow's first stage.
101
234
  */
102
- export function NewDealForm({ owner, pipeline, companies = [], currencyCode = 'GBP', now = new Date(), onCreate, text, }) {
235
+ export function PipelineStageFields({ id, pipelines, stage, onStage, disabled, text, }) {
236
+ const words = withText(text);
237
+ const pipeline = pipelines.find((candidate) => candidate.stages?.some((option) => option.urn === stage)) ?? pipelines[0];
238
+ const stages = pipeline ? orderedStages(pipeline) : [];
239
+ return (_jsxs(_Fragment, { children: [pipelines.length > 1 && (_jsx(Field, { id: `${id}-workflow`, label: words.workflow, children: _jsxs(Select, { value: pipeline?.urn ?? '', disabled: disabled ?? false, onValueChange: (urn) => {
240
+ const first = orderedStages(pipelines.find((candidate) => candidate.urn === urn))[0];
241
+ if (first)
242
+ onStage(first);
243
+ }, children: [_jsx(SelectTrigger, { id: `${id}-workflow`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: pipelines.map((option) => (_jsx(SelectItem, { value: option.urn, children: option.name }, option.urn))) })] }) })), _jsx(Field, { id: `${id}-stage`, label: words.stage, children: _jsxs(Select, { value: stages.some((option) => option.urn === stage) ? stage : '', disabled: disabled ?? false, onValueChange: (urn) => onStage(stages.find((option) => option.urn === urn)), children: [_jsx(SelectTrigger, { id: `${id}-stage`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: stages.map((option) => (_jsx(SelectItem, { value: option.urn, children: option.name }, option.urn))) })] }) })] }));
244
+ }
245
+ /**
246
+ * A new deal that didn't start as a lead: its title, companies and contacts (found by searching), value, workflow and stage (the first
247
+ * workflow's first stage, to start with), expected close, probability and assignee.
248
+ */
249
+ export function NewDealForm({ owner, pipelines, companies = [], people = [], team = [], currencyCode = 'GBP', now = new Date(), onCreate, text, }) {
103
250
  const words = withText(text);
104
251
  const id = useId();
105
- const stages = orderedStages(pipeline);
106
252
  const [title, setTitle] = useState('');
107
- const [company, setCompany] = useState('');
253
+ const [chosenCompanies, setCompanies] = useState([]);
254
+ const [contacts, setContacts] = useState([]);
255
+ const [assignee, setAssignee] = useState('');
108
256
  const [value, setValue] = useState('');
109
- const [stage, setStage] = useState(stages[0]?.urn ?? '');
257
+ const [currency, setCurrency] = useState(currencyCode);
258
+ const [stage, setStage] = useState(pipelines[0] ? (orderedStages(pipelines[0])[0]?.urn ?? '') : '');
110
259
  const [close, setClose] = useState(inDays(now, 30));
111
260
  const [probability, setProbability] = useState('');
112
261
  const { saving, error, setError, run } = useSave();
113
262
  const submit = async () => {
114
- const minor = value.trim() ? minorOrUndefined(value, currencyCode) : 0;
263
+ const targetValue = moneyOf(value, currency);
115
264
  const chance = probability.trim() ? Number(probability) : undefined;
116
265
  if (!title.trim())
117
266
  return setError(words.titleRequired);
118
- if (minor === undefined)
267
+ if (targetValue === undefined)
119
268
  return setError(words.invalidAmount);
120
269
  if (chance !== undefined && !(chance >= 0 && chance <= 100))
121
270
  return setError(words.invalidProbability);
122
271
  await run(() => onCreate({
123
272
  owner: ref(owner),
124
273
  title: title.trim(),
125
- contactCompanies: company ? [{ urn: company }] : [],
126
- contactIdentities: [],
274
+ contactCompanies: chosenCompanies.map((urn) => ({ urn })),
275
+ contactIdentities: contacts.map((urn) => ({ urn })),
127
276
  workflowStage: stage ? { urn: stage } : null,
128
277
  outcome: 'OPEN',
129
278
  probability: chance ?? null,
130
- targetValue: minor ? fromMinor(minor, currencyCode) : null,
279
+ targetValue,
131
280
  targetCloseTimestamp: dayTimestamp(close),
281
+ assignee: assignee ? { urn: assignee } : null,
132
282
  invoices: [],
133
283
  }));
134
284
  };
135
- return (_jsx(FormFrame, { title: words.newDeal, submit: words.createDeal, submitting: words.creating, saving: saving, error: error, onSubmit: submit, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [_jsx(Field, { id: `${id}-title`, label: words.title, children: _jsx(Input, { id: `${id}-title`, value: title, onChange: (event) => setTitle(event.target.value), "aria-describedby": errorId }) }), _jsx(Field, { id: `${id}-company`, label: words.company, children: _jsx(CompanySelect, { id: `${id}-company`, value: company, onChange: setCompany, companies: companies, none: words.noCompany }) }), _jsx(Field, { id: `${id}-value`, label: `${words.value} (${currencyCode})`, children: _jsx(Input, { id: `${id}-value`, inputMode: "decimal", value: value, onChange: (event) => setValue(event.target.value) }) }), _jsx(Field, { id: `${id}-stage`, label: words.stage, children: _jsxs(Select, { value: stage, onValueChange: setStage, children: [_jsx(SelectTrigger, { id: `${id}-stage`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: stages.map((option) => (_jsx(SelectItem, { value: option.urn, children: option.name }, option.urn))) })] }) }), _jsx(Field, { id: `${id}-close`, label: words.expectedClose, children: _jsx(Input, { id: `${id}-close`, type: "date", value: close, onChange: (event) => setClose(event.target.value) }) }), _jsx(Field, { id: `${id}-probability`, label: `${words.probability} (%)`, children: _jsx(Input, { id: `${id}-probability`, inputMode: "numeric", value: probability, onChange: (event) => setProbability(event.target.value) }) })] })) }));
285
+ return (_jsx(FormFrame, { title: words.newDeal, submit: words.createDeal, submitting: words.creating, saving: saving, error: error, onSubmit: submit, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [_jsx(Field, { id: `${id}-title`, label: words.title, children: _jsx(Input, { id: `${id}-title`, value: title, onChange: (event) => setTitle(event.target.value), "aria-describedby": errorId }) }), _jsx(Field, { id: `${id}-companies`, label: words.companies, children: _jsx(ChoiceCombobox, { id: `${id}-companies`, value: chosenCompanies, onChange: setCompanies, choices: companies, placeholder: words.searchCompanies, text: text }) }), _jsx(Field, { id: `${id}-contacts`, label: words.contacts, children: _jsx(ChoiceCombobox, { id: `${id}-contacts`, value: contacts, onChange: setContacts, choices: people, placeholder: words.searchContacts, text: text }) }), _jsx(Field, { id: `${id}-value`, label: words.value, children: _jsx(MoneyInput, { id: `${id}-value`, amount: value, currencyCode: currency, onAmount: setValue, onCurrency: setCurrency, text: text }) }), _jsx(PipelineStageFields, { id: id, pipelines: pipelines, stage: stage, onStage: (next) => setStage(next.urn), text: text }), _jsx(Field, { id: `${id}-assignee`, label: words.assignee, children: _jsx(ChoiceSelect, { id: `${id}-assignee`, value: assignee, onChange: setAssignee, choices: team, none: words.unassigned, text: text }) }), _jsx(Field, { id: `${id}-close`, label: words.expectedClose, children: _jsx(Input, { id: `${id}-close`, type: "date", value: close, onChange: (event) => setClose(event.target.value) }) }), _jsx(Field, { id: `${id}-probability`, label: `${words.probability} (%)`, children: _jsx(Input, { id: `${id}-probability`, inputMode: "numeric", value: probability, onChange: (event) => setProbability(event.target.value) }) })] })) }));
136
286
  }
137
- const INVOICE_STATUSES = ['DRAFT', 'AUTHORISED'];
138
- const EMPTY_LINE = { description: '', quantity: '1', unitPrice: '' };
139
- /** What a line, typed in, comes to: its net price and tax in minor units, or undefined when it isn't complete. */
287
+ const TAXABILITY_LABELS = {
288
+ TAXABLE: 'Taxable',
289
+ PARTIALLY_TAXABLE: 'Partly taxable',
290
+ NON_TAXABLE: 'Not taxable',
291
+ TAX_EXEMPT: 'Exempt',
292
+ NOT_APPLICABLE: 'Not applicable',
293
+ };
294
+ const TAXABILITIES = Object.keys(TAXABILITY_LABELS);
295
+ /** Taxed at the invoice's rate; the others have no tax. */
296
+ const TAXED = ['TAXABLE', 'PARTIALLY_TAXABLE'];
297
+ const EMPTY_LINE = {
298
+ description: '',
299
+ quantity: '1',
300
+ unitPrice: '',
301
+ itemCode: '',
302
+ discountRate: '',
303
+ taxability: 'TAXABLE',
304
+ taxName: '',
305
+ };
306
+ /**
307
+ * What a line, typed in, comes to, in minor units: before discount, the discount, its net price and tax. Undefined
308
+ * when it isn't complete or its discount isn't 0 to 100.
309
+ */
140
310
  function priceLine(line, currencyCode, rate) {
141
311
  const quantity = Number(line.quantity);
142
312
  const unit = minorOrUndefined(line.unitPrice, currencyCode);
143
- if (!line.description.trim() || !(quantity > 0) || !unit)
313
+ const discountRate = line.discountRate.trim() ? Number(line.discountRate) : 0;
314
+ if (!line.description.trim() || !(quantity > 0) || !unit || !(discountRate >= 0 && discountRate <= 100))
144
315
  return undefined;
145
- const price = Math.round(unit * quantity);
146
- return { description: line.description.trim(), quantity, unit, price, tax: Math.round((price * rate) / 100) };
316
+ const gross = Math.round(unit * quantity);
317
+ const discount = Math.round((gross * discountRate) / 100);
318
+ const price = gross - discount;
319
+ const tax = TAXED.includes(line.taxability) ? Math.round((price * rate) / 100) : 0;
320
+ return { line, quantity, unit, discountRate, discount, price, tax };
321
+ }
322
+ /** The line as the API takes it: its unit price in major units, its amounts as money. */
323
+ function lineDraft(priced, code) {
324
+ const { line } = priced;
325
+ return {
326
+ description: line.description.trim(),
327
+ quantity: priced.quantity,
328
+ unitPrice: priced.unit / 10 ** fractionDigits(code),
329
+ price: fromMinor(priced.price, code),
330
+ tax: fromMinor(priced.tax, code),
331
+ taxability: line.taxability,
332
+ ...(line.itemCode.trim() ? { itemCode: line.itemCode.trim() } : {}),
333
+ ...(priced.discountRate
334
+ ? { discountRate: priced.discountRate, discountPrice: fromMinor(priced.discount, code) }
335
+ : {}),
336
+ ...(line.taxName.trim() ? { taxName: line.taxName.trim() } : {}),
337
+ };
147
338
  }
148
339
  /**
149
- * A new invoice to a customer: its lines (description, quantity, unit price) and a tax rate, which give its subtotal,
150
- * tax and total (the API keeps an invoice's amounts as given), its dates and status, and the deal it's for, if any.
340
+ * One invoice line with all its fields, as a step of the invoice form: description, item code, quantity, unit price,
341
+ * discount, tax treatment and tax name, with what it comes to. `Done` goes back to the invoice with it kept.
151
342
  */
152
- export function NewInvoiceForm({ owner, companies = [], deals = [], currencyCode: defaultCurrency = 'GBP', now = new Date(), onCreate, text, }) {
343
+ function InvoiceLineStep({ number, initial, currencyCode, rate, onDone, onBack, text, }) {
153
344
  const words = withText(text);
154
345
  const id = useId();
155
- const [customer, setCustomer] = useState('');
346
+ const [line, setLine] = useState(initial);
347
+ const { saving, error, setError, run } = useSave();
348
+ const set = (field, value) => setLine((current) => ({ ...current, [field]: value }));
349
+ const priced = priceLine(line, currencyCode, Number.isFinite(rate) ? rate : 0);
350
+ const money = (minor) => formatMoney(fromMinor(minor, currencyCode));
351
+ const input = (field, label, inputMode) => (_jsx(Field, { id: `${id}-${field}`, label: label, children: _jsx(Input, { id: `${id}-${field}`, inputMode: inputMode, value: line[field], onChange: (event) => set(field, event.target.value) }) }));
352
+ return (_jsx(FormFrame, { title: `${words.line} ${number}`, submit: words.done, submitting: words.saving, saving: saving, error: error, back: { label: words.back, onBack }, onSubmit: async () => {
353
+ const discount = line.discountRate.trim() ? Number(line.discountRate) : 0;
354
+ if (!(discount >= 0 && discount <= 100))
355
+ return setError(words.invalidDiscount);
356
+ await run(async () => onDone(line));
357
+ }, children: () => (_jsxs(_Fragment, { children: [input('description', words.description), input('itemCode', words.itemCode), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [input('quantity', words.quantity, 'decimal'), input('unitPrice', `${words.unitPrice} (${currencyCode})`, 'decimal'), input('discountRate', words.discountRate, 'decimal'), _jsx(Field, { id: `${id}-taxability`, label: words.taxability, children: _jsxs(Select, { value: line.taxability, onValueChange: (next) => set('taxability', next), children: [_jsx(SelectTrigger, { id: `${id}-taxability`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: TAXABILITIES.map((option) => (_jsx(SelectItem, { value: option, children: TAXABILITY_LABELS[option] }, option))) })] }) })] }), input('taxName', words.taxName), _jsxs("dl", { "aria-live": "polite", className: "grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm", children: [_jsx("dt", { className: "text-muted-foreground", children: words.price }), _jsx("dd", { className: "tabular-nums", children: priced ? money(priced.price) : '-' }), _jsx("dt", { className: "text-muted-foreground", children: words.tax }), _jsx("dd", { className: "tabular-nums", children: priced ? money(priced.tax) : '-' })] })] })) }));
358
+ }
359
+ const recipientKey = (owner) => `baack-crm:invoice-recipient:${owner}`;
360
+ /** The recipient last used for this owner's invoices, kept in the browser; else the owner itself. */
361
+ function lastRecipient(owner) {
362
+ try {
363
+ const saved = JSON.parse(localStorage.getItem(recipientKey(owner)) ?? 'null');
364
+ if (saved && typeof saved.company === 'string')
365
+ return { company: saved.company, identity: typeof saved.identity === 'string' ? saved.identity : '' };
366
+ }
367
+ catch {
368
+ // No storage: the owner, as on first use.
369
+ }
370
+ return { company: owner, identity: '' };
371
+ }
372
+ function keepRecipient(owner, party) {
373
+ try {
374
+ localStorage.setItem(recipientKey(owner), JSON.stringify({ company: party.company, identity: party.identity }));
375
+ }
376
+ catch {
377
+ // Not kept; next time starts from the owner.
378
+ }
379
+ }
380
+ const partyRefs = (party) => ({
381
+ company: party.company ? { urn: party.company } : null,
382
+ identity: party.identity ? { urn: party.identity } : null,
383
+ });
384
+ /**
385
+ * A new invoice: who pays it (the remitter) and who's paid (the recipient), each a company, a person or both, found by
386
+ * searching; a company not in Baack yet can be added by name. The recipient starts as the one used last, else the
387
+ * owner. An invoice can be a sale (a customer pays the owner) or a cost (the owner pays a supplier). Its amount is
388
+ * lines, each opening into all its fields, or a total including tax, with a tax rate; then its dates, status, and
389
+ * the deal it's for, if any.
390
+ */
391
+ export function NewInvoiceForm({ owner, companies = [], people = [], deals = [], currencyCode: defaultCurrency = 'GBP', now = new Date(), onCreate, text, }) {
392
+ const words = withText(text);
393
+ const id = useId();
394
+ const ownerUrn = ref(owner).urn;
395
+ const [remitter, setRemitter] = useState({ company: '', identity: '' });
396
+ const [recipient, setRecipient] = useState(() => lastRecipient(ownerUrn));
397
+ // A party whose new company or person is being made, in a step of the form.
398
+ const [adding, setAdding] = useState();
399
+ const [editing, setEditing] = useState();
156
400
  const [deal, setDeal] = useState('');
157
401
  const [currencyCode, setCurrencyCode] = useState(defaultCurrency);
158
402
  const [status, setStatus] = useState('DRAFT');
159
- const [issued, setIssued] = useState(today(now));
403
+ // Not issued yet, as drafts usually aren't: set when it's sent.
404
+ const [issued, setIssued] = useState('');
160
405
  const [due, setDue] = useState(inDays(now, 30));
161
406
  const [rate, setRate] = useState('20');
407
+ const [amountAs, setAmountAs] = useState('lines');
162
408
  const [lines, setLines] = useState([EMPTY_LINE]);
409
+ const [total, setTotal] = useState('');
163
410
  const { saving, error, setError, run } = useSave();
164
411
  const change = (index, field, value) => setLines((current) => current.map((line, at) => (at === index ? { ...line, [field]: value } : line)));
412
+ const hasParty = (party) => Boolean(party.company || party.identity || party.newCompany || party.newContact);
165
413
  const submit = async () => {
166
414
  const taxRate = Number(rate);
167
- const code = currencyCode.trim().toUpperCase();
168
- if (!customer)
169
- return setError(words.customerRequired);
415
+ const code = currencyCode;
416
+ if (!hasParty(remitter))
417
+ return setError(words.remitterRequired);
418
+ if (!hasParty(recipient))
419
+ return setError(words.recipientRequired);
170
420
  if (!(taxRate >= 0 && taxRate <= 100))
171
421
  return setError(words.invalidRate);
172
- const priced = lines.map((line) => priceLine(line, code, taxRate));
173
- if (priced.some((line) => line === undefined))
174
- return setError(words.linesRequired);
175
- const done = priced;
176
- const subTotal = done.reduce((sum, line) => sum + line.price, 0);
177
- const tax = done.reduce((sum, line) => sum + line.tax, 0);
178
- const party = { company: { urn: customer }, identity: null };
422
+ let done = [];
423
+ let subTotal;
424
+ let tax;
425
+ if (amountAs === 'total') {
426
+ // A total includes tax: the subtotal and tax are worked out from it at the rate.
427
+ const gross = minorOrUndefined(total, code);
428
+ if (!gross)
429
+ return setError(words.totalRequired);
430
+ subTotal = Math.round(gross / (1 + taxRate / 100));
431
+ tax = gross - subTotal;
432
+ }
433
+ else {
434
+ const priced = lines.map((line) => priceLine(line, code, taxRate));
435
+ if (priced.some((line) => line === undefined))
436
+ return setError(words.linesRequired);
437
+ const complete = priced;
438
+ done = complete.map((line) => lineDraft(line, code));
439
+ subTotal = complete.reduce((sum, line) => sum + line.price, 0);
440
+ tax = complete.reduce((sum, line) => sum + line.tax, 0);
441
+ }
179
442
  const linked = deals.find((candidate) => candidate.urn === deal);
180
- await run(() => onCreate({
181
- owner: ref(owner),
182
- recipient: party,
183
- remitter: party,
184
- status,
185
- currencyCode: code,
186
- lineItemTax: taxRate ? 'EXCLUSIVE' : 'NO_TAX',
187
- subTotal: fromMinor(subTotal, code),
188
- tax: fromMinor(tax, code),
189
- total: fromMinor(subTotal + tax, code),
190
- paid: fromMinor(0, code),
191
- issuedTimestamp: status === 'DRAFT' ? null : dayTimestamp(issued),
192
- dueTimestamp: dayTimestamp(due),
193
- }, done.map((line) => ({
194
- description: line.description,
195
- quantity: line.quantity,
196
- // A line's unit price is in major units; its price and tax are money.
197
- unitPrice: line.unit / 10 ** fractionDigits(code),
198
- price: fromMinor(line.price, code),
199
- tax: fromMinor(line.tax, code),
200
- })), linked ? { deal: linked } : {}));
443
+ await run(async () => {
444
+ await onCreate({
445
+ owner: ref(owner),
446
+ remitter: partyRefs(remitter),
447
+ recipient: partyRefs(recipient),
448
+ status,
449
+ currencyCode: code,
450
+ // A total is given with its tax in it; lines are priced before tax.
451
+ lineItemTax: !taxRate ? 'NO_TAX' : amountAs === 'total' ? 'INCLUSIVE' : 'EXCLUSIVE',
452
+ subTotal: fromMinor(subTotal, code),
453
+ tax: fromMinor(tax, code),
454
+ total: fromMinor(subTotal + tax, code),
455
+ paid: fromMinor(0, code),
456
+ issuedTimestamp: dayTimestamp(issued),
457
+ dueTimestamp: dayTimestamp(due),
458
+ }, done, {
459
+ ...(linked ? { deal: linked } : {}),
460
+ ...(remitter.newCompany ? { remitterCompanyName: remitter.newCompany } : {}),
461
+ ...(recipient.newCompany ? { recipientCompanyName: recipient.newCompany } : {}),
462
+ ...(remitter.newContact ? { remitterContact: remitter.newContact } : {}),
463
+ ...(recipient.newContact ? { recipientContact: recipient.newContact } : {}),
464
+ });
465
+ // A new record's URN isn't known here, so only an existing recipient is kept for next time.
466
+ if (!recipient.newCompany && !recipient.newContact)
467
+ keepRecipient(ownerUrn, recipient);
468
+ });
201
469
  };
202
- return (_jsx(FormFrame, { title: words.newInvoice, submit: words.createInvoice, submitting: words.creating, saving: saving, error: error, onSubmit: submit, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [_jsx(Field, { id: `${id}-customer`, label: words.customer, children: _jsx(CompanySelect, { id: `${id}-customer`, value: customer, onChange: setCustomer, companies: companies, none: words.noCompany }) }), _jsx(Field, { id: `${id}-deal`, label: words.forDeal, children: _jsxs(Select, { value: deal || NONE, onValueChange: (next) => setDeal(next === NONE ? '' : next), children: [_jsx(SelectTrigger, { id: `${id}-deal`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: NONE, children: words.noDeal }), deals.map((option) => (_jsx(SelectItem, { value: option.urn, children: option.title }, option.urn)))] })] }) }), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsx(Field, { id: `${id}-currency`, label: words.currency, children: _jsx(Input, { id: `${id}-currency`, value: currencyCode, maxLength: 3, onChange: (event) => setCurrencyCode(event.target.value) }) }), _jsx(Field, { id: `${id}-status`, label: words.status, children: _jsxs(Select, { value: status, onValueChange: (next) => setStatus(next), children: [_jsx(SelectTrigger, { id: `${id}-status`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: INVOICE_STATUSES.map((option) => (_jsx(SelectItem, { value: option, children: option === 'DRAFT' ? 'Draft' : words.awaitingPayment }, option))) })] }) }), _jsx(Field, { id: `${id}-issued`, label: words.issuedOn, children: _jsx(Input, { id: `${id}-issued`, type: "date", value: issued, onChange: (event) => setIssued(event.target.value) }) }), _jsx(Field, { id: `${id}-due`, label: words.dueOn, children: _jsx(Input, { id: `${id}-due`, type: "date", value: due, onChange: (event) => setDue(event.target.value) }) })] }), _jsxs("fieldset", { className: "grid gap-2", "aria-describedby": errorId, children: [_jsx("legend", { className: "mb-1 text-sm font-medium", children: words.lines }), lines.map((line, index) => (_jsxs("div", { className: "grid grid-cols-[1fr_4rem_6rem_auto] items-end gap-2", children: [_jsx(Field, { id: `${id}-line-${index}-description`, label: `${words.description} ${index + 1}`, children: _jsx(Input, { id: `${id}-line-${index}-description`, value: line.description, onChange: (event) => change(index, 'description', event.target.value) }) }), _jsx(Field, { id: `${id}-line-${index}-quantity`, label: words.quantity, children: _jsx(Input, { id: `${id}-line-${index}-quantity`, inputMode: "decimal", value: line.quantity, onChange: (event) => change(index, 'quantity', event.target.value) }) }), _jsx(Field, { id: `${id}-line-${index}-price`, label: words.unitPrice, children: _jsx(Input, { id: `${id}-line-${index}-price`, inputMode: "decimal", value: line.unitPrice, onChange: (event) => change(index, 'unitPrice', event.target.value) }) }), _jsx(Button, { type: "button", variant: "ghost", size: "icon", "aria-label": `${words.removeLine} ${index + 1}`, disabled: lines.length === 1, onClick: () => setLines((current) => current.filter((_, at) => at !== index)), children: _jsx(X, { "aria-hidden": "true" }) })] }, index))), _jsx("div", { children: _jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: () => setLines((current) => [...current, EMPTY_LINE]), children: [_jsx(Plus, { "aria-hidden": "true" }), words.addLine] }) })] }), _jsx(Field, { id: `${id}-rate`, label: words.taxRate, children: _jsx(Input, { id: `${id}-rate`, inputMode: "decimal", value: rate, onChange: (event) => setRate(event.target.value) }) })] })) }));
470
+ if (adding) {
471
+ const party = adding.which === 'remitter' ? remitter : recipient;
472
+ const setParty = adding.which === 'remitter' ? setRemitter : setRecipient;
473
+ return adding.record === 'company' ? (_jsx(NewCompanyStep, { initial: party.newCompany ?? '', text: text, onBack: () => setAdding(undefined), onUse: (name) => {
474
+ setParty({ ...party, company: '', newCompany: name });
475
+ setAdding(undefined);
476
+ } })) : (_jsx(NewContactStep, { initial: party.newContact, text: text, onBack: () => setAdding(undefined), onUse: (contact) => {
477
+ setParty({ ...party, identity: '', newContact: contact });
478
+ setAdding(undefined);
479
+ } }));
480
+ }
481
+ if (editing !== undefined && lines[editing]) {
482
+ return (_jsx(InvoiceLineStep, { number: editing + 1, initial: lines[editing], currencyCode: currencyCode, rate: Number(rate), text: text, onBack: () => setEditing(undefined), onDone: (line) => {
483
+ setLines((current) => current.map((other, at) => (at === editing ? line : other)));
484
+ setEditing(undefined);
485
+ } }));
486
+ }
487
+ const partyFields = (which, party, setParty) => (_jsxs("fieldset", { className: "grid gap-3", children: [_jsx("legend", { className: "mb-1 text-sm font-medium", children: which === 'remitter' ? words.remitter : words.recipient }), _jsx(Field, { id: `${id}-${which}-company`, label: which === 'remitter' ? words.remitterCompany : words.recipientCompany, hint: which === 'recipient' ? words.recipientHint : undefined, children: _jsx(ChoiceCombobox, { id: `${id}-${which}-company`, single: true, value: party.company ? [party.company] : [], onChange: ([company = '']) => setParty({ ...party, company, newCompany: undefined }), choices: companies, placeholder: words.searchCompanies, add: { label: words.addCompany, onAdd: () => setAdding({ which, record: 'company' }) }, pending: party.newCompany
488
+ ? { name: party.newCompany, onClear: () => setParty({ ...party, newCompany: undefined }) }
489
+ : undefined, describedBy: which === 'recipient' ? `${id}-${which}-company-hint` : undefined, text: text }) }), _jsx(Field, { id: `${id}-${which}-person`, label: which === 'remitter' ? words.remitterPerson : words.recipientPerson, children: _jsx(ChoiceCombobox, { id: `${id}-${which}-person`, single: true, value: party.identity ? [party.identity] : [], onChange: ([identity = '']) => setParty({ ...party, identity, newContact: undefined }), choices: people, placeholder: words.searchPeople, add: { label: words.addContact, onAdd: () => setAdding({ which, record: 'contact' }) }, pending: party.newContact
490
+ ? { name: draftName(party.newContact), onClear: () => setParty({ ...party, newContact: undefined }) }
491
+ : undefined, text: text }) })] }));
492
+ return (_jsx(FormFrame, { title: words.newInvoice, submit: words.createInvoice, submitting: words.creating, saving: saving, error: error, onSubmit: submit, children: ({ error: errorId }) => (_jsxs(_Fragment, { children: [partyFields('remitter', remitter, setRemitter), partyFields('recipient', recipient, setRecipient), _jsx(Field, { id: `${id}-deal`, label: words.forDeal, children: _jsxs(Select, { value: deal || NONE, onValueChange: (next) => setDeal(next === NONE ? '' : next), children: [_jsx(SelectTrigger, { id: `${id}-deal`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: NONE, children: words.noDeal }), deals.map((option) => (_jsx(SelectItem, { value: option.urn, children: option.title }, option.urn)))] })] }) }), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsx(Field, { id: `${id}-currency`, label: words.currency, children: _jsxs(Select, { value: currencyCode, onValueChange: setCurrencyCode, children: [_jsx(SelectTrigger, { id: `${id}-currency`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: (CURRENCIES.includes(currencyCode) ? CURRENCIES : [currencyCode, ...CURRENCIES]).map((code) => (_jsx(SelectItem, { value: code, children: code }, code))) })] }) }), _jsx(Field, { id: `${id}-status`, label: words.status, children: _jsxs(Select, { value: status, onValueChange: (next) => setStatus(next), children: [_jsx(SelectTrigger, { id: `${id}-status`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: INVOICE_STATUSES.map((option) => (_jsx(SelectItem, { value: option, children: INVOICE_STATUS_LABELS[option] }, option))) })] }) }), _jsx(Field, { id: `${id}-issued`, label: words.issuedOn, children: _jsx(Input, { id: `${id}-issued`, type: "date", value: issued, onChange: (event) => setIssued(event.target.value) }) }), _jsx(Field, { id: `${id}-due`, label: words.dueOn, children: _jsx(Input, { id: `${id}-due`, type: "date", value: due, onChange: (event) => setDue(event.target.value) }) })] }), _jsx(Field, { id: `${id}-amount-as`, label: words.amountAs, children: _jsxs(Select, { value: amountAs, onValueChange: (next) => setAmountAs(next), children: [_jsx(SelectTrigger, { id: `${id}-amount-as`, className: "w-full", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "lines", children: words.amountAsLines }), _jsx(SelectItem, { value: "total", children: words.amountAsTotal })] })] }) }), amountAs === 'total' && (_jsx(Field, { id: `${id}-total`, label: `${words.totalWithTax} (${currencyCode})`, hint: words.totalHint, children: _jsx(Input, { id: `${id}-total`, inputMode: "decimal", value: total, onChange: (event) => setTotal(event.target.value), "aria-describedby": [`${id}-total-hint`, errorId].filter(Boolean).join(' ') }) })), _jsxs("fieldset", { className: "grid gap-2", "aria-describedby": errorId, hidden: amountAs === 'total', children: [_jsx("legend", { className: "mb-1 text-sm font-medium", children: words.lines }), lines.map((line, index) => (_jsxs("div", { className: "grid grid-cols-[1fr_4rem_6rem_auto_auto] items-end gap-2", children: [_jsx(Field, { id: `${id}-line-${index}-description`, label: `${words.description} ${index + 1}`, children: _jsx(Input, { id: `${id}-line-${index}-description`, value: line.description, onChange: (event) => change(index, 'description', event.target.value) }) }), _jsx(Field, { id: `${id}-line-${index}-quantity`, label: words.quantity, children: _jsx(Input, { id: `${id}-line-${index}-quantity`, inputMode: "decimal", value: line.quantity, onChange: (event) => change(index, 'quantity', event.target.value) }) }), _jsx(Field, { id: `${id}-line-${index}-price`, label: words.unitPrice, children: _jsx(Input, { id: `${id}-line-${index}-price`, inputMode: "decimal", value: line.unitPrice, onChange: (event) => change(index, 'unitPrice', event.target.value) }) }), _jsx(Button, { type: "button", variant: "ghost", size: "icon", "aria-label": `${words.lineDetails}: ${words.line} ${index + 1}`, onClick: () => setEditing(index), children: _jsx(ChevronRight, { "aria-hidden": "true" }) }), _jsx(Button, { type: "button", variant: "ghost", size: "icon", "aria-label": `${words.removeLine} ${index + 1}`, disabled: lines.length === 1, onClick: () => setLines((current) => current.filter((_, at) => at !== index)), children: _jsx(X, { "aria-hidden": "true" }) })] }, index))), _jsx("div", { children: _jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: () => setLines((current) => [...current, EMPTY_LINE]), children: [_jsx(Plus, { "aria-hidden": "true" }), words.addLine] }) })] }), _jsx(Field, { id: `${id}-rate`, label: words.taxRate, children: _jsx(Input, { id: `${id}-rate`, inputMode: "decimal", value: rate, onChange: (event) => setRate(event.target.value) }) })] })) }));
203
493
  }
204
494
  //# sourceMappingURL=Forms.js.map