server.ts 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. import { createHash } from 'node:crypto'
  2. import {
  3. type AccountingCustomer,
  4. type AccountingInvoice,
  5. type AccountingPayment,
  6. CUSTOMER_ENTITY,
  7. INVOICE_ENTITY,
  8. PAYMENT_ENTITY,
  9. invoiceUrl as appInvoiceUrl,
  10. loadCustomerForAccounting,
  11. loadInvoiceForAccounting,
  12. loadInvoicePdfForAccounting,
  13. loadPaymentForAccounting,
  14. recordPulledPayment,
  15. removePulledPayment,
  16. workshopCurrency,
  17. workshopDistanceUnit,
  18. } from '@/features/integrations/Lib/accounting-sync'
  19. import { oauthSpec, resolveClient } from '@/features/integrations/Lib/oauth'
  20. import {
  21. ConnectorHttpError,
  22. type ConnectorContext,
  23. type ConnectorServer,
  24. type JobOutcome,
  25. type LinkRecord,
  26. } from '@/features/integrations/Lib/types'
  27. import { zonedDayKey } from '@/lib/timezone'
  28. import { manifest } from './manifest'
  29. import {
  30. API_BASE,
  31. CONNECTIONS_URL,
  32. type InvoiceStatus,
  33. REVOKE_URL,
  34. STATUS_RANK,
  35. WALK_IN_NAME,
  36. type XeroAccount,
  37. type XeroBrandingTheme,
  38. type XeroConnection,
  39. type XeroContact,
  40. type XeroInvoice,
  41. type XeroItem,
  42. type XeroOrganisation,
  43. type XeroPayment,
  44. type XeroTrackingCategory,
  45. buildContact,
  46. buildInvoice,
  47. buildPayment,
  48. checksumOf,
  49. contactName,
  50. contactNumber,
  51. contactUrl,
  52. defaultDueDate,
  53. errorMessage,
  54. invoiceUrl,
  55. methodAccountKey,
  56. modifiedSinceHeader,
  57. parseXeroDate,
  58. paymentDay,
  59. referenceFor,
  60. sameName,
  61. xeroDayKey,
  62. round2,
  63. whereString,
  64. } from './mapping'
  65. import {
  66. type TaxRateEntry,
  67. type XeroTaxRate,
  68. pickTaxedRate,
  69. pickZeroRate,
  70. rateLabel,
  71. salesRates,
  72. } from './tax'
  73. const PROVIDER = 'xero'
  74. /**
  75. * The lines are built to add up to the printed invoice to the cent, so any
  76. * difference means Xero changed something: a rate, an amount, its own tax.
  77. */
  78. const TOTAL_TOLERANCE = 0.005
  79. /** How long the organisation's lists (rates, accounts, items, tracking) are trusted. */
  80. const CATALOG_TTL_MS = 6 * 60 * 60 * 1000
  81. /** A payment waiting for its invoice to be approved in Xero is retried this often, for this long. */
  82. const APPROVAL_RETRY_SECONDS = 60 * 60
  83. const APPROVAL_WAIT_DAYS = 30
  84. const NO_TENANT = 'choose the Xero organisation in the settings'
  85. /** How far a payment may exceed Xero's amount due and still be the same payment, rounded differently. */
  86. const ROUNDING_SLACK = 0.05
  87. class XeroError extends Error {
  88. status: number
  89. /** Xero's correlation id for the failed call; their support asks for it. */
  90. requestId: string | null
  91. constructor(status: number, body: string, requestId: string | null = null) {
  92. super(`Xero: ${errorMessage(body)}${requestId ? ` (correlation id ${requestId})` : ''}`)
  93. this.status = status
  94. this.requestId = requestId
  95. }
  96. }
  97. /* ---------- settings and state ---------- */
  98. type ReferenceChoice = 'vehicle' | 'title' | 'invoiceNumber' | 'customerReference' | 'none'
  99. function settingsOf(ctx: ConnectorContext) {
  100. const s = ctx.connection.settings
  101. const str = (k: string) => (typeof s[k] === 'string' && (s[k] as string).trim()) || null
  102. const startDate = str('startDate')
  103. const status = str('invoiceStatus')
  104. const reference = str('reference')
  105. return {
  106. tenantId: str('tenantId'),
  107. pushInvoices: s.pushInvoices !== false,
  108. pushOnComplete: s.pushOnComplete === true,
  109. startDate: startDate && /^\d{4}-\d{2}-\d{2}$/.test(startDate) ? startDate : null,
  110. invoiceStatus: (status === 'DRAFT' || status === 'SUBMITTED'
  111. ? status
  112. : 'AUTHORISED') as InvoiceStatus,
  113. xeroNumbers: s.invoiceNumbers === 'xero',
  114. reference: (reference === 'title' ||
  115. reference === 'invoiceNumber' ||
  116. reference === 'customerReference' ||
  117. reference === 'none'
  118. ? reference
  119. : 'vehicle') as ReferenceChoice,
  120. includeVehicle: s.includeVehicle !== false,
  121. includeNotes: s.includeNotes !== false,
  122. notesAbove: s.notesPosition === 'above',
  123. includePartNumbers: s.includePartNumbers !== false,
  124. brandingThemeId: str('brandingThemeId'),
  125. laborAccount: str('laborAccount'),
  126. partsAccount: str('partsAccount'),
  127. shopFeeAccount: str('shopFeeAccount'),
  128. laborItem: str('laborItem'),
  129. partsItem: str('partsItem'),
  130. matchItemsByPartNumber: s.matchItemsByPartNumber === true,
  131. billedTax: s.taxAmounts !== 'xero',
  132. taxType: str('taxType'),
  133. zeroTaxType: str('zeroTaxType'),
  134. tracking: [str('tracking1'), str('tracking2')].filter((v): v is string => Boolean(v)),
  135. sendFromXero: s.sendFromXero === true,
  136. markAsSent: s.markAsSent !== false,
  137. attachPdf: s.attachPdf !== false,
  138. updateContacts: s.updateContacts !== false,
  139. /** Use a contact found by email even when its name is another. */
  140. reuseByEmail: s.sameEmail === 'reuse',
  141. voidOnDelete: s.voidOnDelete !== false,
  142. pushPayments: s.pushPayments !== false,
  143. paymentAccount: str('paymentAccount'),
  144. methodAccounts: {
  145. cashAccount: str('cashAccount'),
  146. cardAccount: str('cardAccount'),
  147. transferAccount: str('transferAccount'),
  148. onlineAccount: str('onlineAccount'),
  149. },
  150. manualPaidAsPayment: s.manualPaidAsPayment === true,
  151. pullPayments: s.pullPayments !== false,
  152. }
  153. }
  154. type Settings = ReturnType<typeof settingsOf>
  155. interface OrgInfo {
  156. tenantId: string
  157. fetchedAt: string
  158. name: string
  159. shortCode: string | null
  160. baseCurrency: string | null
  161. countryCode: string | null
  162. paysTax: boolean
  163. paymentTerms: XeroOrganisation['PaymentTerms'] | null
  164. /** PARTNER organisations cannot invoice at all. */
  165. edition: string | null
  166. }
  167. /** The organisation's lists, read at most every few hours, for one tenant. */
  168. interface Catalog {
  169. tenantId: string
  170. fetchedAt: string
  171. rates: TaxRateEntry[]
  172. defaultSalesAccount: string | null
  173. bankAccountId: string | null
  174. /** Items that can be sold, with their own sales account when they have one. */
  175. items: { code: string; salesAccount: string | null }[]
  176. tracking: { id: string; name: string; categoryId: string; categoryName: string }[]
  177. }
  178. interface State {
  179. org: OrgInfo | null
  180. catalog: Catalog | null
  181. walkIn: { tenantId: string; contactId: string } | null
  182. lastPull: { tenantId: string; at: string } | null
  183. }
  184. function stateOf(ctx: ConnectorContext): State {
  185. const s = ctx.connection.state
  186. const obj = (v: unknown) => (typeof v === 'object' && v !== null ? v : null)
  187. return {
  188. org: obj(s.org) as OrgInfo | null,
  189. catalog: obj(s.catalog) as Catalog | null,
  190. walkIn: obj(s.walkIn) as State['walkIn'],
  191. lastPull: obj(s.lastPull) as State['lastPull'],
  192. }
  193. }
  194. function fresh(at: string | undefined): boolean {
  195. const t = at ? Date.parse(at) : Number.NaN
  196. return Number.isFinite(t) && Date.now() - t < CATALOG_TTL_MS
  197. }
  198. /* ---------- calls ---------- */
  199. interface CallInit {
  200. method?: string
  201. body?: unknown
  202. query?: Record<string, string>
  203. headers?: Record<string, string>
  204. }
  205. /**
  206. * One call to the Accounting API for the chosen organisation. Every call
  207. * names the tenant in a header; Xero answers JSON when asked, and puts its
  208. * reasons in a validation body that the error carries to the log.
  209. */
  210. async function api<T>(ctx: ConnectorContext, path: string, init: CallInit = {}): Promise<T> {
  211. const tenantId = settingsOf(ctx).tenantId
  212. if (!tenantId) throw new Error(`No Xero organisation chosen; ${NO_TENANT}`)
  213. const url = new URL(`${API_BASE}/${path}`)
  214. for (const [k, v] of Object.entries(init.query ?? {})) url.searchParams.set(k, v)
  215. try {
  216. return await ctx.http.json<T>(url.toString(), {
  217. method: init.method ?? (init.body !== undefined ? 'POST' : 'GET'),
  218. headers: { Accept: 'application/json', 'xero-tenant-id': tenantId, ...init.headers },
  219. ...(init.body !== undefined && { body: JSON.stringify(init.body) }),
  220. })
  221. } catch (err) {
  222. if (err instanceof ConnectorHttpError) throw new XeroError(err.status, err.body, err.requestId)
  223. throw err
  224. }
  225. }
  226. function isNotFound(err: unknown): boolean {
  227. return err instanceof XeroError && err.status === 404
  228. }
  229. async function connectionsOf(ctx: ConnectorContext): Promise<XeroConnection[]> {
  230. try {
  231. const list = await ctx.http.json<XeroConnection[]>(CONNECTIONS_URL, {
  232. headers: { Accept: 'application/json' },
  233. })
  234. return (Array.isArray(list) ? list : []).filter(
  235. (c) => !c.tenantType || c.tenantType === 'ORGANISATION'
  236. )
  237. } catch (err) {
  238. if (err instanceof ConnectorHttpError) throw new XeroError(err.status, err.body, err.requestId)
  239. throw err
  240. }
  241. }
  242. /** Every page of a list endpoint. Xero pages by number and returns fewer than a page at the end. */
  243. async function listAll<T>(
  244. ctx: ConnectorContext,
  245. path: string,
  246. key: string,
  247. init: CallInit = {},
  248. pageSize = 100
  249. ): Promise<T[]> {
  250. const out: T[] = []
  251. for (let page = 1; page <= 100; page++) {
  252. const res = await api<Record<string, T[] | undefined>>(ctx, path, {
  253. ...init,
  254. query: { ...init.query, page: String(page), pageSize: String(pageSize) },
  255. })
  256. const rows = res[key] ?? []
  257. out.push(...rows)
  258. if (rows.length < pageSize) break
  259. }
  260. return out
  261. }
  262. /* ---------- organisation and lists ---------- */
  263. async function loadOrg(ctx: ConnectorContext, opts: { refresh?: boolean } = {}): Promise<OrgInfo> {
  264. const tenantId = settingsOf(ctx).tenantId
  265. if (!tenantId) throw new Error(`No Xero organisation chosen; ${NO_TENANT}`)
  266. const cached = stateOf(ctx).org
  267. if (!opts.refresh && cached?.tenantId === tenantId && fresh(cached.fetchedAt)) return cached
  268. const res = await api<{ Organisations?: XeroOrganisation[] }>(ctx, 'Organisation')
  269. const o = res.Organisations?.[0] ?? {}
  270. const org: OrgInfo = {
  271. tenantId,
  272. fetchedAt: new Date().toISOString(),
  273. name: o.Name ?? o.LegalName ?? 'Xero',
  274. shortCode: o.ShortCode ?? null,
  275. baseCurrency: o.BaseCurrency ?? null,
  276. countryCode: o.CountryCode ?? null,
  277. // Absent on older answers: assume registered, which only adds tax codes.
  278. paysTax: o.PaysTax !== false,
  279. paymentTerms: o.PaymentTerms ?? null,
  280. edition: (o as { Edition?: string }).Edition ?? null,
  281. }
  282. await ctx.saveState({ org })
  283. return org
  284. }
  285. async function loadCatalog(
  286. ctx: ConnectorContext,
  287. opts: { refresh?: boolean } = {}
  288. ): Promise<Catalog> {
  289. const tenantId = settingsOf(ctx).tenantId
  290. if (!tenantId) throw new Error(`No Xero organisation chosen; ${NO_TENANT}`)
  291. const cached = stateOf(ctx).catalog
  292. if (
  293. !opts.refresh &&
  294. cached?.tenantId === tenantId &&
  295. fresh(cached.fetchedAt) &&
  296. Array.isArray(cached.items)
  297. ) {
  298. return cached
  299. }
  300. const [rates, accounts, items, tracking] = await Promise.all([
  301. api<{ TaxRates?: XeroTaxRate[] }>(ctx, 'TaxRates'),
  302. api<{ Accounts?: XeroAccount[] }>(ctx, 'Accounts'),
  303. api<{ Items?: XeroItem[] }>(ctx, 'Items'),
  304. api<{ TrackingCategories?: XeroTrackingCategory[] }>(ctx, 'TrackingCategories'),
  305. ])
  306. const active = (accounts.Accounts ?? []).filter((a) => !a.Status || a.Status === 'ACTIVE')
  307. const revenue = active.filter((a) => a.Class === 'REVENUE' && a.Code)
  308. // Xero's own charts call it Sales, code 200 in most; any revenue account will do after that.
  309. const sales =
  310. revenue.find((a) => a.Code === '200') ??
  311. revenue.find((a) => a.Type === 'SALES' || /^sales$/i.test(a.Name ?? '')) ??
  312. revenue[0] ??
  313. null
  314. const bank = active.find((a) => a.Type === 'BANK') ?? null
  315. const catalog: Catalog = {
  316. tenantId,
  317. fetchedAt: new Date().toISOString(),
  318. rates: salesRates(rates.TaxRates ?? []),
  319. defaultSalesAccount: sales?.Code ?? null,
  320. bankAccountId: bank?.AccountID ?? null,
  321. items: (items.Items ?? [])
  322. .filter((i) => i.IsSold !== false)
  323. .map((i) => ({ code: i.Code, salesAccount: i.SalesDetails?.AccountCode ?? null })),
  324. tracking: (tracking.TrackingCategories ?? [])
  325. .filter((c) => !c.Status || c.Status === 'ACTIVE')
  326. .flatMap((c) =>
  327. (c.Options ?? [])
  328. .filter((o) => !o.Status || o.Status === 'ACTIVE')
  329. .map((o) => ({
  330. id: o.TrackingOptionID,
  331. name: o.Name,
  332. categoryId: c.TrackingCategoryID,
  333. categoryName: c.Name,
  334. }))
  335. ),
  336. }
  337. await ctx.saveState({ catalog })
  338. return catalog
  339. }
  340. /* ---------- links, scoped to the organisation ---------- */
  341. /** A link counts only for the organisation it was made in; switching organisation starts afresh. */
  342. async function linkFor(
  343. ctx: ConnectorContext,
  344. entityType: string,
  345. entityId: string
  346. ): Promise<LinkRecord | null> {
  347. const link = await ctx.links.get(entityType, entityId)
  348. if (!link) return null
  349. return link.metadata?.tenantId === settingsOf(ctx).tenantId ? link : null
  350. }
  351. async function setLink(
  352. ctx: ConnectorContext,
  353. entityType: string,
  354. entityId: string,
  355. link: { remoteId: string; remoteUrl?: string | null; checksum?: string | null },
  356. metadata: Record<string, unknown> = {}
  357. ): Promise<void> {
  358. await ctx.links.set(entityType, entityId, {
  359. remoteId: link.remoteId,
  360. remoteUrl: link.remoteUrl ?? null,
  361. checksum: link.checksum ?? null,
  362. metadata: { ...metadata, tenantId: settingsOf(ctx).tenantId },
  363. })
  364. }
  365. async function patchLink(
  366. ctx: ConnectorContext,
  367. entityType: string,
  368. entityId: string,
  369. link: LinkRecord,
  370. patch: Record<string, unknown>
  371. ): Promise<void> {
  372. await ctx.links.set(entityType, entityId, {
  373. remoteId: link.remoteId,
  374. remoteUrl: link.remoteUrl,
  375. checksum: link.checksum,
  376. metadata: { ...(link.metadata ?? {}), ...patch },
  377. })
  378. }
  379. /* ---------- contacts ---------- */
  380. async function findContact(ctx: ConnectorContext, where: string): Promise<XeroContact | null> {
  381. const res = await api<{ Contacts?: XeroContact[] }>(ctx, 'Contacts', {
  382. query: { where, summaryOnly: 'true' },
  383. })
  384. return (res.Contacts ?? []).find((c) => c.ContactStatus !== 'ARCHIVED') ?? null
  385. }
  386. /**
  387. * Every live contact a where-clause finds, in full: the summary form leaves
  388. * out the first and last name, which matching by name needs.
  389. */
  390. async function findContacts(ctx: ConnectorContext, where: string): Promise<XeroContact[]> {
  391. const res = await api<{ Contacts?: XeroContact[] }>(ctx, 'Contacts', { query: { where } })
  392. return (res.Contacts ?? []).filter((c) => c.ContactStatus !== 'ARCHIVED')
  393. }
  394. /** A contact made here before, by the code this app gave it; Xero looks that up by path. */
  395. async function contactByNumber(ctx: ConnectorContext, number: string): Promise<XeroContact | null> {
  396. try {
  397. const res = await api<{ Contacts?: XeroContact[] }>(
  398. ctx,
  399. `Contacts/${encodeURIComponent(number)}`
  400. )
  401. const found = res.Contacts?.[0]
  402. return found && found.ContactStatus !== 'ARCHIVED' ? found : null
  403. } catch (err) {
  404. if (isNotFound(err)) return null
  405. throw err
  406. }
  407. }
  408. async function walkInContact(ctx: ConnectorContext): Promise<string> {
  409. const tenantId = settingsOf(ctx).tenantId
  410. const cached = stateOf(ctx).walkIn
  411. if (cached && cached.tenantId === tenantId) return cached.contactId
  412. let contact = await findContact(ctx, `Name==${whereString(WALK_IN_NAME)}`)
  413. if (!contact) {
  414. const res = await api<{ Contacts?: XeroContact[] }>(ctx, 'Contacts', {
  415. method: 'PUT',
  416. query: { summarizeErrors: 'true' },
  417. body: { Contacts: [{ Name: WALK_IN_NAME }] },
  418. })
  419. contact = res.Contacts?.[0] ?? null
  420. }
  421. if (!contact) throw new Error('Xero did not return the walk-in contact')
  422. await ctx.saveState({ walkIn: { tenantId, contactId: contact.ContactID } })
  423. return contact.ContactID
  424. }
  425. function isDuplicateName(err: unknown): boolean {
  426. return (
  427. err instanceof XeroError && err.status === 400 && /already (exists|assigned)/i.test(err.message)
  428. )
  429. }
  430. async function createContact(ctx: ConnectorContext, c: AccountingCustomer): Promise<XeroContact> {
  431. const name = contactName(c)
  432. const put = async (body: Record<string, unknown>) => {
  433. const res = await api<{ Contacts?: XeroContact[] }>(ctx, 'Contacts', {
  434. method: 'PUT',
  435. query: { summarizeErrors: 'true' },
  436. body: { Contacts: [body] },
  437. })
  438. const made = res.Contacts?.[0]
  439. if (!made) throw new Error('Xero did not return the new contact')
  440. return made
  441. }
  442. try {
  443. return await put(buildContact(c, name))
  444. } catch (err) {
  445. if (!isDuplicateName(err)) throw err
  446. // Xero keeps names unique; the customer number tells two of the same name apart.
  447. const suffix = c.customerNumber ?? c.id.slice(-4)
  448. return put(buildContact(c, `${name} (${suffix})`.slice(0, 255)))
  449. }
  450. }
  451. /**
  452. * A link made before a shared email stopped being enough is checked once.
  453. * Links this app made with a contact of its own are fine; any other, or one
  454. * whose record of how it was made was lost, is compared with the contact in
  455. * Xero. When the contact is neither one this app made nor one with the
  456. * customer's name, it is another customer behind the same address: the link
  457. * is dropped so the customer gets a contact of its own. That only happens
  458. * while the customer is as it was when linked (the stored checksum is
  459. * today's); a customer edited here since may simply have been renamed, so
  460. * that link is kept and the log asks for a look.
  461. */
  462. async function verifiedLink(
  463. ctx: ConnectorContext,
  464. c: AccountingCustomer,
  465. link: LinkRecord,
  466. checksum: string
  467. ): Promise<LinkRecord | null> {
  468. if (link.metadata?.verified === true || link.metadata?.reused === false) return link
  469. const settings = settingsOf(ctx)
  470. if (!settings.reuseByEmail) {
  471. let contact: XeroContact | null = null
  472. try {
  473. const res = await api<{ Contacts?: XeroContact[] }>(ctx, `Contacts/${link.remoteId}`)
  474. contact = res.Contacts?.[0] ?? null
  475. } catch (err) {
  476. if (!isNotFound(err)) throw err
  477. }
  478. if (!contact) {
  479. await ctx.links.remove(CUSTOMER_ENTITY, c.id)
  480. return null
  481. }
  482. const label = contact.Name ?? link.remoteId
  483. if (contact.ContactNumber !== contactNumber(c) && !sameName(c, contact)) {
  484. if (link.checksum === checksum) {
  485. await ctx.links.remove(CUSTOMER_ENTITY, c.id)
  486. await ctx.log(
  487. 'warn',
  488. `Customer ${c.name} was linked to the Xero contact "${label}" because they share an email address, but the names differ; the customer now gets a contact of its own, and its unpaid invoices move to it when next sent.`
  489. )
  490. return null
  491. }
  492. await ctx.log(
  493. 'warn',
  494. `Customer ${c.name} is linked to the Xero contact "${label}", whose name is different. The customer was changed here after it was linked, so this may be a rename and the link was kept. If "${label}" is another customer, give this customer its own contact in Xero.`
  495. )
  496. }
  497. }
  498. const next = { ...link, metadata: { ...(link.metadata ?? {}), verified: true } }
  499. await ctx.links.set(CUSTOMER_ENTITY, c.id, next)
  500. return next
  501. }
  502. /**
  503. * The Xero contact for a customer, made or updated as needed. A contact
  504. * already in Xero is found by the number this app gives its contacts, then
  505. * by email, then by name, so a bookkeeper's existing contact is reused
  506. * rather than doubled. An email address can be shared by several customers,
  507. * so a contact found by email is used only when its name agrees too, unless
  508. * the workshop chose to trust email alone; otherwise the customer gets a new
  509. * contact and the log names the one that shares the address.
  510. */
  511. async function ensureContact(
  512. ctx: ConnectorContext,
  513. c: AccountingCustomer | null
  514. ): Promise<{ id: string; email: string | null; taxExempt: boolean }> {
  515. if (!c) return { id: await walkInContact(ctx), email: null, taxExempt: false }
  516. const settings = settingsOf(ctx)
  517. const org = await loadOrg(ctx)
  518. const name = contactName(c)
  519. const checksum = checksumOf(buildContact(c, name))
  520. const found = await linkFor(ctx, CUSTOMER_ENTITY, c.id)
  521. const link = found ? await verifiedLink(ctx, c, found, checksum) : null
  522. const result = (id: string) => ({ id, email: c.email, taxExempt: c.taxExempt })
  523. if (link) {
  524. if (link.checksum === checksum || !settings.updateContacts) return result(link.remoteId)
  525. try {
  526. await updateContact(ctx, link.remoteId, c, name)
  527. // How the link was made, and that it was checked, stay with it.
  528. await setLink(
  529. ctx,
  530. CUSTOMER_ENTITY,
  531. c.id,
  532. {
  533. remoteId: link.remoteId,
  534. remoteUrl: contactUrl(org.shortCode, link.remoteId),
  535. checksum,
  536. },
  537. link.metadata ?? {}
  538. )
  539. return result(link.remoteId)
  540. } catch (err) {
  541. if (!isNotFound(err)) throw err
  542. await ctx.links.remove(CUSTOMER_ENTITY, c.id)
  543. }
  544. }
  545. const email = c.email?.trim()
  546. let existing = await contactByNumber(ctx, contactNumber(c))
  547. let sharesEmail: XeroContact | null = null
  548. if (!existing && email) {
  549. const withEmail = await findContacts(ctx, `EmailAddress==${whereString(email)}`)
  550. existing =
  551. withEmail.find((x) => sameName(c, x)) ??
  552. (settings.reuseByEmail ? (withEmail[0] ?? null) : null)
  553. if (!existing) sharesEmail = withEmail[0] ?? null
  554. }
  555. existing ??= await findContact(ctx, `Name==${whereString(name)}`)
  556. const remote = existing ?? (await createContact(ctx, c))
  557. if (!existing && sharesEmail) {
  558. await ctx.log(
  559. 'warn',
  560. `Customer ${c.name} got a new Xero contact, "${remote.Name ?? name}": the contact "${sharesEmail.Name ?? sharesEmail.ContactID}" has the same email address but another name. If they are the same customer, merge the two contacts in Xero, or choose to use the existing contact under "Customers with the same email" in the integration settings.`
  561. )
  562. }
  563. await setLink(
  564. ctx,
  565. CUSTOMER_ENTITY,
  566. c.id,
  567. {
  568. remoteId: remote.ContactID,
  569. remoteUrl: contactUrl(org.shortCode, remote.ContactID),
  570. checksum,
  571. },
  572. { reused: Boolean(existing), verified: true }
  573. )
  574. return result(remote.ContactID)
  575. }
  576. /** Copies the customer's details over. A name another contact already holds stays as it was. */
  577. async function updateContact(
  578. ctx: ConnectorContext,
  579. contactId: string,
  580. c: AccountingCustomer,
  581. name: string
  582. ): Promise<void> {
  583. const body: Record<string, unknown> = { ...buildContact(c, name), ContactID: contactId }
  584. try {
  585. await api(ctx, `Contacts/${contactId}`, { body: { Contacts: [body] } })
  586. } catch (err) {
  587. if (!isDuplicateName(err)) throw err
  588. const { Name: _name, ...rest } = body
  589. await api(ctx, `Contacts/${contactId}`, { body: { Contacts: [rest] } })
  590. }
  591. }
  592. /* ---------- tax ---------- */
  593. interface ResolvedTax {
  594. registered: boolean
  595. taxType: string | null
  596. zeroTaxType: string | null
  597. note: string | null
  598. }
  599. async function resolveTax(
  600. ctx: ConnectorContext,
  601. inv: AccountingInvoice,
  602. org: OrgInfo,
  603. taxExempt: boolean
  604. ): Promise<ResolvedTax> {
  605. const settings = settingsOf(ctx)
  606. if (!org.paysTax) {
  607. return {
  608. registered: false,
  609. taxType: null,
  610. zeroTaxType: null,
  611. note:
  612. inv.taxAmount > 0
  613. ? `The Xero organisation is not registered for tax, so invoice ${inv.invoiceNumber} went over without its ${round2(inv.taxAmount)} tax. Turn on tax in Xero's financial settings if it should carry it.`
  614. : null,
  615. }
  616. }
  617. let catalog = await loadCatalog(ctx)
  618. const zero = pickZeroRate(catalog.rates, settings.zeroTaxType)
  619. const taxed = inv.taxRate > 0 && !taxExempt
  620. if (!taxed)
  621. return { registered: true, taxType: null, zeroTaxType: zero?.taxType ?? null, note: null }
  622. let pick = pickTaxedRate(catalog.rates, inv.taxRate, settings.taxType)
  623. if (!pick.matched && !settings.taxType) {
  624. // The rate may be new in Xero since the list was read.
  625. catalog = await loadCatalog(ctx, { refresh: true })
  626. pick = pickTaxedRate(catalog.rates, inv.taxRate, settings.taxType)
  627. }
  628. let note: string | null = null
  629. if (!pick.matched) {
  630. note = pick.entry
  631. ? `Invoice ${inv.invoiceNumber} charges ${inv.taxRate}% but was booked under "${pick.entry.name}" (${pick.entry.percent}%), the tax rate chosen in the integration settings.`
  632. : `No Xero tax rate carries ${inv.taxRate}%, so invoice ${inv.invoiceNumber} went over without one and Xero used each account's default. Add a ${inv.taxRate}% rate in Xero or choose one in the integration settings.`
  633. }
  634. return {
  635. registered: true,
  636. taxType: pick.entry?.taxType ?? null,
  637. zeroTaxType: zero?.taxType ?? null,
  638. note,
  639. }
  640. }
  641. /* ---------- invoices ---------- */
  642. /** Why the invoice stays out of Xero, or null when it goes. */
  643. function whyNotEligible(inv: AccountingInvoice, s: Settings, tz: string): string | null {
  644. if (!s.pushInvoices) return 'invoice push switched off'
  645. if (!inv.invoiceNumber) return 'no invoice number'
  646. const issued = Boolean(inv.issuedAt) || (s.pushOnComplete && inv.status === 'completed')
  647. if (!issued) return 'not issued yet'
  648. // Completed, but its customer's invoices need a reference / PO this job
  649. // does not have yet. It waits here as it waits in the app; once it has
  650. // gone out some other way (sent, paid) it is the ledger's like any other.
  651. if (!inv.issuedAt && inv.awaitingReference) return 'waiting for the customer reference / PO'
  652. if (s.startDate && zonedDayKey(inv.invoiceDate, tz) < s.startDate) {
  653. return 'dated before the start date'
  654. }
  655. return null
  656. }
  657. /**
  658. * The currency to put on the invoice: none when the workshop bills in the
  659. * organisation's own currency, which is Xero's default. Another currency is
  660. * sent as it is; Xero accepts it when the organisation has multi-currency
  661. * and that currency added, and says so when it has not.
  662. */
  663. async function currencyFor(ctx: ConnectorContext, org: OrgInfo): Promise<string | null> {
  664. const ours = await workshopCurrency(ctx.connection.organizationId)
  665. if (!ours || !org.baseCurrency || ours === org.baseCurrency) return null
  666. return ours
  667. }
  668. async function readInvoice(ctx: ConnectorContext, invoiceId: string): Promise<XeroInvoice> {
  669. const res = await api<{ Invoices?: XeroInvoice[] }>(ctx, `Invoices/${invoiceId}`)
  670. const inv = res.Invoices?.[0]
  671. if (!inv) throw new XeroError(404, '{"Message":"Invoice not found"}')
  672. return inv
  673. }
  674. function isGone(inv: XeroInvoice): boolean {
  675. return inv.Status === 'VOIDED' || inv.Status === 'DELETED'
  676. }
  677. /** The invoice's number belongs to one voided or deleted in Xero, which Xero never gives out again. */
  678. class NumberTaken extends Error {
  679. invoice: XeroInvoice
  680. constructor(invoice: XeroInvoice) {
  681. super(
  682. `Invoice number ${invoice.InvoiceNumber} is taken by a ${invoice.Status?.toLowerCase()} invoice in Xero`
  683. )
  684. this.invoice = invoice
  685. }
  686. }
  687. /**
  688. * An invoice voided or deleted in Xero cannot come back under its number.
  689. * With Torqvoice numbers it is left out, and the link remembers that so later
  690. * edits are skipped without failing; given a new number here, it is sent as
  691. * a new invoice. With Xero numbering it simply goes over again as new.
  692. */
  693. async function markGone(
  694. ctx: ConnectorContext,
  695. inv: AccountingInvoice,
  696. remote: XeroInvoice
  697. ): Promise<JobOutcome> {
  698. const status = (remote.Status ?? 'voided').toLowerCase()
  699. await setLink(
  700. ctx,
  701. INVOICE_ENTITY,
  702. inv.id,
  703. { remoteId: remote.InvoiceID, remoteUrl: null, checksum: null },
  704. { goneInXero: status, invoiceNumber: inv.invoiceNumber }
  705. )
  706. await ctx.log(
  707. 'warn',
  708. `Invoice ${inv.invoiceNumber} was ${status} in Xero, and Xero does not give its number out again, so edits here are not sent. Give the invoice a new number in Torqvoice to send it as a new invoice.`
  709. )
  710. return { summary: `invoice ${inv.invoiceNumber} ${status} in Xero; not sent again` }
  711. }
  712. function hasMoney(inv: XeroInvoice): boolean {
  713. return (inv.AmountPaid ?? 0) > 0 || (inv.Payments?.length ?? 0) > 0 || inv.Status === 'PAID'
  714. }
  715. /** The record is gone here: void or delete Xero's copy unless money was taken against it. */
  716. async function retireInvoice(
  717. ctx: ConnectorContext,
  718. serviceRecordId: string,
  719. why: 'deleted' | 'cancelled' = 'deleted'
  720. ): Promise<JobOutcome> {
  721. const settings = settingsOf(ctx)
  722. const link = await linkFor(ctx, INVOICE_ENTITY, serviceRecordId)
  723. if (!link) return { summary: 'nothing to do' }
  724. if (!settings.voidOnDelete) {
  725. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  726. return { summary: 'left in Xero, voiding switched off' }
  727. }
  728. try {
  729. const current = await readInvoice(ctx, link.remoteId)
  730. const label = current.InvoiceNumber ?? current.InvoiceID
  731. if (current.Status === 'VOIDED' || current.Status === 'DELETED') {
  732. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  733. return { summary: `invoice ${label} already ${current.Status.toLowerCase()} in Xero` }
  734. }
  735. if (hasMoney(current)) {
  736. await ctx.log(
  737. 'warn',
  738. `Invoice ${label} was ${why} here but has payments in Xero; left as is${why === 'cancelled' ? '. Book the credit note or refund there by hand' : ''}`
  739. )
  740. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  741. return { summary: 'left in Xero, has payments' }
  742. }
  743. // A draft or one awaiting approval is deleted; an approved one can only be voided.
  744. const status = current.Status === 'AUTHORISED' ? 'VOIDED' : 'DELETED'
  745. await api(ctx, `Invoices/${current.InvoiceID}`, {
  746. body: { Invoices: [{ InvoiceID: current.InvoiceID, Status: status }] },
  747. })
  748. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  749. return { summary: `invoice ${label} ${status.toLowerCase()} in Xero` }
  750. } catch (err) {
  751. if (!isNotFound(err)) throw err
  752. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  753. return { summary: 'already gone from Xero' }
  754. }
  755. }
  756. /** The tracking options chosen, as Xero names them on a line; at most one per category. */
  757. function trackingFor(catalog: Catalog, chosen: string[]): { Name: string; Option: string }[] {
  758. const out: { Name: string; Option: string }[] = []
  759. const seen = new Set<string>()
  760. for (const value of chosen) {
  761. const optionId = value.includes(':') ? value.split(':')[1] : value
  762. const option = catalog.tracking.find((t) => t.id === optionId)
  763. if (!option || seen.has(option.categoryId)) continue
  764. seen.add(option.categoryId)
  765. out.push({ Name: option.categoryName, Option: option.name })
  766. }
  767. return out
  768. }
  769. async function buildBody(
  770. ctx: ConnectorContext,
  771. inv: AccountingInvoice,
  772. contact: { id: string; taxExempt: boolean },
  773. org: OrgInfo
  774. ): Promise<{ body: Record<string, unknown>; note: string | null }> {
  775. const settings = settingsOf(ctx)
  776. const tax = await resolveTax(ctx, inv, org, contact.taxExempt)
  777. const catalog = await loadCatalog(ctx)
  778. const fallback = catalog.defaultSalesAccount
  779. if (!fallback && !(settings.laborAccount && settings.partsAccount)) {
  780. throw new Error(
  781. 'The Xero organisation has no sales account to book to; choose the accounts in the integration settings'
  782. )
  783. }
  784. const invoiceDay = zonedDayKey(inv.invoiceDate, ctx.timezone)
  785. const body = buildInvoice(inv, {
  786. contactId: contact.id,
  787. status: settings.invoiceStatus,
  788. invoiceNumber: settings.xeroNumbers ? null : inv.invoiceNumber,
  789. reference: referenceFor(inv, settings.reference),
  790. dueDate: inv.dueDate
  791. ? zonedDayKey(inv.dueDate, ctx.timezone)
  792. : defaultDueDate(invoiceDay, org.paymentTerms ?? undefined),
  793. brandingThemeId: settings.brandingThemeId,
  794. currency: await currencyFor(ctx, org),
  795. timezone: ctx.timezone,
  796. url: appInvoiceUrl(ctx.appUrl, inv),
  797. includeVehicle: settings.includeVehicle,
  798. includeNotes: settings.includeNotes,
  799. notesAbove: settings.notesAbove,
  800. includePartNumbers: settings.includePartNumbers,
  801. distanceUnit: await workshopDistanceUnit(ctx.connection.organizationId),
  802. accounts: {
  803. labor: settings.laborAccount,
  804. parts: settings.partsAccount,
  805. shopFee: settings.shopFeeAccount,
  806. fallback: fallback ?? settings.laborAccount ?? '',
  807. },
  808. items: { labor: settings.laborItem, parts: settings.partsItem },
  809. partItemCodes: new Set(settings.matchItemsByPartNumber ? catalog.items.map((i) => i.code) : []),
  810. itemAccounts: new Map(
  811. catalog.items.flatMap((i) => (i.salesAccount ? [[i.code, i.salesAccount] as const] : []))
  812. ),
  813. registeredForTax: tax.registered,
  814. taxType: tax.taxType,
  815. zeroTaxType: tax.zeroTaxType,
  816. billedTax: settings.billedTax,
  817. taxExempt: contact.taxExempt,
  818. tracking: trackingFor(catalog, settings.tracking),
  819. sentToContact: settings.markAsSent && !settings.sendFromXero,
  820. })
  821. return { body, note: tax.note }
  822. }
  823. /**
  824. * A new invoice in Xero. When the Torqvoice number is used and Xero already
  825. * has an invoice of that number that links back to this job, an earlier
  826. * push lost its link and that invoice is adopted instead of doubled.
  827. */
  828. async function createInvoice(
  829. ctx: ConnectorContext,
  830. body: Record<string, unknown>,
  831. inv: AccountingInvoice,
  832. checksum: string
  833. ): Promise<{ invoice: XeroInvoice; adopted: boolean }> {
  834. const number = typeof body.InvoiceNumber === 'string' ? body.InvoiceNumber : null
  835. if (number) {
  836. const found = await api<{ Invoices?: XeroInvoice[] }>(ctx, 'Invoices', {
  837. query: { InvoiceNumbers: number, summaryOnly: 'true' },
  838. })
  839. const sales = (found.Invoices ?? []).filter((i) => i.Type === 'ACCREC')
  840. const live = sales.filter((i) => !isGone(i))
  841. // Xero keeps a voided or deleted invoice's number taken for good.
  842. const gone = sales.find(isGone)
  843. if (!live.length && gone) throw new NumberTaken(gone)
  844. if (live.length) {
  845. const full = (await readInvoice(ctx, live[0].InvoiceID)) as XeroInvoice & { Url?: string }
  846. // Ours when it links back to this job, or, without a link to compare,
  847. // when it is for the same customer on the same day.
  848. const ours = body.Url
  849. ? full.Url === body.Url
  850. : full.Contact?.ContactID === (body.Contact as { ContactID?: string }).ContactID &&
  851. zonedDayKey(parseXeroDate(full.Date) ?? new Date(0), 'UTC') === body.Date
  852. if (ours) {
  853. await ctx.log('info', `Invoice ${number} was already in Xero; linked to it`)
  854. await relinkPayments(ctx, inv, full)
  855. return {
  856. invoice: hasMoney(full) ? full : await saveInvoice(ctx, full, body),
  857. adopted: true,
  858. }
  859. }
  860. // Xero keeps sales invoice numbers unique and would refuse a second one.
  861. throw new Error(
  862. `Xero already has an invoice numbered ${number} that did not come from Torqvoice, so invoice ${inv.invoiceNumber} cannot be added under that number. Renumber one of them, or choose "Let Xero number them" in the integration settings.`
  863. )
  864. }
  865. }
  866. const res = await api<{ Invoices?: XeroInvoice[] }>(ctx, 'Invoices', {
  867. method: 'PUT',
  868. // Summarised, a refused invoice is a 400 with Xero's reasons, never a 200.
  869. query: { unitdp: '4', summarizeErrors: 'true' },
  870. // A retry after a lost answer must not make a second invoice.
  871. headers: { 'Idempotency-Key': `tv-${inv.id}-${checksum.slice(0, 24)}` },
  872. body: { Invoices: [body] },
  873. })
  874. const made = res.Invoices?.[0]
  875. if (!made) throw new Error('Xero did not return the new invoice')
  876. return { invoice: made, adopted: false }
  877. }
  878. /**
  879. * After a lost link (a reconnect forgets what was sent), the payments Xero
  880. * already holds for an invoice found again are linked to the ones here by
  881. * amount and day, so they are not recorded a second time. A payment that
  882. * came from Xero is known by its own id.
  883. */
  884. async function relinkPayments(
  885. ctx: ConnectorContext,
  886. inv: AccountingInvoice,
  887. remote: XeroInvoice
  888. ): Promise<void> {
  889. const theirs = (remote.Payments ?? []).filter((x) => x.Status !== 'DELETED')
  890. const taken = new Set<string>()
  891. for (const p of inv.payments) {
  892. if (await linkFor(ctx, PAYMENT_ENTITY, p.id)) continue
  893. const fromXero = p.provider === PROVIDER && p.externalId
  894. const day = zonedDayKey(p.date, ctx.timezone)
  895. const match = fromXero
  896. ? theirs.find((x) => x.PaymentID === p.externalId)
  897. : theirs.find(
  898. (x) =>
  899. !taken.has(x.PaymentID) &&
  900. Math.abs((x.Amount ?? 0) - round2(p.amount)) <= ROUNDING_SLACK &&
  901. xeroDayKey(x.Date) === day
  902. )
  903. if (!match) continue
  904. taken.add(match.PaymentID)
  905. await setLink(
  906. ctx,
  907. PAYMENT_ENTITY,
  908. p.id,
  909. { remoteId: match.PaymentID },
  910. { createdByUs: !fromXero, serviceRecordId: inv.id, relinked: true }
  911. )
  912. }
  913. }
  914. /**
  915. * Writes our body over an invoice Xero still lets us change. An update never
  916. * moves it back in approval: a draft someone approved in Xero stays approved.
  917. */
  918. async function saveInvoice(
  919. ctx: ConnectorContext,
  920. current: XeroInvoice,
  921. body: Record<string, unknown>
  922. ): Promise<XeroInvoice> {
  923. const ours = STATUS_RANK[String(body.Status)] ?? 0
  924. const theirs = STATUS_RANK[current.Status ?? ''] ?? 0
  925. const next: Record<string, unknown> = { ...body, InvoiceID: current.InvoiceID }
  926. if (theirs > ours) next.Status = current.Status
  927. // An invoice Xero numbered keeps its number.
  928. if (!body.InvoiceNumber) delete next.InvoiceNumber
  929. const res = await api<{ Invoices?: XeroInvoice[] }>(ctx, `Invoices/${current.InvoiceID}`, {
  930. query: { unitdp: '4' },
  931. body: { Invoices: [next] },
  932. })
  933. return res.Invoices?.[0] ?? current
  934. }
  935. async function pushInvoice(ctx: ConnectorContext, serviceRecordId: string): Promise<JobOutcome> {
  936. const settings = settingsOf(ctx)
  937. if (!settings.tenantId) return { summary: NO_TENANT }
  938. const inv = await loadInvoiceForAccounting(ctx.connection.organizationId, serviceRecordId)
  939. if (!inv) return retireInvoice(ctx, serviceRecordId)
  940. // Cancelled here: its number is kept, and Xero's copy is voided like a deleted one.
  941. if (inv.status === 'cancelled') return retireInvoice(ctx, serviceRecordId, 'cancelled')
  942. const skip = whyNotEligible(inv, settings, ctx.timezone)
  943. if (skip) return { summary: skip }
  944. const org = await loadOrg(ctx)
  945. const contact = await ensureContact(ctx, inv.customer)
  946. const { body, note } = await buildBody(ctx, inv, contact, org)
  947. const checksum = checksumOf(body)
  948. let link = await linkFor(ctx, INVOICE_ENTITY, serviceRecordId)
  949. if (link?.metadata?.goneInXero) {
  950. if (!settings.xeroNumbers && link.metadata.invoiceNumber === inv.invoiceNumber) {
  951. return {
  952. summary: `invoice ${inv.invoiceNumber} ${link.metadata.goneInXero} in Xero; not sent again`,
  953. }
  954. }
  955. // Renumbered here, or numbered by Xero: it goes over as a new invoice.
  956. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  957. link = null
  958. }
  959. let saved: XeroInvoice | null = null
  960. let action = 'unchanged'
  961. if (!link || link.checksum !== checksum) {
  962. if (note) await ctx.log('warn', note)
  963. if (link) {
  964. try {
  965. const current = await readInvoice(ctx, link.remoteId)
  966. if (isGone(current)) {
  967. // Gone in Xero: with Xero numbering a new one is made below; under
  968. // the same Torqvoice number Xero would refuse it.
  969. if (!settings.xeroNumbers) return markGone(ctx, inv, current)
  970. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  971. link = null
  972. } else if (hasMoney(current)) {
  973. saved = current
  974. action = await settledDifference(ctx, inv, current, link, checksum)
  975. } else {
  976. saved = await saveInvoice(ctx, current, body)
  977. action = 'updated'
  978. }
  979. } catch (err) {
  980. if (!isNotFound(err)) throw err
  981. await ctx.links.remove(INVOICE_ENTITY, serviceRecordId)
  982. link = null
  983. }
  984. }
  985. if (!link) {
  986. try {
  987. const made = await createInvoice(ctx, body, inv, checksum)
  988. saved = made.invoice
  989. action = made.adopted ? 'found in Xero and linked again' : 'created'
  990. } catch (err) {
  991. if (err instanceof NumberTaken) return markGone(ctx, inv, err.invoice)
  992. throw err
  993. }
  994. }
  995. if (saved && action !== 'left as paid') {
  996. await setLink(
  997. ctx,
  998. INVOICE_ENTITY,
  999. serviceRecordId,
  1000. {
  1001. remoteId: saved.InvoiceID,
  1002. remoteUrl: invoiceUrl(org.shortCode, saved.InvoiceID),
  1003. checksum,
  1004. },
  1005. {
  1006. invoiceNumber: saved.InvoiceNumber ?? null,
  1007. contactId: contact.id,
  1008. // The PDF changed with the invoice; the same file name overwrites the old one in Xero.
  1009. attached: false,
  1010. emailed: link?.metadata?.emailed ?? false,
  1011. }
  1012. )
  1013. checkTotals(ctx, inv, saved, settings, org)
  1014. }
  1015. }
  1016. link = await linkFor(ctx, INVOICE_ENTITY, serviceRecordId)
  1017. if (link) {
  1018. if (settings.attachPdf && link.metadata?.attached !== true) {
  1019. if (await attachPdf(ctx, link.remoteId, inv)) {
  1020. await patchLink(ctx, INVOICE_ENTITY, serviceRecordId, link, { attached: true })
  1021. link = await linkFor(ctx, INVOICE_ENTITY, serviceRecordId)
  1022. }
  1023. }
  1024. if (link && settings.sendFromXero && link.metadata?.emailed !== true) {
  1025. if (await emailFromXero(ctx, link.remoteId, inv, contact.email)) {
  1026. await patchLink(ctx, INVOICE_ENTITY, serviceRecordId, link, { emailed: true })
  1027. }
  1028. }
  1029. }
  1030. let paymentsPushed = 0
  1031. let waiting = false
  1032. if (settings.pushPayments && link) {
  1033. const pushed = await pushPendingPayments(ctx, inv, link.remoteId)
  1034. paymentsPushed = pushed.count
  1035. waiting = pushed.waitingForApproval
  1036. }
  1037. const summary = `invoice ${inv.invoiceNumber} ${action}`
  1038. const extra = [
  1039. paymentsPushed ? `${paymentsPushed} payments recorded` : null,
  1040. waiting ? 'payments wait for approval in Xero' : null,
  1041. ].filter(Boolean)
  1042. return { summary: extra.length ? `${summary}, ${extra.join(', ')}` : summary }
  1043. }
  1044. /**
  1045. * The invoice changed here after money was taken against it in Xero, which
  1046. * Xero no longer lets anyone edit. When Xero already holds the same total
  1047. * and customer, only the checksum moved (a setting such as an account
  1048. * changed) and it is refreshed quietly; otherwise the workshop hears once.
  1049. */
  1050. async function settledDifference(
  1051. ctx: ConnectorContext,
  1052. inv: AccountingInvoice,
  1053. current: XeroInvoice,
  1054. link: LinkRecord,
  1055. checksum: string
  1056. ): Promise<string> {
  1057. const sameTotal = Math.abs((current.Total ?? 0) - inv.totalAmount) <= TOTAL_TOLERANCE
  1058. if (sameTotal) {
  1059. await ctx.links.set(INVOICE_ENTITY, inv.id, {
  1060. remoteId: link.remoteId,
  1061. remoteUrl: link.remoteUrl,
  1062. checksum,
  1063. metadata: link.metadata,
  1064. })
  1065. return 'left as paid'
  1066. }
  1067. if (link.metadata?.warnedChecksum !== checksum) {
  1068. await ctx.log(
  1069. 'warn',
  1070. `Invoice ${inv.invoiceNumber} changed here (total ${round2(inv.totalAmount)}) after a payment was recorded against it in Xero (total ${round2(current.Total ?? 0)}); Xero does not allow editing it, so it was left as is. Remove the payment in Xero to let the change through.`
  1071. )
  1072. await patchLink(ctx, INVOICE_ENTITY, inv.id, link, { warnedChecksum: checksum })
  1073. }
  1074. return 'left as paid'
  1075. }
  1076. function checkTotals(
  1077. ctx: ConnectorContext,
  1078. inv: AccountingInvoice,
  1079. saved: XeroInvoice,
  1080. settings: Settings,
  1081. org: OrgInfo
  1082. ): void {
  1083. if (saved.Total === undefined) return
  1084. if (Math.abs(saved.Total - inv.totalAmount) <= TOTAL_TOLERANCE) return
  1085. const hint = !org.paysTax
  1086. ? 'the organisation is not registered for tax in Xero'
  1087. : !settings.billedTax
  1088. ? 'Xero worked the tax out itself; set Tax amounts to "as billed" to send yours'
  1089. : 'check the tax rates in the integration settings'
  1090. void ctx.log(
  1091. 'warn',
  1092. `Invoice ${inv.invoiceNumber}: Xero total ${round2(saved.Total)} differs from ${round2(inv.totalAmount)} here; ${hint}`,
  1093. { xero: saved.Total, torqvoice: inv.totalAmount }
  1094. )
  1095. }
  1096. /** The invoice the customer received, attached to Xero's copy. */
  1097. async function attachPdf(
  1098. ctx: ConnectorContext,
  1099. invoiceId: string,
  1100. inv: AccountingInvoice
  1101. ): Promise<boolean> {
  1102. try {
  1103. const pdf = await loadInvoicePdfForAccounting(ctx.connection.organizationId, inv.id)
  1104. if (!pdf) return false
  1105. const filename = `${String(inv.invoiceNumber).replace(/[^\w.-]+/g, '_')}.pdf`
  1106. const tenantId = settingsOf(ctx).tenantId ?? ''
  1107. const url = `${API_BASE}/Invoices/${invoiceId}/Attachments/${encodeURIComponent(filename)}?IncludeOnline=true`
  1108. const res = await ctx.http.fetch(url, {
  1109. method: 'PUT',
  1110. headers: {
  1111. Accept: 'application/json',
  1112. 'Content-Type': 'application/pdf',
  1113. 'xero-tenant-id': tenantId,
  1114. },
  1115. body: pdf.buffer as BodyInit,
  1116. })
  1117. if (!res.ok) throw new XeroError(res.status, await res.text())
  1118. return true
  1119. } catch (err) {
  1120. await ctx.log(
  1121. 'warn',
  1122. `Invoice ${inv.invoiceNumber} is in Xero but its PDF could not be attached: ${err instanceof Error ? err.message : String(err)}`
  1123. )
  1124. return false
  1125. }
  1126. }
  1127. /** Xero sends its own copy to the contact. Only an approved invoice with an email can go. */
  1128. async function emailFromXero(
  1129. ctx: ConnectorContext,
  1130. invoiceId: string,
  1131. inv: AccountingInvoice,
  1132. email: string | null
  1133. ): Promise<boolean> {
  1134. if (!email) {
  1135. await ctx.log(
  1136. 'warn',
  1137. `Invoice ${inv.invoiceNumber} was not emailed from Xero: the customer has no email address`
  1138. )
  1139. return true
  1140. }
  1141. try {
  1142. const current = await readInvoice(ctx, invoiceId)
  1143. if (current.Status !== 'AUTHORISED' && current.Status !== 'PAID') return false
  1144. await api(ctx, `Invoices/${invoiceId}/Email`, { body: {} })
  1145. return true
  1146. } catch (err) {
  1147. await ctx.log(
  1148. 'warn',
  1149. `Invoice ${inv.invoiceNumber} could not be emailed from Xero: ${err instanceof Error ? err.message : String(err)}`
  1150. )
  1151. return true
  1152. }
  1153. }
  1154. /* ---------- payments ---------- */
  1155. /** The bank or clearing account a payment from here goes into. */
  1156. async function paymentAccountFor(
  1157. ctx: ConnectorContext,
  1158. p: Pick<AccountingPayment, 'method' | 'provider'>
  1159. ): Promise<string> {
  1160. const settings = settingsOf(ctx)
  1161. const key = methodAccountKey(p)
  1162. const chosen = (key && settings.methodAccounts[key]) || settings.paymentAccount
  1163. if (chosen) return chosen
  1164. const catalog = await loadCatalog(ctx)
  1165. if (catalog.bankAccountId) return catalog.bankAccountId
  1166. throw new Error(
  1167. 'The Xero organisation has no bank account to record payments in; add one in Xero or choose an account in the integration settings'
  1168. )
  1169. }
  1170. /**
  1171. * Records the payments here that Xero does not have yet. Xero takes payments
  1172. * only on an approved invoice, so on a draft they wait and go over once it is
  1173. * approved there (the next edit, pull or retry sends them).
  1174. */
  1175. async function pushPendingPayments(
  1176. ctx: ConnectorContext,
  1177. inv: AccountingInvoice,
  1178. invoiceId: string
  1179. ): Promise<{ count: number; waitingForApproval: boolean }> {
  1180. const settings = settingsOf(ctx)
  1181. const pending: AccountingPayment[] = []
  1182. for (const p of inv.payments) {
  1183. if (!(await linkFor(ctx, PAYMENT_ENTITY, p.id))) pending.push(p)
  1184. }
  1185. const manual =
  1186. settings.manualPaidAsPayment &&
  1187. inv.manuallyPaid &&
  1188. !(await linkFor(ctx, PAYMENT_ENTITY, `manual:${inv.id}`))
  1189. if (!pending.length && !manual) return { count: 0, waitingForApproval: false }
  1190. const current = await readInvoice(ctx, invoiceId)
  1191. if (current.Status !== 'AUTHORISED' && current.Status !== 'PAID') {
  1192. return {
  1193. count: 0,
  1194. waitingForApproval: current.Status === 'DRAFT' || current.Status === 'SUBMITTED',
  1195. }
  1196. }
  1197. // Xero refuses a payment above what it shows as owed. A few cents over is
  1198. // its per-line tax rounding against ours, and the payment is trimmed to fit;
  1199. // more than that means the invoices disagree, which the log says.
  1200. let remaining = current.AmountDue ?? Number.POSITIVE_INFINITY
  1201. let count = 0
  1202. for (const p of pending) {
  1203. let amount = round2(p.amount)
  1204. if (amount > remaining + 0.005) {
  1205. if (amount - remaining <= ROUNDING_SLACK && remaining > 0) {
  1206. amount = round2(remaining)
  1207. } else {
  1208. await ctx.log(
  1209. 'warn',
  1210. `A payment of ${amount} on invoice ${inv.invoiceNumber} is more than Xero shows as owed (${round2(Math.max(0, remaining))}); it was not recorded in Xero`
  1211. )
  1212. continue
  1213. }
  1214. }
  1215. await pushPaymentRow(ctx, { ...p, amount }, invoiceId)
  1216. remaining -= amount
  1217. count++
  1218. }
  1219. if (manual) {
  1220. const due = round2(Math.max(0, remaining))
  1221. if (due > 0 && Number.isFinite(due)) {
  1222. await pushPaymentRow(
  1223. ctx,
  1224. {
  1225. id: `manual:${inv.id}`,
  1226. serviceRecordId: inv.id,
  1227. amount: due,
  1228. date: inv.issuedAt ?? new Date(),
  1229. method: 'other',
  1230. note: 'Marked as paid by hand in Torqvoice',
  1231. provider: null,
  1232. externalId: null,
  1233. },
  1234. invoiceId,
  1235. { manual: true }
  1236. )
  1237. count++
  1238. }
  1239. }
  1240. return { count, waitingForApproval: false }
  1241. }
  1242. async function pushPaymentRow(
  1243. ctx: ConnectorContext,
  1244. p: AccountingPayment,
  1245. invoiceId: string,
  1246. extra: Record<string, unknown> = {}
  1247. ): Promise<void> {
  1248. const body = buildPayment(p, {
  1249. invoiceId,
  1250. accountId: await paymentAccountFor(ctx, p),
  1251. timezone: ctx.timezone,
  1252. })
  1253. const res = await api<{ Payments?: XeroPayment[] }>(ctx, 'Payments', {
  1254. method: 'PUT',
  1255. query: { summarizeErrors: 'true' },
  1256. headers: { 'Idempotency-Key': `tv-payment-${p.id}` },
  1257. body: { Payments: [body] },
  1258. })
  1259. const made = res.Payments?.[0]
  1260. if (!made) throw new Error('Xero did not return the payment')
  1261. await setLink(
  1262. ctx,
  1263. PAYMENT_ENTITY,
  1264. p.id,
  1265. { remoteId: made.PaymentID },
  1266. { createdByUs: true, serviceRecordId: p.serviceRecordId, ...extra }
  1267. )
  1268. }
  1269. async function pushPayment(ctx: ConnectorContext, paymentId: string): Promise<JobOutcome> {
  1270. const settings = settingsOf(ctx)
  1271. if (!settings.tenantId) return { summary: NO_TENANT }
  1272. const p = await loadPaymentForAccounting(ctx.connection.organizationId, paymentId)
  1273. const link = await linkFor(ctx, PAYMENT_ENTITY, paymentId)
  1274. if (!p) {
  1275. if (!link) return { summary: 'nothing to do' }
  1276. if (link.metadata?.createdByUs !== true) {
  1277. // A payment Xero made and this app then deleted stays in Xero.
  1278. await ctx.links.remove(PAYMENT_ENTITY, paymentId)
  1279. return { summary: 'payment came from Xero; left there' }
  1280. }
  1281. try {
  1282. await api(ctx, `Payments/${link.remoteId}`, {
  1283. body: { Payments: [{ PaymentID: link.remoteId, Status: 'DELETED' }] },
  1284. })
  1285. } catch (err) {
  1286. if (!isNotFound(err)) throw err
  1287. }
  1288. await ctx.links.remove(PAYMENT_ENTITY, paymentId)
  1289. return { summary: 'payment removed from Xero' }
  1290. }
  1291. if (link) return { summary: 'unchanged' }
  1292. if (!settings.pushPayments) return { summary: 'payments not sent' }
  1293. // The payment needs its invoice in Xero first; pushing the invoice also
  1294. // records every payment on it, this one included.
  1295. const outcome = await pushInvoice(ctx, p.serviceRecordId)
  1296. if (await linkFor(ctx, PAYMENT_ENTITY, paymentId)) return { summary: 'payment recorded' }
  1297. const age = Date.now() - p.date.getTime()
  1298. if (outcome.summary?.includes('wait for approval') && age < APPROVAL_WAIT_DAYS * 86_400_000) {
  1299. return {
  1300. summary: 'waiting for the invoice to be approved in Xero',
  1301. rescheduleInSeconds: APPROVAL_RETRY_SECONDS,
  1302. }
  1303. }
  1304. return { summary: `payment not recorded: ${outcome.summary ?? 'invoice not in Xero'}` }
  1305. }
  1306. /* ---------- customers on edit ---------- */
  1307. async function pushCustomer(ctx: ConnectorContext, customerId: string): Promise<JobOutcome> {
  1308. const settings = settingsOf(ctx)
  1309. if (!settings.tenantId) return { summary: NO_TENANT }
  1310. if (!settings.updateContacts) return { summary: 'contact updates switched off' }
  1311. const link = await linkFor(ctx, CUSTOMER_ENTITY, customerId)
  1312. // Customers reach Xero with their first invoice; an edit before that is nothing yet.
  1313. if (!link) return { summary: 'not in Xero yet' }
  1314. const c = await loadCustomerForAccounting(ctx.connection.organizationId, customerId)
  1315. if (!c) return { summary: 'customer gone' }
  1316. await ensureContact(ctx, c)
  1317. return { summary: 'contact updated' }
  1318. }
  1319. /* ---------- pull ---------- */
  1320. function pullSince(ctx: ConnectorContext): Date {
  1321. const tenantId = settingsOf(ctx).tenantId
  1322. const last = stateOf(ctx).lastPull
  1323. const at = last && last.tenantId === tenantId ? Date.parse(last.at) : Number.NaN
  1324. const start = Number.isFinite(at) ? at : Date.now() - 86_400_000
  1325. // A minute of overlap so a change landing during the last pull is not missed.
  1326. return new Date(start - 60_000)
  1327. }
  1328. /**
  1329. * What changed in Xero since the last pull: payments recorded there against
  1330. * invoices from here are recorded here too, and ones deleted there removed
  1331. * again; invoices voided or deleted there lose their link, so the next edit
  1332. * here makes a new one; and invoices approved there get any payments that
  1333. * were waiting for the approval.
  1334. */
  1335. async function pullChanges(ctx: ConnectorContext): Promise<JobOutcome> {
  1336. const settings = settingsOf(ctx)
  1337. if (!settings.tenantId) return { summary: NO_TENANT }
  1338. const startedAt = new Date()
  1339. const since = pullSince(ctx)
  1340. const modified = { 'If-Modified-Since': modifiedSinceHeader(since) }
  1341. const orgId = ctx.connection.organizationId
  1342. let recorded = 0
  1343. let removed = 0
  1344. if (settings.pullPayments) {
  1345. const payments = await listAll<XeroPayment>(ctx, 'Payments', 'Payments', {
  1346. headers: modified,
  1347. query: { where: 'PaymentType=="ACCRECPAYMENT"' },
  1348. })
  1349. const known = await ctx.links.remoteIds(PAYMENT_ENTITY)
  1350. for (const p of payments) {
  1351. if (p.Status === 'DELETED') {
  1352. const link = await ctx.links.byRemoteId(PAYMENT_ENTITY, p.PaymentID)
  1353. if (!link) continue
  1354. if (link.metadata?.createdByUs === true) {
  1355. await ctx.log(
  1356. 'warn',
  1357. `A payment sent from here was removed in Xero (${p.Reference ?? p.PaymentID}); the payment here is kept`
  1358. )
  1359. await ctx.links.remove(PAYMENT_ENTITY, link.entityId)
  1360. continue
  1361. }
  1362. if (await removePulledPayment(orgId, link.entityId, PROVIDER)) removed++
  1363. await ctx.links.remove(PAYMENT_ENTITY, link.entityId)
  1364. continue
  1365. }
  1366. if (known.has(p.PaymentID)) continue
  1367. const invoiceId = p.Invoice?.InvoiceID
  1368. const amount = p.Amount ?? 0
  1369. if (!invoiceId || !(amount > 0)) continue
  1370. const invoiceLink = await ctx.links.byRemoteId(INVOICE_ENTITY, invoiceId)
  1371. if (!invoiceLink || invoiceLink.metadata?.tenantId !== settings.tenantId) continue
  1372. const made = await recordPulledPayment(orgId, {
  1373. serviceRecordId: invoiceLink.entityId,
  1374. amount: round2(amount),
  1375. date: paymentDay(p.Date, ctx.timezone),
  1376. method: 'other',
  1377. provider: PROVIDER,
  1378. externalId: p.PaymentID,
  1379. note: ['Recorded in Xero', p.Reference ? `Ref ${p.Reference}` : null]
  1380. .filter(Boolean)
  1381. .join('. '),
  1382. })
  1383. if (!made) continue
  1384. await setLink(
  1385. ctx,
  1386. PAYMENT_ENTITY,
  1387. made.id,
  1388. { remoteId: p.PaymentID },
  1389. { createdByUs: false, serviceRecordId: invoiceLink.entityId }
  1390. )
  1391. known.add(p.PaymentID)
  1392. if (made.created) recorded++
  1393. }
  1394. }
  1395. let unlinked = 0
  1396. let released = 0
  1397. const invoices = await listAll<XeroInvoice>(ctx, 'Invoices', 'Invoices', {
  1398. headers: modified,
  1399. query: { Statuses: 'VOIDED,DELETED,AUTHORISED', summaryOnly: 'true' },
  1400. })
  1401. for (const remote of invoices) {
  1402. const link = await ctx.links.byRemoteId(INVOICE_ENTITY, remote.InvoiceID)
  1403. if (!link || link.metadata?.tenantId !== settings.tenantId) continue
  1404. if (isGone(remote)) {
  1405. if (link.metadata?.goneInXero) continue
  1406. const status = (remote.Status ?? 'voided').toLowerCase()
  1407. if (settings.xeroNumbers) {
  1408. await ctx.links.remove(INVOICE_ENTITY, link.entityId)
  1409. await ctx.log(
  1410. 'warn',
  1411. `Invoice ${remote.InvoiceNumber ?? remote.InvoiceID} was ${status} in Xero; it will be sent again as a new invoice if edited here`
  1412. )
  1413. } else {
  1414. await ctx.links.set(INVOICE_ENTITY, link.entityId, {
  1415. remoteId: link.remoteId,
  1416. remoteUrl: link.remoteUrl,
  1417. checksum: link.checksum,
  1418. metadata: {
  1419. ...(link.metadata ?? {}),
  1420. goneInXero: status,
  1421. invoiceNumber: remote.InvoiceNumber ?? link.metadata?.invoiceNumber ?? null,
  1422. },
  1423. })
  1424. await ctx.log(
  1425. 'warn',
  1426. `Invoice ${remote.InvoiceNumber ?? remote.InvoiceID} was ${status} in Xero, and Xero does not give its number out again, so edits here are not sent. Give the invoice a new number in Torqvoice to send it as a new invoice.`
  1427. )
  1428. }
  1429. unlinked++
  1430. continue
  1431. }
  1432. if (!settings.pushPayments) continue
  1433. // Approved in Xero since the last pull: payments waiting for that go now.
  1434. const inv = await loadInvoiceForAccounting(orgId, link.entityId)
  1435. if (!inv) continue
  1436. const pushed = await pushPendingPayments(ctx, inv, remote.InvoiceID)
  1437. released += pushed.count
  1438. }
  1439. await ctx.saveState({ lastPull: { tenantId: settings.tenantId, at: startedAt.toISOString() } })
  1440. const parts = [
  1441. recorded ? `${recorded} payments recorded` : null,
  1442. removed ? `${removed} payments removed` : null,
  1443. unlinked ? `${unlinked} invoices voided or deleted in Xero` : null,
  1444. released ? `${released} waiting payments sent` : null,
  1445. ].filter(Boolean)
  1446. return { summary: parts.length ? parts.join(', ') : 'no changes' }
  1447. }
  1448. /* ---------- connector ---------- */
  1449. function entityId(payload: Record<string, unknown>): string | null {
  1450. return typeof payload.entityId === 'string' ? payload.entityId : null
  1451. }
  1452. /** Settings lists, read for the organisation chosen, or empty before one is. */
  1453. function forTenant<T>(fn: (ctx: ConnectorContext) => Promise<T[]>) {
  1454. return async (ctx: ConnectorContext) => (settingsOf(ctx).tenantId ? fn(ctx) : [])
  1455. }
  1456. export const connector: ConnectorServer = {
  1457. manifest,
  1458. /**
  1459. * Who connected: the organisations they allowed. The tenant ids are kept
  1460. * off the row; a hash of them is enough to tell two consents apart.
  1461. */
  1462. async identify(ctx) {
  1463. const orgs = await connectionsOf(ctx)
  1464. if (!orgs.length)
  1465. throw new Error('No Xero organisation was allowed; connect again and choose one')
  1466. const ids = orgs.map((o) => o.tenantId).sort()
  1467. const name =
  1468. orgs.length === 1
  1469. ? (orgs[0].tenantName ?? 'Xero')
  1470. : `${orgs[0].tenantName ?? 'Xero'} and ${orgs.length - 1} more`
  1471. return {
  1472. id: `xero-${createHash('sha256').update(ids.join(',')).digest('hex').slice(0, 16)}`,
  1473. name,
  1474. }
  1475. },
  1476. /** One organisation allowed: it is the one, and the form need not ask. */
  1477. async onConnect(ctx) {
  1478. if (settingsOf(ctx).tenantId) return
  1479. const orgs = await connectionsOf(ctx)
  1480. if (orgs.length === 1) return { settings: { tenantId: orgs[0].tenantId } }
  1481. },
  1482. async test(ctx) {
  1483. try {
  1484. const orgs = await connectionsOf(ctx)
  1485. const tenantId = settingsOf(ctx).tenantId
  1486. if (!tenantId) return { ok: true }
  1487. if (!orgs.some((o) => o.tenantId === tenantId)) {
  1488. return {
  1489. ok: false,
  1490. message:
  1491. 'The chosen Xero organisation is no longer connected to Torqvoice. Reconnect and allow it, or choose another.',
  1492. }
  1493. }
  1494. const org = await loadOrg(ctx, { refresh: true })
  1495. if (org.edition === 'PARTNER') {
  1496. return {
  1497. ok: false,
  1498. message: `${org.name} is a Xero Partner Edition organisation, which cannot hold invoices. Choose another organisation.`,
  1499. }
  1500. }
  1501. return { ok: true, message: org.name }
  1502. } catch (err) {
  1503. return { ok: false, message: err instanceof Error ? err.message : String(err) }
  1504. }
  1505. },
  1506. remoteOptions: {
  1507. async organisations(ctx) {
  1508. const orgs = await connectionsOf(ctx)
  1509. return orgs
  1510. .map((o) => ({ value: o.tenantId, label: o.tenantName ?? o.tenantId }))
  1511. .sort((a, b) => a.label.localeCompare(b.label))
  1512. },
  1513. salesAccounts: forTenant(async (ctx) => {
  1514. const res = await api<{ Accounts?: XeroAccount[] }>(ctx, 'Accounts')
  1515. return (res.Accounts ?? [])
  1516. .filter((a) => a.Class === 'REVENUE' && a.Code && (!a.Status || a.Status === 'ACTIVE'))
  1517. .sort((a, b) => String(a.Code).localeCompare(String(b.Code), undefined, { numeric: true }))
  1518. .map((a) => ({ value: String(a.Code), label: `${a.Code} ${a.Name ?? ''}`.trim() }))
  1519. }),
  1520. paymentAccounts: forTenant(async (ctx) => {
  1521. const res = await api<{ Accounts?: XeroAccount[] }>(ctx, 'Accounts')
  1522. return (res.Accounts ?? [])
  1523. .filter(
  1524. (a) =>
  1525. (!a.Status || a.Status === 'ACTIVE') &&
  1526. (a.Type === 'BANK' || a.EnablePaymentsToAccount === true)
  1527. )
  1528. .sort((a, b) => (a.Name ?? '').localeCompare(b.Name ?? ''))
  1529. .map((a) => ({
  1530. value: a.AccountID,
  1531. label: a.Code ? `${a.Name ?? a.Code} (${a.Code})` : (a.Name ?? a.AccountID),
  1532. }))
  1533. }),
  1534. items: forTenant(async (ctx) => {
  1535. const res = await api<{ Items?: XeroItem[] }>(ctx, 'Items')
  1536. return (res.Items ?? [])
  1537. .filter((i) => i.IsSold !== false)
  1538. .sort((a, b) => a.Code.localeCompare(b.Code))
  1539. .map((i) => ({
  1540. value: i.Code,
  1541. label: `${i.Code}${i.Name ? ` ${i.Name}` : ''}${i.IsTrackedAsInventory ? ' (tracked)' : ''}`,
  1542. }))
  1543. }),
  1544. taxRates: forTenant(async (ctx) => {
  1545. const catalog = await loadCatalog(ctx, { refresh: true })
  1546. return catalog.rates
  1547. .filter((r) => r.percent > 0)
  1548. .map((r) => ({ value: r.taxType, label: rateLabel(r) }))
  1549. }),
  1550. /** Only zero rates: a rate with a percentage on an untaxed line would add tax nobody billed. */
  1551. zeroTaxRates: forTenant(async (ctx) => {
  1552. const catalog = await loadCatalog(ctx, { refresh: true })
  1553. return catalog.rates
  1554. .filter((r) => r.percent === 0)
  1555. .map((r) => ({ value: r.taxType, label: rateLabel(r) }))
  1556. }),
  1557. trackingOptions: forTenant(async (ctx) => {
  1558. const catalog = await loadCatalog(ctx, { refresh: true })
  1559. return catalog.tracking.map((t) => ({
  1560. value: `${t.categoryId}:${t.id}`,
  1561. label: `${t.categoryName}: ${t.name}`,
  1562. }))
  1563. }),
  1564. brandingThemes: forTenant(async (ctx) => {
  1565. const res = await api<{ BrandingThemes?: XeroBrandingTheme[] }>(ctx, 'BrandingThemes')
  1566. return (res.BrandingThemes ?? [])
  1567. .sort((a, b) => (a.SortOrder ?? 0) - (b.SortOrder ?? 0))
  1568. .map((t) => ({ value: t.BrandingThemeID, label: t.Name }))
  1569. }),
  1570. },
  1571. jobs: {
  1572. 'accounting.invoice': async (ctx, payload) => {
  1573. const id = entityId(payload)
  1574. if (!id) return { summary: 'no record id' }
  1575. return pushInvoice(ctx, id)
  1576. },
  1577. 'accounting.payment': async (ctx, payload) => {
  1578. const id = entityId(payload)
  1579. if (!id) return { summary: 'no payment id' }
  1580. return pushPayment(ctx, id)
  1581. },
  1582. 'accounting.customer': async (ctx, payload) => {
  1583. const id = entityId(payload)
  1584. if (!id) return { summary: 'no customer id' }
  1585. return pushCustomer(ctx, id)
  1586. },
  1587. 'accounting.pull': pullChanges,
  1588. },
  1589. /** Hand the refresh token back, which removes Torqvoice from the organisations it reached. */
  1590. async onDisconnect(ctx) {
  1591. const spec = oauthSpec(manifest)
  1592. const client = spec ? resolveClient(spec, ctx.credentials) : null
  1593. const token =
  1594. typeof ctx.credentials.refreshToken === 'string' ? ctx.credentials.refreshToken : null
  1595. if (!client || !token) return
  1596. try {
  1597. await fetch(REVOKE_URL, {
  1598. method: 'POST',
  1599. headers: {
  1600. Authorization: `Basic ${Buffer.from(`${client.clientId}:${client.clientSecret}`).toString('base64')}`,
  1601. 'Content-Type': 'application/x-www-form-urlencoded',
  1602. },
  1603. body: new URLSearchParams({ token }).toString(),
  1604. })
  1605. } catch (err) {
  1606. await ctx.log('warn', `Could not revoke the Xero token: ${String(err)}`)
  1607. }
  1608. },
  1609. }