fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* P014: lib/db.ts's `getSql()` used to hardcode `ssl: "require"`
|
||||
* unconditionally. That is correct for every REAL deployment target this
|
||||
* app has (Vercel Postgres, managed Postgres) but made ANY plain,
|
||||
* non-TLS Postgres -- compose.dev.yaml's own local-dev container, or a
|
||||
* throwaway restore-drill target -- silently unreachable through this
|
||||
* function, contradicting compose.dev.yaml's own doc comment and its
|
||||
* "UNVERIFIED... not smoke-tested" caveat. Found and fixed while executing
|
||||
* P014's real restore drill (see docs/runbook/backup-restore.md).
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { sslMode } from "@/lib/db";
|
||||
|
||||
describe("sslMode", () => {
|
||||
const saved = process.env.DATABASE_SSL;
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.DATABASE_SSL;
|
||||
else process.env.DATABASE_SSL = saved;
|
||||
});
|
||||
beforeEach(() => {
|
||||
delete process.env.DATABASE_SSL;
|
||||
});
|
||||
|
||||
it("defaults to \"require\" when DATABASE_SSL is unset -- unchanged behavior for every real deployment", () => {
|
||||
expect(sslMode()).toBe("require");
|
||||
});
|
||||
|
||||
for (const value of ["false", "FALSE", "disable", "off", "0", " false "]) {
|
||||
it(`treats DATABASE_SSL=${JSON.stringify(value)} as an explicit opt-out (false)`, () => {
|
||||
process.env.DATABASE_SSL = value;
|
||||
expect(sslMode()).toBe(false);
|
||||
});
|
||||
}
|
||||
|
||||
it("an unrecognized value falls back to the safe default (\"require\"), not an accidental opt-out", () => {
|
||||
process.env.DATABASE_SSL = "yes-please";
|
||||
expect(sslMode()).toBe("require");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* Unit tests for the dependency probes behind GET /api/health + GET
|
||||
* /api/ready (BACKLOG P0-3). Each check is exercised via dependency
|
||||
* injection (fake sql/fetch/stripe clients) rather than real network I/O,
|
||||
* matching the fake-over-mock-global convention used elsewhere in this repo
|
||||
* (e.g. tests/p0/document-intelligence-adapter.test.ts).
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import {
|
||||
checkDatabase,
|
||||
checkEngine,
|
||||
checkStripe,
|
||||
checkQueue,
|
||||
hasDegradedDependency,
|
||||
isReady,
|
||||
type DependencyResults,
|
||||
type SqlPing,
|
||||
} from "@/lib/health-checks";
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return {
|
||||
ok: status < 400,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
describe("checkDatabase", () => {
|
||||
const saved = process.env.DATABASE_URL;
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.DATABASE_URL;
|
||||
else process.env.DATABASE_URL = saved;
|
||||
});
|
||||
|
||||
it("reports not_configured when DATABASE_URL is unset, without calling the client", async () => {
|
||||
delete process.env.DATABASE_URL;
|
||||
let called = false;
|
||||
const fakeSql: SqlPing = async () => {
|
||||
called = true;
|
||||
return [{ "?column?": 1 }];
|
||||
};
|
||||
const result = await checkDatabase(fakeSql);
|
||||
expect(result.status).toBe("not_configured");
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it("reports ok when the ping round trip succeeds", async () => {
|
||||
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
|
||||
const fakeSql: SqlPing = async () => [{ "?column?": 1 }];
|
||||
const result = await checkDatabase(fakeSql);
|
||||
expect(result.status).toBe("ok");
|
||||
expect(typeof result.latencyMs).toBe("number");
|
||||
});
|
||||
|
||||
it("reports error with the driver message when the ping fails", async () => {
|
||||
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
|
||||
const fakeSql: SqlPing = async () => {
|
||||
throw new Error("ECONNREFUSED 127.0.0.1:5432");
|
||||
};
|
||||
const result = await checkDatabase(fakeSql);
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.detail).toContain("ECONNREFUSED");
|
||||
});
|
||||
|
||||
it("reports error on timeout rather than hanging", async () => {
|
||||
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
|
||||
const fakeSql: SqlPing = () => new Promise(() => {}); // never resolves
|
||||
const result = await checkDatabase(fakeSql, 20);
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.detail).toContain("timed out");
|
||||
});
|
||||
|
||||
it("reports not_configured when DATABASE_URL is set but no client is available", async () => {
|
||||
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
|
||||
const result = await checkDatabase(null);
|
||||
expect(result.status).toBe("not_configured");
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkEngine", () => {
|
||||
const saved = process.env.ENGINE_URL;
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.ENGINE_URL;
|
||||
else process.env.ENGINE_URL = saved;
|
||||
});
|
||||
|
||||
it("reports not_configured when ENGINE_URL is unset", async () => {
|
||||
delete process.env.ENGINE_URL;
|
||||
const result = await checkEngine(async () => jsonResponse({ ok: true }));
|
||||
expect(result.status).toBe("not_configured");
|
||||
});
|
||||
|
||||
it("reports ok when the engine's /health responds 2xx", async () => {
|
||||
process.env.ENGINE_URL = "http://engine.local:8000";
|
||||
const fetchMock = (async (url: string) => {
|
||||
expect(url).toBe("http://engine.local:8000/health");
|
||||
return jsonResponse({ ok: true });
|
||||
}) as unknown as typeof fetch;
|
||||
const result = await checkEngine(fetchMock);
|
||||
expect(result.status).toBe("ok");
|
||||
});
|
||||
|
||||
it("reports error when the engine responds non-2xx", async () => {
|
||||
process.env.ENGINE_URL = "http://engine.local:8000";
|
||||
const result = await checkEngine(async () => jsonResponse({}, 500));
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.detail).toContain("500");
|
||||
});
|
||||
|
||||
it("reports error when the fetch throws (host unreachable)", async () => {
|
||||
process.env.ENGINE_URL = "http://engine.local:8000";
|
||||
const result = await checkEngine(async () => {
|
||||
throw new Error("fetch failed");
|
||||
});
|
||||
expect(result.status).toBe("error");
|
||||
});
|
||||
|
||||
it("REGRESSION: reports error (with the abort message in detail) when the probe times out via AbortController -- the exact 2026-09-30 prod symptom", async () => {
|
||||
// Mätt i prod 2026-09-30: ENGINE_URL satt i Coolify-env mot en
|
||||
// oprovisionerad host -> AbortController:n nbröt efter 2 s och
|
||||
// /api/health rapporterade {"engine":"error",
|
||||
// "detail":{"engine":"This operation was aborted"}}. Kollen ska
|
||||
// vara ÄRLIG här: URL:en ÄR satt, så detta är error -- inte
|
||||
// not_configured och aldrig ok.
|
||||
process.env.ENGINE_URL = "http://0pt-engine:8000";
|
||||
const result = await checkEngine(async () => {
|
||||
throw new DOMException("This operation was aborted", "AbortError");
|
||||
});
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.detail).toContain("aborted");
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkStripe", () => {
|
||||
it("reports not_configured when no client is available (no STRIPE_SECRET_KEY)", async () => {
|
||||
const result = await checkStripe(null);
|
||||
expect(result.status).toBe("not_configured");
|
||||
});
|
||||
|
||||
it("reports ok when balance.retrieve() succeeds", async () => {
|
||||
const result = await checkStripe({ balance: { retrieve: async () => ({ available: [] }) } });
|
||||
expect(result.status).toBe("ok");
|
||||
});
|
||||
|
||||
it("reports error when balance.retrieve() rejects (e.g. revoked key)", async () => {
|
||||
const result = await checkStripe({
|
||||
balance: {
|
||||
retrieve: async () => {
|
||||
throw new Error("Invalid API Key provided");
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.detail).toContain("Invalid API Key");
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkQueue", () => {
|
||||
const saved = process.env.REDIS_URL;
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.REDIS_URL;
|
||||
else process.env.REDIS_URL = saved;
|
||||
});
|
||||
|
||||
it("reports not_configured when REDIS_URL is unset", async () => {
|
||||
delete process.env.REDIS_URL;
|
||||
expect((await checkQueue()).status).toBe("not_configured");
|
||||
});
|
||||
|
||||
it("reports ok only when the real probe completes", async () => {
|
||||
process.env.REDIS_URL = "redis://localhost:6379";
|
||||
const result = await checkQueue(async () => undefined);
|
||||
expect(result.status).toBe("ok");
|
||||
});
|
||||
|
||||
it("reports error when a configured queue cannot be reached", async () => {
|
||||
process.env.REDIS_URL = "redis://localhost:6379";
|
||||
const result = await checkQueue(async () => {
|
||||
throw new Error("connection refused");
|
||||
});
|
||||
expect(result.status).toBe("error");
|
||||
expect(result.detail).toContain("connection refused");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasDegradedDependency / isReady", () => {
|
||||
function deps(overrides: Partial<DependencyResults> = {}): DependencyResults {
|
||||
return {
|
||||
db: { status: "not_configured" },
|
||||
engine: { status: "not_configured" },
|
||||
stripe: { status: "not_configured" },
|
||||
queue: { status: "not_configured" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it("hasDegradedDependency is false when nothing is configured", () => {
|
||||
expect(hasDegradedDependency(deps())).toBe(false);
|
||||
});
|
||||
|
||||
it("hasDegradedDependency is true when any dependency errored", () => {
|
||||
expect(hasDegradedDependency(deps({ engine: { status: "error", detail: "boom" } }))).toBe(true);
|
||||
});
|
||||
|
||||
it("isReady is false when db is not ok, even if nothing else is broken", () => {
|
||||
expect(isReady(deps())).toBe(false);
|
||||
expect(isReady(deps({ db: { status: "error" } }))).toBe(false);
|
||||
});
|
||||
|
||||
it("isReady is true once db is ok and no configured integration is failing", () => {
|
||||
expect(isReady(deps({ db: { status: "ok" } }))).toBe(true);
|
||||
});
|
||||
|
||||
it("isReady stays true for integrations that are merely absent (0pt boots without them)", () => {
|
||||
expect(
|
||||
isReady(
|
||||
deps({
|
||||
db: { status: "ok" },
|
||||
engine: { status: "not_configured" },
|
||||
stripe: { status: "not_configured" },
|
||||
queue: { status: "not_configured" },
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("REGRESSION: isReady is false when a CONFIGURED integration is failing its live round trip", () => {
|
||||
// Mätt i prod 2026-09-25: ENGINE_URL pekade på 0pt-engine:8000, en värd
|
||||
// utan DNS-post någonstans i flottan, och /api/ready svarade ändå
|
||||
// {"ready":true,...,"engine":"error"}. En konfigurerad-men-död motor är
|
||||
// inte "valfri" -- någon har bett om den och den svarar inte.
|
||||
expect(isReady(deps({ db: { status: "ok" }, engine: { status: "error", detail: "fetch failed" } }))).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isReady(deps({ db: { status: "ok" }, stripe: { status: "error", detail: "bad key" } }))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Klient-adaptern (kernel-transport över host-API): offline = no-op + varning
|
||||
* (INGEN fetch, inget tyst förlorat), 409 -> ConflictError med aktuell
|
||||
* version, presence via kernelns upsertPresence.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
OfflineError,
|
||||
OrderNotesClient,
|
||||
OrderNotesTransport,
|
||||
} from "@/lib/order-notes-client";
|
||||
|
||||
describe("OrderNotesTransport (kernel CollaborationTransport)", () => {
|
||||
it("send() i offline-läge kastar OfflineError utan nätverksanrop (no-op, ej tyst)", async () => {
|
||||
const t = new OrderNotesTransport("admin-simon");
|
||||
t.setOffline(true);
|
||||
await expect(
|
||||
t.send({ id: "n1", actorId: "x", clock: 1, type: "note.update", payload: { body: "y" } }),
|
||||
).rejects.toBeInstanceOf(OfflineError);
|
||||
});
|
||||
|
||||
it("connect/disconnect växlar presence via upsertPresence (online -> offline)", async () => {
|
||||
const t = new OrderNotesTransport("admin-simon");
|
||||
await t.connect();
|
||||
expect(t.getPresence().find((p) => p.participantId === "admin-simon")?.status).toBe("online");
|
||||
await t.disconnect();
|
||||
expect(t.getPresence().find((p) => p.participantId === "admin-simon")?.status).toBe("offline");
|
||||
});
|
||||
|
||||
it("observeRemote advanserar Lamport-klockan och notifyar listeners", async () => {
|
||||
const t = new OrderNotesTransport("me");
|
||||
const seen: string[] = [];
|
||||
t.onOperation((op) => seen.push(`${op.id}@${op.clock}`));
|
||||
t.observeRemote({ id: "n1", actorId: "anna", clock: 4, type: "note.upsert", payload: { body: "x" } });
|
||||
expect(seen).toEqual(["n1@4"]);
|
||||
expect(t.getPresence().find((p) => p.participantId === "anna")?.status).toBe("online");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OrderNotesClient över host-API", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("offline-läge: add() är no-op — fetch anropas EJ, OfflineError kastas (ingen tyst förlust)", async () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
||||
const client = new OrderNotesClient("admin-simon");
|
||||
client.transport.setOffline(true);
|
||||
await expect(client.add("order-1", "utkast")).rejects.toBeInstanceOf(OfflineError);
|
||||
expect(fetchSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("409 från servern -> ConflictError med serverns aktuella version", async () => {
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response(JSON.stringify({ error: "version_conflict", current_version: 3 }), { status: 409 }),
|
||||
);
|
||||
const client = new OrderNotesClient("admin-simon");
|
||||
await expect(
|
||||
client.update(
|
||||
{ note_id: "n1", order_id: "o1", author_id: "a", body: "old", version: 1, clock: 1, updated_at: "" },
|
||||
"new",
|
||||
1,
|
||||
),
|
||||
).rejects.toMatchObject({ currentVersion: 3 });
|
||||
});
|
||||
|
||||
it("load(): varje servernot replays som kernel-operation (klockor advanserar)", async () => {
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
notes: [
|
||||
{ note_id: "n1", order_id: "o1", author_id: "anna", body: "A", version: 1, clock: 2, updated_at: "" },
|
||||
{ note_id: "n2", order_id: "o1", author_id: "bosse", body: "B", version: 2, clock: 5, updated_at: "" },
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
);
|
||||
const client = new OrderNotesClient("admin-simon");
|
||||
const { notes, versions } = await client.load("o1");
|
||||
expect(notes).toHaveLength(2);
|
||||
expect(versions.get("n2")).toBe(2);
|
||||
expect(client.transport.getPresence().find((p) => p.participantId === "bosse")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* P014: lib/orders-store.ts previously had ZERO test coverage and no
|
||||
* idempotency mechanism -- a retried POST /api/orders created a second,
|
||||
* indistinguishable row every time (recon: "Duplicate delivery idempotent:
|
||||
* NOT MET"). These tests exercise the in-memory fallback path directly
|
||||
* (no DATABASE_URL is set in this test environment, matching every other
|
||||
* test in this repo) and prove: a retry under the same Idempotency-Key
|
||||
* replays the original order; a reused key with a different submission is
|
||||
* refused as a conflict, not silently merged; and omitting the key
|
||||
* preserves the exact pre-P014 "always create a new order" behavior.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import {
|
||||
createOrder,
|
||||
findOrderByIdempotencyKey,
|
||||
IdempotencyKeyConflictError,
|
||||
type OrderConfig,
|
||||
} from "@/lib/orders-store";
|
||||
|
||||
const CONFIG_A: OrderConfig = { markets: ["SE"], type: "Bolag", fieldIds: ["identity"], volume: 1000 };
|
||||
const CONFIG_B: OrderConfig = { markets: ["NO"], type: "Bolag", fieldIds: ["identity"], volume: 5000 };
|
||||
|
||||
describe("createOrder idempotency (in-memory fallback)", () => {
|
||||
it("no Idempotency-Key: every call creates a distinct order (unchanged pre-P014 behavior)", async () => {
|
||||
const first = await createOrder("custom", CONFIG_A);
|
||||
const second = await createOrder("custom", CONFIG_A);
|
||||
expect(first.order.order_id).not.toBe(second.order.order_id);
|
||||
expect(first.replayed).toBe(false);
|
||||
expect(second.replayed).toBe(false);
|
||||
});
|
||||
|
||||
it("same Idempotency-Key + same (flow, config): the second call replays the first order, no duplicate row", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
const first = await createOrder("custom", CONFIG_A, key);
|
||||
const second = await createOrder("custom", CONFIG_A, key);
|
||||
|
||||
expect(first.replayed).toBe(false);
|
||||
expect(second.replayed).toBe(true);
|
||||
expect(second.order.order_id).toBe(first.order.order_id);
|
||||
expect(second.order.created_at).toBe(first.order.created_at);
|
||||
});
|
||||
|
||||
it("retrying the SAME key three times still yields exactly one underlying order", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
const a = await createOrder("custom", CONFIG_A, key);
|
||||
const b = await createOrder("custom", CONFIG_A, key);
|
||||
const c = await createOrder("custom", CONFIG_A, key);
|
||||
const ids = new Set([a.order.order_id, b.order.order_id, c.order.order_id]);
|
||||
expect(ids.size).toBe(1);
|
||||
});
|
||||
|
||||
it("same Idempotency-Key reused with a DIFFERENT config: refused as a conflict, not silently merged", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
await createOrder("custom", CONFIG_A, key);
|
||||
await expect(createOrder("custom", CONFIG_B, key)).rejects.toBeInstanceOf(IdempotencyKeyConflictError);
|
||||
});
|
||||
|
||||
it("same Idempotency-Key reused with a DIFFERENT flow: refused as a conflict", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
await createOrder("custom", CONFIG_A, key);
|
||||
await expect(createOrder("subscription", CONFIG_A, key)).rejects.toBeInstanceOf(IdempotencyKeyConflictError);
|
||||
});
|
||||
|
||||
it("a conflicting retry does not mutate or replace the original order", async () => {
|
||||
const key = `idem_${crypto.randomUUID()}`;
|
||||
const original = await createOrder("custom", CONFIG_A, key);
|
||||
await expect(createOrder("custom", CONFIG_B, key)).rejects.toThrow();
|
||||
const stillThere = await findOrderByIdempotencyKey(key);
|
||||
expect(stillThere?.order_id).toBe(original.order.order_id);
|
||||
expect(stillThere?.config).toEqual(CONFIG_A);
|
||||
});
|
||||
|
||||
it("different Idempotency-Keys for the same config create independent orders", async () => {
|
||||
const a = await createOrder("custom", CONFIG_A, `idem_${crypto.randomUUID()}`);
|
||||
const b = await createOrder("custom", CONFIG_A, `idem_${crypto.randomUUID()}`);
|
||||
expect(a.order.order_id).not.toBe(b.order.order_id);
|
||||
});
|
||||
|
||||
it("an empty-string Idempotency-Key is treated as absent (no dedup, no crash)", async () => {
|
||||
const a = await createOrder("custom", CONFIG_A, "");
|
||||
const b = await createOrder("custom", CONFIG_A, " ");
|
||||
expect(a.order.order_id).not.toBe(b.order.order_id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createOrder, getOwnedOrder, listOwnedOrders, setOwnedStatusIfCurrent,
|
||||
IdempotencyKeyConflictError,
|
||||
} from "@/lib/orders-store";
|
||||
|
||||
const alpha = { tenantId: "tenant-alpha", subject: "buyer-alpha" };
|
||||
const beta = { tenantId: "tenant-beta", subject: "buyer-beta" };
|
||||
const config = { markets: ["SE"], volume: 1000 };
|
||||
|
||||
describe("payment-order ownership (in-memory contract)", () => {
|
||||
it("binds a new order to the verified tenant and buyer, never to client config", async () => {
|
||||
const result = await createOrder("custom", config, undefined, alpha);
|
||||
expect(result.order.tenant_id).toBe(alpha.tenantId);
|
||||
expect(result.order.buyer_subject).toBe(alpha.subject);
|
||||
expect(await getOwnedOrder(result.order.order_id, alpha.tenantId)).not.toBeNull();
|
||||
expect(await getOwnedOrder(result.order.order_id, beta.tenantId)).toBeNull();
|
||||
expect((await listOwnedOrders(beta.tenantId)).some((o) => o.order_id === result.order.order_id)).toBe(false);
|
||||
});
|
||||
|
||||
it("legacy anonymous rows remain invisible and cannot be mutated by a buyer", async () => {
|
||||
const legacy = (await createOrder("custom", config)).order;
|
||||
expect(await getOwnedOrder(legacy.order_id, alpha.tenantId)).toBeNull();
|
||||
expect(await setOwnedStatusIfCurrent(legacy.order_id, alpha.tenantId, "draft", "quoted")).toBeNull();
|
||||
});
|
||||
|
||||
it("an owner cannot change another tenant's status even at the same valid state", async () => {
|
||||
const order = (await createOrder("custom", config, undefined, alpha)).order;
|
||||
expect(await setOwnedStatusIfCurrent(order.order_id, beta.tenantId, "draft", "quoted")).toBeNull();
|
||||
expect((await getOwnedOrder(order.order_id, alpha.tenantId))?.status).toBe("draft");
|
||||
expect((await setOwnedStatusIfCurrent(order.order_id, alpha.tenantId, "draft", "quoted"))?.status).toBe("quoted");
|
||||
});
|
||||
|
||||
it("idempotency keys are tenant-namespaced, and another buyer in the same tenant cannot replay", async () => {
|
||||
const key = `ownership-${crypto.randomUUID()}`;
|
||||
const a1 = await createOrder("custom", config, key, alpha);
|
||||
const a2 = await createOrder("custom", config, key, alpha);
|
||||
const b1 = await createOrder("custom", config, key, beta);
|
||||
expect(a2.replayed).toBe(true);
|
||||
expect(a1.order.order_id).toBe(a2.order.order_id);
|
||||
expect(a1.order.order_id).not.toBe(b1.order.order_id);
|
||||
await expect(createOrder("custom", config, key, { ...alpha, subject: "other-buyer" }))
|
||||
.rejects.toBeInstanceOf(IdempotencyKeyConflictError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { createOrder, getOrder, setStatusIfCurrent } from "@/lib/orders-store";
|
||||
|
||||
it("rejects a stale status writer in the in-memory fallback", async () => {
|
||||
const { order } = await createOrder("custom", { markets: ["SE"], type: "Bolag" });
|
||||
expect((await setStatusIfCurrent(order.order_id, "draft", "quoted"))?.status).toBe("quoted");
|
||||
expect(await setStatusIfCurrent(order.order_id, "draft", "accepted")).toBeNull();
|
||||
expect((await getOrder(order.order_id))?.status).toBe("quoted");
|
||||
});
|
||||
Reference in New Issue
Block a user