@yolk-sdk/emulators 0.1.0-canary.124 → 0.1.0-canary.125
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fortnox/api.mjs +1 -0
- package/dist/fortnox/api.mjs.map +1 -1
- package/dist/fortnox/state.d.mts +4 -0
- package/dist/fortnox/state.d.mts.map +1 -1
- package/dist/fortnox/state.mjs +2 -0
- package/dist/fortnox/state.mjs.map +1 -1
- package/package.json +5 -5
- package/src/fortnox/api.ts +1 -1
- package/src/fortnox/state.ts +2 -0
package/dist/fortnox/api.mjs
CHANGED
package/dist/fortnox/api.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.mjs","names":[],"sources":["../../src/fortnox/api.ts"],"sourcesContent":["/**\n * Fortnox emulator API: the route table (with its evidence) and the stateful route handlers\n * registered on the `@emulators/core` app (internal; re-exported by `src/fortnox.ts`).\n *\n * Wire shapes follow the synthetic Fortnox conformance fixtures, copied as data. Each route lists\n * the conformance cases whose claims it follows; the observed quirks are implemented here.\n *\n * @experimental\n */\nimport type { Hono } from '@emulators/core'\nimport { Predicate, Result } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { answeredOutsideCore, emulatorJobHeader, handlerFailedResponse } from '../emulator-http.ts'\nimport { fortnoxReadRoutes } from './read-api.ts'\nimport {\n connectorRoute,\n contains,\n dateRange,\n errorInformation,\n fortnoxEmulatorErrorCodes,\n invalidField,\n isIsoDate,\n isJsonObject,\n matchesSearch,\n paginate,\n pdfResponse,\n resourceUrl,\n today,\n unsupportedQuery,\n jsonResponse,\n type FortnoxApiEnv,\n type FortnoxApiRoute,\n type FortnoxEmulatorQuirks,\n type RouteHandler,\n type SearchTable\n} from './route-kit.ts'\nimport {\n buildRow,\n compareNumbers,\n defaultEmailInformation,\n formatQuantity,\n fortnoxEmulatorCountries,\n fortnoxEmulatorVatCodes,\n invoiceFromSeed,\n invoiceTotals,\n newRowDefaults,\n type FortnoxEmulatorCustomer,\n type FortnoxEmulatorInvoice,\n type FortnoxEmulatorInvoiceRow,\n type FortnoxEmulatorInvoiceRowSeed,\n type FortnoxEmulatorInvoiceSeed,\n type FortnoxEmulatorState\n} from './state.ts'\n\nexport {\n errorInformation,\n fortnoxEmulatorBasePath,\n fortnoxEmulatorErrorCodes,\n type FortnoxApiEnv,\n type FortnoxEmulatorQuirks\n} from './route-kit.ts'\n\nconst codes = fortnoxEmulatorErrorCodes\n\n// Messages copied from the rejection fixture.\nconst customerNotFound = (): Response =>\n errorInformation(404, codes.customerNotFound, 'Synthetic placeholder: customer not found.')\n\nconst invoiceCustomerNotFound = (): Response =>\n errorInformation(400, codes.invoiceCustomerNotFound, 'Synthetic placeholder: customer not found.')\n\nconst invoiceNotFound = (): Response =>\n errorInformation(404, codes.invoiceNotFound, 'Synthetic: invoice not found.')\n\nconst invalidBody = (message: string): Response =>\n errorInformation(400, codes.invalidBody, `Synthetic: ${message}`)\n\nconst noReferencedEntity = (kind: string, value: string): Response =>\n invalidField(`${kind} ${value} does not exist in the emulated company.`)\n\n/**\n * Customer and invoice writes do not emulate references to articles, cost centers, or projects\n * (Fortnox would derive row and booking values from them); the read-only article and cost center\n * routes do not change that.\n */\nconst unsupportedReference = (kind: string, value: string): Response =>\n invalidField(`${kind} ${value}: references on customer and invoice writes are not emulated.`)\n\nconst readOnlyField = (message: string): Response =>\n errorInformation(400, codes.readOnlyField, `Synthetic: ${message}`)\n\nconst notEditable = (message: string): Response =>\n errorInformation(400, codes.notEditable, `Synthetic: ${message}`)\n\n/** `date` plus `days`, or `undefined` when the result is not a representable `YYYY-MM-DD` date. */\nconst addDays = (date: string, days: number): string | undefined => {\n const result = new Date(Date.parse(`${date}T00:00:00.000Z`) + days * 24 * 60 * 60 * 1000)\n\n if (Number.isNaN(result.getTime())) return undefined\n\n const iso = result.toISOString().slice(0, 10)\n\n return isIsoDate(iso) ? iso : undefined\n}\n\nconst maxTermsOfPaymentDays = 365\n\n/**\n * `TermsOfPayment` as a whole number of days (`0`–`365`, no sign or leading zeros), or\n * `undefined` when the value is not emulated. Fortnox also knows named terms (such as `K`); the\n * emulated company has day terms only.\n */\nconst termsOfPaymentDays = (value: string): number | undefined => {\n if (!/^(?:0|[1-9]\\d{0,2})$/.test(value)) return undefined\n\n const days = Number(value)\n\n return days <= maxTermsOfPaymentDays ? days : undefined\n}\n\nconst unsupportedTermsOfPayment = (value: string): Response =>\n invalidField(\n `TermsOfPayment ${value} is not emulated (whole days from 0 to ${maxTermsOfPaymentDays} only).`\n )\n\n/**\n * The customer categorical values the emulator deliberately models. This is the emulated subset,\n * not Fortnox's full enum: other values (for example export or EU reverse-charge VAT) would change\n * invoice VAT, which the emulator does not model, so they are rejected.\n */\nconst emulatedCustomerVatTypes: ReadonlyArray<string> = ['SEVAT']\n\nconst emulatedCustomerTypes: ReadonlyArray<string> = ['COMPANY', 'PRIVATE']\n\nconst unsupportedVatType = (value: string): Response =>\n invalidField(\n `VATType ${value} is not emulated (supported: ${emulatedCustomerVatTypes.join(', ')}).`\n )\n\nconst customerUrl = (env: FortnoxApiEnv, customerNumber: string): string =>\n resourceUrl(env, 'customers', customerNumber)\n\nconst invoiceUrl = (env: FortnoxApiEnv, documentNumber: string): string =>\n resourceUrl(env, 'invoices', documentNumber)\n\nconst renderCustomer = (env: FortnoxApiEnv, customer: FortnoxEmulatorCustomer) => ({\n '@url': customerUrl(env, customer.CustomerNumber),\n ...customer\n})\n\n// No fixture records the customer list: rows carry the list-only `Phone` and a subset of fields.\nconst renderCustomerRow = (env: FortnoxApiEnv, customer: FortnoxEmulatorCustomer) => ({\n '@url': customerUrl(env, customer.CustomerNumber),\n Address1: customer.Address1,\n Address2: customer.Address2,\n City: customer.City,\n CustomerNumber: customer.CustomerNumber,\n Email: customer.Email,\n Name: customer.Name,\n OrganisationNumber: customer.OrganisationNumber,\n Phone: customer.Phone1,\n ZipCode: customer.ZipCode\n})\n\ntype EmailInformationFields = {\n -readonly [\n K in keyof FortnoxEmulatorInvoice['EmailInformation']\n ]: FortnoxEmulatorInvoice['EmailInformation'][K]\n}\n\n/**\n * A single-invoice read: JSON-number amounts. `dropEmptyCopies` leaves empty CC/BCC addresses out\n * of `EmailInformation`, as the email-send fixture response does.\n */\nconst renderInvoice = (\n env: FortnoxApiEnv,\n invoice: FortnoxEmulatorInvoice,\n dropEmptyCopies = false\n) => {\n const source = invoice.EmailInformation\n\n const email: Partial<EmailInformationFields> = {\n EmailAddressFrom: source.EmailAddressFrom,\n EmailAddressTo: source.EmailAddressTo\n }\n\n if (!dropEmptyCopies || source.EmailAddressCC !== '') {\n email.EmailAddressCC = source.EmailAddressCC\n }\n\n if (!dropEmptyCopies || source.EmailAddressBCC !== '') {\n email.EmailAddressBCC = source.EmailAddressBCC\n }\n\n email.EmailSubject = source.EmailSubject\n email.EmailBody = source.EmailBody\n\n return {\n '@url': invoiceUrl(env, invoice.DocumentNumber),\n ...invoice,\n EmailInformation: email\n }\n}\n\n/** An invoice list row, in the list fixture's shape: `CurrencyRate` is a numeric string. */\nconst renderInvoiceRow = (env: FortnoxApiEnv, invoice: FortnoxEmulatorInvoice) => ({\n '@url': invoiceUrl(env, invoice.DocumentNumber),\n Balance: invoice.Balance,\n Booked: invoice.Booked,\n Cancelled: invoice.Cancelled,\n CostCenter: invoice.CostCenter,\n Currency: invoice.Currency,\n CurrencyRate: String(invoice.CurrencyRate),\n CurrencyUnit: invoice.CurrencyUnit,\n CustomerName: invoice.CustomerName,\n CustomerNumber: invoice.CustomerNumber,\n DocumentNumber: invoice.DocumentNumber,\n DueDate: invoice.DueDate,\n ExternalInvoiceReference1: invoice.ExternalInvoiceReference1,\n ExternalInvoiceReference2: invoice.ExternalInvoiceReference2,\n FinalPayDate: invoice.FinalPayDate,\n InvoiceDate: invoice.InvoiceDate,\n InvoiceType: invoice.InvoiceType,\n NoxFinans: invoice.NoxFinans,\n OCR: invoice.OCR,\n VoucherNumber: invoice.VoucherNumber,\n VoucherSeries: invoice.VoucherSeries,\n VoucherYear: invoice.VoucherYear,\n WayOfDelivery: invoice.WayOfDelivery,\n TermsOfPayment: invoice.TermsOfPayment,\n Project: invoice.Project,\n Sent: invoice.Sent,\n Total: invoice.Total\n})\n\n/** The 400 for the first query key the route does not emulate, or `undefined`. */\nconst unsupportedQueryKey = (\n query: URLSearchParams,\n allowed: ReadonlyArray<string>\n): Response | undefined => {\n const key = [...query.keys()].find(candidate => !allowed.includes(candidate))\n\n return key === undefined ? undefined : unsupportedQuery(key)\n}\n\nconst customerSearch = {\n customernumber: (customer, value) => customer.CustomerNumber === value,\n name: (customer, value) => contains(customer.Name, value),\n organisationnumber: (customer, value) => contains(customer.OrganisationNumber, value),\n email: (customer, value) => contains(customer.Email, value),\n city: (customer, value) => contains(customer.City, value),\n phone: (customer, value) => contains(customer.Phone1, value) || contains(customer.Phone2, value)\n} satisfies SearchTable<FortnoxEmulatorCustomer>\n\nconst customerListQueryKeys: ReadonlyArray<string> = [\n 'page',\n 'limit',\n 'filter',\n ...Object.keys(customerSearch)\n]\n\nconst listCustomers: RouteHandler = (state, { query }, env) => {\n const filter = query.get('filter')\n\n if (filter !== null && filter !== 'active' && filter !== 'inactive') {\n return invalidField(`unknown customer filter ${filter}.`)\n }\n\n const matching = state.customers.filter(\n customer =>\n (filter === null || customer.Active === (filter === 'active')) &&\n matchesSearch(customer, query, customerSearch)\n )\n\n const page = paginate(matching, query)\n\n if (page instanceof Response) return page\n\n return jsonResponse(200, {\n Customers: page.items.map(customer => renderCustomerRow(env, customer)),\n MetaInformation: page.meta\n })\n}\n\nconst findCustomer = (state: FortnoxEmulatorState, customerNumber: string) =>\n state.customers.find(customer => customer.CustomerNumber === customerNumber)\n\nconst findInvoice = (state: FortnoxEmulatorState, documentNumber: string) =>\n state.invoices.find(invoice => invoice.DocumentNumber === documentNumber)\n\nconst getCustomer: RouteHandler = (state, { params }, env) => {\n const customer = findCustomer(state, params.CustomerNumber ?? '')\n\n return customer === undefined\n ? customerNotFound()\n : jsonResponse(200, { Customer: renderCustomer(env, customer) })\n}\n\n/** The single resource object of a `{ <envelope>: { ... } }` write body. */\nconst envelopeObject = (\n body: Schema.Json | undefined,\n envelope: string\n): Schema.JsonObject | Response => {\n const value = isJsonObject(body) ? body[envelope] : undefined\n\n return isJsonObject(body) &&\n Object.keys(body).every(key => key === envelope) &&\n isJsonObject(value)\n ? value\n : invalidBody(`the request body must be { \"${envelope}\": { ... } }.`)\n}\n\nconst writableCustomerStrings = [\n 'Name',\n 'OrganisationNumber',\n 'Email',\n 'Phone1',\n 'Phone2',\n 'Address1',\n 'Address2',\n 'City',\n 'ZipCode',\n 'CountryCode',\n 'Currency',\n 'VATNumber',\n 'VATType',\n 'TermsOfPayment',\n 'OurReference',\n 'YourReference',\n 'Comments',\n 'EmailInvoice',\n 'Type',\n 'CostCenter'\n] as const\n\ntype CustomerStringField = (typeof writableCustomerStrings)[number]\n\nconst isCustomerStringField = (key: string): key is CustomerStringField =>\n writableCustomerStrings.some(field => field === key)\n\ntype CustomerUpdates = {\n -readonly [K in keyof FortnoxEmulatorCustomer]?: FortnoxEmulatorCustomer[K]\n}\n\n/**\n * Why a customer field value is not emulated (fail closed), or `undefined`. The emulated company\n * has only SEK, terms of payment in whole days (0–365), `VATType` `SEVAT`, and `Type` `COMPANY` or\n * `PRIVATE`; cost center references are not emulated on writes.\n */\nconst unsupportedCustomerValue = (\n key: CustomerStringField,\n value: string\n): Response | undefined => {\n switch (key) {\n case 'Currency':\n return value === 'SEK' ? undefined : noReferencedEntity('Currency', value)\n case 'CostCenter':\n return value === '' ? undefined : unsupportedReference('CostCenter', value)\n case 'TermsOfPayment':\n return termsOfPaymentDays(value) === undefined ? unsupportedTermsOfPayment(value) : undefined\n case 'VATType':\n return emulatedCustomerVatTypes.includes(value) ? undefined : unsupportedVatType(value)\n case 'Type':\n return emulatedCustomerTypes.includes(value)\n ? undefined\n : invalidField(\n `Type ${value} is not emulated (supported: ${emulatedCustomerTypes.join(', ')}).`\n )\n default:\n return undefined\n }\n}\n\n/**\n * Quirk 2: an empty string keeps the stored value (unless the `emptyStringClears` drill knob is\n * set); omitted fields keep theirs. Quirk 5: `Country` is read-only. Unknown fields, wrong types,\n * and values the emulator does not support (non-SEK `Currency`, a `CostCenter`, `TermsOfPayment`\n * other than 0–365 days, `VATType` other than `SEVAT`, `Type` other than `COMPANY`/`PRIVATE`) are\n * rejected; the update is atomic.\n */\nconst customerUpdates = (\n fields: Schema.JsonObject,\n customer: FortnoxEmulatorCustomer,\n env: FortnoxApiEnv\n): CustomerUpdates | Response => {\n const updates: CustomerUpdates = {}\n\n for (const [key, value] of Object.entries(fields)) {\n if (key === 'Country') {\n return readOnlyField('Country is read-only; set CountryCode instead.')\n }\n\n if (key === 'CustomerNumber') {\n if (value !== customer.CustomerNumber) {\n return invalidField('CustomerNumber cannot be changed.')\n }\n\n continue\n }\n\n if (key === 'Active') {\n if (!Predicate.isBoolean(value)) return invalidField('Active must be a boolean.')\n\n updates.Active = value\n\n continue\n }\n\n if (!isCustomerStringField(key)) {\n return invalidField(`unknown customer field ${key}.`)\n }\n\n if (!Predicate.isString(value)) {\n return invalidField(`${key} must be a string.`)\n }\n\n if (value === '' && !env.quirks.emptyStringClears) {\n continue\n }\n\n const unsupported = unsupportedCustomerValue(key, value)\n\n if (unsupported !== undefined) return unsupported\n\n if (key === 'CountryCode' && value !== '') {\n const country = fortnoxEmulatorCountries.get(value)\n\n if (country === undefined) return invalidField(`unknown CountryCode ${value}.`)\n\n updates.Country = country\n }\n\n updates[key] = value\n }\n\n return updates\n}\n\nconst updateCustomer: RouteHandler = (state, { params, body }, env) => {\n const customer = findCustomer(state, params.CustomerNumber ?? '')\n\n if (customer === undefined) return customerNotFound()\n\n const fields = envelopeObject(body, 'Customer')\n\n if (fields instanceof Response) return fields\n\n const updates = customerUpdates(fields, customer, env)\n\n if (updates instanceof Response) return updates\n\n const updated: FortnoxEmulatorCustomer = { ...customer, ...updates }\n\n state.customers = state.customers.map(existing =>\n existing.CustomerNumber === updated.CustomerNumber ? updated : existing\n )\n\n return jsonResponse(200, { Customer: renderCustomer(env, updated) })\n}\n\ntype InvoiceFilter = 'cancelled' | 'fullypaid' | 'unpaid' | 'unpaidoverdue' | 'unbooked'\n\nconst invoiceFilters: ReadonlyArray<InvoiceFilter> = [\n 'cancelled',\n 'fullypaid',\n 'unpaid',\n 'unpaidoverdue',\n 'unbooked'\n]\n\nconst isInvoiceFilter = (value: string): value is InvoiceFilter =>\n invoiceFilters.some(filter => filter === value)\n\n/**\n * Quirk 3: the payment-status filters consider booked invoices only (unless the\n * `paymentFiltersIncludeUnbooked` drill knob is set); `unbooked` returns unbooked, uncancelled\n * invoices; `unpaidoverdue` needs a `DueDate` before today (UTC, from the emulator clock).\n */\nconst matchesInvoiceFilter = (\n invoice: FortnoxEmulatorInvoice,\n filter: InvoiceFilter,\n env: FortnoxApiEnv\n): boolean => {\n const considered =\n (invoice.Booked || env.quirks.paymentFiltersIncludeUnbooked) && !invoice.Cancelled\n\n switch (filter) {\n case 'cancelled':\n return invoice.Cancelled\n case 'unbooked':\n return !invoice.Booked && !invoice.Cancelled\n case 'unpaid':\n return considered && invoice.Balance > 0\n case 'unpaidoverdue':\n return (\n considered &&\n invoice.Balance > 0 &&\n invoice.DueDate !== null &&\n isIsoDate(invoice.DueDate) &&\n invoice.DueDate < today(env)\n )\n case 'fullypaid':\n return considered && invoice.Balance === 0\n }\n}\n\nconst invoiceSearch = {\n customernumber: (invoice, value) => invoice.CustomerNumber === value,\n customername: (invoice, value) => contains(invoice.CustomerName, value),\n documentnumber: (invoice, value) => invoice.DocumentNumber === value,\n ocr: (invoice, value) => invoice.OCR === value\n} satisfies SearchTable<FortnoxEmulatorInvoice>\n\nconst invoiceListQueryKeys: ReadonlyArray<string> = [\n 'page',\n 'limit',\n 'filter',\n 'fromdate',\n 'todate',\n ...Object.keys(invoiceSearch)\n]\n\nconst listInvoices: RouteHandler = (state, { query }, env) => {\n const filter = query.get('filter')\n\n if (filter !== null && !isInvoiceFilter(filter)) {\n return invalidField(`unknown invoice filter ${filter}.`)\n }\n\n const range = dateRange(query)\n\n if (range instanceof Response) return range\n\n const matching = state.invoices.filter(\n invoice =>\n (filter === null || matchesInvoiceFilter(invoice, filter, env)) &&\n (range.from === null || invoice.InvoiceDate >= range.from) &&\n (range.to === null || invoice.InvoiceDate <= range.to) &&\n matchesSearch(invoice, query, invoiceSearch)\n )\n\n const page = paginate(matching, query)\n\n if (page instanceof Response) return page\n\n return jsonResponse(200, {\n Invoices: page.items.map(invoice => renderInvoiceRow(env, invoice)),\n MetaInformation: page.meta\n })\n}\n\nconst getInvoice: RouteHandler = (state, { params }, env) => {\n const invoice = findInvoice(state, params.DocumentNumber ?? '')\n\n return invoice === undefined\n ? invoiceNotFound()\n : jsonResponse(200, { Invoice: renderInvoice(env, invoice) })\n}\n\ntype RowPatch = {\n -readonly [K in keyof FortnoxEmulatorInvoiceRowSeed]?: FortnoxEmulatorInvoiceRowSeed[K]\n}\n\nconst vatRates: ReadonlyArray<number> = [...fortnoxEmulatorVatCodes.keys()]\n\n/**\n * One row of an `InvoiceRows` write. `null` means omitted. References to articles, cost centers,\n * and projects are not emulated on writes; accounts must be in 1000-8999.\n */\nconst rowPatch = (value: Schema.Json, index: number): RowPatch | Response => {\n if (!isJsonObject(value)) {\n return invalidField(`InvoiceRows[${index}] must be an object.`)\n }\n\n const patch: RowPatch = {}\n const label = (key: string) => `InvoiceRows[${index}].${key}`\n\n for (const [key, field] of Object.entries(value)) {\n if (field === null) continue\n\n switch (key) {\n case 'RowId':\n if (!Predicate.isNumber(field) || !Number.isSafeInteger(field) || field < 1) {\n return invalidField(`${label(key)} must be a positive integer.`)\n }\n\n patch.RowId = field\n break\n case 'AccountNumber':\n if (\n !Predicate.isNumber(field) ||\n !Number.isInteger(field) ||\n field < 1000 ||\n field > 8999\n ) {\n return invalidField(`${label(key)} must be an account number from 1000 to 8999.`)\n }\n\n patch.AccountNumber = field\n break\n case 'ArticleNumber':\n case 'CostCenter':\n case 'Project':\n if (!Predicate.isString(field)) return invalidField(`${label(key)} must be a string.`)\n\n if (field !== '') return unsupportedReference(key, field)\n\n patch[key] = field\n break\n case 'Description':\n case 'Unit':\n if (!Predicate.isString(field)) return invalidField(`${label(key)} must be a string.`)\n\n patch[key] = field\n break\n case 'DeliveredQuantity': {\n const quantity = Predicate.isString(field) ? Number(field.trim()) : field\n\n if (\n !Predicate.isNumber(quantity) ||\n !Number.isFinite(quantity) ||\n quantity < 0 ||\n (Predicate.isString(field) && field.trim() === '')\n ) {\n return invalidField(`${label(key)} must be a non-negative number.`)\n }\n\n patch.DeliveredQuantity = formatQuantity(quantity)\n break\n }\n\n case 'Price':\n if (!Predicate.isNumber(field) || !Number.isFinite(field)) {\n return invalidField(`${label(key)} must be a finite number.`)\n }\n\n patch.Price = field\n break\n case 'Discount':\n if (!Predicate.isNumber(field) || !Number.isFinite(field) || field < 0) {\n return invalidField(`${label(key)} must be a non-negative number.`)\n }\n\n patch.Discount = field\n break\n case 'DiscountType':\n if (field !== 'PERCENT' && field !== 'AMOUNT') {\n return invalidField(`${label(key)} must be PERCENT or AMOUNT.`)\n }\n\n patch.DiscountType = field\n break\n case 'VAT':\n if (!Predicate.isNumber(field) || !vatRates.includes(field)) {\n return invalidField(`${label(key)} must be one of ${vatRates.join(', ')}.`)\n }\n\n patch.VAT = field\n break\n default:\n return invalidField(`${label(key)} is not a writable invoice row field.`)\n }\n }\n\n return patch\n}\n\nconst rowPatches = (value: Schema.Json): ReadonlyArray<RowPatch> | Response => {\n if (!Array.isArray(value)) {\n return invalidField('InvoiceRows must be an array.')\n }\n\n const patches: Array<RowPatch> = []\n\n for (const [index, row] of value.entries()) {\n const patch = rowPatch(row, index)\n\n if (patch instanceof Response) return patch\n\n patches.push(patch)\n }\n\n return patches\n}\n\ntype RowIds = { next: number }\n\n/**\n * Quirk 1: `InvoiceRows` replaces the row list. Without any `RowId`, rows match existing rows by\n * position; with a `RowId`, that row is updated and rows without one are added. A matched row\n * keeps every omitted field, including `Discount`/`DiscountType` (unless the `stickyRowDiscount`\n * drill knob is off, which resets them); `Discount: 0` clears. RowIds are regenerated for every\n * row, and totals follow from the fields.\n */\nconst mergeRows = (\n existing: ReadonlyArray<FortnoxEmulatorInvoiceRow>,\n patches: ReadonlyArray<RowPatch>,\n ids: RowIds,\n env: FortnoxApiEnv\n): ReadonlyArray<FortnoxEmulatorInvoiceRow> | Response => {\n const byRowId = patches.some(patch => patch.RowId !== undefined)\n const rows: Array<FortnoxEmulatorInvoiceRow> = []\n\n for (const [index, patch] of patches.entries()) {\n const base = byRowId\n ? existing.find(row => patch.RowId !== undefined && row.RowId === patch.RowId)\n : existing[index]\n\n if (byRowId && patch.RowId !== undefined && base === undefined) {\n return invalidField(`InvoiceRows[${index}].RowId ${patch.RowId} does not exist.`)\n }\n\n const start = { ...newRowDefaults, ...base }\n\n // Drill knob only: forget the matched row's discount instead of keeping it.\n if (base !== undefined && !env.quirks.stickyRowDiscount) {\n start.Discount = 0\n start.DiscountType = 'PERCENT'\n }\n\n rows.push(buildRow({ ...start, ...patch, RowId: ids.next++ }))\n }\n\n return rows\n}\n\nconst invoiceTextFields = ['Comments', 'OurReference', 'YourReference', 'OCR'] as const\n\ntype InvoiceTextField = (typeof invoiceTextFields)[number]\n\nconst isInvoiceTextField = (key: string): key is InvoiceTextField =>\n invoiceTextFields.some(field => field === key)\n\nconst invoiceReadOnlyFields: ReadonlyArray<string> = [\n 'Balance',\n 'Booked',\n 'Cancelled',\n 'CustomerName',\n 'FinalPayDate',\n 'Gross',\n 'Net',\n 'Sent',\n 'Total',\n 'TotalToPay',\n 'TotalVAT',\n 'VoucherNumber',\n 'VoucherSeries',\n 'VoucherYear'\n]\n\ntype InvoiceScalars = {\n CustomerNumber?: string\n Currency?: string\n InvoiceDate?: string\n DueDate?: string\n CostCenter?: string\n Project?: string\n} & { -readonly [K in InvoiceTextField]?: string }\n\ntype InvoiceUpdates = {\n readonly scalars: InvoiceScalars\n readonly customer: FortnoxEmulatorCustomer | undefined\n readonly rows: ReadonlyArray<RowPatch> | undefined\n}\n\n/**\n * The writable invoice fields of a create or update body (the connector's invoice mutation\n * fields). Quirk 4: an unknown `CustomerNumber` is rejected with the rejection fixture's 400\n * `ErrorInformation`; other invalid or read-only fields are rejected with 400 too.\n */\nconst invoiceUpdates = (\n fields: Schema.JsonObject,\n state: FortnoxEmulatorState,\n existing: FortnoxEmulatorInvoice | undefined\n): InvoiceUpdates | Response => {\n const scalars: InvoiceScalars = {}\n let customer: FortnoxEmulatorCustomer | undefined\n let rows: ReadonlyArray<RowPatch> | undefined\n\n for (const [key, value] of Object.entries(fields)) {\n if (key === 'DocumentNumber') {\n if (existing === undefined || value !== existing.DocumentNumber) {\n return readOnlyField('DocumentNumber is assigned by Fortnox and cannot be changed.')\n }\n\n continue\n }\n\n if (key === 'InvoiceRows') {\n const patches = rowPatches(value)\n\n if (patches instanceof Response) return patches\n\n if (existing === undefined && patches.some(patch => patch.RowId !== undefined)) {\n return readOnlyField('RowId is assigned by Fortnox.')\n }\n\n rows = patches\n\n continue\n }\n\n if (invoiceReadOnlyFields.includes(key)) {\n return readOnlyField(`${key} is read-only.`)\n }\n\n if (!Predicate.isString(value)) {\n return invalidField(\n key === 'CustomerNumber' || key === 'Currency' || isInvoiceTextField(key)\n ? `${key} must be a string.`\n : `unknown or unsupported invoice field ${key}.`\n )\n }\n\n switch (key) {\n case 'CustomerNumber':\n customer = findCustomer(state, value)\n\n if (customer === undefined) return invoiceCustomerNotFound()\n\n scalars.CustomerNumber = value\n break\n case 'Currency':\n if (value !== 'SEK') return noReferencedEntity('Currency', value)\n\n scalars.Currency = value\n break\n case 'InvoiceDate':\n case 'DueDate':\n if (!isIsoDate(value)) return invalidField(`${key} must be a YYYY-MM-DD date.`)\n\n scalars[key] = value\n break\n case 'CostCenter':\n case 'Project':\n if (value !== '') return unsupportedReference(key, value)\n\n scalars[key] = value\n break\n default:\n if (!isInvoiceTextField(key)) {\n return invalidField(`unknown or unsupported invoice field ${key}.`)\n }\n\n scalars[key] = value\n }\n }\n\n return { scalars, customer, rows }\n}\n\nconst replaceInvoice = (state: FortnoxEmulatorState, updated: FortnoxEmulatorInvoice): void => {\n state.invoices = state.invoices.map(invoice =>\n invoice.DocumentNumber === updated.DocumentNumber ? updated : invoice\n )\n}\n\nconst updateInvoice: RouteHandler = (state, { params, body }, env) => {\n const invoice = findInvoice(state, params.DocumentNumber ?? '')\n\n if (invoice === undefined) return invoiceNotFound()\n\n const fields = envelopeObject(body, 'Invoice')\n\n if (fields instanceof Response) return fields\n\n if (invoice.Booked) return notEditable('a booked invoice cannot be updated.')\n\n if (invoice.Cancelled) return notEditable('a cancelled invoice cannot be updated.')\n\n const updates = invoiceUpdates(fields, state, invoice)\n\n if (updates instanceof Response) return updates\n\n let updated: FortnoxEmulatorInvoice = {\n ...invoice,\n ...updates.scalars,\n CustomerName: updates.customer?.Name ?? invoice.CustomerName\n }\n\n if (updates.rows !== undefined) {\n const ids: RowIds = { next: state.counters.nextRowId }\n const rows = mergeRows(invoice.InvoiceRows, updates.rows, ids, env)\n\n if (rows instanceof Response) return rows\n\n const totals = invoiceTotals(rows)\n\n updated = { ...updated, InvoiceRows: rows, ...totals, Balance: totals.Total }\n state.counters = { ...state.counters, nextRowId: ids.next }\n }\n\n replaceInvoice(state, updated)\n\n return jsonResponse(200, { Invoice: renderInvoice(env, updated) })\n}\n\nconst createInvoice: RouteHandler = (state, { body }, env) => {\n const fields = envelopeObject(body, 'Invoice')\n\n if (fields instanceof Response) return fields\n\n const updates = invoiceUpdates(fields, state, undefined)\n\n if (updates instanceof Response) return updates\n\n const { customer } = updates\n\n if (customer === undefined) return invalidField('CustomerNumber is required.')\n\n // The invoice inherits the customer's currency when it names none; check the effective value\n // (a seeded customer can carry any currency) before anything is committed.\n const currency = updates.scalars.Currency ?? customer.Currency\n\n if (currency !== 'SEK') return noReferencedEntity('Currency', currency)\n\n // Likewise the inherited VAT type (invoice VAT comes from the rows only) and payment terms,\n // which the invoice records and derives its due date from.\n if (!emulatedCustomerVatTypes.includes(customer.VATType)) {\n return unsupportedVatType(customer.VATType)\n }\n\n const terms = termsOfPaymentDays(customer.TermsOfPayment)\n\n if (terms === undefined) return unsupportedTermsOfPayment(customer.TermsOfPayment)\n\n const invoiceDate = updates.scalars.InvoiceDate ?? today(env)\n const dueDate = updates.scalars.DueDate ?? addDays(invoiceDate, terms)\n\n if (dueDate === undefined) {\n return invalidField(\n `the due date ${invoiceDate} + ${terms} days is not a representable YYYY-MM-DD date.`\n )\n }\n\n const ids: RowIds = { next: state.counters.nextRowId }\n\n const seed: FortnoxEmulatorInvoiceSeed = {\n ...updates.scalars,\n DocumentNumber: String(state.counters.nextDocumentNumber),\n CustomerNumber: customer.CustomerNumber,\n InvoiceDate: invoiceDate,\n DueDate: dueDate,\n EmailInformation: defaultEmailInformation(customer, state.company),\n InvoiceRows: updates.rows ?? []\n }\n\n const invoice = invoiceFromSeed(seed, customer, state.company, ids)\n\n state.invoices = [...state.invoices, invoice].sort((left, right) =>\n compareNumbers(left.DocumentNumber, right.DocumentNumber)\n )\n state.counters = {\n nextRowId: ids.next,\n nextDocumentNumber: state.counters.nextDocumentNumber + 1\n }\n\n return jsonResponse(201, { Invoice: renderInvoice(env, invoice) })\n}\n\nconst previewInvoice: RouteHandler = (state, { params }) =>\n findInvoice(state, params.DocumentNumber ?? '') === undefined ? invoiceNotFound() : pdfResponse()\n\n/** Marks the invoice `Sent` and records an outbox entry. Nothing is ever delivered. */\nconst emailInvoice: RouteHandler = (state, { params }, env) => {\n const invoice = findInvoice(state, params.DocumentNumber ?? '')\n\n if (invoice === undefined) return invoiceNotFound()\n\n if (invoice.Cancelled) return notEditable('a cancelled invoice cannot be sent.')\n\n const email = invoice.EmailInformation\n\n if (email.EmailAddressTo.trim() === '') {\n return invalidField('the invoice has no EmailInformation.EmailAddressTo.')\n }\n\n const updated: FortnoxEmulatorInvoice = { ...invoice, Sent: true }\n\n replaceInvoice(state, updated)\n state.outbox = [\n ...state.outbox,\n {\n DocumentNumber: invoice.DocumentNumber,\n EmailAddressTo: email.EmailAddressTo,\n EmailAddressCC: email.EmailAddressCC,\n EmailAddressBCC: email.EmailAddressBCC,\n EmailSubject: email.EmailSubject.replaceAll('{no}', invoice.DocumentNumber),\n sentAt: new Date(env.now()).toISOString()\n }\n ]\n\n return jsonResponse(200, { Invoice: renderInvoice(env, updated, true) })\n}\n\nconst companyInformation: RouteHandler = state =>\n jsonResponse(200, { CompanyInformation: state.company })\n\nconst listCase = 'fortnox.invoice.list-populated'\n\nconst previewCase = 'fortnox.invoice.preview-pdf'\n\nconst filtersCase = 'fortnox.invoice.payment-filters-exclude-unbooked'\n\nconst discountCase = 'fortnox.invoice.row-discount-sticky'\n\nconst emptyStringCase = 'fortnox.customer.empty-string-keeps-value'\n\nconst rejectionCase = 'fortnox.write.rejection-error-information'\n\nconst emailCase = 'fortnox.invoice.send-email'\n\n/** The route table: evidence plus handler. `fortnoxEmulatorRoutes` is its evidence part. */\nexport const fortnoxApiRoutes: ReadonlyArray<FortnoxApiRoute> = [\n connectorRoute('GET', '/companyinformation', false, [], companyInformation),\n connectorRoute('GET', '/customers', false, [], listCustomers, customerListQueryKeys),\n connectorRoute(\n 'GET',\n '/customers/{CustomerNumber}',\n false,\n [emptyStringCase, rejectionCase],\n getCustomer\n ),\n connectorRoute('PUT', '/customers/{CustomerNumber}', true, [emptyStringCase], updateCustomer),\n connectorRoute(\n 'GET',\n '/invoices',\n false,\n [listCase, filtersCase],\n listInvoices,\n invoiceListQueryKeys\n ),\n connectorRoute('POST', '/invoices', true, [rejectionCase], createInvoice),\n connectorRoute('GET', '/invoices/{DocumentNumber}', false, [discountCase, emailCase], getInvoice),\n connectorRoute('PUT', '/invoices/{DocumentNumber}', true, [discountCase], updateInvoice),\n connectorRoute('GET', '/invoices/{DocumentNumber}/preview', false, [previewCase], previewInvoice),\n connectorRoute('GET', '/invoices/{DocumentNumber}/email', true, [emailCase], emailInvoice),\n ...fortnoxReadRoutes\n]\n\n/** One observed Fortnox quirk the emulator implements, and the case that claims it. */\nexport type FortnoxEmulatorQuirk = {\n readonly id: string\n /** `METHOD path` of the route that implements it. */\n readonly route: string\n /** The conformance case whose claim it follows; `undefined` when no case covers it yet. */\n readonly caseId: string | undefined\n /** The drill knob that flips it, if any. */\n readonly knob: keyof FortnoxEmulatorQuirks | undefined\n readonly summary: string\n}\n\n/** The observed quirks, each tied to its conformance case id. */\nexport const fortnoxEmulatorQuirks: ReadonlyArray<FortnoxEmulatorQuirk> = [\n {\n id: 'row-discount-sticky',\n route: 'PUT /3/invoices/{DocumentNumber}',\n caseId: discountCase,\n knob: 'stickyRowDiscount',\n summary:\n 'InvoiceRows replaces the rows; rows without RowId match by position; an omitted Discount/DiscountType keeps its value; Discount 0 clears; RowIds regenerate; totals are recomputed.'\n },\n {\n id: 'empty-string-keeps-value',\n route: 'PUT /3/customers/{CustomerNumber}',\n caseId: emptyStringCase,\n knob: 'emptyStringClears',\n summary: 'A customer update with \"\" for a string field keeps the stored value.'\n },\n {\n id: 'payment-filters-exclude-unbooked',\n route: 'GET /3/invoices',\n caseId: filtersCase,\n knob: 'paymentFiltersIncludeUnbooked',\n summary:\n 'unpaid, unpaidoverdue, and fullypaid consider booked invoices only; unbooked lists unbooked, uncancelled invoices; unpaidoverdue needs DueDate before today.'\n },\n {\n id: 'rejection-error-information',\n route: 'POST /3/invoices',\n caseId: rejectionCase,\n knob: undefined,\n summary:\n 'Writes for an unknown customer, or with invalid fields, answer 400 with a lowercase ErrorInformation { error, message, code }.'\n },\n {\n id: 'customer-country-read-only',\n route: 'PUT /3/customers/{CustomerNumber}',\n caseId: undefined,\n knob: undefined,\n summary:\n 'Customer Country is read-only (derived from CountryCode); sending it answers 400 ErrorInformation. No conformance case covers it yet.'\n }\n]\n\nconst templatePattern = (template: string): RegExp =>\n new RegExp(\n `^${template\n .split(/(\\{[A-Za-z]+\\})/)\n .map(part =>\n /^\\{[A-Za-z]+\\}$/.test(part) ? '([^/]+)' : part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n )\n .join('')}$`\n )\n\nconst compiledRoutes = fortnoxApiRoutes.map(route => ({\n route,\n pattern: templatePattern(route.path)\n}))\n\n/** The route answering `method` + concrete `path`, or `undefined` (fail closed). */\nexport const matchFortnoxRoute = (method: string, path: string): FortnoxApiRoute | undefined =>\n compiledRoutes.find(\n candidate => candidate.route.method === method.toUpperCase() && candidate.pattern.test(path)\n )?.route\n\nconst decodeJsonText = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Json))\n\n/** Parsed JSON, or `undefined` for invalid JSON. */\nexport const parseJsonText = (text: string): Schema.Json | undefined => {\n const result = decodeJsonText(text)\n\n return Result.isSuccess(result) ? result.success : undefined\n}\n\n/** `{Name}` path templates become `:Name` core route parameters. */\nconst corePath = (template: string): string => template.replace(/\\{([A-Za-z]+)\\}/g, ':$1')\n\n/**\n * The wrapper's fault decision for the core request of job `jobId` (its `emulatorJobHeader`),\n * asked only once the route would answer successfully: `true` when a fault answers instead (it is\n * used up, and the wrapper sends its answer), `false` when none applies.\n */\nexport type FortnoxFaultDecision = (jobId: string | undefined) => boolean\n\n/**\n * Register every route of the table on the core app, over the generation's state. Each request is\n * planned, then faulted, then committed: the handler runs on a draft of the state (handlers replace\n * whole lists and counters, never edit them in place, so a shallow copy keeps every write off the\n * state); a refusal (any answer that is not 2xx) is sent as is and uses up no fault; a successful\n * answer asks `decideFault`, and only an unfaulted one commits the draft. The three steps run\n * synchronously together, so no other request interleaves. A handler that throws answers\n * `handlerFailedResponse()` (nothing written), which the wrapper turns into its `ErrorInformation`\n * 500 with `responseError` in the ledger.\n */\nexport const registerFortnoxApi = (\n app: Hono,\n state: FortnoxEmulatorState,\n env: FortnoxApiEnv,\n decideFault: FortnoxFaultDecision\n): void => {\n for (const route of fortnoxApiRoutes) {\n app.on(route.method, corePath(route.path), async context => {\n try {\n const query = new URL(context.req.url).searchParams\n\n // Fail closed on query parameters the route does not emulate, before the handler can write.\n const unsupported = unsupportedQueryKey(query, route.queryKeys)\n\n if (unsupported !== undefined) return unsupported\n\n const text = await context.req.text()\n const draft: FortnoxEmulatorState = { ...state }\n\n const response = route.handler(\n draft,\n {\n params: context.req.param(),\n query,\n body: text === '' ? undefined : parseJsonText(text)\n },\n env\n )\n\n if (!response.ok) return response\n\n if (decideFault(context.req.header(emulatorJobHeader))) return answeredOutsideCore()\n\n Object.assign(state, draft)\n\n return response\n } catch {\n return handlerFailedResponse()\n }\n })\n }\n}\n"],"mappings":";;;;;;;;AA8DA,MAAM,QAAQ;AAGd,MAAM,yBACJ,iBAAiB,KAAK,MAAM,kBAAkB,4CAA4C;AAE5F,MAAM,gCACJ,iBAAiB,KAAK,MAAM,yBAAyB,4CAA4C;AAEnG,MAAM,wBACJ,iBAAiB,KAAK,MAAM,iBAAiB,+BAA+B;AAE9E,MAAM,eAAe,YACnB,iBAAiB,KAAK,MAAM,aAAa,cAAc,SAAS;AAElE,MAAM,sBAAsB,MAAc,UACxC,aAAa,GAAG,KAAK,GAAG,MAAM,yCAAyC;;;;;;AAOzE,MAAM,wBAAwB,MAAc,UAC1C,aAAa,GAAG,KAAK,GAAG,MAAM,8DAA8D;AAE9F,MAAM,iBAAiB,YACrB,iBAAiB,KAAK,MAAM,eAAe,cAAc,SAAS;AAEpE,MAAM,eAAe,YACnB,iBAAiB,KAAK,MAAM,aAAa,cAAc,SAAS;;AAGlE,MAAM,WAAW,MAAc,SAAqC;CAClE,MAAM,SAAS,IAAI,KAAK,KAAK,MAAM,GAAG,KAAK,eAAe,IAAI,OAAO,KAAK,KAAK,KAAK,GAAI;CAExF,IAAI,OAAO,MAAM,OAAO,QAAQ,CAAC,GAAG,OAAO,KAAA;CAE3C,MAAM,MAAM,OAAO,YAAY,CAAC,CAAC,MAAM,GAAG,EAAE;CAE5C,OAAO,UAAU,GAAG,IAAI,MAAM,KAAA;AAChC;AAEA,MAAM,wBAAwB;;;;;;AAO9B,MAAM,sBAAsB,UAAsC;CAChE,IAAI,CAAC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AAI,OAAO;GAEzB,IAAI,YAAY,QAAQ,IAAI,OAAA,mBAAwB,CAAC,GAAG,OAAO,oBAAoB;GAEnF,OAAO,OAAO,OAAO,KAAK;GAE1B,OAAO;EACT,QAAQ;GACN,OAAO,sBAAsB;EAC/B;CACF,CAAC;AAEL"}
|
|
1
|
+
{"version":3,"file":"api.mjs","names":[],"sources":["../../src/fortnox/api.ts"],"sourcesContent":["/**\n * Fortnox emulator API: the route table (with its evidence) and the stateful route handlers\n * registered on the `@emulators/core` app (internal; re-exported by `src/fortnox.ts`).\n *\n * Wire shapes follow the synthetic Fortnox conformance fixtures, copied as data. Each route lists\n * the conformance cases whose claims it follows; the observed quirks are implemented here.\n *\n * @experimental\n */\nimport type { Hono } from '@emulators/core'\nimport { Predicate, Result } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport { answeredOutsideCore, emulatorJobHeader, handlerFailedResponse } from '../emulator-http.ts'\nimport { fortnoxReadRoutes } from './read-api.ts'\nimport {\n connectorRoute,\n contains,\n dateRange,\n errorInformation,\n fortnoxEmulatorErrorCodes,\n invalidField,\n isIsoDate,\n isJsonObject,\n matchesSearch,\n paginate,\n pdfResponse,\n resourceUrl,\n today,\n unsupportedQuery,\n jsonResponse,\n type FortnoxApiEnv,\n type FortnoxApiRoute,\n type FortnoxEmulatorQuirks,\n type RouteHandler,\n type SearchTable\n} from './route-kit.ts'\nimport {\n buildRow,\n compareNumbers,\n defaultEmailInformation,\n formatQuantity,\n fortnoxEmulatorCountries,\n fortnoxEmulatorVatCodes,\n invoiceFromSeed,\n invoiceTotals,\n newRowDefaults,\n type FortnoxEmulatorCustomer,\n type FortnoxEmulatorInvoice,\n type FortnoxEmulatorInvoiceRow,\n type FortnoxEmulatorInvoiceRowSeed,\n type FortnoxEmulatorInvoiceSeed,\n type FortnoxEmulatorState\n} from './state.ts'\n\nexport {\n errorInformation,\n fortnoxEmulatorBasePath,\n fortnoxEmulatorErrorCodes,\n type FortnoxApiEnv,\n type FortnoxEmulatorQuirks\n} from './route-kit.ts'\n\nconst codes = fortnoxEmulatorErrorCodes\n\n// Messages copied from the rejection fixture.\nconst customerNotFound = (): Response =>\n errorInformation(404, codes.customerNotFound, 'Synthetic placeholder: customer not found.')\n\nconst invoiceCustomerNotFound = (): Response =>\n errorInformation(400, codes.invoiceCustomerNotFound, 'Synthetic placeholder: customer not found.')\n\nconst invoiceNotFound = (): Response =>\n errorInformation(404, codes.invoiceNotFound, 'Synthetic: invoice not found.')\n\nconst invalidBody = (message: string): Response =>\n errorInformation(400, codes.invalidBody, `Synthetic: ${message}`)\n\nconst noReferencedEntity = (kind: string, value: string): Response =>\n invalidField(`${kind} ${value} does not exist in the emulated company.`)\n\n/**\n * Customer and invoice writes do not emulate references to articles, cost centers, or projects\n * (Fortnox would derive row and booking values from them); the read-only article and cost center\n * routes do not change that.\n */\nconst unsupportedReference = (kind: string, value: string): Response =>\n invalidField(`${kind} ${value}: references on customer and invoice writes are not emulated.`)\n\nconst readOnlyField = (message: string): Response =>\n errorInformation(400, codes.readOnlyField, `Synthetic: ${message}`)\n\nconst notEditable = (message: string): Response =>\n errorInformation(400, codes.notEditable, `Synthetic: ${message}`)\n\n/** `date` plus `days`, or `undefined` when the result is not a representable `YYYY-MM-DD` date. */\nconst addDays = (date: string, days: number): string | undefined => {\n const result = new Date(Date.parse(`${date}T00:00:00.000Z`) + days * 24 * 60 * 60 * 1000)\n\n if (Number.isNaN(result.getTime())) return undefined\n\n const iso = result.toISOString().slice(0, 10)\n\n return isIsoDate(iso) ? iso : undefined\n}\n\nconst maxTermsOfPaymentDays = 365\n\n/**\n * `TermsOfPayment` as a whole number of days (`0`–`365`, no sign or leading zeros), or\n * `undefined` when the value is not emulated. Fortnox also knows named terms (such as `K`); the\n * emulated company has day terms only.\n */\nconst termsOfPaymentDays = (value: string): number | undefined => {\n if (!/^(?:0|[1-9]\\d{0,2})$/.test(value)) return undefined\n\n const days = Number(value)\n\n return days <= maxTermsOfPaymentDays ? days : undefined\n}\n\nconst unsupportedTermsOfPayment = (value: string): Response =>\n invalidField(\n `TermsOfPayment ${value} is not emulated (whole days from 0 to ${maxTermsOfPaymentDays} only).`\n )\n\n/**\n * The customer categorical values the emulator deliberately models. This is the emulated subset,\n * not Fortnox's full enum: other values (for example export or EU reverse-charge VAT) would change\n * invoice VAT, which the emulator does not model, so they are rejected.\n */\nconst emulatedCustomerVatTypes: ReadonlyArray<string> = ['SEVAT']\n\nconst emulatedCustomerTypes: ReadonlyArray<string> = ['COMPANY', 'PRIVATE']\n\nconst unsupportedVatType = (value: string): Response =>\n invalidField(\n `VATType ${value} is not emulated (supported: ${emulatedCustomerVatTypes.join(', ')}).`\n )\n\nconst customerUrl = (env: FortnoxApiEnv, customerNumber: string): string =>\n resourceUrl(env, 'customers', customerNumber)\n\nconst invoiceUrl = (env: FortnoxApiEnv, documentNumber: string): string =>\n resourceUrl(env, 'invoices', documentNumber)\n\nconst renderCustomer = (env: FortnoxApiEnv, customer: FortnoxEmulatorCustomer) => ({\n '@url': customerUrl(env, customer.CustomerNumber),\n ...customer\n})\n\n// No fixture records the customer list: rows carry the list-only `Phone` and a subset of fields.\nconst renderCustomerRow = (env: FortnoxApiEnv, customer: FortnoxEmulatorCustomer) => ({\n '@url': customerUrl(env, customer.CustomerNumber),\n Address1: customer.Address1,\n Address2: customer.Address2,\n City: customer.City,\n CustomerNumber: customer.CustomerNumber,\n Email: customer.Email,\n Name: customer.Name,\n OrganisationNumber: customer.OrganisationNumber,\n Phone: customer.Phone1,\n ZipCode: customer.ZipCode\n})\n\ntype EmailInformationFields = {\n -readonly [\n K in keyof FortnoxEmulatorInvoice['EmailInformation']\n ]: FortnoxEmulatorInvoice['EmailInformation'][K]\n}\n\n/**\n * A single-invoice read: JSON-number amounts. `dropEmptyCopies` leaves empty CC/BCC addresses out\n * of `EmailInformation`, as the email-send fixture response does.\n */\nconst renderInvoice = (\n env: FortnoxApiEnv,\n invoice: FortnoxEmulatorInvoice,\n dropEmptyCopies = false\n) => {\n const source = invoice.EmailInformation\n\n const email: Partial<EmailInformationFields> = {\n EmailAddressFrom: source.EmailAddressFrom,\n EmailAddressTo: source.EmailAddressTo\n }\n\n if (!dropEmptyCopies || source.EmailAddressCC !== '') {\n email.EmailAddressCC = source.EmailAddressCC\n }\n\n if (!dropEmptyCopies || source.EmailAddressBCC !== '') {\n email.EmailAddressBCC = source.EmailAddressBCC\n }\n\n email.EmailSubject = source.EmailSubject\n email.EmailBody = source.EmailBody\n\n return {\n '@url': invoiceUrl(env, invoice.DocumentNumber),\n ...invoice,\n EmailInformation: email\n }\n}\n\n/** An invoice list row, in the list fixture's shape: `CurrencyRate` is a numeric string. */\nconst renderInvoiceRow = (env: FortnoxApiEnv, invoice: FortnoxEmulatorInvoice) => ({\n '@url': invoiceUrl(env, invoice.DocumentNumber),\n Balance: invoice.Balance,\n Booked: invoice.Booked,\n Cancelled: invoice.Cancelled,\n CostCenter: invoice.CostCenter,\n Currency: invoice.Currency,\n CurrencyRate: String(invoice.CurrencyRate),\n CurrencyUnit: invoice.CurrencyUnit,\n CustomerName: invoice.CustomerName,\n CustomerNumber: invoice.CustomerNumber,\n DocumentNumber: invoice.DocumentNumber,\n DueDate: invoice.DueDate,\n ExternalInvoiceReference1: invoice.ExternalInvoiceReference1,\n ExternalInvoiceReference2: invoice.ExternalInvoiceReference2,\n FinalPayDate: invoice.FinalPayDate,\n InvoiceDate: invoice.InvoiceDate,\n InvoiceType: invoice.InvoiceType,\n NoxFinans: invoice.NoxFinans,\n OCR: invoice.OCR,\n VoucherNumber: invoice.VoucherNumber,\n VoucherSeries: invoice.VoucherSeries,\n VoucherYear: invoice.VoucherYear,\n WayOfDelivery: invoice.WayOfDelivery,\n TermsOfPayment: invoice.TermsOfPayment,\n Project: invoice.Project,\n Sent: invoice.Sent,\n Total: invoice.Total\n})\n\n/** The 400 for the first query key the route does not emulate, or `undefined`. */\nconst unsupportedQueryKey = (\n query: URLSearchParams,\n allowed: ReadonlyArray<string>\n): Response | undefined => {\n const key = [...query.keys()].find(candidate => !allowed.includes(candidate))\n\n return key === undefined ? undefined : unsupportedQuery(key)\n}\n\nconst customerSearch = {\n customernumber: (customer, value) => customer.CustomerNumber === value,\n name: (customer, value) => contains(customer.Name, value),\n organisationnumber: (customer, value) => contains(customer.OrganisationNumber, value),\n email: (customer, value) => contains(customer.Email, value),\n city: (customer, value) => contains(customer.City, value),\n phone: (customer, value) => contains(customer.Phone1, value) || contains(customer.Phone2, value)\n} satisfies SearchTable<FortnoxEmulatorCustomer>\n\nconst customerListQueryKeys: ReadonlyArray<string> = [\n 'page',\n 'limit',\n 'filter',\n ...Object.keys(customerSearch)\n]\n\nconst listCustomers: RouteHandler = (state, { query }, env) => {\n const filter = query.get('filter')\n\n if (filter !== null && filter !== 'active' && filter !== 'inactive') {\n return invalidField(`unknown customer filter ${filter}.`)\n }\n\n const matching = state.customers.filter(\n customer =>\n (filter === null || customer.Active === (filter === 'active')) &&\n matchesSearch(customer, query, customerSearch)\n )\n\n const page = paginate(matching, query)\n\n if (page instanceof Response) return page\n\n return jsonResponse(200, {\n Customers: page.items.map(customer => renderCustomerRow(env, customer)),\n MetaInformation: page.meta\n })\n}\n\nconst findCustomer = (state: FortnoxEmulatorState, customerNumber: string) =>\n state.customers.find(customer => customer.CustomerNumber === customerNumber)\n\nconst findInvoice = (state: FortnoxEmulatorState, documentNumber: string) =>\n state.invoices.find(invoice => invoice.DocumentNumber === documentNumber)\n\nconst getCustomer: RouteHandler = (state, { params }, env) => {\n const customer = findCustomer(state, params.CustomerNumber ?? '')\n\n return customer === undefined\n ? customerNotFound()\n : jsonResponse(200, { Customer: renderCustomer(env, customer) })\n}\n\n/** The single resource object of a `{ <envelope>: { ... } }` write body. */\nconst envelopeObject = (\n body: Schema.Json | undefined,\n envelope: string\n): Schema.JsonObject | Response => {\n const value = isJsonObject(body) ? body[envelope] : undefined\n\n return isJsonObject(body) &&\n Object.keys(body).every(key => key === envelope) &&\n isJsonObject(value)\n ? value\n : invalidBody(`the request body must be { \"${envelope}\": { ... } }.`)\n}\n\nconst writableCustomerStrings = [\n 'Name',\n 'OrganisationNumber',\n 'Email',\n 'Phone1',\n 'Phone2',\n 'Address1',\n 'Address2',\n 'City',\n 'ZipCode',\n 'CountryCode',\n 'Currency',\n 'VATNumber',\n 'VATType',\n 'TermsOfPayment',\n 'OurReference',\n 'YourReference',\n 'Comments',\n 'EmailInvoice',\n 'Type',\n 'CostCenter'\n] as const\n\ntype CustomerStringField = (typeof writableCustomerStrings)[number]\n\nconst isCustomerStringField = (key: string): key is CustomerStringField =>\n writableCustomerStrings.some(field => field === key)\n\ntype CustomerUpdates = {\n -readonly [K in keyof FortnoxEmulatorCustomer]?: FortnoxEmulatorCustomer[K]\n}\n\n/**\n * Why a customer field value is not emulated (fail closed), or `undefined`. The emulated company\n * has only SEK, terms of payment in whole days (0–365), `VATType` `SEVAT`, and `Type` `COMPANY` or\n * `PRIVATE`; cost center references are not emulated on writes.\n */\nconst unsupportedCustomerValue = (\n key: CustomerStringField,\n value: string\n): Response | undefined => {\n switch (key) {\n case 'Currency':\n return value === 'SEK' ? undefined : noReferencedEntity('Currency', value)\n case 'CostCenter':\n return value === '' ? undefined : unsupportedReference('CostCenter', value)\n case 'TermsOfPayment':\n return termsOfPaymentDays(value) === undefined ? unsupportedTermsOfPayment(value) : undefined\n case 'VATType':\n return emulatedCustomerVatTypes.includes(value) ? undefined : unsupportedVatType(value)\n case 'Type':\n return emulatedCustomerTypes.includes(value)\n ? undefined\n : invalidField(\n `Type ${value} is not emulated (supported: ${emulatedCustomerTypes.join(', ')}).`\n )\n default:\n return undefined\n }\n}\n\n/**\n * Quirk 2: an empty string keeps the stored value (unless the `emptyStringClears` drill knob is\n * set); omitted fields keep theirs. Quirk 5: `Country` is read-only. Unknown fields, wrong types,\n * and values the emulator does not support (non-SEK `Currency`, a `CostCenter`, `TermsOfPayment`\n * other than 0–365 days, `VATType` other than `SEVAT`, `Type` other than `COMPANY`/`PRIVATE`) are\n * rejected; the update is atomic.\n */\nconst customerUpdates = (\n fields: Schema.JsonObject,\n customer: FortnoxEmulatorCustomer,\n env: FortnoxApiEnv\n): CustomerUpdates | Response => {\n const updates: CustomerUpdates = {}\n\n for (const [key, value] of Object.entries(fields)) {\n if (key === 'Country') {\n return readOnlyField('Country is read-only; set CountryCode instead.')\n }\n\n if (key === 'CustomerNumber') {\n if (value !== customer.CustomerNumber) {\n return invalidField('CustomerNumber cannot be changed.')\n }\n\n continue\n }\n\n if (key === 'Active') {\n if (!Predicate.isBoolean(value)) return invalidField('Active must be a boolean.')\n\n updates.Active = value\n\n continue\n }\n\n if (!isCustomerStringField(key)) {\n return invalidField(`unknown customer field ${key}.`)\n }\n\n if (!Predicate.isString(value)) {\n return invalidField(`${key} must be a string.`)\n }\n\n if (value === '' && !env.quirks.emptyStringClears) {\n continue\n }\n\n const unsupported = unsupportedCustomerValue(key, value)\n\n if (unsupported !== undefined) return unsupported\n\n if (key === 'CountryCode' && value !== '') {\n const country = fortnoxEmulatorCountries.get(value)\n\n if (country === undefined) return invalidField(`unknown CountryCode ${value}.`)\n\n updates.Country = country\n }\n\n updates[key] = value\n }\n\n return updates\n}\n\nconst updateCustomer: RouteHandler = (state, { params, body }, env) => {\n const customer = findCustomer(state, params.CustomerNumber ?? '')\n\n if (customer === undefined) return customerNotFound()\n\n const fields = envelopeObject(body, 'Customer')\n\n if (fields instanceof Response) return fields\n\n const updates = customerUpdates(fields, customer, env)\n\n if (updates instanceof Response) return updates\n\n const updated: FortnoxEmulatorCustomer = { ...customer, ...updates }\n\n state.customers = state.customers.map(existing =>\n existing.CustomerNumber === updated.CustomerNumber ? updated : existing\n )\n\n return jsonResponse(200, { Customer: renderCustomer(env, updated) })\n}\n\ntype InvoiceFilter = 'cancelled' | 'fullypaid' | 'unpaid' | 'unpaidoverdue' | 'unbooked'\n\nconst invoiceFilters: ReadonlyArray<InvoiceFilter> = [\n 'cancelled',\n 'fullypaid',\n 'unpaid',\n 'unpaidoverdue',\n 'unbooked'\n]\n\nconst isInvoiceFilter = (value: string): value is InvoiceFilter =>\n invoiceFilters.some(filter => filter === value)\n\n/**\n * Quirk 3: the payment-status filters consider booked invoices only (unless the\n * `paymentFiltersIncludeUnbooked` drill knob is set); `unbooked` returns unbooked, uncancelled\n * invoices; `unpaidoverdue` needs a `DueDate` before today (UTC, from the emulator clock).\n */\nconst matchesInvoiceFilter = (\n invoice: FortnoxEmulatorInvoice,\n filter: InvoiceFilter,\n env: FortnoxApiEnv\n): boolean => {\n const considered =\n (invoice.Booked || env.quirks.paymentFiltersIncludeUnbooked) && !invoice.Cancelled\n\n switch (filter) {\n case 'cancelled':\n return invoice.Cancelled\n case 'unbooked':\n return !invoice.Booked && !invoice.Cancelled\n case 'unpaid':\n return considered && invoice.Balance > 0\n case 'unpaidoverdue':\n return (\n considered &&\n invoice.Balance > 0 &&\n invoice.DueDate !== null &&\n isIsoDate(invoice.DueDate) &&\n invoice.DueDate < today(env)\n )\n case 'fullypaid':\n return considered && invoice.Balance === 0\n }\n}\n\nconst invoiceSearch = {\n customernumber: (invoice, value) => invoice.CustomerNumber === value,\n customername: (invoice, value) => contains(invoice.CustomerName, value),\n documentnumber: (invoice, value) => invoice.DocumentNumber === value,\n ocr: (invoice, value) => invoice.OCR === value\n} satisfies SearchTable<FortnoxEmulatorInvoice>\n\nconst invoiceListQueryKeys: ReadonlyArray<string> = [\n 'page',\n 'limit',\n 'filter',\n 'fromdate',\n 'todate',\n ...Object.keys(invoiceSearch)\n]\n\nconst listInvoices: RouteHandler = (state, { query }, env) => {\n const filter = query.get('filter')\n\n if (filter !== null && !isInvoiceFilter(filter)) {\n return invalidField(`unknown invoice filter ${filter}.`)\n }\n\n const range = dateRange(query)\n\n if (range instanceof Response) return range\n\n const matching = state.invoices.filter(\n invoice =>\n (filter === null || matchesInvoiceFilter(invoice, filter, env)) &&\n (range.from === null || invoice.InvoiceDate >= range.from) &&\n (range.to === null || invoice.InvoiceDate <= range.to) &&\n matchesSearch(invoice, query, invoiceSearch)\n )\n\n const page = paginate(matching, query)\n\n if (page instanceof Response) return page\n\n return jsonResponse(200, {\n Invoices: page.items.map(invoice => renderInvoiceRow(env, invoice)),\n MetaInformation: page.meta\n })\n}\n\nconst getInvoice: RouteHandler = (state, { params }, env) => {\n const invoice = findInvoice(state, params.DocumentNumber ?? '')\n\n return invoice === undefined\n ? invoiceNotFound()\n : jsonResponse(200, { Invoice: renderInvoice(env, invoice) })\n}\n\ntype RowPatch = {\n -readonly [K in keyof FortnoxEmulatorInvoiceRowSeed]?: FortnoxEmulatorInvoiceRowSeed[K]\n}\n\nconst vatRates: ReadonlyArray<number> = [...fortnoxEmulatorVatCodes.keys()]\n\n/**\n * One row of an `InvoiceRows` write. `null` means omitted. References to articles, cost centers,\n * and projects are not emulated on writes; accounts must be in 1000-8999.\n */\nconst rowPatch = (value: Schema.Json, index: number): RowPatch | Response => {\n if (!isJsonObject(value)) {\n return invalidField(`InvoiceRows[${index}] must be an object.`)\n }\n\n const patch: RowPatch = {}\n const label = (key: string) => `InvoiceRows[${index}].${key}`\n\n for (const [key, field] of Object.entries(value)) {\n if (field === null) continue\n\n switch (key) {\n case 'RowId':\n if (!Predicate.isNumber(field) || !Number.isSafeInteger(field) || field < 1) {\n return invalidField(`${label(key)} must be a positive integer.`)\n }\n\n patch.RowId = field\n break\n case 'AccountNumber':\n if (\n !Predicate.isNumber(field) ||\n !Number.isInteger(field) ||\n field < 1000 ||\n field > 8999\n ) {\n return invalidField(`${label(key)} must be an account number from 1000 to 8999.`)\n }\n\n patch.AccountNumber = field\n break\n case 'ArticleNumber':\n case 'CostCenter':\n case 'Project':\n if (!Predicate.isString(field)) return invalidField(`${label(key)} must be a string.`)\n\n if (field !== '') return unsupportedReference(key, field)\n\n patch[key] = field\n break\n case 'Description':\n case 'Unit':\n if (!Predicate.isString(field)) return invalidField(`${label(key)} must be a string.`)\n\n patch[key] = field\n break\n case 'DeliveredQuantity': {\n const quantity = Predicate.isString(field) ? Number(field.trim()) : field\n\n if (\n !Predicate.isNumber(quantity) ||\n !Number.isFinite(quantity) ||\n quantity < 0 ||\n (Predicate.isString(field) && field.trim() === '')\n ) {\n return invalidField(`${label(key)} must be a non-negative number.`)\n }\n\n patch.DeliveredQuantity = formatQuantity(quantity)\n break\n }\n\n case 'Price':\n if (!Predicate.isNumber(field) || !Number.isFinite(field)) {\n return invalidField(`${label(key)} must be a finite number.`)\n }\n\n patch.Price = field\n break\n case 'Discount':\n if (!Predicate.isNumber(field) || !Number.isFinite(field) || field < 0) {\n return invalidField(`${label(key)} must be a non-negative number.`)\n }\n\n patch.Discount = field\n break\n case 'DiscountType':\n if (field !== 'PERCENT' && field !== 'AMOUNT') {\n return invalidField(`${label(key)} must be PERCENT or AMOUNT.`)\n }\n\n patch.DiscountType = field\n break\n case 'VAT':\n if (!Predicate.isNumber(field) || !vatRates.includes(field)) {\n return invalidField(`${label(key)} must be one of ${vatRates.join(', ')}.`)\n }\n\n patch.VAT = field\n break\n default:\n return invalidField(`${label(key)} is not a writable invoice row field.`)\n }\n }\n\n return patch\n}\n\nconst rowPatches = (value: Schema.Json): ReadonlyArray<RowPatch> | Response => {\n if (!Array.isArray(value)) {\n return invalidField('InvoiceRows must be an array.')\n }\n\n const patches: Array<RowPatch> = []\n\n for (const [index, row] of value.entries()) {\n const patch = rowPatch(row, index)\n\n if (patch instanceof Response) return patch\n\n patches.push(patch)\n }\n\n return patches\n}\n\ntype RowIds = { next: number }\n\n/**\n * Quirk 1: `InvoiceRows` replaces the row list. Without any `RowId`, rows match existing rows by\n * position; with a `RowId`, that row is updated and rows without one are added. A matched row\n * keeps every omitted field, including `Discount`/`DiscountType` (unless the `stickyRowDiscount`\n * drill knob is off, which resets them); `Discount: 0` clears. RowIds are regenerated for every\n * row, and totals follow from the fields.\n */\nconst mergeRows = (\n existing: ReadonlyArray<FortnoxEmulatorInvoiceRow>,\n patches: ReadonlyArray<RowPatch>,\n ids: RowIds,\n env: FortnoxApiEnv\n): ReadonlyArray<FortnoxEmulatorInvoiceRow> | Response => {\n const byRowId = patches.some(patch => patch.RowId !== undefined)\n const rows: Array<FortnoxEmulatorInvoiceRow> = []\n\n for (const [index, patch] of patches.entries()) {\n const base = byRowId\n ? existing.find(row => patch.RowId !== undefined && row.RowId === patch.RowId)\n : existing[index]\n\n if (byRowId && patch.RowId !== undefined && base === undefined) {\n return invalidField(`InvoiceRows[${index}].RowId ${patch.RowId} does not exist.`)\n }\n\n const start = { ...newRowDefaults, ...base }\n\n // Drill knob only: forget the matched row's discount instead of keeping it.\n if (base !== undefined && !env.quirks.stickyRowDiscount) {\n start.Discount = 0\n start.DiscountType = 'PERCENT'\n }\n\n rows.push(buildRow({ ...start, ...patch, RowId: ids.next++ }))\n }\n\n return rows\n}\n\nconst invoiceTextFields = ['Comments', 'Remarks', 'OurReference', 'YourReference', 'OCR'] as const\n\ntype InvoiceTextField = (typeof invoiceTextFields)[number]\n\nconst isInvoiceTextField = (key: string): key is InvoiceTextField =>\n invoiceTextFields.some(field => field === key)\n\nconst invoiceReadOnlyFields: ReadonlyArray<string> = [\n 'Balance',\n 'Booked',\n 'Cancelled',\n 'CustomerName',\n 'FinalPayDate',\n 'Gross',\n 'Net',\n 'Sent',\n 'Total',\n 'TotalToPay',\n 'TotalVAT',\n 'VoucherNumber',\n 'VoucherSeries',\n 'VoucherYear'\n]\n\ntype InvoiceScalars = {\n CustomerNumber?: string\n Currency?: string\n InvoiceDate?: string\n DueDate?: string\n CostCenter?: string\n Project?: string\n} & { -readonly [K in InvoiceTextField]?: string }\n\ntype InvoiceUpdates = {\n readonly scalars: InvoiceScalars\n readonly customer: FortnoxEmulatorCustomer | undefined\n readonly rows: ReadonlyArray<RowPatch> | undefined\n}\n\n/**\n * The writable invoice fields of a create or update body (the connector's invoice mutation\n * fields). Quirk 4: an unknown `CustomerNumber` is rejected with the rejection fixture's 400\n * `ErrorInformation`; other invalid or read-only fields are rejected with 400 too.\n */\nconst invoiceUpdates = (\n fields: Schema.JsonObject,\n state: FortnoxEmulatorState,\n existing: FortnoxEmulatorInvoice | undefined\n): InvoiceUpdates | Response => {\n const scalars: InvoiceScalars = {}\n let customer: FortnoxEmulatorCustomer | undefined\n let rows: ReadonlyArray<RowPatch> | undefined\n\n for (const [key, value] of Object.entries(fields)) {\n if (key === 'DocumentNumber') {\n if (existing === undefined || value !== existing.DocumentNumber) {\n return readOnlyField('DocumentNumber is assigned by Fortnox and cannot be changed.')\n }\n\n continue\n }\n\n if (key === 'InvoiceRows') {\n const patches = rowPatches(value)\n\n if (patches instanceof Response) return patches\n\n if (existing === undefined && patches.some(patch => patch.RowId !== undefined)) {\n return readOnlyField('RowId is assigned by Fortnox.')\n }\n\n rows = patches\n\n continue\n }\n\n if (invoiceReadOnlyFields.includes(key)) {\n return readOnlyField(`${key} is read-only.`)\n }\n\n if (!Predicate.isString(value)) {\n return invalidField(\n key === 'CustomerNumber' || key === 'Currency' || isInvoiceTextField(key)\n ? `${key} must be a string.`\n : `unknown or unsupported invoice field ${key}.`\n )\n }\n\n switch (key) {\n case 'CustomerNumber':\n customer = findCustomer(state, value)\n\n if (customer === undefined) return invoiceCustomerNotFound()\n\n scalars.CustomerNumber = value\n break\n case 'Currency':\n if (value !== 'SEK') return noReferencedEntity('Currency', value)\n\n scalars.Currency = value\n break\n case 'InvoiceDate':\n case 'DueDate':\n if (!isIsoDate(value)) return invalidField(`${key} must be a YYYY-MM-DD date.`)\n\n scalars[key] = value\n break\n case 'CostCenter':\n case 'Project':\n if (value !== '') return unsupportedReference(key, value)\n\n scalars[key] = value\n break\n default:\n if (!isInvoiceTextField(key)) {\n return invalidField(`unknown or unsupported invoice field ${key}.`)\n }\n\n scalars[key] = value\n }\n }\n\n return { scalars, customer, rows }\n}\n\nconst replaceInvoice = (state: FortnoxEmulatorState, updated: FortnoxEmulatorInvoice): void => {\n state.invoices = state.invoices.map(invoice =>\n invoice.DocumentNumber === updated.DocumentNumber ? updated : invoice\n )\n}\n\nconst updateInvoice: RouteHandler = (state, { params, body }, env) => {\n const invoice = findInvoice(state, params.DocumentNumber ?? '')\n\n if (invoice === undefined) return invoiceNotFound()\n\n const fields = envelopeObject(body, 'Invoice')\n\n if (fields instanceof Response) return fields\n\n if (invoice.Booked) return notEditable('a booked invoice cannot be updated.')\n\n if (invoice.Cancelled) return notEditable('a cancelled invoice cannot be updated.')\n\n const updates = invoiceUpdates(fields, state, invoice)\n\n if (updates instanceof Response) return updates\n\n let updated: FortnoxEmulatorInvoice = {\n ...invoice,\n ...updates.scalars,\n CustomerName: updates.customer?.Name ?? invoice.CustomerName\n }\n\n if (updates.rows !== undefined) {\n const ids: RowIds = { next: state.counters.nextRowId }\n const rows = mergeRows(invoice.InvoiceRows, updates.rows, ids, env)\n\n if (rows instanceof Response) return rows\n\n const totals = invoiceTotals(rows)\n\n updated = { ...updated, InvoiceRows: rows, ...totals, Balance: totals.Total }\n state.counters = { ...state.counters, nextRowId: ids.next }\n }\n\n replaceInvoice(state, updated)\n\n return jsonResponse(200, { Invoice: renderInvoice(env, updated) })\n}\n\nconst createInvoice: RouteHandler = (state, { body }, env) => {\n const fields = envelopeObject(body, 'Invoice')\n\n if (fields instanceof Response) return fields\n\n const updates = invoiceUpdates(fields, state, undefined)\n\n if (updates instanceof Response) return updates\n\n const { customer } = updates\n\n if (customer === undefined) return invalidField('CustomerNumber is required.')\n\n // The invoice inherits the customer's currency when it names none; check the effective value\n // (a seeded customer can carry any currency) before anything is committed.\n const currency = updates.scalars.Currency ?? customer.Currency\n\n if (currency !== 'SEK') return noReferencedEntity('Currency', currency)\n\n // Likewise the inherited VAT type (invoice VAT comes from the rows only) and payment terms,\n // which the invoice records and derives its due date from.\n if (!emulatedCustomerVatTypes.includes(customer.VATType)) {\n return unsupportedVatType(customer.VATType)\n }\n\n const terms = termsOfPaymentDays(customer.TermsOfPayment)\n\n if (terms === undefined) return unsupportedTermsOfPayment(customer.TermsOfPayment)\n\n const invoiceDate = updates.scalars.InvoiceDate ?? today(env)\n const dueDate = updates.scalars.DueDate ?? addDays(invoiceDate, terms)\n\n if (dueDate === undefined) {\n return invalidField(\n `the due date ${invoiceDate} + ${terms} days is not a representable YYYY-MM-DD date.`\n )\n }\n\n const ids: RowIds = { next: state.counters.nextRowId }\n\n const seed: FortnoxEmulatorInvoiceSeed = {\n ...updates.scalars,\n DocumentNumber: String(state.counters.nextDocumentNumber),\n CustomerNumber: customer.CustomerNumber,\n InvoiceDate: invoiceDate,\n DueDate: dueDate,\n EmailInformation: defaultEmailInformation(customer, state.company),\n InvoiceRows: updates.rows ?? []\n }\n\n const invoice = invoiceFromSeed(seed, customer, state.company, ids)\n\n state.invoices = [...state.invoices, invoice].sort((left, right) =>\n compareNumbers(left.DocumentNumber, right.DocumentNumber)\n )\n state.counters = {\n nextRowId: ids.next,\n nextDocumentNumber: state.counters.nextDocumentNumber + 1\n }\n\n return jsonResponse(201, { Invoice: renderInvoice(env, invoice) })\n}\n\nconst previewInvoice: RouteHandler = (state, { params }) =>\n findInvoice(state, params.DocumentNumber ?? '') === undefined ? invoiceNotFound() : pdfResponse()\n\n/** Marks the invoice `Sent` and records an outbox entry. Nothing is ever delivered. */\nconst emailInvoice: RouteHandler = (state, { params }, env) => {\n const invoice = findInvoice(state, params.DocumentNumber ?? '')\n\n if (invoice === undefined) return invoiceNotFound()\n\n if (invoice.Cancelled) return notEditable('a cancelled invoice cannot be sent.')\n\n const email = invoice.EmailInformation\n\n if (email.EmailAddressTo.trim() === '') {\n return invalidField('the invoice has no EmailInformation.EmailAddressTo.')\n }\n\n const updated: FortnoxEmulatorInvoice = { ...invoice, Sent: true }\n\n replaceInvoice(state, updated)\n state.outbox = [\n ...state.outbox,\n {\n DocumentNumber: invoice.DocumentNumber,\n EmailAddressTo: email.EmailAddressTo,\n EmailAddressCC: email.EmailAddressCC,\n EmailAddressBCC: email.EmailAddressBCC,\n EmailSubject: email.EmailSubject.replaceAll('{no}', invoice.DocumentNumber),\n sentAt: new Date(env.now()).toISOString()\n }\n ]\n\n return jsonResponse(200, { Invoice: renderInvoice(env, updated, true) })\n}\n\nconst companyInformation: RouteHandler = state =>\n jsonResponse(200, { CompanyInformation: state.company })\n\nconst listCase = 'fortnox.invoice.list-populated'\n\nconst previewCase = 'fortnox.invoice.preview-pdf'\n\nconst filtersCase = 'fortnox.invoice.payment-filters-exclude-unbooked'\n\nconst discountCase = 'fortnox.invoice.row-discount-sticky'\n\nconst emptyStringCase = 'fortnox.customer.empty-string-keeps-value'\n\nconst rejectionCase = 'fortnox.write.rejection-error-information'\n\nconst emailCase = 'fortnox.invoice.send-email'\n\n/** The route table: evidence plus handler. `fortnoxEmulatorRoutes` is its evidence part. */\nexport const fortnoxApiRoutes: ReadonlyArray<FortnoxApiRoute> = [\n connectorRoute('GET', '/companyinformation', false, [], companyInformation),\n connectorRoute('GET', '/customers', false, [], listCustomers, customerListQueryKeys),\n connectorRoute(\n 'GET',\n '/customers/{CustomerNumber}',\n false,\n [emptyStringCase, rejectionCase],\n getCustomer\n ),\n connectorRoute('PUT', '/customers/{CustomerNumber}', true, [emptyStringCase], updateCustomer),\n connectorRoute(\n 'GET',\n '/invoices',\n false,\n [listCase, filtersCase],\n listInvoices,\n invoiceListQueryKeys\n ),\n connectorRoute('POST', '/invoices', true, [rejectionCase], createInvoice),\n connectorRoute('GET', '/invoices/{DocumentNumber}', false, [discountCase, emailCase], getInvoice),\n connectorRoute('PUT', '/invoices/{DocumentNumber}', true, [discountCase], updateInvoice),\n connectorRoute('GET', '/invoices/{DocumentNumber}/preview', false, [previewCase], previewInvoice),\n connectorRoute('GET', '/invoices/{DocumentNumber}/email', true, [emailCase], emailInvoice),\n ...fortnoxReadRoutes\n]\n\n/** One observed Fortnox quirk the emulator implements, and the case that claims it. */\nexport type FortnoxEmulatorQuirk = {\n readonly id: string\n /** `METHOD path` of the route that implements it. */\n readonly route: string\n /** The conformance case whose claim it follows; `undefined` when no case covers it yet. */\n readonly caseId: string | undefined\n /** The drill knob that flips it, if any. */\n readonly knob: keyof FortnoxEmulatorQuirks | undefined\n readonly summary: string\n}\n\n/** The observed quirks, each tied to its conformance case id. */\nexport const fortnoxEmulatorQuirks: ReadonlyArray<FortnoxEmulatorQuirk> = [\n {\n id: 'row-discount-sticky',\n route: 'PUT /3/invoices/{DocumentNumber}',\n caseId: discountCase,\n knob: 'stickyRowDiscount',\n summary:\n 'InvoiceRows replaces the rows; rows without RowId match by position; an omitted Discount/DiscountType keeps its value; Discount 0 clears; RowIds regenerate; totals are recomputed.'\n },\n {\n id: 'empty-string-keeps-value',\n route: 'PUT /3/customers/{CustomerNumber}',\n caseId: emptyStringCase,\n knob: 'emptyStringClears',\n summary: 'A customer update with \"\" for a string field keeps the stored value.'\n },\n {\n id: 'payment-filters-exclude-unbooked',\n route: 'GET /3/invoices',\n caseId: filtersCase,\n knob: 'paymentFiltersIncludeUnbooked',\n summary:\n 'unpaid, unpaidoverdue, and fullypaid consider booked invoices only; unbooked lists unbooked, uncancelled invoices; unpaidoverdue needs DueDate before today.'\n },\n {\n id: 'rejection-error-information',\n route: 'POST /3/invoices',\n caseId: rejectionCase,\n knob: undefined,\n summary:\n 'Writes for an unknown customer, or with invalid fields, answer 400 with a lowercase ErrorInformation { error, message, code }.'\n },\n {\n id: 'customer-country-read-only',\n route: 'PUT /3/customers/{CustomerNumber}',\n caseId: undefined,\n knob: undefined,\n summary:\n 'Customer Country is read-only (derived from CountryCode); sending it answers 400 ErrorInformation. No conformance case covers it yet.'\n }\n]\n\nconst templatePattern = (template: string): RegExp =>\n new RegExp(\n `^${template\n .split(/(\\{[A-Za-z]+\\})/)\n .map(part =>\n /^\\{[A-Za-z]+\\}$/.test(part) ? '([^/]+)' : part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n )\n .join('')}$`\n )\n\nconst compiledRoutes = fortnoxApiRoutes.map(route => ({\n route,\n pattern: templatePattern(route.path)\n}))\n\n/** The route answering `method` + concrete `path`, or `undefined` (fail closed). */\nexport const matchFortnoxRoute = (method: string, path: string): FortnoxApiRoute | undefined =>\n compiledRoutes.find(\n candidate => candidate.route.method === method.toUpperCase() && candidate.pattern.test(path)\n )?.route\n\nconst decodeJsonText = Schema.decodeUnknownResult(Schema.fromJsonString(Schema.Json))\n\n/** Parsed JSON, or `undefined` for invalid JSON. */\nexport const parseJsonText = (text: string): Schema.Json | undefined => {\n const result = decodeJsonText(text)\n\n return Result.isSuccess(result) ? result.success : undefined\n}\n\n/** `{Name}` path templates become `:Name` core route parameters. */\nconst corePath = (template: string): string => template.replace(/\\{([A-Za-z]+)\\}/g, ':$1')\n\n/**\n * The wrapper's fault decision for the core request of job `jobId` (its `emulatorJobHeader`),\n * asked only once the route would answer successfully: `true` when a fault answers instead (it is\n * used up, and the wrapper sends its answer), `false` when none applies.\n */\nexport type FortnoxFaultDecision = (jobId: string | undefined) => boolean\n\n/**\n * Register every route of the table on the core app, over the generation's state. Each request is\n * planned, then faulted, then committed: the handler runs on a draft of the state (handlers replace\n * whole lists and counters, never edit them in place, so a shallow copy keeps every write off the\n * state); a refusal (any answer that is not 2xx) is sent as is and uses up no fault; a successful\n * answer asks `decideFault`, and only an unfaulted one commits the draft. The three steps run\n * synchronously together, so no other request interleaves. A handler that throws answers\n * `handlerFailedResponse()` (nothing written), which the wrapper turns into its `ErrorInformation`\n * 500 with `responseError` in the ledger.\n */\nexport const registerFortnoxApi = (\n app: Hono,\n state: FortnoxEmulatorState,\n env: FortnoxApiEnv,\n decideFault: FortnoxFaultDecision\n): void => {\n for (const route of fortnoxApiRoutes) {\n app.on(route.method, corePath(route.path), async context => {\n try {\n const query = new URL(context.req.url).searchParams\n\n // Fail closed on query parameters the route does not emulate, before the handler can write.\n const unsupported = unsupportedQueryKey(query, route.queryKeys)\n\n if (unsupported !== undefined) return unsupported\n\n const text = await context.req.text()\n const draft: FortnoxEmulatorState = { ...state }\n\n const response = route.handler(\n draft,\n {\n params: context.req.param(),\n query,\n body: text === '' ? undefined : parseJsonText(text)\n },\n env\n )\n\n if (!response.ok) return response\n\n if (decideFault(context.req.header(emulatorJobHeader))) return answeredOutsideCore()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7 @@ export declare const FortnoxEmulatorInvoice: Schema.Struct<{
|
|
|
79
79
|
OCR: Schema.String;
|
|
80
80
|
OurReference: Schema.String;
|
|
81
81
|
Project: Schema.String;
|
|
82
|
+
Remarks: Schema.String;
|
|
82
83
|
Sent: Schema.Boolean;
|
|
83
84
|
TermsOfPayment: Schema.String;
|
|
84
85
|
Total: Schema.Finite;
|
|
@@ -462,6 +463,7 @@ export declare const FortnoxEmulatorStateSchema: Schema.Struct<{
|
|
|
462
463
|
OCR: Schema.String;
|
|
463
464
|
OurReference: Schema.String;
|
|
464
465
|
Project: Schema.String;
|
|
466
|
+
Remarks: Schema.String;
|
|
465
467
|
Sent: Schema.Boolean;
|
|
466
468
|
TermsOfPayment: Schema.String;
|
|
467
469
|
Total: Schema.Finite;
|
|
@@ -555,6 +557,7 @@ export declare const FortnoxEmulatorInvoiceSeed: Schema.Struct<{
|
|
|
555
557
|
readonly OCR: Schema.optionalKey<Schema.String>;
|
|
556
558
|
readonly OurReference: Schema.optionalKey<Schema.String>;
|
|
557
559
|
readonly Project: Schema.optionalKey<Schema.String>;
|
|
560
|
+
readonly Remarks: Schema.optionalKey<Schema.String>;
|
|
558
561
|
readonly Sent: Schema.optionalKey<Schema.Boolean>;
|
|
559
562
|
readonly TermsOfPayment: Schema.optionalKey<Schema.String>;
|
|
560
563
|
readonly Total: Schema.optionalKey<Schema.Finite>;
|
|
@@ -905,6 +908,7 @@ export declare const FortnoxEmulatorSeed: Schema.Struct<{
|
|
|
905
908
|
readonly OCR: Schema.optionalKey<Schema.String>;
|
|
906
909
|
readonly OurReference: Schema.optionalKey<Schema.String>;
|
|
907
910
|
readonly Project: Schema.optionalKey<Schema.String>;
|
|
911
|
+
readonly Remarks: Schema.optionalKey<Schema.String>;
|
|
908
912
|
readonly Sent: Schema.optionalKey<Schema.Boolean>;
|
|
909
913
|
readonly TermsOfPayment: Schema.optionalKey<Schema.String>;
|
|
910
914
|
readonly Total: Schema.optionalKey<Schema.Finite>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.d.mts","names":[],"sources":["../../src/fortnox/state.ts"],"mappings":";;;qBAuDa,2BAAyB,OAAA;;;;;;;;;;;;;;;;;;;;;YAE1B,mCAAmC,0BAA0B;;
|
|
1
|
+
{"version":3,"file":"state.d.mts","names":[],"sources":["../../src/fortnox/state.ts"],"mappings":";;;qBAuDa,2BAAyB,OAAA;;;;;;;;;;;;;;;;;;;;;YAE1B,mCAAmC,0BAA0B;;qBAqD5D,wBAAsB,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAEvB,gCAAgC,uBAAuB;;qBA6BtD,yBAAuB,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;YAExB,iCAAiC,wBAAwB;;qBAiBxD,wBAAsB,OAAA;;;;;;;;;;;;;YAEvB,gCAAgC,uBAAuB;;qBAGtD,4BAA0B,OAAA;;;;;;;;;YAU3B,oCAAoC,2BAA2B;cAIrE,UAAQ,OAAA;;;;;;;qBAQD,4BAA0B,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAa3B;EACV,SAAS;EACT,WAAW,cAAc;EACzB,UAAU,cAAc;EACxB,QAAQ,cAAc;EACtB,iBAAiB,SAAS;IACxB;;qBAGS,+BAA6B,OAAA;;;;;;;;;;;;;;YAe9B,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
|
78
|
+
Remarks: Schema.String,
|
|
78
79
|
Sent: Schema.Boolean,
|
|
79
80
|
TermsOfPayment: Schema.String,
|
|
80
81
|
Total: Schema.Finite,
|
|
@@ -550,6 +551,7 @@ const invoiceFromSeed = (seed, customer, company, ids) => {
|
|
|
550
551
|
OCR: seed.OCR ?? "",
|
|
551
552
|
OurReference: seed.OurReference ?? "",
|
|
552
553
|
Project: seed.Project ?? "",
|
|
554
|
+
Remarks: seed.Remarks ?? "",
|
|
553
555
|
Sent: seed.Sent ?? false,
|
|
554
556
|
TermsOfPayment: seed.TermsOfPayment ?? customer?.TermsOfPayment ?? "30",
|
|
555
557
|
Total: totals.Total,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.mjs","names":[],"sources":["../../src/fortnox/state.ts"],"sourcesContent":["/**\n * Fortnox emulator state: the typed entities, the seed input, the default seed, and the\n * account-variance profiles (internal; re-exported by `src/fortnox.ts`).\n *\n * Entity shapes and the default entities follow the synthetic Fortnox conformance fixtures, copied\n * as data (the same customer and document numbers as `fortnoxConformanceFixtureSeeds`), never\n * imported from SDK code. Where no fixture records a value, the default is synthesized and says\n * so below: customer 1002, most invoice rows, and the company information have no fixture. The\n * read-only resources (articles, prices, offers, payments, the inbox, settings, registers, ...)\n * have no fixture at all; they live in `src/fortnox/read-state.ts`.\n *\n * @experimental\n */\nimport { Predicate, Result, Struct } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport {\n buildReadState,\n compareNumbers,\n defaultReadEntities,\n duplicate,\n emptyCompanyReadEntities,\n fortnoxReadSeedFields,\n fortnoxReadStateFields,\n round2,\n type FortnoxReadEntities,\n type FortnoxReadState\n} from './read-state.ts'\n\nexport { compareNumbers, round2 } from './read-state.ts'\n\nconst DiscountType = Schema.Literals(['PERCENT', 'AMOUNT'])\n\nconst rowFields = {\n RowId: Schema.Int,\n AccountNumber: Schema.NullOr(Schema.Int),\n ArticleNumber: Schema.String,\n ContributionPercent: Schema.String,\n ContributionValue: Schema.String,\n CostCenter: Schema.String,\n DeliveredQuantity: Schema.String,\n Description: Schema.String,\n Discount: Schema.Finite,\n DiscountType,\n HouseWork: Schema.Boolean,\n Price: Schema.Finite,\n PriceExcludingVAT: Schema.Finite,\n Project: Schema.String,\n Total: Schema.Finite,\n TotalExcludingVAT: Schema.Finite,\n Unit: Schema.String,\n VAT: Schema.Finite,\n VATCode: Schema.String\n}\n\n/** A stored invoice row, in the single-invoice wire shape. Totals are derived. */\nexport const FortnoxEmulatorInvoiceRow = Schema.Struct(rowFields)\n\nexport type FortnoxEmulatorInvoiceRow = typeof FortnoxEmulatorInvoiceRow.Type\n\nconst EmailInformation = Schema.Struct({\n EmailAddressFrom: Schema.String,\n EmailAddressTo: Schema.String,\n EmailAddressCC: Schema.String,\n EmailAddressBCC: Schema.String,\n EmailSubject: Schema.String,\n EmailBody: Schema.String\n})\n\nconst invoiceFields = {\n DocumentNumber: Schema.String,\n CustomerNumber: Schema.String,\n CustomerName: Schema.String,\n Balance: Schema.Finite,\n Booked: Schema.Boolean,\n Cancelled: Schema.Boolean,\n Comments: Schema.String,\n CostCenter: Schema.String,\n Credit: Schema.String,\n Currency: Schema.String,\n CurrencyRate: Schema.Finite,\n CurrencyUnit: Schema.Finite,\n DueDate: Schema.NullOr(Schema.String),\n EmailInformation,\n ExternalInvoiceReference1: Schema.String,\n ExternalInvoiceReference2: Schema.String,\n FinalPayDate: Schema.NullOr(Schema.String),\n Gross: Schema.Finite,\n InvoiceDate: Schema.String,\n InvoiceRows: Schema.Array(FortnoxEmulatorInvoiceRow),\n InvoiceType: Schema.String,\n Net: Schema.Finite,\n NotCompleted: Schema.Boolean,\n NoxFinans: Schema.Boolean,\n OCR: Schema.String,\n OurReference: Schema.String,\n Project: Schema.String,\n Sent: Schema.Boolean,\n TermsOfPayment: Schema.String,\n Total: Schema.Finite,\n TotalToPay: Schema.Finite,\n TotalVAT: Schema.Finite,\n VoucherNumber: Schema.NullOr(Schema.Int),\n VoucherSeries: Schema.NullOr(Schema.String),\n VoucherYear: Schema.NullOr(Schema.Int),\n WayOfDelivery: Schema.String,\n YourReference: Schema.String\n}\n\n/** A stored customer invoice with its rows. */\nexport const FortnoxEmulatorInvoice = Schema.Struct(invoiceFields)\n\nexport type FortnoxEmulatorInvoice = typeof FortnoxEmulatorInvoice.Type\n\nconst customerFields = {\n CustomerNumber: Schema.String,\n Name: Schema.String,\n Active: Schema.Boolean,\n Address1: Schema.String,\n Address2: Schema.String,\n City: Schema.String,\n Comments: Schema.String,\n CostCenter: Schema.String,\n Country: Schema.String,\n CountryCode: Schema.String,\n Currency: Schema.String,\n Email: Schema.String,\n EmailInvoice: Schema.String,\n OrganisationNumber: Schema.String,\n OurReference: Schema.String,\n Phone1: Schema.String,\n Phone2: Schema.String,\n TermsOfPayment: Schema.String,\n Type: Schema.String,\n VATNumber: Schema.String,\n VATType: Schema.String,\n YourReference: Schema.String,\n ZipCode: Schema.String\n}\n\n/** A stored customer. `Country` is read-only (derived from `CountryCode`). */\nexport const FortnoxEmulatorCustomer = Schema.Struct(customerFields)\n\nexport type FortnoxEmulatorCustomer = typeof FortnoxEmulatorCustomer.Type\n\nconst companyFields = {\n CompanyName: Schema.String,\n OrganizationNumber: Schema.String,\n DatabaseNumber: Schema.Int,\n Address: Schema.String,\n City: Schema.String,\n ZipCode: Schema.String,\n CountryCode: Schema.String,\n VisitAddress: Schema.String,\n VisitCity: Schema.String,\n VisitZipCode: Schema.String,\n VisitCountryCode: Schema.String\n}\n\n/** The company the credential belongs to (`GET /3/companyinformation`). */\nexport const FortnoxEmulatorCompany = Schema.Struct(companyFields)\n\nexport type FortnoxEmulatorCompany = typeof FortnoxEmulatorCompany.Type\n\n/** A recorded (never delivered) invoice email. */\nexport const FortnoxEmulatorOutboxEntry = Schema.Struct({\n DocumentNumber: Schema.String,\n EmailAddressTo: Schema.String,\n EmailAddressCC: Schema.String,\n EmailAddressBCC: Schema.String,\n EmailSubject: Schema.String,\n /** ISO timestamp from the emulator clock. */\n sentAt: Schema.String\n})\n\nexport type FortnoxEmulatorOutboxEntry = typeof FortnoxEmulatorOutboxEntry.Type\n\nconst Counter = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))\n\nconst Counters = Schema.Struct({\n /** Next RowId handed out; RowIds are regenerated on every row update. */\n nextRowId: Counter,\n /** Next DocumentNumber handed out by `POST /3/invoices`. */\n nextDocumentNumber: Counter\n})\n\n/** The whole emulator state (JSON-compatible; what `snapshot()` returns). */\nexport const FortnoxEmulatorStateSchema = Schema.Struct({\n company: FortnoxEmulatorCompany,\n customers: Schema.Array(FortnoxEmulatorCustomer),\n invoices: Schema.Array(FortnoxEmulatorInvoice),\n outbox: Schema.Array(FortnoxEmulatorOutboxEntry),\n counters: Counters,\n ...fortnoxReadStateFields\n})\n\n/**\n * The emulator state. The container is mutable (route handlers replace whole entity lists);\n * every entity is replaced, never edited in place. No route writes the read-only parts.\n */\nexport type FortnoxEmulatorState = {\n company: FortnoxEmulatorCompany\n customers: ReadonlyArray<FortnoxEmulatorCustomer>\n invoices: ReadonlyArray<FortnoxEmulatorInvoice>\n outbox: ReadonlyArray<FortnoxEmulatorOutboxEntry>\n counters: typeof Counters.Type\n} & FortnoxReadState\n\n/** A seeded invoice row: the writable row fields; totals and `VATCode` are derived. */\nexport const FortnoxEmulatorInvoiceRowSeed = Schema.Struct({\n RowId: Schema.optionalKey(Schema.Int),\n AccountNumber: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n ArticleNumber: Schema.optionalKey(Schema.String),\n CostCenter: Schema.optionalKey(Schema.String),\n DeliveredQuantity: Schema.optionalKey(Schema.String),\n Description: Schema.optionalKey(Schema.String),\n Discount: Schema.optionalKey(Schema.Finite),\n DiscountType: Schema.optionalKey(DiscountType),\n Price: Schema.optionalKey(Schema.Finite),\n Project: Schema.optionalKey(Schema.String),\n Unit: Schema.optionalKey(Schema.String),\n VAT: Schema.optionalKey(Schema.Finite)\n})\n\nexport type FortnoxEmulatorInvoiceRowSeed = typeof FortnoxEmulatorInvoiceRowSeed.Type\n\nconst { InvoiceRows: _invoiceRows, ...invoiceScalarFields } = invoiceFields\n\n/**\n * A seeded invoice: `DocumentNumber` and `CustomerNumber` are required; everything else has a\n * synthetic default. Totals (`Net`, `Gross`, `TotalVAT`, `Total`, `TotalToPay`) are always\n * computed from the rows; `Balance` defaults to `Total`.\n */\nexport const FortnoxEmulatorInvoiceSeed = Schema.Struct({\n ...Struct.mapOmit(invoiceScalarFields, ['DocumentNumber', 'CustomerNumber'], Schema.optionalKey),\n InvoiceRows: Schema.optionalKey(Schema.Array(FortnoxEmulatorInvoiceRowSeed))\n})\n\nexport type FortnoxEmulatorInvoiceSeed = typeof FortnoxEmulatorInvoiceSeed.Type\n\n/** A seeded customer: `CustomerNumber` and `Name` are required; `Country` follows `CountryCode`. */\nexport const FortnoxEmulatorCustomerSeed = Schema.Struct(\n Struct.mapOmit(customerFields, ['CustomerNumber', 'Name'], Schema.optionalKey)\n)\n\nexport type FortnoxEmulatorCustomerSeed = typeof FortnoxEmulatorCustomerSeed.Type\n\n/** Account-variance profiles for the default seed. */\nexport const FortnoxEmulatorProfile = Schema.Literals([\n 'default',\n 'empty-company',\n 'no-booked-invoices'\n])\n\nexport type FortnoxEmulatorProfile = typeof FortnoxEmulatorProfile.Type\n\n/**\n * A typed seed. Start from `profile` (default `'default'`, the fixture entities); `company`,\n * `customers`, `invoices`, and each read-only part (`articles`, `priceLists`, `prices`,\n * `costCenters`, `invoicePayments`, `supplierInvoicePayments`, `offers`, `printTemplates`,\n * `inboxFolders`, `inboxFiles`, `companySettings`, `lockedPeriod`, `predefinedAccounts`, `labels`,\n * `modesOfPayment`, `termsOfPayment`, `termsOfDelivery`, `waysOfDelivery`, `units`, `me`), when\n * given, replace that part of the profile. Parts that reference others (offers name customers,\n * invoice payments name invoices, ...) must stay consistent with them; replacing `customers` or\n * `invoices` without seeding `offers` or `invoicePayments` starts those empty.\n */\nexport const FortnoxEmulatorSeed = Schema.Struct({\n profile: Schema.optionalKey(FortnoxEmulatorProfile),\n company: Schema.optionalKey(FortnoxEmulatorCompany),\n customers: Schema.optionalKey(Schema.Array(FortnoxEmulatorCustomerSeed)),\n invoices: Schema.optionalKey(Schema.Array(FortnoxEmulatorInvoiceSeed)),\n ...fortnoxReadSeedFields\n})\n\nexport type FortnoxEmulatorSeed = typeof FortnoxEmulatorSeed.Type\n\nconst strict = { onExcessProperty: 'error' } as const\n\nconst decodeSeedInput = Schema.decodeUnknownResult(FortnoxEmulatorSeed, strict)\n\nconst decodeStateInput = Schema.decodeUnknownResult(FortnoxEmulatorStateSchema, strict)\n\nconst issueMessage = (issue: Schema.SchemaError['issue']): string =>\n new Schema.SchemaError(issue).message\n\n/** `CountryCode` to the Swedish country name Fortnox derives `Country` from (a small table). */\nexport const fortnoxEmulatorCountries = new Map([\n ['SE', 'Sverige'],\n ['NO', 'Norge'],\n ['DK', 'Danmark'],\n ['FI', 'Finland'],\n ['DE', 'Tyskland'],\n ['GB', 'Storbritannien'],\n ['US', 'USA']\n])\n\n/** VAT percent to Fortnox sales VAT code. */\nexport const fortnoxEmulatorVatCodes = new Map([\n [25, 'MP1'],\n [12, 'MP2'],\n [6, 'MP3'],\n [0, 'MF']\n])\n\n/** Row total: `Price × DeliveredQuantity`, less a percent (or amount) discount. */\nexport const rowTotal = (\n row: Pick<FortnoxEmulatorInvoiceRow, 'Price' | 'DeliveredQuantity' | 'Discount' | 'DiscountType'>\n): number => {\n const gross = row.Price * Number(row.DeliveredQuantity)\n\n return round2(\n row.DiscountType === 'AMOUNT' ? gross - row.Discount : (gross * (100 - row.Discount)) / 100\n )\n}\n\ntype RowInput = Pick<\n FortnoxEmulatorInvoiceRow,\n | 'RowId'\n | 'AccountNumber'\n | 'ArticleNumber'\n | 'CostCenter'\n | 'DeliveredQuantity'\n | 'Description'\n | 'Discount'\n | 'DiscountType'\n | 'Price'\n | 'Project'\n | 'Unit'\n | 'VAT'\n>\n\n/** A full row (fixture key order) with derived totals and VAT code. */\nexport const buildRow = (input: RowInput): FortnoxEmulatorInvoiceRow => {\n const total = rowTotal(input)\n\n return {\n AccountNumber: input.AccountNumber,\n ArticleNumber: input.ArticleNumber,\n ContributionPercent: '0',\n ContributionValue: '0',\n CostCenter: input.CostCenter,\n DeliveredQuantity: input.DeliveredQuantity,\n Description: input.Description,\n Discount: input.Discount,\n DiscountType: input.DiscountType,\n HouseWork: false,\n Price: input.Price,\n PriceExcludingVAT: input.Price,\n Project: input.Project,\n RowId: input.RowId,\n Total: total,\n TotalExcludingVAT: total,\n Unit: input.Unit,\n VAT: input.VAT,\n VATCode: fortnoxEmulatorVatCodes.get(input.VAT) ?? ''\n }\n}\n\n/** Defaults for a new row (no positional match). */\nexport const newRowDefaults: Omit<RowInput, 'RowId'> = {\n AccountNumber: 3001,\n ArticleNumber: '',\n CostCenter: '',\n DeliveredQuantity: '1.00',\n Description: '',\n Discount: 0,\n DiscountType: 'PERCENT',\n Price: 0,\n Project: '',\n Unit: '',\n VAT: 25\n}\n\n/** Fortnox-style quantity: two decimals (`\"2.00\"`). */\nexport const formatQuantity = (value: number): string => value.toFixed(2)\n\nexport type InvoiceTotals = Pick<\n FortnoxEmulatorInvoice,\n 'Net' | 'Gross' | 'TotalVAT' | 'Total' | 'TotalToPay'\n>\n\n/**\n * Invoice totals from the rows: `Net = Gross = Σ row totals`, `TotalVAT = Σ row total × VAT%`,\n * and `Total = TotalToPay = Net + TotalVAT` rounded to whole kronor (half up), matching the\n * synthetic row-discount fixture (1150 + 287.5 → 1438).\n */\nexport const invoiceTotals = (rows: ReadonlyArray<FortnoxEmulatorInvoiceRow>): InvoiceTotals => {\n const net = round2(rows.reduce((sum, row) => sum + row.Total, 0))\n const vat = round2(rows.reduce((sum, row) => sum + (row.Total * row.VAT) / 100, 0))\n const total = Math.round(net + vat)\n\n return { Net: net, Gross: net, TotalVAT: vat, Total: total, TotalToPay: total }\n}\n\n// Default entities. Fixture-derived: customer 1001 (empty-string fixture) and the invoice headers\n// of 101-105 (list, payment-filter, row-discount, and email fixtures). Where two fixtures disagree\n// the more specific one wins: invoice 103 (and its two rows) follows the row-discount fixture, not\n// the list fixture (its Balance, DueDate, InvoiceDate, and OCR differ there). Synthesized: customer\n// 1002, the rows of invoices 101, 102, 104, and 105 (chosen so their computed totals equal the\n// fixture totals), the company information (no fixture), and every default `customerFromSeed` and\n// `invoiceFromSeed` fill in for a field the seed omits.\n\nconst exampleCustomer: FortnoxEmulatorCustomerSeed = {\n CustomerNumber: '1001',\n Name: 'Example Customer AB',\n Active: true,\n Address1: 'Exempelgatan 1',\n Address2: '',\n City: 'Exempelstad',\n Comments: 'Synthetic note: invoice monthly by email.',\n CostCenter: '',\n CountryCode: 'SE',\n Currency: 'SEK',\n Email: 'billing@example.test',\n EmailInvoice: 'billing@example.test',\n OrganisationNumber: '000000-0000',\n OurReference: '',\n Phone1: '',\n Phone2: '',\n TermsOfPayment: '30',\n Type: 'COMPANY',\n VATNumber: '',\n VATType: 'SEVAT',\n YourReference: '',\n ZipCode: '000 00'\n}\n\nconst exampleTrading: FortnoxEmulatorCustomerSeed = {\n CustomerNumber: '1002',\n Name: 'Example Trading AB',\n Active: true,\n Address1: 'Exempelvägen 2',\n City: 'Exempelstad',\n Comments: '',\n CountryCode: 'SE',\n Currency: 'SEK',\n Email: 'accounts@example.test',\n EmailInvoice: 'accounts@example.test',\n OrganisationNumber: '000000-0001',\n TermsOfPayment: '30',\n Type: 'COMPANY',\n VATType: 'SEVAT',\n ZipCode: '000 01'\n}\n\nconst singleRow = (description: string, price: number): FortnoxEmulatorInvoiceRowSeed => ({\n AccountNumber: 3001,\n Description: description,\n DeliveredQuantity: '1.00',\n Price: price,\n VAT: 25,\n Discount: 0,\n DiscountType: 'PERCENT'\n})\n\nconst defaultInvoices: ReadonlyArray<FortnoxEmulatorInvoiceSeed> = [\n {\n DocumentNumber: '101',\n CustomerNumber: '1001',\n Balance: 0,\n Booked: true,\n DueDate: '2026-09-30',\n FinalPayDate: '2026-09-20',\n InvoiceDate: '2026-08-31',\n OCR: '10151',\n Sent: true,\n VoucherNumber: 12,\n VoucherSeries: 'B',\n VoucherYear: 3,\n InvoiceRows: [singleRow('Monthly service (synthetic)', 1000)]\n },\n {\n DocumentNumber: '102',\n CustomerNumber: '1002',\n Balance: 3750,\n Booked: true,\n DueDate: '2026-09-30',\n InvoiceDate: '2026-08-31',\n OCR: '10250',\n Sent: true,\n VoucherNumber: 13,\n VoucherSeries: 'B',\n VoucherYear: 3,\n InvoiceRows: [singleRow('Project delivery (synthetic)', 3000)]\n },\n {\n DocumentNumber: '103',\n CustomerNumber: '1001',\n Booked: false,\n DueDate: '2026-10-31',\n InvoiceDate: '2026-09-30',\n OCR: '10350',\n InvoiceRows: [\n {\n RowId: 1,\n AccountNumber: 3001,\n Description: 'Consulting hours (synthetic)',\n DeliveredQuantity: '2.00',\n Unit: 'h',\n Price: 500,\n VAT: 25,\n Discount: 5,\n DiscountType: 'PERCENT'\n },\n {\n RowId: 2,\n AccountNumber: 3001,\n Description: 'Travel (synthetic)',\n DeliveredQuantity: '1.00',\n Price: 250,\n VAT: 25,\n Discount: 0,\n DiscountType: 'PERCENT'\n }\n ]\n },\n {\n DocumentNumber: '104',\n CustomerNumber: '1001',\n Balance: 625,\n Booked: true,\n DueDate: '2026-10-31',\n InvoiceDate: '2026-09-30',\n VoucherNumber: 14,\n VoucherSeries: 'B',\n VoucherYear: 3,\n EmailInformation: {\n EmailAddressFrom: 'invoices@example.test',\n EmailAddressTo: 'billing@example.test',\n EmailAddressCC: '',\n EmailAddressBCC: '',\n EmailSubject: 'Invoice {no} from Example AB',\n EmailBody: 'Synthetic invoice email body.'\n },\n InvoiceRows: [singleRow('Support hours (synthetic)', 500)]\n },\n {\n DocumentNumber: '105',\n CustomerNumber: '1001',\n Booked: false,\n DueDate: '2026-09-15',\n InvoiceDate: '2026-08-16',\n InvoiceRows: [singleRow('Workshop (synthetic)', 1000)]\n }\n]\n\nconst defaultCompany: FortnoxEmulatorCompany = {\n CompanyName: 'Example AB',\n OrganizationNumber: '000000-0002',\n DatabaseNumber: 100001,\n Address: 'Exempelgatan 10',\n City: 'Exempelstad',\n ZipCode: '000 02',\n CountryCode: 'SE',\n VisitAddress: 'Exempelgatan 10',\n VisitCity: 'Exempelstad',\n VisitZipCode: '000 02',\n VisitCountryCode: 'SE'\n}\n\ntype ProfileEntities = {\n readonly company: FortnoxEmulatorCompany\n readonly customers: ReadonlyArray<FortnoxEmulatorCustomerSeed>\n readonly invoices: ReadonlyArray<FortnoxEmulatorInvoiceSeed>\n readonly reads: FortnoxReadEntities\n}\n\nconst unbooked = (invoice: FortnoxEmulatorInvoiceSeed): FortnoxEmulatorInvoiceSeed => {\n const { Balance: _balance, FinalPayDate: _finalPayDate, ...rest } = invoice\n\n return { ...rest, Booked: false, VoucherNumber: null, VoucherSeries: null, VoucherYear: null }\n}\n\nconst profileEntities = (profile: FortnoxEmulatorProfile): ProfileEntities => {\n switch (profile) {\n case 'default':\n return {\n company: defaultCompany,\n customers: [exampleCustomer, exampleTrading],\n invoices: defaultInvoices,\n reads: defaultReadEntities\n }\n case 'empty-company':\n return {\n company: defaultCompany,\n customers: [],\n invoices: [],\n reads: emptyCompanyReadEntities\n }\n case 'no-booked-invoices':\n // Payments follow booked invoices: with every invoice unbooked, there are none.\n return {\n company: defaultCompany,\n customers: [exampleCustomer, exampleTrading],\n invoices: defaultInvoices.map(unbooked),\n reads: { ...defaultReadEntities, invoicePayments: [] }\n }\n }\n}\n\nconst customerFromSeed = (seed: FortnoxEmulatorCustomerSeed): FortnoxEmulatorCustomer => {\n const countryCode = seed.CountryCode ?? 'SE'\n\n return {\n CustomerNumber: seed.CustomerNumber,\n Name: seed.Name,\n Active: seed.Active ?? true,\n Address1: seed.Address1 ?? '',\n Address2: seed.Address2 ?? '',\n City: seed.City ?? '',\n Comments: seed.Comments ?? '',\n CostCenter: seed.CostCenter ?? '',\n Country: seed.Country ?? fortnoxEmulatorCountries.get(countryCode) ?? '',\n CountryCode: countryCode,\n Currency: seed.Currency ?? 'SEK',\n Email: seed.Email ?? '',\n EmailInvoice: seed.EmailInvoice ?? '',\n OrganisationNumber: seed.OrganisationNumber ?? '',\n OurReference: seed.OurReference ?? '',\n Phone1: seed.Phone1 ?? '',\n Phone2: seed.Phone2 ?? '',\n TermsOfPayment: seed.TermsOfPayment ?? '30',\n Type: seed.Type ?? 'COMPANY',\n VATNumber: seed.VATNumber ?? '',\n VATType: seed.VATType ?? 'SEVAT',\n YourReference: seed.YourReference ?? '',\n ZipCode: seed.ZipCode ?? ''\n }\n}\n\n/** Default invoice email for a customer (the email fixture's sender, subject, and body). */\nexport const defaultEmailInformation = (\n customer: FortnoxEmulatorCustomer | undefined,\n company: FortnoxEmulatorCompany\n): FortnoxEmulatorInvoice['EmailInformation'] => ({\n EmailAddressFrom: 'invoices@example.test',\n EmailAddressTo: customer?.EmailInvoice ?? '',\n EmailAddressCC: '',\n EmailAddressBCC: '',\n EmailSubject: `Invoice {no} from ${company.CompanyName}`,\n EmailBody: 'Synthetic invoice email body.'\n})\n\nexport type RowIdSource = { next: number }\n\nconst rowFromSeed = (\n seed: FortnoxEmulatorInvoiceRowSeed,\n ids: RowIdSource\n): FortnoxEmulatorInvoiceRow =>\n buildRow({\n ...newRowDefaults,\n ...seed,\n DeliveredQuantity: formatQuantity(Number(seed.DeliveredQuantity ?? '1')),\n RowId: seed.RowId ?? ids.next++\n })\n\n/** Build a stored invoice from a seed; row ids come from `ids` unless the seed names them. */\nexport const invoiceFromSeed = (\n seed: FortnoxEmulatorInvoiceSeed,\n customer: FortnoxEmulatorCustomer | undefined,\n company: FortnoxEmulatorCompany,\n ids: RowIdSource\n): FortnoxEmulatorInvoice => {\n const rows = (seed.InvoiceRows ?? []).map(row => rowFromSeed(row, ids))\n const totals = invoiceTotals(rows)\n\n return {\n DocumentNumber: seed.DocumentNumber,\n CustomerNumber: seed.CustomerNumber,\n CustomerName: seed.CustomerName ?? customer?.Name ?? '',\n Balance: seed.Balance ?? totals.Total,\n Booked: seed.Booked ?? false,\n Cancelled: seed.Cancelled ?? false,\n Comments: seed.Comments ?? '',\n CostCenter: seed.CostCenter ?? '',\n Credit: seed.Credit ?? 'false',\n Currency: seed.Currency ?? customer?.Currency ?? 'SEK',\n CurrencyRate: seed.CurrencyRate ?? 1,\n CurrencyUnit: seed.CurrencyUnit ?? 1,\n DueDate: seed.DueDate ?? null,\n EmailInformation: seed.EmailInformation ?? defaultEmailInformation(customer, company),\n ExternalInvoiceReference1: seed.ExternalInvoiceReference1 ?? '',\n ExternalInvoiceReference2: seed.ExternalInvoiceReference2 ?? '',\n FinalPayDate: seed.FinalPayDate ?? null,\n Gross: totals.Gross,\n InvoiceDate: seed.InvoiceDate ?? '2026-09-30',\n InvoiceRows: rows,\n InvoiceType: seed.InvoiceType ?? 'INVOICE',\n Net: totals.Net,\n NotCompleted: seed.NotCompleted ?? false,\n NoxFinans: seed.NoxFinans ?? false,\n OCR: seed.OCR ?? '',\n OurReference: seed.OurReference ?? '',\n Project: seed.Project ?? '',\n Sent: seed.Sent ?? false,\n TermsOfPayment: seed.TermsOfPayment ?? customer?.TermsOfPayment ?? '30',\n Total: totals.Total,\n TotalToPay: totals.TotalToPay,\n TotalVAT: totals.TotalVAT,\n VoucherNumber: seed.VoucherNumber ?? null,\n VoucherSeries: seed.VoucherSeries ?? null,\n VoucherYear: seed.VoucherYear ?? null,\n WayOfDelivery: seed.WayOfDelivery ?? '',\n YourReference: seed.YourReference ?? ''\n }\n}\n\nconst quantityProblem = (rows: ReadonlyArray<FortnoxEmulatorInvoiceRowSeed>) =>\n rows.find(\n row => row.DeliveredQuantity !== undefined && !Number.isFinite(Number(row.DeliveredQuantity))\n )\n\n/** Integrity problems a decoded seed can still have (duplicates, dangling references). */\nconst seedProblem = (entities: ProfileEntities): string | undefined => {\n const customerNumbers = entities.customers.map(customer => customer.CustomerNumber)\n const documentNumbers = entities.invoices.map(invoice => invoice.DocumentNumber)\n\n const rowIds = entities.invoices.flatMap(invoice =>\n (invoice.InvoiceRows ?? []).flatMap(row => (row.RowId === undefined ? [] : [row.RowId]))\n )\n\n const duplicateCustomer = duplicate(customerNumbers)\n const duplicateInvoice = duplicate(documentNumbers)\n const duplicateRow = duplicate(rowIds)\n\n if (duplicateCustomer !== undefined) return `duplicate CustomerNumber ${duplicateCustomer}`\n\n if (duplicateInvoice !== undefined) return `duplicate DocumentNumber ${duplicateInvoice}`\n\n if (duplicateRow !== undefined) return `duplicate RowId ${duplicateRow}`\n\n const dangling = entities.invoices.find(\n invoice => !customerNumbers.includes(invoice.CustomerNumber)\n )\n\n if (dangling !== undefined) {\n return `invoice ${dangling.DocumentNumber} references missing customer ${dangling.CustomerNumber}`\n }\n\n const badQuantity = entities.invoices.find(\n invoice => quantityProblem(invoice.InvoiceRows ?? []) !== undefined\n )\n\n return badQuantity === undefined\n ? undefined\n : `invoice ${badQuantity.DocumentNumber} has a non-numeric DeliveredQuantity`\n}\n\nconst nextNumber = (numbers: ReadonlyArray<string>): number =>\n numbers.reduce((max, value) => {\n const parsed = Number(value)\n\n return Number.isSafeInteger(parsed) && parsed >= max ? parsed + 1 : max\n }, 1)\n\n/** Build the emulator state for a decoded seed; a string is an integrity problem. */\nconst stateFromSeed = (seed: FortnoxEmulatorSeed): FortnoxEmulatorState | string => {\n const {\n profile: profileName,\n company,\n customers: customerSeeds,\n invoices: invoiceSeeds,\n ...readSeeds\n } = seed\n\n const profile = profileEntities(profileName ?? 'default')\n\n const entities: ProfileEntities = {\n company: company ?? profile.company,\n customers: customerSeeds ?? profile.customers,\n invoices: invoiceSeeds ?? profile.invoices,\n // Profile offers and invoice payments reference profile customers and invoices; a seed that\n // replaces those without seeding the dependents starts with none, so it stays valid.\n reads: {\n ...profile.reads,\n offers: customerSeeds === undefined ? profile.reads.offers : [],\n invoicePayments: invoiceSeeds === undefined ? profile.reads.invoicePayments : [],\n ...readSeeds\n }\n }\n\n const problem = seedProblem(entities)\n\n if (problem !== undefined) {\n return problem\n }\n\n const customers = entities.customers\n .map(customerFromSeed)\n .sort((left, right) => compareNumbers(left.CustomerNumber, right.CustomerNumber))\n\n const explicitRowIds = entities.invoices.flatMap(invoice =>\n (invoice.InvoiceRows ?? []).flatMap(row => (row.RowId === undefined ? [] : [row.RowId]))\n )\n\n const ids: RowIdSource = { next: Math.max(0, ...explicitRowIds) + 1 }\n\n const invoices = entities.invoices\n .map(invoice =>\n invoiceFromSeed(\n invoice,\n customers.find(customer => customer.CustomerNumber === invoice.CustomerNumber),\n entities.company,\n ids\n )\n )\n .sort((left, right) => compareNumbers(left.DocumentNumber, right.DocumentNumber))\n\n const reads = buildReadState(entities.reads, {\n customers,\n invoiceNumbers: invoices.map(invoice => invoice.DocumentNumber)\n })\n\n if (Predicate.isString(reads)) return reads\n\n return {\n ...reads,\n company: entities.company,\n customers,\n invoices,\n outbox: [],\n counters: {\n nextRowId: ids.next,\n nextDocumentNumber: nextNumber(invoices.map(invoice => invoice.DocumentNumber))\n }\n }\n}\n\n/** Decode and build a seed; a string is the reason it is invalid. */\nexport const buildSeedState = (input: unknown): FortnoxEmulatorState | string => {\n const decoded = decodeSeedInput(input)\n\n return Result.isFailure(decoded)\n ? issueMessage(decoded.failure.issue)\n : stateFromSeed(decoded.success)\n}\n\n/** Decode a full state (a restored snapshot); a string is the reason it is invalid. */\nexport const decodeState = (input: unknown): FortnoxEmulatorState | string => {\n const decoded = decodeStateInput(input)\n\n if (Result.isFailure(decoded)) {\n return issueMessage(decoded.failure.issue)\n }\n\n return { ...decoded.success }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8BA,MAAM,eAAe,OAAO,SAAS,CAAC,WAAW,QAAQ,CAAC;AAE1D,MAAM,YAAY;CAChB,OAAO,OAAO;CACd,eAAe,OAAO,OAAO,OAAO,GAAG;CACvC,eAAe,OAAO;CACtB,qBAAqB,OAAO;CAC5B,mBAAmB,OAAO;CAC1B,YAAY,OAAO;CACnB,mBAAmB,OAAO;CAC1B,aAAa,OAAO;CACpB,UAAU,OAAO;CACjB;CACA,WAAW,OAAO;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IAC3B,aAAa,QAAQ,QAAQ,KAAK,IAClC,cAAc,QAAQ,OAAO;AACnC;;AAGA,MAAa,eAAe,UAAkD;CAC5E,MAAM,UAAU,iBAAiB,KAAK;CAEtC,IAAI,OAAO,UAAU,OAAO,GAC1B,OAAO,aAAa,QAAQ,QAAQ,KAAK;CAG3C,OAAO,EAAE,GAAG,QAAQ,QAAQ;AAC9B"}
|
|
1
|
+
{"version":3,"file":"state.mjs","names":[],"sources":["../../src/fortnox/state.ts"],"sourcesContent":["/**\n * Fortnox emulator state: the typed entities, the seed input, the default seed, and the\n * account-variance profiles (internal; re-exported by `src/fortnox.ts`).\n *\n * Entity shapes and the default entities follow the synthetic Fortnox conformance fixtures, copied\n * as data (the same customer and document numbers as `fortnoxConformanceFixtureSeeds`), never\n * imported from SDK code. Where no fixture records a value, the default is synthesized and says\n * so below: customer 1002, most invoice rows, and the company information have no fixture. The\n * read-only resources (articles, prices, offers, payments, the inbox, settings, registers, ...)\n * have no fixture at all; they live in `src/fortnox/read-state.ts`.\n *\n * @experimental\n */\nimport { Predicate, Result, Struct } from 'effect'\nimport * as Schema from 'effect/Schema'\nimport {\n buildReadState,\n compareNumbers,\n defaultReadEntities,\n duplicate,\n emptyCompanyReadEntities,\n fortnoxReadSeedFields,\n fortnoxReadStateFields,\n round2,\n type FortnoxReadEntities,\n type FortnoxReadState\n} from './read-state.ts'\n\nexport { compareNumbers, round2 } from './read-state.ts'\n\nconst DiscountType = Schema.Literals(['PERCENT', 'AMOUNT'])\n\nconst rowFields = {\n RowId: Schema.Int,\n AccountNumber: Schema.NullOr(Schema.Int),\n ArticleNumber: Schema.String,\n ContributionPercent: Schema.String,\n ContributionValue: Schema.String,\n CostCenter: Schema.String,\n DeliveredQuantity: Schema.String,\n Description: Schema.String,\n Discount: Schema.Finite,\n DiscountType,\n HouseWork: Schema.Boolean,\n Price: Schema.Finite,\n PriceExcludingVAT: Schema.Finite,\n Project: Schema.String,\n Total: Schema.Finite,\n TotalExcludingVAT: Schema.Finite,\n Unit: Schema.String,\n VAT: Schema.Finite,\n VATCode: Schema.String\n}\n\n/** A stored invoice row, in the single-invoice wire shape. Totals are derived. */\nexport const FortnoxEmulatorInvoiceRow = Schema.Struct(rowFields)\n\nexport type FortnoxEmulatorInvoiceRow = typeof FortnoxEmulatorInvoiceRow.Type\n\nconst EmailInformation = Schema.Struct({\n EmailAddressFrom: Schema.String,\n EmailAddressTo: Schema.String,\n EmailAddressCC: Schema.String,\n EmailAddressBCC: Schema.String,\n EmailSubject: Schema.String,\n EmailBody: Schema.String\n})\n\nconst invoiceFields = {\n DocumentNumber: Schema.String,\n CustomerNumber: Schema.String,\n CustomerName: Schema.String,\n Balance: Schema.Finite,\n Booked: Schema.Boolean,\n Cancelled: Schema.Boolean,\n Comments: Schema.String,\n CostCenter: Schema.String,\n Credit: Schema.String,\n Currency: Schema.String,\n CurrencyRate: Schema.Finite,\n CurrencyUnit: Schema.Finite,\n DueDate: Schema.NullOr(Schema.String),\n EmailInformation,\n ExternalInvoiceReference1: Schema.String,\n ExternalInvoiceReference2: Schema.String,\n FinalPayDate: Schema.NullOr(Schema.String),\n Gross: Schema.Finite,\n InvoiceDate: Schema.String,\n InvoiceRows: Schema.Array(FortnoxEmulatorInvoiceRow),\n InvoiceType: Schema.String,\n Net: Schema.Finite,\n NotCompleted: Schema.Boolean,\n NoxFinans: Schema.Boolean,\n OCR: Schema.String,\n OurReference: Schema.String,\n Project: Schema.String,\n Remarks: Schema.String,\n Sent: Schema.Boolean,\n TermsOfPayment: Schema.String,\n Total: Schema.Finite,\n TotalToPay: Schema.Finite,\n TotalVAT: Schema.Finite,\n VoucherNumber: Schema.NullOr(Schema.Int),\n VoucherSeries: Schema.NullOr(Schema.String),\n VoucherYear: Schema.NullOr(Schema.Int),\n WayOfDelivery: Schema.String,\n YourReference: Schema.String\n}\n\n/** A stored customer invoice with its rows. */\nexport const FortnoxEmulatorInvoice = Schema.Struct(invoiceFields)\n\nexport type FortnoxEmulatorInvoice = typeof FortnoxEmulatorInvoice.Type\n\nconst customerFields = {\n CustomerNumber: Schema.String,\n Name: Schema.String,\n Active: Schema.Boolean,\n Address1: Schema.String,\n Address2: Schema.String,\n City: Schema.String,\n Comments: Schema.String,\n CostCenter: Schema.String,\n Country: Schema.String,\n CountryCode: Schema.String,\n Currency: Schema.String,\n Email: Schema.String,\n EmailInvoice: Schema.String,\n OrganisationNumber: Schema.String,\n OurReference: Schema.String,\n Phone1: Schema.String,\n Phone2: Schema.String,\n TermsOfPayment: Schema.String,\n Type: Schema.String,\n VATNumber: Schema.String,\n VATType: Schema.String,\n YourReference: Schema.String,\n ZipCode: Schema.String\n}\n\n/** A stored customer. `Country` is read-only (derived from `CountryCode`). */\nexport const FortnoxEmulatorCustomer = Schema.Struct(customerFields)\n\nexport type FortnoxEmulatorCustomer = typeof FortnoxEmulatorCustomer.Type\n\nconst companyFields = {\n CompanyName: Schema.String,\n OrganizationNumber: Schema.String,\n DatabaseNumber: Schema.Int,\n Address: Schema.String,\n City: Schema.String,\n ZipCode: Schema.String,\n CountryCode: Schema.String,\n VisitAddress: Schema.String,\n VisitCity: Schema.String,\n VisitZipCode: Schema.String,\n VisitCountryCode: Schema.String\n}\n\n/** The company the credential belongs to (`GET /3/companyinformation`). */\nexport const FortnoxEmulatorCompany = Schema.Struct(companyFields)\n\nexport type FortnoxEmulatorCompany = typeof FortnoxEmulatorCompany.Type\n\n/** A recorded (never delivered) invoice email. */\nexport const FortnoxEmulatorOutboxEntry = Schema.Struct({\n DocumentNumber: Schema.String,\n EmailAddressTo: Schema.String,\n EmailAddressCC: Schema.String,\n EmailAddressBCC: Schema.String,\n EmailSubject: Schema.String,\n /** ISO timestamp from the emulator clock. */\n sentAt: Schema.String\n})\n\nexport type FortnoxEmulatorOutboxEntry = typeof FortnoxEmulatorOutboxEntry.Type\n\nconst Counter = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))\n\nconst Counters = Schema.Struct({\n /** Next RowId handed out; RowIds are regenerated on every row update. */\n nextRowId: Counter,\n /** Next DocumentNumber handed out by `POST /3/invoices`. */\n nextDocumentNumber: Counter\n})\n\n/** The whole emulator state (JSON-compatible; what `snapshot()` returns). */\nexport const FortnoxEmulatorStateSchema = Schema.Struct({\n company: FortnoxEmulatorCompany,\n customers: Schema.Array(FortnoxEmulatorCustomer),\n invoices: Schema.Array(FortnoxEmulatorInvoice),\n outbox: Schema.Array(FortnoxEmulatorOutboxEntry),\n counters: Counters,\n ...fortnoxReadStateFields\n})\n\n/**\n * The emulator state. The container is mutable (route handlers replace whole entity lists);\n * every entity is replaced, never edited in place. No route writes the read-only parts.\n */\nexport type FortnoxEmulatorState = {\n company: FortnoxEmulatorCompany\n customers: ReadonlyArray<FortnoxEmulatorCustomer>\n invoices: ReadonlyArray<FortnoxEmulatorInvoice>\n outbox: ReadonlyArray<FortnoxEmulatorOutboxEntry>\n counters: typeof Counters.Type\n} & FortnoxReadState\n\n/** A seeded invoice row: the writable row fields; totals and `VATCode` are derived. */\nexport const FortnoxEmulatorInvoiceRowSeed = Schema.Struct({\n RowId: Schema.optionalKey(Schema.Int),\n AccountNumber: Schema.optionalKey(Schema.NullOr(Schema.Int)),\n ArticleNumber: Schema.optionalKey(Schema.String),\n CostCenter: Schema.optionalKey(Schema.String),\n DeliveredQuantity: Schema.optionalKey(Schema.String),\n Description: Schema.optionalKey(Schema.String),\n Discount: Schema.optionalKey(Schema.Finite),\n DiscountType: Schema.optionalKey(DiscountType),\n Price: Schema.optionalKey(Schema.Finite),\n Project: Schema.optionalKey(Schema.String),\n Unit: Schema.optionalKey(Schema.String),\n VAT: Schema.optionalKey(Schema.Finite)\n})\n\nexport type FortnoxEmulatorInvoiceRowSeed = typeof FortnoxEmulatorInvoiceRowSeed.Type\n\nconst { InvoiceRows: _invoiceRows, ...invoiceScalarFields } = invoiceFields\n\n/**\n * A seeded invoice: `DocumentNumber` and `CustomerNumber` are required; everything else has a\n * synthetic default. Totals (`Net`, `Gross`, `TotalVAT`, `Total`, `TotalToPay`) are always\n * computed from the rows; `Balance` defaults to `Total`.\n */\nexport const FortnoxEmulatorInvoiceSeed = Schema.Struct({\n ...Struct.mapOmit(invoiceScalarFields, ['DocumentNumber', 'CustomerNumber'], Schema.optionalKey),\n InvoiceRows: Schema.optionalKey(Schema.Array(FortnoxEmulatorInvoiceRowSeed))\n})\n\nexport type FortnoxEmulatorInvoiceSeed = typeof FortnoxEmulatorInvoiceSeed.Type\n\n/** A seeded customer: `CustomerNumber` and `Name` are required; `Country` follows `CountryCode`. */\nexport const FortnoxEmulatorCustomerSeed = Schema.Struct(\n Struct.mapOmit(customerFields, ['CustomerNumber', 'Name'], Schema.optionalKey)\n)\n\nexport type FortnoxEmulatorCustomerSeed = typeof FortnoxEmulatorCustomerSeed.Type\n\n/** Account-variance profiles for the default seed. */\nexport const FortnoxEmulatorProfile = Schema.Literals([\n 'default',\n 'empty-company',\n 'no-booked-invoices'\n])\n\nexport type FortnoxEmulatorProfile = typeof FortnoxEmulatorProfile.Type\n\n/**\n * A typed seed. Start from `profile` (default `'default'`, the fixture entities); `company`,\n * `customers`, `invoices`, and each read-only part (`articles`, `priceLists`, `prices`,\n * `costCenters`, `invoicePayments`, `supplierInvoicePayments`, `offers`, `printTemplates`,\n * `inboxFolders`, `inboxFiles`, `companySettings`, `lockedPeriod`, `predefinedAccounts`, `labels`,\n * `modesOfPayment`, `termsOfPayment`, `termsOfDelivery`, `waysOfDelivery`, `units`, `me`), when\n * given, replace that part of the profile. Parts that reference others (offers name customers,\n * invoice payments name invoices, ...) must stay consistent with them; replacing `customers` or\n * `invoices` without seeding `offers` or `invoicePayments` starts those empty.\n */\nexport const FortnoxEmulatorSeed = Schema.Struct({\n profile: Schema.optionalKey(FortnoxEmulatorProfile),\n company: Schema.optionalKey(FortnoxEmulatorCompany),\n customers: Schema.optionalKey(Schema.Array(FortnoxEmulatorCustomerSeed)),\n invoices: Schema.optionalKey(Schema.Array(FortnoxEmulatorInvoiceSeed)),\n ...fortnoxReadSeedFields\n})\n\nexport type FortnoxEmulatorSeed = typeof FortnoxEmulatorSeed.Type\n\nconst strict = { onExcessProperty: 'error' } as const\n\nconst decodeSeedInput = Schema.decodeUnknownResult(FortnoxEmulatorSeed, strict)\n\nconst decodeStateInput = Schema.decodeUnknownResult(FortnoxEmulatorStateSchema, strict)\n\nconst issueMessage = (issue: Schema.SchemaError['issue']): string =>\n new Schema.SchemaError(issue).message\n\n/** `CountryCode` to the Swedish country name Fortnox derives `Country` from (a small table). */\nexport const fortnoxEmulatorCountries = new Map([\n ['SE', 'Sverige'],\n ['NO', 'Norge'],\n ['DK', 'Danmark'],\n ['FI', 'Finland'],\n ['DE', 'Tyskland'],\n ['GB', 'Storbritannien'],\n ['US', 'USA']\n])\n\n/** VAT percent to Fortnox sales VAT code. */\nexport const fortnoxEmulatorVatCodes = new Map([\n [25, 'MP1'],\n [12, 'MP2'],\n [6, 'MP3'],\n [0, 'MF']\n])\n\n/** Row total: `Price × DeliveredQuantity`, less a percent (or amount) discount. */\nexport const rowTotal = (\n row: Pick<FortnoxEmulatorInvoiceRow, 'Price' | 'DeliveredQuantity' | 'Discount' | 'DiscountType'>\n): number => {\n const gross = row.Price * Number(row.DeliveredQuantity)\n\n return round2(\n row.DiscountType === 'AMOUNT' ? gross - row.Discount : (gross * (100 - row.Discount)) / 100\n )\n}\n\ntype RowInput = Pick<\n FortnoxEmulatorInvoiceRow,\n | 'RowId'\n | 'AccountNumber'\n | 'ArticleNumber'\n | 'CostCenter'\n | 'DeliveredQuantity'\n | 'Description'\n | 'Discount'\n | 'DiscountType'\n | 'Price'\n | 'Project'\n | 'Unit'\n | 'VAT'\n>\n\n/** A full row (fixture key order) with derived totals and VAT code. */\nexport const buildRow = (input: RowInput): FortnoxEmulatorInvoiceRow => {\n const total = rowTotal(input)\n\n return {\n AccountNumber: input.AccountNumber,\n ArticleNumber: input.ArticleNumber,\n ContributionPercent: '0',\n ContributionValue: '0',\n CostCenter: input.CostCenter,\n DeliveredQuantity: input.DeliveredQuantity,\n Description: input.Description,\n Discount: input.Discount,\n DiscountType: input.DiscountType,\n HouseWork: false,\n Price: input.Price,\n PriceExcludingVAT: input.Price,\n Project: input.Project,\n RowId: input.RowId,\n Total: total,\n TotalExcludingVAT: total,\n Unit: input.Unit,\n VAT: input.VAT,\n VATCode: fortnoxEmulatorVatCodes.get(input.VAT) ?? ''\n }\n}\n\n/** Defaults for a new row (no positional match). */\nexport const newRowDefaults: Omit<RowInput, 'RowId'> = {\n AccountNumber: 3001,\n ArticleNumber: '',\n CostCenter: '',\n DeliveredQuantity: '1.00',\n Description: '',\n Discount: 0,\n DiscountType: 'PERCENT',\n Price: 0,\n Project: '',\n Unit: '',\n VAT: 25\n}\n\n/** Fortnox-style quantity: two decimals (`\"2.00\"`). */\nexport const formatQuantity = (value: number): string => value.toFixed(2)\n\nexport type InvoiceTotals = Pick<\n FortnoxEmulatorInvoice,\n 'Net' | 'Gross' | 'TotalVAT' | 'Total' | 'TotalToPay'\n>\n\n/**\n * Invoice totals from the rows: `Net = Gross = Σ row totals`, `TotalVAT = Σ row total × VAT%`,\n * and `Total = TotalToPay = Net + TotalVAT` rounded to whole kronor (half up), matching the\n * synthetic row-discount fixture (1150 + 287.5 → 1438).\n */\nexport const invoiceTotals = (rows: ReadonlyArray<FortnoxEmulatorInvoiceRow>): InvoiceTotals => {\n const net = round2(rows.reduce((sum, row) => sum + row.Total, 0))\n const vat = round2(rows.reduce((sum, row) => sum + (row.Total * row.VAT) / 100, 0))\n const total = Math.round(net + vat)\n\n return { Net: net, Gross: net, TotalVAT: vat, Total: total, TotalToPay: total }\n}\n\n// Default entities. Fixture-derived: customer 1001 (empty-string fixture) and the invoice headers\n// of 101-105 (list, payment-filter, row-discount, and email fixtures). Where two fixtures disagree\n// the more specific one wins: invoice 103 (and its two rows) follows the row-discount fixture, not\n// the list fixture (its Balance, DueDate, InvoiceDate, and OCR differ there). Synthesized: customer\n// 1002, the rows of invoices 101, 102, 104, and 105 (chosen so their computed totals equal the\n// fixture totals), the company information (no fixture), and every default `customerFromSeed` and\n// `invoiceFromSeed` fill in for a field the seed omits.\n\nconst exampleCustomer: FortnoxEmulatorCustomerSeed = {\n CustomerNumber: '1001',\n Name: 'Example Customer AB',\n Active: true,\n Address1: 'Exempelgatan 1',\n Address2: '',\n City: 'Exempelstad',\n Comments: 'Synthetic note: invoice monthly by email.',\n CostCenter: '',\n CountryCode: 'SE',\n Currency: 'SEK',\n Email: 'billing@example.test',\n EmailInvoice: 'billing@example.test',\n OrganisationNumber: '000000-0000',\n OurReference: '',\n Phone1: '',\n Phone2: '',\n TermsOfPayment: '30',\n Type: 'COMPANY',\n VATNumber: '',\n VATType: 'SEVAT',\n YourReference: '',\n ZipCode: '000 00'\n}\n\nconst exampleTrading: FortnoxEmulatorCustomerSeed = {\n CustomerNumber: '1002',\n Name: 'Example Trading AB',\n Active: true,\n Address1: 'Exempelvägen 2',\n City: 'Exempelstad',\n Comments: '',\n CountryCode: 'SE',\n Currency: 'SEK',\n Email: 'accounts@example.test',\n EmailInvoice: 'accounts@example.test',\n OrganisationNumber: '000000-0001',\n TermsOfPayment: '30',\n Type: 'COMPANY',\n VATType: 'SEVAT',\n ZipCode: '000 01'\n}\n\nconst singleRow = (description: string, price: number): FortnoxEmulatorInvoiceRowSeed => ({\n AccountNumber: 3001,\n Description: description,\n DeliveredQuantity: '1.00',\n Price: price,\n VAT: 25,\n Discount: 0,\n DiscountType: 'PERCENT'\n})\n\nconst defaultInvoices: ReadonlyArray<FortnoxEmulatorInvoiceSeed> = [\n {\n DocumentNumber: '101',\n CustomerNumber: '1001',\n Balance: 0,\n Booked: true,\n DueDate: '2026-09-30',\n FinalPayDate: '2026-09-20',\n InvoiceDate: '2026-08-31',\n OCR: '10151',\n Sent: true,\n VoucherNumber: 12,\n VoucherSeries: 'B',\n VoucherYear: 3,\n InvoiceRows: [singleRow('Monthly service (synthetic)', 1000)]\n },\n {\n DocumentNumber: '102',\n CustomerNumber: '1002',\n Balance: 3750,\n Booked: true,\n DueDate: '2026-09-30',\n InvoiceDate: '2026-08-31',\n OCR: '10250',\n Sent: true,\n VoucherNumber: 13,\n VoucherSeries: 'B',\n VoucherYear: 3,\n InvoiceRows: [singleRow('Project delivery (synthetic)', 3000)]\n },\n {\n DocumentNumber: '103',\n CustomerNumber: '1001',\n Booked: false,\n DueDate: '2026-10-31',\n InvoiceDate: '2026-09-30',\n OCR: '10350',\n InvoiceRows: [\n {\n RowId: 1,\n AccountNumber: 3001,\n Description: 'Consulting hours (synthetic)',\n DeliveredQuantity: '2.00',\n Unit: 'h',\n Price: 500,\n VAT: 25,\n Discount: 5,\n DiscountType: 'PERCENT'\n },\n {\n RowId: 2,\n AccountNumber: 3001,\n Description: 'Travel (synthetic)',\n DeliveredQuantity: '1.00',\n Price: 250,\n VAT: 25,\n Discount: 0,\n DiscountType: 'PERCENT'\n }\n ]\n },\n {\n DocumentNumber: '104',\n CustomerNumber: '1001',\n Balance: 625,\n Booked: true,\n DueDate: '2026-10-31',\n InvoiceDate: '2026-09-30',\n VoucherNumber: 14,\n VoucherSeries: 'B',\n VoucherYear: 3,\n EmailInformation: {\n EmailAddressFrom: 'invoices@example.test',\n EmailAddressTo: 'billing@example.test',\n EmailAddressCC: '',\n EmailAddressBCC: '',\n EmailSubject: 'Invoice {no} from Example AB',\n EmailBody: 'Synthetic invoice email body.'\n },\n InvoiceRows: [singleRow('Support hours (synthetic)', 500)]\n },\n {\n DocumentNumber: '105',\n CustomerNumber: '1001',\n Booked: false,\n DueDate: '2026-09-15',\n InvoiceDate: '2026-08-16',\n InvoiceRows: [singleRow('Workshop (synthetic)', 1000)]\n }\n]\n\nconst defaultCompany: FortnoxEmulatorCompany = {\n CompanyName: 'Example AB',\n OrganizationNumber: '000000-0002',\n DatabaseNumber: 100001,\n Address: 'Exempelgatan 10',\n City: 'Exempelstad',\n ZipCode: '000 02',\n CountryCode: 'SE',\n VisitAddress: 'Exempelgatan 10',\n VisitCity: 'Exempelstad',\n VisitZipCode: '000 02',\n VisitCountryCode: 'SE'\n}\n\ntype ProfileEntities = {\n readonly company: FortnoxEmulatorCompany\n readonly customers: ReadonlyArray<FortnoxEmulatorCustomerSeed>\n readonly invoices: ReadonlyArray<FortnoxEmulatorInvoiceSeed>\n readonly reads: FortnoxReadEntities\n}\n\nconst unbooked = (invoice: FortnoxEmulatorInvoiceSeed): FortnoxEmulatorInvoiceSeed => {\n const { Balance: _balance, FinalPayDate: _finalPayDate, ...rest } = invoice\n\n return { ...rest, Booked: false, VoucherNumber: null, VoucherSeries: null, VoucherYear: null }\n}\n\nconst profileEntities = (profile: FortnoxEmulatorProfile): ProfileEntities => {\n switch (profile) {\n case 'default':\n return {\n company: defaultCompany,\n customers: [exampleCustomer, exampleTrading],\n invoices: defaultInvoices,\n reads: defaultReadEntities\n }\n case 'empty-company':\n return {\n company: defaultCompany,\n customers: [],\n invoices: [],\n reads: emptyCompanyReadEntities\n }\n case 'no-booked-invoices':\n // Payments follow booked invoices: with every invoice unbooked, there are none.\n return {\n company: defaultCompany,\n customers: [exampleCustomer, exampleTrading],\n invoices: defaultInvoices.map(unbooked),\n reads: { ...defaultReadEntities, invoicePayments: [] }\n }\n }\n}\n\nconst customerFromSeed = (seed: FortnoxEmulatorCustomerSeed): FortnoxEmulatorCustomer => {\n const countryCode = seed.CountryCode ?? 'SE'\n\n return {\n CustomerNumber: seed.CustomerNumber,\n Name: seed.Name,\n Active: seed.Active ?? true,\n Address1: seed.Address1 ?? '',\n Address2: seed.Address2 ?? '',\n City: seed.City ?? '',\n Comments: seed.Comments ?? '',\n CostCenter: seed.CostCenter ?? '',\n Country: seed.Country ?? fortnoxEmulatorCountries.get(countryCode) ?? '',\n CountryCode: countryCode,\n Currency: seed.Currency ?? 'SEK',\n Email: seed.Email ?? '',\n EmailInvoice: seed.EmailInvoice ?? '',\n OrganisationNumber: seed.OrganisationNumber ?? '',\n OurReference: seed.OurReference ?? '',\n Phone1: seed.Phone1 ?? '',\n Phone2: seed.Phone2 ?? '',\n TermsOfPayment: seed.TermsOfPayment ?? '30',\n Type: seed.Type ?? 'COMPANY',\n VATNumber: seed.VATNumber ?? '',\n VATType: seed.VATType ?? 'SEVAT',\n YourReference: seed.YourReference ?? '',\n ZipCode: seed.ZipCode ?? ''\n }\n}\n\n/** Default invoice email for a customer (the email fixture's sender, subject, and body). */\nexport const defaultEmailInformation = (\n customer: FortnoxEmulatorCustomer | undefined,\n company: FortnoxEmulatorCompany\n): FortnoxEmulatorInvoice['EmailInformation'] => ({\n EmailAddressFrom: 'invoices@example.test',\n EmailAddressTo: customer?.EmailInvoice ?? '',\n EmailAddressCC: '',\n EmailAddressBCC: '',\n EmailSubject: `Invoice {no} from ${company.CompanyName}`,\n EmailBody: 'Synthetic invoice email body.'\n})\n\nexport type RowIdSource = { next: number }\n\nconst rowFromSeed = (\n seed: FortnoxEmulatorInvoiceRowSeed,\n ids: RowIdSource\n): FortnoxEmulatorInvoiceRow =>\n buildRow({\n ...newRowDefaults,\n ...seed,\n DeliveredQuantity: formatQuantity(Number(seed.DeliveredQuantity ?? '1')),\n RowId: seed.RowId ?? ids.next++\n })\n\n/** Build a stored invoice from a seed; row ids come from `ids` unless the seed names them. */\nexport const invoiceFromSeed = (\n seed: FortnoxEmulatorInvoiceSeed,\n customer: FortnoxEmulatorCustomer | undefined,\n company: FortnoxEmulatorCompany,\n ids: RowIdSource\n): FortnoxEmulatorInvoice => {\n const rows = (seed.InvoiceRows ?? []).map(row => rowFromSeed(row, ids))\n const totals = invoiceTotals(rows)\n\n return {\n DocumentNumber: seed.DocumentNumber,\n CustomerNumber: seed.CustomerNumber,\n CustomerName: seed.CustomerName ?? customer?.Name ?? '',\n Balance: seed.Balance ?? totals.Total,\n Booked: seed.Booked ?? false,\n Cancelled: seed.Cancelled ?? false,\n Comments: seed.Comments ?? '',\n CostCenter: seed.CostCenter ?? '',\n Credit: seed.Credit ?? 'false',\n Currency: seed.Currency ?? customer?.Currency ?? 'SEK',\n CurrencyRate: seed.CurrencyRate ?? 1,\n CurrencyUnit: seed.CurrencyUnit ?? 1,\n DueDate: seed.DueDate ?? null,\n EmailInformation: seed.EmailInformation ?? defaultEmailInformation(customer, company),\n ExternalInvoiceReference1: seed.ExternalInvoiceReference1 ?? '',\n ExternalInvoiceReference2: seed.ExternalInvoiceReference2 ?? '',\n FinalPayDate: seed.FinalPayDate ?? null,\n Gross: totals.Gross,\n InvoiceDate: seed.InvoiceDate ?? '2026-09-30',\n InvoiceRows: rows,\n InvoiceType: seed.InvoiceType ?? 'INVOICE',\n Net: totals.Net,\n NotCompleted: seed.NotCompleted ?? false,\n NoxFinans: seed.NoxFinans ?? false,\n OCR: seed.OCR ?? '',\n OurReference: seed.OurReference ?? '',\n Project: seed.Project ?? '',\n Remarks: seed.Remarks ?? '',\n Sent: seed.Sent ?? false,\n TermsOfPayment: seed.TermsOfPayment ?? customer?.TermsOfPayment ?? '30',\n Total: totals.Total,\n TotalToPay: totals.TotalToPay,\n TotalVAT: totals.TotalVAT,\n VoucherNumber: seed.VoucherNumber ?? null,\n VoucherSeries: seed.VoucherSeries ?? null,\n VoucherYear: seed.VoucherYear ?? null,\n WayOfDelivery: seed.WayOfDelivery ?? '',\n YourReference: seed.YourReference ?? ''\n }\n}\n\nconst quantityProblem = (rows: ReadonlyArray<FortnoxEmulatorInvoiceRowSeed>) =>\n rows.find(\n row => row.DeliveredQuantity !== undefined && !Number.isFinite(Number(row.DeliveredQuantity))\n )\n\n/** Integrity problems a decoded seed can still have (duplicates, dangling references). */\nconst seedProblem = (entities: ProfileEntities): string | undefined => {\n const customerNumbers = entities.customers.map(customer => customer.CustomerNumber)\n const documentNumbers = entities.invoices.map(invoice => invoice.DocumentNumber)\n\n const rowIds = entities.invoices.flatMap(invoice =>\n (invoice.InvoiceRows ?? []).flatMap(row => (row.RowId === undefined ? [] : [row.RowId]))\n )\n\n const duplicateCustomer = duplicate(customerNumbers)\n const duplicateInvoice = duplicate(documentNumbers)\n const duplicateRow = duplicate(rowIds)\n\n if (duplicateCustomer !== undefined) return `duplicate CustomerNumber ${duplicateCustomer}`\n\n if (duplicateInvoice !== undefined) return `duplicate DocumentNumber ${duplicateInvoice}`\n\n if (duplicateRow !== undefined) return `duplicate RowId ${duplicateRow}`\n\n const dangling = entities.invoices.find(\n invoice => !customerNumbers.includes(invoice.CustomerNumber)\n )\n\n if (dangling !== undefined) {\n return `invoice ${dangling.DocumentNumber} references missing customer ${dangling.CustomerNumber}`\n }\n\n const badQuantity = entities.invoices.find(\n invoice => quantityProblem(invoice.InvoiceRows ?? []) !== undefined\n )\n\n return badQuantity === undefined\n ? undefined\n : `invoice ${badQuantity.DocumentNumber} has a non-numeric DeliveredQuantity`\n}\n\nconst nextNumber = (numbers: ReadonlyArray<string>): number =>\n numbers.reduce((max, value) => {\n const parsed = Number(value)\n\n return Number.isSafeInteger(parsed) && parsed >= max ? parsed + 1 : max\n }, 1)\n\n/** Build the emulator state for a decoded seed; a string is an integrity problem. */\nconst stateFromSeed = (seed: FortnoxEmulatorSeed): FortnoxEmulatorState | string => {\n const {\n profile: profileName,\n company,\n customers: customerSeeds,\n invoices: invoiceSeeds,\n ...readSeeds\n } = seed\n\n const profile = profileEntities(profileName ?? 'default')\n\n const entities: ProfileEntities = {\n company: company ?? profile.company,\n customers: customerSeeds ?? profile.customers,\n invoices: invoiceSeeds ?? profile.invoices,\n // Profile offers and invoice payments reference profile customers and invoices; a seed that\n // replaces those without seeding the dependents starts with none, so it stays valid.\n reads: {\n ...profile.reads,\n offers: customerSeeds === undefined ? profile.reads.offers : [],\n invoicePayments: invoiceSeeds === undefined ? profile.reads.invoicePayments : [],\n ...readSeeds\n }\n }\n\n const problem = seedProblem(entities)\n\n if (problem !== undefined) {\n return problem\n }\n\n const customers = entities.customers\n .map(customerFromSeed)\n .sort((left, right) => compareNumbers(left.CustomerNumber, right.CustomerNumber))\n\n const explicitRowIds = entities.invoices.flatMap(invoice =>\n (invoice.InvoiceRows ?? []).flatMap(row => (row.RowId === undefined ? [] : [row.RowId]))\n )\n\n const ids: RowIdSource = { next: Math.max(0, ...explicitRowIds) + 1 }\n\n const invoices = entities.invoices\n .map(invoice =>\n invoiceFromSeed(\n invoice,\n customers.find(customer => customer.CustomerNumber === invoice.CustomerNumber),\n entities.company,\n ids\n )\n )\n .sort((left, right) => compareNumbers(left.DocumentNumber, right.DocumentNumber))\n\n const reads = buildReadState(entities.reads, {\n customers,\n invoiceNumbers: invoices.map(invoice => invoice.DocumentNumber)\n })\n\n if (Predicate.isString(reads)) return reads\n\n return {\n ...reads,\n company: entities.company,\n customers,\n invoices,\n outbox: [],\n counters: {\n nextRowId: ids.next,\n nextDocumentNumber: nextNumber(invoices.map(invoice => invoice.DocumentNumber))\n }\n }\n}\n\n/** Decode and build a seed; a string is the reason it is invalid. */\nexport const buildSeedState = (input: unknown): FortnoxEmulatorState | string => {\n const decoded = decodeSeedInput(input)\n\n return Result.isFailure(decoded)\n ? issueMessage(decoded.failure.issue)\n : stateFromSeed(decoded.success)\n}\n\n/** Decode a full state (a restored snapshot); a string is the reason it is invalid. */\nexport const decodeState = (input: unknown): FortnoxEmulatorState | string => {\n const decoded = decodeStateInput(input)\n\n if (Result.isFailure(decoded)) {\n return issueMessage(decoded.failure.issue)\n }\n\n return { ...decoded.success }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8BA,MAAM,eAAe,OAAO,SAAS,CAAC,WAAW,QAAQ,CAAC;AAE1D,MAAM,YAAY;CAChB,OAAO,OAAO;CACd,eAAe,OAAO,OAAO,OAAO,GAAG;CACvC,eAAe,OAAO;CACtB,qBAAqB,OAAO;CAC5B,mBAAmB,OAAO;CAC1B,YAAY,OAAO;CACnB,mBAAmB,OAAO;CAC1B,aAAa,OAAO;CACpB,UAAU,OAAO;CACjB;CACA,WAAW,OAAO;CAClB,OAAO,OAAO;CACd,mBAAmB,OAAO;CAC1B,SAAS,OAAO;CAChB,OAAO,OAAO;CACd,mBAAmB,OAAO;CAC1B,MAAM,OAAO;CACb,KAAK,OAAO;CACZ,SAAS,OAAO;AAClB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iBAAiB,KAAK;CAEtC,IAAI,OAAO,UAAU,OAAO,GAC1B,OAAO,aAAa,QAAQ,QAAQ,KAAK;CAG3C,OAAO,EAAE,GAAG,QAAQ,QAAQ;AAC9B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk-sdk/emulators",
|
|
3
|
-
"version": "0.1.0-canary.
|
|
3
|
+
"version": "0.1.0-canary.125",
|
|
4
4
|
"description": "Experimental emulators for outside services: an Effect HttpClient router, Vercel AI Gateway, OpenAI Chat Completions, Anthropic Messages, OpenAI Responses (Codex, xAI Grok), and OpenCode Go fetch-handler emulators with subscription-usage routes, fixture-driven fake EmailClient and R2 (R2Presigner, R2ObjectClient) backends, stateful Fortnox, Microsoft Graph, Dropbox, Notion, Todoist, Telegram, GitHub, Google (Gmail, Calendar, Drive), LinkedIn search (Exa, Enrich Layer), and synthetic and Afloat MCP emulators, and a loopback Node server.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -143,10 +143,10 @@
|
|
|
143
143
|
"effect": "4.1.2"
|
|
144
144
|
},
|
|
145
145
|
"devDependencies": {
|
|
146
|
-
"@yolk-sdk/
|
|
147
|
-
"@yolk-sdk/
|
|
148
|
-
"@yolk-sdk/connectors": "^0.1.0-canary.
|
|
149
|
-
"@yolk-sdk/mcp": "^0.1.0-canary.
|
|
146
|
+
"@yolk-sdk/conformance": "^0.1.0-canary.125",
|
|
147
|
+
"@yolk-sdk/agent": "^0.1.0-canary.125",
|
|
148
|
+
"@yolk-sdk/connectors": "^0.1.0-canary.125",
|
|
149
|
+
"@yolk-sdk/mcp": "^0.1.0-canary.125"
|
|
150
150
|
},
|
|
151
151
|
"scripts": {
|
|
152
152
|
"build": "tsdown",
|
package/src/fortnox/api.ts
CHANGED
|
@@ -724,7 +724,7 @@ const mergeRows = (
|
|
|
724
724
|
return rows
|
|
725
725
|
}
|
|
726
726
|
|
|
727
|
-
const invoiceTextFields = ['Comments', 'OurReference', 'YourReference', 'OCR'] as const
|
|
727
|
+
const invoiceTextFields = ['Comments', 'Remarks', 'OurReference', 'YourReference', 'OCR'] as const
|
|
728
728
|
|
|
729
729
|
type InvoiceTextField = (typeof invoiceTextFields)[number]
|
|
730
730
|
|
package/src/fortnox/state.ts
CHANGED
|
@@ -94,6 +94,7 @@ const invoiceFields = {
|
|
|
94
94
|
OCR: Schema.String,
|
|
95
95
|
OurReference: Schema.String,
|
|
96
96
|
Project: Schema.String,
|
|
97
|
+
Remarks: Schema.String,
|
|
97
98
|
Sent: Schema.Boolean,
|
|
98
99
|
TermsOfPayment: Schema.String,
|
|
99
100
|
Total: Schema.Finite,
|
|
@@ -691,6 +692,7 @@ export const invoiceFromSeed = (
|
|
|
691
692
|
OCR: seed.OCR ?? '',
|
|
692
693
|
OurReference: seed.OurReference ?? '',
|
|
693
694
|
Project: seed.Project ?? '',
|
|
695
|
+
Remarks: seed.Remarks ?? '',
|
|
694
696
|
Sent: seed.Sent ?? false,
|
|
695
697
|
TermsOfPayment: seed.TermsOfPayment ?? customer?.TermsOfPayment ?? '30',
|
|
696
698
|
Total: totals.Total,
|