@yolk-sdk/emulators 0.1.0-canary.106 → 0.1.0-canary.108

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/README.md CHANGED
@@ -15,7 +15,8 @@ for the host R2 ports (`R2Presigner`, `R2ObjectClient`).
15
15
  Emulators never import other `@yolk-sdk/*` code: their wire shapes follow conformance fixtures
16
16
  (verified recordings for the Gateway, synthetic placeholders elsewhere), and each emulated route
17
17
  names the conformance cases behind it. The Fortnox emulator is a stateful stand-in for the Fortnox
18
- `/3` API that reproduces the observed quirks the Fortnox conformance cases claim, the Microsoft
18
+ `/3` API that reproduces the observed quirks the Fortnox conformance cases claim (and answers the
19
+ connector's other reads with unverified synthetic shapes), the Microsoft
19
20
  Graph emulator is a stateful stand-in for the Outlook, calendar, and OneDrive routes the Microsoft
20
21
  conformance cases use. The Dropbox, Notion, Todoist, Telegram, GitHub, Google, LinkedIn search, and
21
22
  MCP emulators are stateful, fixture-only stand-ins for the Dropbox RPC and upload routes, the Notion
@@ -683,9 +684,35 @@ Routes (base path `/3`, JSON bodies, `Authorization: Bearer <non-empty>`; a miss
683
684
  | `GET /3/invoices/{DocumentNumber}/preview` | A small synthetic PDF (`application/pdf`); does not mark the invoice sent |
684
685
  | `GET /3/invoices/{DocumentNumber}/email` | Marks the invoice `Sent` and records an outbox entry in state; never sends anything |
685
686
 
686
- `GET /3/companyinformation` and `GET /3/customers` have no recorded fixture: they cite no
687
- conformance case ids, use minimal shapes named after the connector's read fields, and are
688
- unverified, uncited read routes (the evidence check warns about them).
687
+ Read-only resources (`GET` only; the connector's article, price, cost center, payment, offer,
688
+ print, inbox, settings, and profile reads, and the host-only offer preview and inbox file
689
+ downloads):
690
+
691
+ | Route | Behavior |
692
+ | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
693
+ | `GET /3/articles`, `GET /3/articles/{ArticleNumber}` | `filter` (`active`/`inactive`), search (`articlenumber`, `description`, `ean`, `suppliernumber`, `manufacturer`, `manufacturerarticlenumber`); list rows send numeric strings; `SalesPrice` is the PreSelected price list's base price |
694
+ | `GET /3/pricelists`, `GET /3/pricelists/{Code}` | Search `code`, `comments` |
695
+ | `GET /3/prices/sublist/{PriceList}/{ArticleNumber}`, `GET /3/prices/{PriceList}/{ArticleNumber}/{FromQuantity}` | One article's tiers in a price list (rows without `Percent`/`Date`); one price. A `sublist` path always reaches the sublist route |
696
+ | `GET /3/costcenters`, `GET /3/costcenters/{Code}` | Inactive ones included |
697
+ | `GET /3/invoicepayments`, `GET /3/supplierinvoicepayments` (and `/{Number}`) | Search `invoicenumber`; customer payments carry their held invoice's snapshot; voucher fields and `ModeOfPaymentAccount` as numeric strings |
698
+ | `GET /3/offers`, `GET /3/offers/{DocumentNumber}`, `GET /3/offers/{DocumentNumber}/preview` | Filters, search, `fromdate`/`todate`; list rows have no rows; totals from the rows; the preview is the synthetic PDF and marks nothing sent |
699
+ | `GET /3/printtemplates` | `type` `invoice` (default), `offer`, or `order`; no `MetaInformation` |
700
+ | `GET /3/inbox`, `GET /3/inbox/{Id}` | A folder Id (`root`, the nine static folders, subfolders) answers `{ Folder }`; a file Id answers its bytes (`application/octet-stream`) |
701
+ | `GET /3/settings/company`, `GET /3/settings/lockedperiod` | `{ CompanySettings }`, `{ LockedPeriod }` |
702
+ | `GET /3/predefinedaccounts` (and `/{Name}`), `GET /3/labels` | Unpaginated, no `MetaInformation`; the single envelope is `PreDefinedAccount` |
703
+ | `GET /3/modesofpayments`, `termsofpayments`, `termsofdeliveries`, `wayofdeliveries`, `units` (and `/{Code}`) | `page`/`limit`, `MetaInformation`; a mode of payment's `AccountNumber` is a string in list rows |
704
+ | `GET /3/me` | `{ Me }` |
705
+
706
+ `GET /3/companyinformation`, `GET /3/customers`, and every read-only route above have no recorded
707
+ fixture: they cite no conformance case ids, use minimal synthetic shapes named after the
708
+ connector's read fields (in the wire types the connector's schemas accept), and are unverified,
709
+ uncited read routes (the evidence check warns about them). Their writes (`POST`, `PUT`, `DELETE`,
710
+ and side-effecting `GET`s such as `/offers/{DocumentNumber}/email` and `/print`) are not emulated
711
+ and fail closed with the 404 below: emulating a connector write needs a conformance case and its
712
+ live run first. Lists of `/3/offers` filter on the stored fields (unverified: `expired` is an
713
+ `ExpireDate` before the injectable `now`, `completed` follows `NotCompleted`, `ordercreated`
714
+ follows `OrderReference` other than `"0"`). A key the state does not hold answers 404
715
+ `ErrorInformation` code `2999011`.
689
716
 
690
717
  Anything else fails closed with a 404 `ErrorInformation` (ledgered); unsupported query parameters
691
718
  (checked per route before it runs, so a rejected write writes nothing), unknown filters, unknown or
@@ -699,8 +726,10 @@ written when the customer it inherits from (a seed can hold anything) carries a
699
726
  `TermsOfPayment` outside the subset, or when its
700
727
  computed due date is not a representable `YYYY-MM-DD` date. An empty string still keeps the
701
728
  stored value. The list filter
702
- `lastmodified` (the connector's `lastModified` input) is not emulated: the emulator tracks no
703
- modification times and answers it with a 400 saying so. Errors use the lowercase `{ ErrorInformation: { error, message, code } }` of the rejection
729
+ `lastmodified` (the connector's `lastModified` input) is not emulated on any list: the emulator
730
+ tracks no modification times and answers it with a 400 saying so. Customer and invoice writes do
731
+ not emulate article, cost center, or project references (a 400), even though the read-only routes
732
+ hold articles and cost centers. Errors use the lowercase `{ ErrorInformation: { error, message, code } }` of the rejection
704
733
  fixture; `fortnoxEmulatorErrorCodes` lists the codes (the `2999xxx` ones are synthetic).
705
734
 
706
735
  Observed quirks (`fortnoxEmulatorQuirks`, each tied to its conformance case):
@@ -719,11 +748,22 @@ Observed quirks (`fortnoxEmulatorQuirks`, each tied to its conformance case):
719
748
  invalid fields answer 400 `ErrorInformation`.
720
749
  5. **Read-only `Country`**: sending a customer `Country` answers 400 (no conformance case yet).
721
750
 
722
- State and seeds: company information, customers, and invoices with rows, plus the email outbox.
723
- The default seed is the synthetic fixture entities, with the same customer and document numbers as
724
- `fortnoxConformanceFixtureSeeds`, so the Fortnox conformance cases run unmodified. Pass
725
- `seed: { profile?, company?, customers?, invoices? }` (typed; entity lists replace the profile's)
726
- with profiles `'default'`, `'empty-company'`, or `'no-booked-invoices'`. `reset()` restores the
751
+ State and seeds: company information, customers, and invoices with rows, plus the email outbox,
752
+ and the read-only resources. The default seed is the synthetic fixture entities, with the same
753
+ customer and document numbers as `fortnoxConformanceFixtureSeeds`, so the Fortnox conformance
754
+ cases run unmodified, plus small synthetic read-only data (Example AB, `example.test`) that stays
755
+ consistent with them. Pass `seed: { profile?, company?, customers?, invoices?, ... }` (typed; each
756
+ given part replaces the profile's) with profiles `'default'`, `'empty-company'` (no business data;
757
+ the settings, registers, print templates, user, and inbox folders stay), or
758
+ `'no-booked-invoices'` (no invoice payments either). The read-only seed keys are `articles`,
759
+ `priceLists`, `prices`, `costCenters`, `invoicePayments`, `supplierInvoicePayments`, `offers`,
760
+ `printTemplates`, `inboxFolders`, `inboxFiles` (bytes as `ContentBase64`), `companySettings`,
761
+ `lockedPeriod`, `predefinedAccounts`, `labels`, `modesOfPayment`, `termsOfPayment`,
762
+ `termsOfDelivery`, `waysOfDelivery`, `units`, and `me`. A seed with a duplicate key or a dangling
763
+ reference is rejected (offers name customers, invoice payments name invoices, prices name price
764
+ lists and articles, ...); replacing `customers` or `invoices` without seeding `offers` or
765
+ `invoicePayments` starts those empty. Supplier invoices are not emulated: a supplier invoice payment stores its own
766
+ snapshot fields. Offers are VAT-exclusive only (`VATIncluded: false`). `reset()` restores the
727
767
  current seed and clears the ledger and faults; `seed(next)` replaces the state and becomes what
728
768
  `reset()` restores; `snapshot()` returns a deep copy of the state.
729
769
 
@@ -1,59 +1,9 @@
1
- import { EmulatorRouteEvidence } from "../route-evidence.mjs";
2
1
  import { FortnoxEmulatorState } from "./state.mjs";
2
+ import { FortnoxApiEnv, FortnoxApiRoute, FortnoxEmulatorQuirks, errorInformation, fortnoxEmulatorBasePath, fortnoxEmulatorErrorCodes } from "./route-kit.mjs";
3
3
  import * as Schema from "effect/Schema";
4
4
  import { Hono } from "@emulators/core";
5
5
 
6
6
  //#region src/fortnox/api.d.ts
7
- /**
8
- * Drill knobs: each flips one observed quirk to the documented-but-wrong behavior, ONLY to prove
9
- * that the conformance cases catch a disagreement. Defaults follow the observed behavior.
10
- */
11
- type FortnoxEmulatorQuirks = {
12
- /** `false`: a positionally matched row that omits `Discount`/`DiscountType` resets them. */readonly stickyRowDiscount?: boolean; /** `true`: a customer update with `""` clears the stored string instead of keeping it. */
13
- readonly emptyStringClears?: boolean; /** `true`: `unpaid`/`unpaidoverdue`/`fullypaid` also match unbooked invoices. */
14
- readonly paymentFiltersIncludeUnbooked?: boolean;
15
- };
16
- type FortnoxApiEnv = {
17
- /** Clock in epoch milliseconds (the `unpaidoverdue` "today", new invoice dates, the outbox). */readonly now: () => number; /** Origin used in `@url` links, for example `https://api.fortnox.se`. */
18
- readonly linkOrigin: string;
19
- readonly quirks: Required<FortnoxEmulatorQuirks>;
20
- };
21
- /**
22
- * `ErrorInformation` codes the emulator answers with. The two customer-not-found codes are copied
23
- * from the rejection fixture; the `2999xxx` codes are synthetic emulator codes.
24
- */
25
- declare const fortnoxEmulatorErrorCodes: {
26
- readonly customerNotFound: 2000204;
27
- readonly invoiceCustomerNotFound: 2000433;
28
- readonly unauthorized: 2999001;
29
- readonly invalidBody: 2999002;
30
- readonly invalidField: 2999003;
31
- readonly readOnlyField: 2999004;
32
- readonly notEditable: 2999005;
33
- readonly invoiceNotFound: 2999006;
34
- readonly unknownRoute: 2999007;
35
- readonly unsupportedQuery: 2999008;
36
- readonly rateLimited: 2999009;
37
- readonly upstreamError: 2999010;
38
- };
39
- /** Fortnox API base path. */
40
- declare const fortnoxEmulatorBasePath = "/3";
41
- /** A Fortnox `ErrorInformation` response with the lowercase fields of the rejection fixture. */
42
- declare const errorInformation: (status: number, code: number, message: string) => Response;
43
- type RouteRequest = {
44
- readonly params: Readonly<Record<string, string>>;
45
- readonly query: URLSearchParams; /** Parsed JSON body; `undefined` when absent or not JSON. */
46
- readonly body: Schema.Json | undefined;
47
- };
48
- type RouteHandler = (state: FortnoxEmulatorState, request: RouteRequest, env: FortnoxApiEnv) => Response;
49
- type FortnoxApiRoute = EmulatorRouteEvidence & {
50
- /**
51
- * Query parameters the route emulates; any other key answers 400 before the handler runs, so
52
- * a rejected request never writes. Empty by default.
53
- */
54
- readonly queryKeys: ReadonlyArray<string>;
55
- readonly handler: RouteHandler;
56
- };
57
7
  /** The route table: evidence plus handler. `fortnoxEmulatorRoutes` is its evidence part. */
58
8
  declare const fortnoxApiRoutes: ReadonlyArray<FortnoxApiRoute>;
59
9
  /** One observed Fortnox quirk the emulator implements, and the case that claims it. */
@@ -88,5 +38,5 @@ type FortnoxFaultDecision = (jobId: string | undefined) => boolean;
88
38
  */
89
39
  declare const registerFortnoxApi: (app: Hono, state: FortnoxEmulatorState, env: FortnoxApiEnv, decideFault: FortnoxFaultDecision) => void;
90
40
  //#endregion
91
- export { FortnoxApiEnv, FortnoxEmulatorQuirk, FortnoxEmulatorQuirks, FortnoxFaultDecision, errorInformation, fortnoxApiRoutes, fortnoxEmulatorBasePath, fortnoxEmulatorErrorCodes, fortnoxEmulatorQuirks, matchFortnoxRoute, parseJsonText, registerFortnoxApi };
41
+ export { type FortnoxApiEnv, FortnoxEmulatorQuirk, type FortnoxEmulatorQuirks, FortnoxFaultDecision, errorInformation, fortnoxApiRoutes, fortnoxEmulatorBasePath, fortnoxEmulatorErrorCodes, fortnoxEmulatorQuirks, matchFortnoxRoute, parseJsonText, registerFortnoxApi };
92
42
  //# sourceMappingURL=api.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.mts","names":[],"sources":["../../src/fortnox/api.ts"],"mappings":";;;;;;;AA0CwC;AAGxC;;KATY,qBAAA;EAce,qGAZhB,iBAAA,YAWA;EAAA,SATA,iBAAA,YAUQ;EAAA,SARR,6BAAA;AAAA;AAAA,KAGC,aAAA;EAYC,yGAVF,GAAA;WAEA,UAAA;EAAA,SACA,MAAA,EAAQ,QAAQ,CAAC,qBAAA;AAAA;;;;;cAOf,yBAAA;EAAA;;;;;;;;;;;;;;cAgBA,uBAAA;;cASA,gBAAA,GAAoB,MAAA,UAAgB,IAAA,UAAc,OAAA,aAAkB,QACR;AAAA,KA6CpE,YAAA;EAAA,SACM,MAAA,EAAQ,QAAA,CAAS,MAAA;EAAA,SACjB,KAAA,EAAO,eAAA,EA/CuD;EAAA,SAiD9D,IAAA,EAAM,MAAA,CAAO,IAAA;AAAA;AAAA,KAMnB,YAAA,IACH,KAAA,EAAO,oBAAA,EACP,OAAA,EAAS,YAAA,EACT,GAAA,EAAK,aAAA,KACF,QAAA;AAAA,KAEA,eAAA,GAAkB,qBAAA;EAfK;;;;EAAA,SAoBjB,SAAA,EAAW,aAAA;EAAA,SACX,OAAA,EAAS,YAAA;AAAA;;cAqgCP,gBAAA,EAAkB,aAAa,CAAC,eAAA;;KA2BjC,oBAAA;EAAA,SACD,EAAA,UAnjCM;EAAA,SAqjCN,KAAA,UArjCiB;EAAA,SAujCjB,MAAA,sBAjjCN;EAAA,SAmjCM,IAAA,QAAY,qBAAqB;EAAA,SACjC,OAAA;AAAA;;cAIE,qBAAA,EAAuB,aAAa,CAAC,oBAAA;;cA0DrC,iBAAA,GAAqB,MAAA,UAAgB,IAAA,aAAe,eAAe;;cAQnE,aAAA,GAAiB,IAAA,aAAe,MAAA,CAAO,IAAI;;;;;;KAc5C,oBAAA,IAAwB,KAAyB;;AApoChD;AAAA;;;;;;;;cAgpCA,kBAAA,GACX,GAAA,EAAK,IAAA,EACL,KAAA,EAAO,oBAAA,EACP,GAAA,EAAK,aAAA,EACL,WAAA,EAAa,oBAAA"}
1
+ {"version":3,"file":"api.d.mts","names":[],"sources":["../../src/fortnox/api.ts"],"mappings":";;;;;;;cAq/Ba,gBAAA,EAAkB,aAAa,CAAC,eAAA;;KA4BjC,oBAAA;EAAA,SACD,EAAA,UAMY;EAAA,SAJZ,KAAA,UAKO;EAAA,SAHP,MAAA,sBAOE;EAAA,SALF,IAAA,QAAY,qBAAqB;EAAA,SACjC,OAAA;AAAA;AAI2D;AAAA,cAAzD,qBAAA,EAAuB,aAAa,CAAC,oBAAA;;cA0DrC,iBAAA,GAAqB,MAAA,UAAgB,IAAA,aAAe,eAAe;;cAQnE,aAAA,GAAiB,IAAA,aAAe,MAAA,CAAO,IAAI;;;;AARwB;AAQhF;KAcY,oBAAA,IAAwB,KAAyB;;;;;;;AAdL;AAcxD;;;cAYa,kBAAA,GACX,GAAA,EAAK,IAAA,EACL,KAAA,EAAO,oBAAA,EACP,GAAA,EAAK,aAAA,EACL,WAAA,EAAa,oBAAA"}
@@ -1,58 +1,25 @@
1
1
  import { answeredOutsideCore, handlerFailedResponse } from "../emulator-http.mjs";
2
- import { buildRow, compareNumbers, defaultEmailInformation, formatQuantity, fortnoxEmulatorCountries, fortnoxEmulatorVatCodes, invoiceFromSeed, invoiceTotals, newRowDefaults } from "./state.mjs";
2
+ import { connectorRoute, contains, dateRange, errorInformation, fortnoxEmulatorBasePath, fortnoxEmulatorErrorCodes, invalidField, isIsoDate, isJsonObject, jsonResponse, matchesSearch, paginate, pdfResponse, resourceUrl, today, unsupportedQuery } from "./route-kit.mjs";
3
+ import { compareNumbers } from "./read-state.mjs";
4
+ import { fortnoxReadRoutes } from "./read-api.mjs";
5
+ import { buildRow, defaultEmailInformation, formatQuantity, fortnoxEmulatorCountries, fortnoxEmulatorVatCodes, invoiceFromSeed, invoiceTotals, newRowDefaults } from "./state.mjs";
3
6
  import { Predicate, Result } from "effect";
4
7
  import * as Schema from "effect/Schema";
5
8
  //#region src/fortnox/api.ts
6
- /**
7
- * `ErrorInformation` codes the emulator answers with. The two customer-not-found codes are copied
8
- * from the rejection fixture; the `2999xxx` codes are synthetic emulator codes.
9
- */
10
- const fortnoxEmulatorErrorCodes = {
11
- customerNotFound: 2000204,
12
- invoiceCustomerNotFound: 2000433,
13
- unauthorized: 2999001,
14
- invalidBody: 2999002,
15
- invalidField: 2999003,
16
- readOnlyField: 2999004,
17
- notEditable: 2999005,
18
- invoiceNotFound: 2999006,
19
- unknownRoute: 2999007,
20
- unsupportedQuery: 2999008,
21
- rateLimited: 2999009,
22
- upstreamError: 2999010
23
- };
24
- /** Fortnox API base path. */
25
- const fortnoxEmulatorBasePath = "/3";
26
- const jsonResponse = (status, body) => new Response(JSON.stringify(body), {
27
- status,
28
- headers: { "content-type": "application/json" }
29
- });
30
- /** A Fortnox `ErrorInformation` response with the lowercase fields of the rejection fixture. */
31
- const errorInformation = (status, code, message) => jsonResponse(status, { ErrorInformation: {
32
- error: 1,
33
- message,
34
- code
35
- } });
36
9
  const codes = fortnoxEmulatorErrorCodes;
37
10
  const customerNotFound = () => errorInformation(404, codes.customerNotFound, "Synthetic placeholder: customer not found.");
38
11
  const invoiceCustomerNotFound = () => errorInformation(400, codes.invoiceCustomerNotFound, "Synthetic placeholder: customer not found.");
39
12
  const invoiceNotFound = () => errorInformation(404, codes.invoiceNotFound, "Synthetic: invoice not found.");
40
13
  const invalidBody = (message) => errorInformation(400, codes.invalidBody, `Synthetic: ${message}`);
41
- const invalidField = (message) => errorInformation(400, codes.invalidField, `Synthetic: ${message}`);
42
14
  const noReferencedEntity = (kind, value) => invalidField(`${kind} ${value} does not exist in the emulated company.`);
15
+ /**
16
+ * Customer and invoice writes do not emulate references to articles, cost centers, or projects
17
+ * (Fortnox would derive row and booking values from them); the read-only article and cost center
18
+ * routes do not change that.
19
+ */
20
+ const unsupportedReference = (kind, value) => invalidField(`${kind} ${value}: references on customer and invoice writes are not emulated.`);
43
21
  const readOnlyField = (message) => errorInformation(400, codes.readOnlyField, `Synthetic: ${message}`);
44
22
  const notEditable = (message) => errorInformation(400, codes.notEditable, `Synthetic: ${message}`);
45
- const unsupportedQuery = (key) => errorInformation(400, codes.unsupportedQuery, key === "lastmodified" ? "Synthetic: query parameter lastmodified is not emulated (the emulator does not track modification times)." : `Synthetic: query parameter ${key} is not emulated.`);
46
- const previewPdfBase64 = "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9LaWRzIFtdIC9Db3VudCAwID4+CmVuZG9iagp0cmFpbGVyCjw8IC9Sb290IDEgMCBSID4+CiUlRU9GCg==";
47
- const previewPdfBytes = () => Uint8Array.from(atob(previewPdfBase64), (character) => character.charCodeAt(0));
48
- const isJsonObject = (value) => value !== void 0 && value !== null && Predicate.isObject(value) && !Array.isArray(value);
49
- const isoDatePattern = /^\d{4}-\d{2}-\d{2}$/;
50
- /** A real `YYYY-MM-DD` calendar date (no JavaScript rollover such as `2026-02-30`). */
51
- const isIsoDate = (value) => {
52
- const parsed = Date.parse(`${value}T00:00:00.000Z`);
53
- return isoDatePattern.test(value) && !Number.isNaN(parsed) && new Date(parsed).toISOString().slice(0, 10) === value;
54
- };
55
- const today = (env) => new Date(env.now()).toISOString().slice(0, 10);
56
23
  /** `date` plus `days`, or `undefined` when the result is not a representable `YYYY-MM-DD` date. */
57
24
  const addDays = (date, days) => {
58
25
  const result = new Date(Date.parse(`${date}T00:00:00.000Z`) + days * 24 * 60 * 60 * 1e3);
@@ -80,8 +47,8 @@ const unsupportedTermsOfPayment = (value) => invalidField(`TermsOfPayment ${valu
80
47
  const emulatedCustomerVatTypes = ["SEVAT"];
81
48
  const emulatedCustomerTypes = ["COMPANY", "PRIVATE"];
82
49
  const unsupportedVatType = (value) => invalidField(`VATType ${value} is not emulated (supported: ${emulatedCustomerVatTypes.join(", ")}).`);
83
- const customerUrl = (env, customerNumber) => `${env.linkOrigin}/3/customers/${encodeURIComponent(customerNumber)}`;
84
- const invoiceUrl = (env, documentNumber) => `${env.linkOrigin}/3/invoices/${encodeURIComponent(documentNumber)}`;
50
+ const customerUrl = (env, customerNumber) => resourceUrl(env, "customers", customerNumber);
51
+ const invoiceUrl = (env, documentNumber) => resourceUrl(env, "invoices", documentNumber);
85
52
  const renderCustomer = (env, customer) => ({
86
53
  "@url": customerUrl(env, customer.CustomerNumber),
87
54
  ...customer
@@ -153,31 +120,6 @@ const unsupportedQueryKey = (query, allowed) => {
153
120
  const key = [...query.keys()].find((candidate) => !allowed.includes(candidate));
154
121
  return key === void 0 ? void 0 : unsupportedQuery(key);
155
122
  };
156
- const positiveInt = (query, key, fallback, maximum) => {
157
- const raw = query.get(key);
158
- if (raw === null) return fallback;
159
- const value = Number(raw);
160
- return /^\d+$/.test(raw) && value >= 1 && value <= maximum ? value : invalidField(`query parameter ${key} must be an integer from 1 to ${maximum}.`);
161
- };
162
- /** Fortnox default and maximum page sizes. */
163
- const defaultLimit = 100;
164
- const maxLimit = 500;
165
- /** One page plus `MetaInformation` (`@TotalPages` is at least 1, as the empty-list fixture shows). */
166
- const paginate = (items, query) => {
167
- const limit = positiveInt(query, "limit", defaultLimit, maxLimit);
168
- const page = positiveInt(query, "page", 1, Number.MAX_SAFE_INTEGER);
169
- if (limit instanceof Response) return limit;
170
- if (page instanceof Response) return page;
171
- return {
172
- items: items.slice((page - 1) * limit, page * limit),
173
- meta: {
174
- "@CurrentPage": page,
175
- "@TotalPages": Math.max(1, Math.ceil(items.length / limit)),
176
- "@TotalResources": items.length
177
- }
178
- };
179
- };
180
- const contains = (value, search) => value.toLowerCase().includes(search.toLowerCase());
181
123
  const customerSearch = {
182
124
  customernumber: (customer, value) => customer.CustomerNumber === value,
183
125
  name: (customer, value) => contains(customer.Name, value),
@@ -195,10 +137,7 @@ const customerListQueryKeys = [
195
137
  const listCustomers = (state, { query }, env) => {
196
138
  const filter = query.get("filter");
197
139
  if (filter !== null && filter !== "active" && filter !== "inactive") return invalidField(`unknown customer filter ${filter}.`);
198
- const page = paginate(state.customers.filter((customer) => (filter === null || customer.Active === (filter === "active")) && Object.entries(customerSearch).every(([key, matches]) => {
199
- const value = query.get(key);
200
- return value === null || matches(customer, value);
201
- })), query);
140
+ const page = paginate(state.customers.filter((customer) => (filter === null || customer.Active === (filter === "active")) && matchesSearch(customer, query, customerSearch)), query);
202
141
  if (page instanceof Response) return page;
203
142
  return jsonResponse(200, {
204
143
  Customers: page.items.map((customer) => renderCustomerRow(env, customer)),
@@ -241,13 +180,13 @@ const writableCustomerStrings = [
241
180
  const isCustomerStringField = (key) => writableCustomerStrings.some((field) => field === key);
242
181
  /**
243
182
  * Why a customer field value is not emulated (fail closed), or `undefined`. The emulated company
244
- * has only SEK, no cost centers, terms of payment in whole days (0–365), `VATType` `SEVAT`, and
245
- * `Type` `COMPANY` or `PRIVATE`.
183
+ * has only SEK, terms of payment in whole days (0–365), `VATType` `SEVAT`, and `Type` `COMPANY` or
184
+ * `PRIVATE`; cost center references are not emulated on writes.
246
185
  */
247
186
  const unsupportedCustomerValue = (key, value) => {
248
187
  switch (key) {
249
188
  case "Currency": return value === "SEK" ? void 0 : noReferencedEntity("Currency", value);
250
- case "CostCenter": return value === "" ? void 0 : noReferencedEntity("CostCenter", value);
189
+ case "CostCenter": return value === "" ? void 0 : unsupportedReference("CostCenter", value);
251
190
  case "TermsOfPayment": return termsOfPaymentDays(value) === void 0 ? unsupportedTermsOfPayment(value) : void 0;
252
191
  case "VATType": return emulatedCustomerVatTypes.includes(value) ? void 0 : unsupportedVatType(value);
253
192
  case "Type": return emulatedCustomerTypes.includes(value) ? void 0 : invalidField(`Type ${value} is not emulated (supported: ${emulatedCustomerTypes.join(", ")}).`);
@@ -342,13 +281,9 @@ const invoiceListQueryKeys = [
342
281
  const listInvoices = (state, { query }, env) => {
343
282
  const filter = query.get("filter");
344
283
  if (filter !== null && !isInvoiceFilter(filter)) return invalidField(`unknown invoice filter ${filter}.`);
345
- const fromDate = query.get("fromdate");
346
- const toDate = query.get("todate");
347
- for (const [key, value] of [["fromdate", fromDate], ["todate", toDate]]) if (value !== null && !isIsoDate(value)) return invalidField(`query parameter ${key} must be a YYYY-MM-DD date.`);
348
- const page = paginate(state.invoices.filter((invoice) => (filter === null || matchesInvoiceFilter(invoice, filter, env)) && (fromDate === null || invoice.InvoiceDate >= fromDate) && (toDate === null || invoice.InvoiceDate <= toDate) && Object.entries(invoiceSearch).every(([key, matches]) => {
349
- const value = query.get(key);
350
- return value === null || matches(invoice, value);
351
- })), query);
284
+ const range = dateRange(query);
285
+ if (range instanceof Response) return range;
286
+ const page = paginate(state.invoices.filter((invoice) => (filter === null || matchesInvoiceFilter(invoice, filter, env)) && (range.from === null || invoice.InvoiceDate >= range.from) && (range.to === null || invoice.InvoiceDate <= range.to) && matchesSearch(invoice, query, invoiceSearch)), query);
352
287
  if (page instanceof Response) return page;
353
288
  return jsonResponse(200, {
354
289
  Invoices: page.items.map((invoice) => renderInvoiceRow(env, invoice)),
@@ -361,8 +296,8 @@ const getInvoice = (state, { params }, env) => {
361
296
  };
362
297
  const vatRates = [...fortnoxEmulatorVatCodes.keys()];
363
298
  /**
364
- * One row of an `InvoiceRows` write. `null` means omitted. Referenced articles, cost centers, and
365
- * projects must exist (the emulated company has none); accounts must be in 1000-8999.
299
+ * One row of an `InvoiceRows` write. `null` means omitted. References to articles, cost centers,
300
+ * and projects are not emulated on writes; accounts must be in 1000-8999.
366
301
  */
367
302
  const rowPatch = (value, index) => {
368
303
  if (!isJsonObject(value)) return invalidField(`InvoiceRows[${index}] must be an object.`);
@@ -383,7 +318,7 @@ const rowPatch = (value, index) => {
383
318
  case "CostCenter":
384
319
  case "Project":
385
320
  if (!Predicate.isString(field)) return invalidField(`${label(key)} must be a string.`);
386
- if (field !== "") return noReferencedEntity(key, field);
321
+ if (field !== "") return unsupportedReference(key, field);
387
322
  patch[key] = field;
388
323
  break;
389
324
  case "Description":
@@ -520,7 +455,7 @@ const invoiceUpdates = (fields, state, existing) => {
520
455
  break;
521
456
  case "CostCenter":
522
457
  case "Project":
523
- if (value !== "") return noReferencedEntity(key, value);
458
+ if (value !== "") return unsupportedReference(key, value);
524
459
  scalars[key] = value;
525
460
  break;
526
461
  default:
@@ -602,10 +537,7 @@ const createInvoice = (state, { body }, env) => {
602
537
  };
603
538
  return jsonResponse(201, { Invoice: renderInvoice(env, invoice) });
604
539
  };
605
- const previewInvoice = (state, { params }) => findInvoice(state, params.DocumentNumber ?? "") === void 0 ? invoiceNotFound() : new Response(previewPdfBytes(), {
606
- status: 200,
607
- headers: { "content-type": "application/pdf" }
608
- });
540
+ const previewInvoice = (state, { params }) => findInvoice(state, params.DocumentNumber ?? "") === void 0 ? invoiceNotFound() : pdfResponse();
609
541
  /** Marks the invoice `Sent` and records an outbox entry. Nothing is ever delivered. */
610
542
  const emailInvoice = (state, { params }, env) => {
611
543
  const invoice = findInvoice(state, params.DocumentNumber ?? "");
@@ -629,16 +561,6 @@ const emailInvoice = (state, { params }, env) => {
629
561
  return jsonResponse(200, { Invoice: renderInvoice(env, updated, true) });
630
562
  };
631
563
  const companyInformation = (state) => jsonResponse(200, { CompanyInformation: state.company });
632
- const connectorRoute = (method, path, write, caseIds, handler, queryKeys = []) => ({
633
- method,
634
- path: `/3${path}`,
635
- kind: "connector",
636
- write,
637
- caseIds,
638
- evidence: "unverified",
639
- queryKeys,
640
- handler
641
- });
642
564
  const listCase = "fortnox.invoice.list-populated";
643
565
  const previewCase = "fortnox.invoice.preview-pdf";
644
566
  const filtersCase = "fortnox.invoice.payment-filters-exclude-unbooked";
@@ -657,7 +579,8 @@ const fortnoxApiRoutes = [
657
579
  connectorRoute("GET", "/invoices/{DocumentNumber}", false, [discountCase, emailCase], getInvoice),
658
580
  connectorRoute("PUT", "/invoices/{DocumentNumber}", true, [discountCase], updateInvoice),
659
581
  connectorRoute("GET", "/invoices/{DocumentNumber}/preview", false, [previewCase], previewInvoice),
660
- connectorRoute("GET", "/invoices/{DocumentNumber}/email", true, [emailCase], emailInvoice)
582
+ connectorRoute("GET", "/invoices/{DocumentNumber}/email", true, [emailCase], emailInvoice),
583
+ ...fortnoxReadRoutes
661
584
  ];
662
585
  /** The observed quirks, each tied to its conformance case id. */
663
586
  const fortnoxEmulatorQuirks = [