@pplethai/cli 0.14.0 → 0.16.0

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.
@@ -0,0 +1,48 @@
1
+ // Offline email (#435). The registry's own mocks for `platform/email`
2
+ // (registry/email/mocks/responses.json) are the answers `npm run dev` gives. This
3
+ // drives the real files through the same matcher a Builder's `callService` uses
4
+ // offline, so a fresh app can send an email against them with nothing deployed.
5
+
6
+ import { describe, expect, it } from "vitest";
7
+ import { answerFromOverlay } from "../src/dev-call-service";
8
+ import { callService } from "../src/call-service";
9
+
10
+ // The registry's files, laid out as `pple registry` writes them into `.pple/registry/`.
11
+ const files: Record<string, unknown> = Object.fromEntries(
12
+ Object.entries(import.meta.glob("../../registry/email/**/*", { eager: true, query: "?raw", import: "default" })).map(
13
+ ([file, text]) => [file.replace("../../registry/email/", "overlay/platform/email/"), text],
14
+ ),
15
+ );
16
+
17
+ const offline: typeof fetch = async (input, init) => {
18
+ const req = new Request(input as RequestInfo, init);
19
+ const prefix = "/platform/email";
20
+ return answerFromOverlay(files, {
21
+ entry: "platform/email",
22
+ path: new URL(req.url).pathname.slice(prefix.length),
23
+ method: req.method,
24
+ persona: "hq-staff",
25
+ overlayRoot: "overlay/",
26
+ });
27
+ };
28
+
29
+ describe("platform/email offline", () => {
30
+ it("answers a send with one sent message and no real delivery", async () => {
31
+ const res = await callService(
32
+ { PPLE_SERVICES_URL: "https://services.test", PPLE_APP_KEY: "k", DEV_PERSONA: "none" },
33
+ "platform/email",
34
+ "",
35
+ {
36
+ method: "POST",
37
+ headers: { "content-type": "application/json" },
38
+ body: JSON.stringify({ to: ["somying@example.com"], subject: "ยืนยัน", body: "ลงทะเบียนแล้ว" }),
39
+ },
40
+ { fetchImpl: offline },
41
+ );
42
+ expect(res.status).toBe(200);
43
+ expect(await res.json()).toEqual({
44
+ sent: [{ to: "somying@example.com", messageId: "offline-mock" }],
45
+ rejected: [],
46
+ });
47
+ });
48
+ });
@@ -0,0 +1,165 @@
1
+ // A fresh template app takes a fake payment end to end, offline (ADR-0037,
2
+ // ADR-0026): the Payer asks the app for a Payment, is sent to the Checkout
3
+ // address, and the platform calls `payment()` when it is paid, which verifies
4
+ // the event and stops there: issuing a legal Receipt is the Builder's decision,
5
+ // never a default (see "the two patterns" below). The platform is the registry's own mocks,
6
+ // as the signed-in Persona. Offline there is no Checkout Page and no platform
7
+ // callback, so this stands in for both: it hands the handler the event the
8
+ // platform would send. A real checkout is a deployed Beta app's.
9
+
10
+ import { describe, expect, it } from "vitest";
11
+ import { createPaymentHandler } from "../src/index";
12
+ import { issueReceipt, paymentHandler, rejectPayment, verifyPaymentEvent, type PaymentPaidEvent, type PaymentReceiptIssuedEvent } from "../src/payment";
13
+ import { makeHarness, testExecutionContext } from "./harness";
14
+ import { offlinePayments } from "./payments-offline";
15
+
16
+ const SERVICES = { PPLE_SERVICES_URL: "https://services.test", PPLE_APP_KEY: "app-key" };
17
+
18
+ const post = (body: unknown) => ({
19
+ method: "POST",
20
+ headers: { "content-type": "application/json" },
21
+ body: JSON.stringify(body),
22
+ });
23
+
24
+ /** What the platform sends when `pay_offline-mock` is paid. */
25
+ const PAID_EVENT: PaymentPaidEvent = {
26
+ type: "payment.paid",
27
+ id: "evt_1",
28
+ payment: {
29
+ id: "pay_offline-mock",
30
+ kind: "donation",
31
+ amountSatang: 50_000,
32
+ description: "รายการทดสอบ",
33
+ reference: "offline-mock",
34
+ mode: "test",
35
+ },
36
+ payer: { name: "บุคคลทดสอบ หนึ่ง", maskedCitizenId: "x-xxxx-xxxxx-xx-0" },
37
+ voucher: { number: "TEST-PV-000001", nameTh: "…", isReceipt: false },
38
+ paidAt: "2026-01-01T00:00:00.000Z",
39
+ };
40
+
41
+ describe("a fresh template app, offline", () => {
42
+ it.each(["hq-staff", "member", "kyc-verified-nonmember", "delegate"])(
43
+ "takes a donation as %s: create, pay, verified, and no Receipt issued until the app decides",
44
+ async (persona) => {
45
+ const h = makeHarness({ services: offlinePayments(persona) }, { ...SERVICES, DEV_PERSONA: persona });
46
+
47
+ // 1. The Payer asks for a Payment and gets the address to pay at.
48
+ const created = await h.request("/api/payments", post({ amountSatang: 50_000 }));
49
+ expect(created.status).toBe(201);
50
+ const { id, checkoutUrl } = (await created.json()) as { id: string; checkoutUrl: string };
51
+ expect(id).toBe("pay_offline-mock");
52
+ expect(checkoutUrl).toMatch(/^https:\/\//);
53
+
54
+ // 2. Paid: the platform calls `payment()`. The handler verifies and does not issue:
55
+ // a legal Receipt is the Builder's decision, so a fresh app never issues one by default (P4).
56
+ const handler = createPaymentHandler({ fetchImpl: h.fetchImpl });
57
+ expect(await handler(PAID_EVENT, h.testEnv, testExecutionContext())).toBeUndefined();
58
+ expect(h.calls.services.map((c) => `${c.method} ${c.path}`)).toEqual([
59
+ "POST /platform/payments",
60
+ "GET /platform/payments/pay_offline-mock",
61
+ ]);
62
+
63
+ // 3. The app can read the Payment back for its page.
64
+ const read = await h.request(`/api/payments/${id}`);
65
+ expect(read.status).toBe(200);
66
+ expect(await read.json()).toMatchObject({ payment: { state: "paid", mode: "test" } });
67
+ },
68
+ );
69
+
70
+ // The Checkout Page turns an unverified Payer away, so the app says so first.
71
+ // The mocks cannot: the Service never sees who is signed in.
72
+ it.each(["unverified", "kyc-pending"])("does not start a payment for %s: they must verify first", async (persona) => {
73
+ const h = makeHarness({ services: offlinePayments(persona) }, { ...SERVICES, DEV_PERSONA: persona });
74
+
75
+ const res = await h.request("/api/payments", post({ amountSatang: 50_000 }));
76
+
77
+ expect(res.status).toBe(403);
78
+ expect(await res.json()).toEqual({ error: "kyc_required" });
79
+ expect(h.calls.services).toEqual([]);
80
+ });
81
+
82
+ it("refuses an amount that is not a positive whole number of satang", async () => {
83
+ const h = makeHarness({ services: offlinePayments("hq-staff") }, SERVICES);
84
+
85
+ for (const amountSatang of [0, -5, 10.5, "100", null]) {
86
+ const res = await h.request("/api/payments", post({ amountSatang }));
87
+ expect(res.status).toBe(400);
88
+ }
89
+ expect(h.calls.services).toEqual([]);
90
+ });
91
+
92
+ describe("the two patterns, which a Builder writes into their own `payment` handler", () => {
93
+ // The same helpers, wired the way payments.md shows. The template's default
94
+ // handler is neither: it only verifies.
95
+ it("issue at payment: verify the event, then issue the Receipt", async () => {
96
+ const h = makeHarness({ services: offlinePayments("hq-staff") }, SERVICES);
97
+ const handler = paymentHandler({
98
+ "payment.paid": async (event, env) => {
99
+ const verified = await verifyPaymentEvent(env, event, h.fetchImpl);
100
+ if (!verified.ok) return verified.reason === "mismatch" ? undefined : new Response(null, { status: 503 });
101
+ const issued = await issueReceipt(env, event.payment.id, h.fetchImpl);
102
+ if (!issued.ok && issued.reason !== "not_paid") return new Response(null, { status: 503 });
103
+ },
104
+ });
105
+
106
+ expect(await handler(PAID_EVENT, h.testEnv, testExecutionContext())).toBeUndefined();
107
+ expect(h.calls.services.map((c) => `${c.method} ${c.path}`)).toEqual([
108
+ "GET /platform/payments/pay_offline-mock",
109
+ "POST /platform/payments/pay_offline-mock/receipt",
110
+ ]);
111
+ });
112
+
113
+ it("verify first: the app's own check decides between issuing and rejecting", async () => {
114
+ const h = makeHarness({ services: offlinePayments("hq-staff") }, SERVICES);
115
+ const outcome = (stockOk: boolean) =>
116
+ paymentHandler({
117
+ "payment.paid": async (event, env) => {
118
+ const verified = await verifyPaymentEvent(env, event, h.fetchImpl);
119
+ if (!verified.ok) return verified.reason === "mismatch" ? undefined : new Response(null, { status: 503 });
120
+ if (stockOk) await issueReceipt(env, event.payment.id, h.fetchImpl);
121
+ else await rejectPayment(env, event.payment.id, h.fetchImpl);
122
+ },
123
+ });
124
+
125
+ await outcome(true)(PAID_EVENT, h.testEnv, testExecutionContext());
126
+ await outcome(false)(PAID_EVENT, h.testEnv, testExecutionContext());
127
+ expect(h.calls.services.map((c) => c.path.split("/").pop())).toEqual(["pay_offline-mock", "receipt", "pay_offline-mock", "reject"]);
128
+ });
129
+ });
130
+
131
+ it("does not issue a Receipt for an event the platform does not agree with", async () => {
132
+ const h = makeHarness({ services: offlinePayments("hq-staff") }, SERVICES);
133
+ const forged = { ...PAID_EVENT, payment: { ...PAID_EVENT.payment, amountSatang: 99_999_900 } };
134
+
135
+ const handler = createPaymentHandler({ fetchImpl: h.fetchImpl });
136
+
137
+ // Answered 2xx so it is not retried, and nothing was issued.
138
+ expect(await handler(forged, h.testEnv, testExecutionContext())).toBeUndefined();
139
+ expect(h.calls.services.map((c) => c.method)).toEqual(["GET"]);
140
+ });
141
+
142
+ it("is told to try again when the platform cannot be reached, so the Receipt is not lost", async () => {
143
+ const h = makeHarness({ services: () => new Response(null, { status: 502 }) }, SERVICES);
144
+
145
+ const handler = createPaymentHandler({ fetchImpl: h.fetchImpl });
146
+
147
+ const answer = await handler(PAID_EVENT, h.testEnv, testExecutionContext());
148
+ expect((answer as Response).status).toBe(503);
149
+ });
150
+
151
+ it("ignores the other outcomes, and the next time the handler hears of a Receipt it only acknowledges", async () => {
152
+ const h = makeHarness({ services: offlinePayments("hq-staff") }, SERVICES);
153
+ const handler = createPaymentHandler({ fetchImpl: h.fetchImpl });
154
+ const issued = {
155
+ type: "payment.receipt_issued",
156
+ id: "evt_receipt_issued_rcp_1",
157
+ payment: PAID_EVENT.payment,
158
+ payer: PAID_EVENT.payer!,
159
+ receipt: { id: "rcp_1", number: "TEST-2569-000001", isTest: true, issuedAt: "2026-01-01T00:00:00.000Z", replaces: null },
160
+ } satisfies PaymentReceiptIssuedEvent;
161
+
162
+ expect(await handler(issued, h.testEnv, testExecutionContext())).toBeUndefined();
163
+ expect(h.calls.services).toEqual([]);
164
+ });
165
+ });
@@ -0,0 +1,67 @@
1
+ // Offline payments (ADR-0026, docs/adr/0037). The registry's own mocks for
2
+ // `platform/payments` (registry/payments/mocks/responses.json) are the
3
+ // answers `npm run dev` gives, as the signed-in Persona. This drives the real
4
+ // files through the same matcher a Builder's `callService` uses offline, with
5
+ // the helpers on top, so what the Skill promises is what runs.
6
+ //
7
+ // There is no Checkout Page or Gateway offline: the Payment is simply paid.
8
+
9
+ import { describe, expect, it } from "vitest";
10
+ import { DEV_PERSONAS } from "../src/dev-personas";
11
+ import { createPayment, getPayment, issueReceipt, rejectPayment } from "../src/payment";
12
+ import { offlinePayments } from "./payments-offline";
13
+
14
+ /** `callService` as `npm run dev` runs it for this Persona. */
15
+ const offlineAs =
16
+ (persona: string): typeof fetch =>
17
+ async (input, init) =>
18
+ offlinePayments(persona)(new Request(input as RequestInfo, init));
19
+
20
+ const env = { PPLE_SERVICES_URL: "https://services.test", PPLE_APP_KEY: "k", DEV_PERSONA: "none" };
21
+ const INPUT = {
22
+ kind: "donation" as const,
23
+ amountSatang: 50_000,
24
+ description: "บริจาค",
25
+ reference: "order-1",
26
+ returnUrl: "http://localhost:5173/thanks",
27
+ };
28
+
29
+ // The entry is `userToken: none`, so the Service never sees who is signed in
30
+ // and the registry refuses a Persona on its mocks. Every Persona gets the same
31
+ // answers: the Payer got through checkout. Whether a Persona may start a
32
+ // payment at all is the app's own gate on `actor.kyc.verified`
33
+ // (test/payment-app.test.ts), which is where the platform's KYC rule is
34
+ // visible to a Builder offline.
35
+ const personas = Object.keys(DEV_PERSONAS);
36
+
37
+ describe("offline payments", () => {
38
+ it("covers Personas that are and are not KYC-verified", () => {
39
+ const kyc = personas.map((name) => DEV_PERSONAS[name]!.actor.kyc.verified);
40
+ expect(kyc).toContain(true);
41
+ expect(kyc).toContain(false);
42
+ });
43
+
44
+ it.each([...personas, "intern"])("%s: a Payment is created, paid, receipted and can be rejected", async (persona) => {
45
+ const fetchImpl = offlineAs(persona);
46
+
47
+ const created = await createPayment(env, INPUT, fetchImpl);
48
+ expect(created).toMatchObject({ ok: true, id: "pay_offline-mock", state: "created" });
49
+
50
+ const read = await getPayment(env, "pay_offline-mock", fetchImpl);
51
+ expect(read).toMatchObject({ ok: true, payment: { state: "paid", mode: "test", receipt: null } });
52
+ if (!read.ok) throw new Error("unreachable");
53
+ // The Voucher says it is not a receipt, and the Payer is masked.
54
+ expect(read.payment.voucher).toMatchObject({ isReceipt: false });
55
+ expect(read.payment.payer?.maskedCitizenId).toMatch(/x/);
56
+
57
+ expect(await issueReceipt(env, "pay_offline-mock", fetchImpl)).toMatchObject({
58
+ ok: true,
59
+ issuedNow: true,
60
+ receipt: { isTest: true, number: expect.stringMatching(/^TEST-/) },
61
+ });
62
+ expect(await rejectPayment(env, "pay_offline-mock", fetchImpl)).toMatchObject({
63
+ ok: true,
64
+ payment: { state: "refunded", refund: { status: "refunded" } },
65
+ });
66
+ });
67
+ });
@@ -0,0 +1,322 @@
1
+ // Payment helpers (docs/adr/0037). Each helper wraps one call to the Private
2
+ // Platform Service `platform/payments` and turns every answer the Service or
3
+ // the gate can give into a named reason, so a Builder switches on `reason`
4
+ // and never reads a status. The fake Service below answers as the real one
5
+ // does (registry/payments/entry.md).
6
+
7
+ import { describe, expect, it } from "vitest";
8
+ import {
9
+ createPayment,
10
+ getPayment,
11
+ issueReceipt,
12
+ paymentHandler,
13
+ rejectPayment,
14
+ verifyPaymentEvent,
15
+ type CreatePaymentInput,
16
+ type PaymentEvent,
17
+ type PaymentPaidEvent,
18
+ type PaymentRecord,
19
+ } from "../src/payment";
20
+ import { makeHarness, serviceRefusal, testExecutionContext } from "./harness";
21
+
22
+ const INPUT: CreatePaymentInput = {
23
+ kind: "donation",
24
+ amountSatang: 50_000,
25
+ description: "บริจาคสนับสนุนพรรค",
26
+ reference: "order-1",
27
+ returnUrl: "https://my-app.ppleth.ai/thanks",
28
+ };
29
+
30
+ const SERVICES = { PPLE_SERVICES_URL: "https://services.test", PPLE_APP_KEY: "app-key", DEV_PERSONA: "none" };
31
+
32
+ describe("createPayment", () => {
33
+ it("asks platform/payments for a Payment and answers the Checkout address to send the Payer to", async () => {
34
+ let body: unknown;
35
+ const h = makeHarness(
36
+ {
37
+ services: async (req) => {
38
+ body = await req.json();
39
+ return Response.json(
40
+ { id: "pay_1", checkoutUrl: "https://pay.example.test/pay_1", state: "created" },
41
+ { status: 201 },
42
+ );
43
+ },
44
+ },
45
+ SERVICES,
46
+ );
47
+
48
+ const result = await createPayment(h.testEnv, INPUT, h.fetchImpl);
49
+
50
+ expect(result).toEqual({
51
+ ok: true,
52
+ id: "pay_1",
53
+ checkoutUrl: "https://pay.example.test/pay_1",
54
+ state: "created",
55
+ });
56
+ expect(h.calls.services).toEqual([
57
+ expect.objectContaining({ path: "/platform/payments", method: "POST" }),
58
+ ]);
59
+ expect(body).toEqual(INPUT);
60
+ });
61
+ });
62
+
63
+ const PAID: PaymentRecord = {
64
+ id: "pay_1",
65
+ kind: "donation",
66
+ amountSatang: 50_000,
67
+ description: "บริจาคสนับสนุนพรรค",
68
+ reference: "order-1",
69
+ state: "paid",
70
+ mode: "test",
71
+ payer: { name: "นางสาวสมหญิง ใจดี", maskedCitizenId: "1-1037-xxxxx-56-1" },
72
+ voucher: { number: "TEST-PV-000001", nameTh: "หลักฐานการรับชำระเงิน", isReceipt: false },
73
+ receipt: null,
74
+ paidAt: "2026-11-15T09:00:00.000Z",
75
+ refusal: null,
76
+ undecided: false,
77
+ refund: null,
78
+ };
79
+
80
+ const RECEIPT = { id: "rcp_1", number: "TEST-2569-000001", isTest: true, issuedAt: "2026-11-15T09:01:00.000Z", replaces: null };
81
+
82
+ describe("every helper names why the platform said no", () => {
83
+ const cases: [string, Response, string, string?][] = [
84
+ ["the gate refusing the App Key", serviceRefusal("invalid_app_key", 401), "invalid_app_key"],
85
+ ["no Use Grant", serviceRefusal("not_granted", 403), "not_granted"],
86
+ ["a Draft app that holds the grant", serviceRefusal("needs_beta", 403), "needs_beta"],
87
+ ["the gate's other refusals", serviceRefusal("provider_unavailable", 502), "upstream_unavailable"],
88
+ [
89
+ "a bad field",
90
+ Response.json({ error: "invalid_payment", field: "amountSatang" }, { status: 400 }),
91
+ "invalid_payment",
92
+ "amountSatang",
93
+ ],
94
+ ["no Checkout Page configured", Response.json({ error: "checkout_unavailable" }, { status: 503 }), "checkout_unavailable"],
95
+ ["a Service that answers nonsense", new Response("oops", { status: 500 }), "upstream_unavailable"],
96
+ ];
97
+
98
+ it.each(cases)("%s", async (_name, answer, reason, field) => {
99
+ const h = makeHarness({ services: () => answer.clone() }, SERVICES);
100
+ const expected = { ok: false, reason, ...(field ? { field } : {}) };
101
+
102
+ expect(await createPayment(h.testEnv, INPUT, h.fetchImpl)).toEqual(expected);
103
+ expect(await getPayment(h.testEnv, "pay_1", h.fetchImpl)).toEqual(expected);
104
+ expect(await issueReceipt(h.testEnv, "pay_1", h.fetchImpl)).toEqual(expected);
105
+ expect(await rejectPayment(h.testEnv, "pay_1", h.fetchImpl)).toEqual(expected);
106
+ });
107
+
108
+ it("says not_configured, and calls nothing, when the platform bindings are missing", async () => {
109
+ const h = makeHarness({}, { PPLE_SERVICES_URL: undefined, PPLE_APP_KEY: undefined, DEV_PERSONA: "none" });
110
+
111
+ expect(await createPayment(h.testEnv, INPUT, h.fetchImpl)).toEqual({ ok: false, reason: "not_configured" });
112
+ expect(h.calls.services).toEqual([]);
113
+ });
114
+
115
+ it("says upstream_unavailable when the call itself fails", async () => {
116
+ const h = makeHarness({}, SERVICES);
117
+ const down: typeof fetch = () => Promise.reject(new Error("offline"));
118
+
119
+ expect(await getPayment(h.testEnv, "pay_1", down)).toEqual({ ok: false, reason: "upstream_unavailable" });
120
+ });
121
+ });
122
+
123
+ describe("getPayment", () => {
124
+ it("reads the Payment back, the one source of truth for its state", async () => {
125
+ const h = makeHarness({ services: () => Response.json(PAID) }, SERVICES);
126
+
127
+ expect(await getPayment(h.testEnv, "pay_1", h.fetchImpl)).toEqual({ ok: true, payment: PAID });
128
+ expect(h.calls.services).toEqual([expect.objectContaining({ path: "/platform/payments/pay_1", method: "GET" })]);
129
+ });
130
+
131
+ it("says not_found for another app's Payment, or one that does not exist", async () => {
132
+ const h = makeHarness({ services: () => Response.json({ error: "not_found" }, { status: 404 }) }, SERVICES);
133
+
134
+ expect(await getPayment(h.testEnv, "pay_other", h.fetchImpl)).toEqual({ ok: false, reason: "not_found" });
135
+ });
136
+
137
+ it("never lets an id change the path it calls", async () => {
138
+ const h = makeHarness({ services: () => Response.json({ error: "not_found" }, { status: 404 }) }, SERVICES);
139
+
140
+ await getPayment(h.testEnv, "../x?y=1", h.fetchImpl);
141
+
142
+ expect(h.calls.services[0]!.path).toBe("/platform/payments/..%2Fx%3Fy%3D1");
143
+ });
144
+ });
145
+
146
+ describe("issueReceipt", () => {
147
+ it("issues the Receipt, and says whether it was issued now or before", async () => {
148
+ let answered = 0;
149
+ const h = makeHarness(
150
+ { services: () => Response.json({ receipt: RECEIPT }, { status: answered++ === 0 ? 201 : 200 }) },
151
+ SERVICES,
152
+ );
153
+
154
+ expect(await issueReceipt(h.testEnv, "pay_1", h.fetchImpl)).toEqual({ ok: true, receipt: RECEIPT, issuedNow: true });
155
+ expect(await issueReceipt(h.testEnv, "pay_1", h.fetchImpl)).toEqual({ ok: true, receipt: RECEIPT, issuedNow: false });
156
+ expect(h.calls.services[0]).toMatchObject({ path: "/platform/payments/pay_1/receipt", method: "POST" });
157
+ });
158
+
159
+ it("says not_paid when there is nothing to issue a Receipt for", async () => {
160
+ const h = makeHarness({ services: () => Response.json({ error: "not_paid" }, { status: 409 }) }, SERVICES);
161
+
162
+ expect(await issueReceipt(h.testEnv, "pay_1", h.fetchImpl)).toEqual({ ok: false, reason: "not_paid" });
163
+ });
164
+ });
165
+
166
+ describe("rejectPayment", () => {
167
+ it("rejects a paid Payment and answers it, refunded or with a Refund Owed", async () => {
168
+ const owed = { ...PAID, state: "rejected", refund: { status: "owed" } };
169
+ const h = makeHarness({ services: () => Response.json(owed) }, SERVICES);
170
+
171
+ expect(await rejectPayment(h.testEnv, "pay_1", h.fetchImpl)).toEqual({ ok: true, payment: owed });
172
+ expect(h.calls.services[0]).toMatchObject({ path: "/platform/payments/pay_1/reject", method: "POST" });
173
+ });
174
+
175
+ it("says has_receipt once a Receipt exists: only a Finance Officer can refund it", async () => {
176
+ const h = makeHarness({ services: () => Response.json({ error: "has_receipt" }, { status: 409 }) }, SERVICES);
177
+
178
+ expect(await rejectPayment(h.testEnv, "pay_1", h.fetchImpl)).toEqual({ ok: false, reason: "has_receipt" });
179
+ });
180
+ });
181
+
182
+ const PAID_EVENT: PaymentPaidEvent = {
183
+ type: "payment.paid",
184
+ id: "evt_1",
185
+ payment: {
186
+ id: "pay_1",
187
+ kind: "donation",
188
+ amountSatang: 50_000,
189
+ description: "บริจาคสนับสนุนพรรค",
190
+ reference: "order-1",
191
+ mode: "test",
192
+ },
193
+ payer: PAID.payer,
194
+ voucher: PAID.voucher,
195
+ paidAt: PAID.paidAt,
196
+ };
197
+
198
+ describe("verifyPaymentEvent", () => {
199
+ // The platform authenticates the delivery itself (the wrapper's own secret
200
+ // never reaches your code), and your handler is handed the parsed event only.
201
+ // To act on money, read the Payment back and compare: what the platform says
202
+ // now is the truth, and it is what you get back.
203
+ it("reads the Payment back and hands you the platform's version when the event matches it", async () => {
204
+ const h = makeHarness({ services: () => Response.json(PAID) }, SERVICES);
205
+
206
+ expect(await verifyPaymentEvent(h.testEnv, PAID_EVENT, h.fetchImpl)).toEqual({ ok: true, payment: PAID });
207
+ expect(h.calls.services[0]).toMatchObject({ path: "/platform/payments/pay_1", method: "GET" });
208
+ });
209
+
210
+ it.each([
211
+ ["another amount", { amountSatang: 1 }],
212
+ ["another reference", { reference: "order-2" }],
213
+ ["another kind", { kind: "membership_fee" }],
214
+ ["another mode", { mode: "live" }],
215
+ ])("refuses an event that claims %s than the Payment has", async (_name, claim) => {
216
+ const h = makeHarness({ services: () => Response.json(PAID) }, SERVICES);
217
+ const forged = { ...PAID_EVENT, payment: { ...PAID_EVENT.payment, ...claim } } as PaymentEvent;
218
+
219
+ expect(await verifyPaymentEvent(h.testEnv, forged, h.fetchImpl)).toEqual({ ok: false, reason: "mismatch" });
220
+ });
221
+
222
+ it("refuses a paid event for a Payment that is not paid", async () => {
223
+ const h = makeHarness({ services: () => Response.json({ ...PAID, state: "created", payer: null }) }, SERVICES);
224
+
225
+ expect(await verifyPaymentEvent(h.testEnv, PAID_EVENT, h.fetchImpl)).toEqual({ ok: false, reason: "mismatch" });
226
+ });
227
+
228
+ it("accepts a late paid event for a Payment that has moved on since", async () => {
229
+ const h = makeHarness({ services: () => Response.json({ ...PAID, state: "rejected" }) }, SERVICES);
230
+
231
+ const result = await verifyPaymentEvent(h.testEnv, PAID_EVENT, h.fetchImpl);
232
+
233
+ expect(result).toMatchObject({ ok: true, payment: { state: "rejected" } });
234
+ });
235
+
236
+ it.each([
237
+ ["payment.refused", ["refused"], ["paid", "created"]],
238
+ ["payment.rejected", ["rejected", "refunded"], ["paid"]],
239
+ ["payment.refunded", ["refunded"], ["rejected", "paid"]],
240
+ ["payment.receipt_issued", ["paid", "refunding", "refunded"], ["created", "refused"]],
241
+ ["payment.receipt_voided", ["refunding", "refunded", "paid"], ["created", "refused"]],
242
+ ])("checks the state %s implies", async (type, agrees, disagrees) => {
243
+ const event = { ...PAID_EVENT, type } as unknown as PaymentEvent;
244
+ for (const state of agrees) {
245
+ const h = makeHarness({ services: () => Response.json({ ...PAID, state }) }, SERVICES);
246
+ expect(await verifyPaymentEvent(h.testEnv, event, h.fetchImpl)).toMatchObject({ ok: true });
247
+ }
248
+ for (const state of disagrees) {
249
+ const h = makeHarness({ services: () => Response.json({ ...PAID, state }) }, SERVICES);
250
+ expect(await verifyPaymentEvent(h.testEnv, event, h.fetchImpl)).toEqual({ ok: false, reason: "mismatch" });
251
+ }
252
+ });
253
+
254
+ it("says not_found for a Payment that is not this app's, and passes a refusal on", async () => {
255
+ const missing = makeHarness({ services: () => Response.json({ error: "not_found" }, { status: 404 }) }, SERVICES);
256
+ const down = makeHarness({ services: () => serviceRefusal("provider_unavailable", 502) }, SERVICES);
257
+
258
+ expect(await verifyPaymentEvent(missing.testEnv, PAID_EVENT, missing.fetchImpl)).toEqual({ ok: false, reason: "not_found" });
259
+ expect(await verifyPaymentEvent(down.testEnv, PAID_EVENT, down.fetchImpl)).toEqual({ ok: false, reason: "upstream_unavailable" });
260
+ });
261
+ });
262
+
263
+ describe("paymentHandler", () => {
264
+ const ctx = testExecutionContext();
265
+ const env = makeHarness({}, SERVICES).testEnv;
266
+
267
+ it("calls the function for the event's type, with the event typed for it", async () => {
268
+ const seen: string[] = [];
269
+ const handler = paymentHandler({
270
+ "payment.paid": (event) => {
271
+ seen.push(`${event.type}:${event.voucher?.number}`);
272
+ },
273
+ });
274
+
275
+ expect(await handler(PAID_EVENT, env, ctx)).toBeUndefined();
276
+ expect(seen).toEqual(["payment.paid:TEST-PV-000001"]);
277
+ });
278
+
279
+ it("hands over a Replacement Receipt's event with the Receipt it replaces", async () => {
280
+ const seen: string[] = [];
281
+ const handler = paymentHandler({
282
+ "payment.receipt_issued": (event) => {
283
+ seen.push(`${event.receipt.number} replaces ${event.receipt.replaces?.number ?? "nothing"}`);
284
+ },
285
+ });
286
+ const replacement = {
287
+ type: "payment.receipt_issued",
288
+ id: "evt_receipt_issued_rcp_2",
289
+ payment: PAID_EVENT.payment,
290
+ payer: { name: "นางสาวสมหญิง ใจงาม", maskedCitizenId: "x-xxxx-xxxxx-78-9" },
291
+ receipt: { ...RECEIPT, id: "rcp_2", number: "TEST-2569-000002", replaces: { id: "rcp_1", number: "TEST-2569-000001" } },
292
+ } satisfies PaymentEvent;
293
+
294
+ expect(await handler(replacement, env, ctx)).toBeUndefined();
295
+ expect(await handler({ ...replacement, receipt: RECEIPT }, env, ctx)).toBeUndefined();
296
+ expect(seen).toEqual(["TEST-2569-000002 replaces TEST-2569-000001", "TEST-2569-000001 replaces nothing"]);
297
+ });
298
+
299
+ it("answers 2xx to a type it does not handle, so a later outcome is not retried forever", async () => {
300
+ const handler = paymentHandler({ "payment.paid": () => {} });
301
+ const later = { ...PAID_EVENT, type: "payment.voided" } as unknown as PaymentEvent;
302
+
303
+ expect(await handler({ ...PAID_EVENT, type: "payment.refunded", refundedAt: null } as PaymentEvent, env, ctx)).toBeUndefined();
304
+ expect(await handler(later, env, ctx)).toBeUndefined();
305
+ });
306
+
307
+ it("keeps what the function returns: a non-2xx Response is 'not delivered' and is sent again", async () => {
308
+ const handler = paymentHandler({ "payment.paid": () => new Response(null, { status: 503 }) });
309
+
310
+ expect(((await handler(PAID_EVENT, env, ctx)) as Response).status).toBe(503);
311
+ });
312
+
313
+ it("lets a throw through, which the platform records as 'not delivered'", async () => {
314
+ const handler = paymentHandler({
315
+ "payment.paid": () => {
316
+ throw new Error("db down");
317
+ },
318
+ });
319
+
320
+ await expect(Promise.resolve().then(() => handler(PAID_EVENT, env, ctx))).rejects.toThrow("db down");
321
+ });
322
+ });
@@ -0,0 +1,29 @@
1
+ // The registry's own `platform/payments` mocks, served the way `npm run dev`
2
+ // serves them (ADR-0026): through the offline matcher, as a Persona. Tests use
3
+ // it as the fake Platform Service, so a test runs the answers a Builder sees
4
+ // offline, not a hand-written copy of them.
5
+
6
+ import { answerFromOverlay } from "../src/dev-call-service";
7
+
8
+ // The registry's files, laid out as `pple registry` writes them into
9
+ // `.pple/registry/`: the platform's entries sit under `platform/`.
10
+ const files: Record<string, unknown> = Object.fromEntries(
11
+ Object.entries(
12
+ import.meta.glob("../../registry/payments/**/*", { eager: true, query: "?raw", import: "default" }),
13
+ ).map(([file, text]) => [file.replace("../../registry/payments/", "overlay/platform/payments/"), text]),
14
+ );
15
+
16
+ /** Handles `{PPLE_SERVICES_URL}/platform/payments/…` as the mocks would for `persona`. */
17
+ export function offlinePayments(persona: string): (req: Request) => Response {
18
+ return (req) => {
19
+ const prefix = "/platform/payments";
20
+ const url = new URL(req.url);
21
+ return answerFromOverlay(files, {
22
+ entry: "platform/payments",
23
+ path: url.pathname.slice(prefix.length),
24
+ method: req.method,
25
+ persona,
26
+ overlayRoot: "overlay/",
27
+ });
28
+ };
29
+ }
@@ -17,5 +17,5 @@
17
17
  "isolatedModules": true,
18
18
  "forceConsistentCasingInFileNames": true
19
19
  },
20
- "include": ["src", "test", "shared"]
20
+ "include": ["src", "test", "shared", "recipes"]
21
21
  }
@@ -59,6 +59,20 @@
59
59
  //
60
60
  // "triggers": { "crons": ["0 1 * * *"] },
61
61
 
62
+ // Durable Objects. Export the class from src/index.ts (the Worker's main
63
+ // module). Local `npm run dev` emulates it with no extra setup: this binding
64
+ // and the migration are enough, and nothing is provisioned in the cloud.
65
+ // A deployed app receives the binding only while it holds Durable Object
66
+ // access — ask a Platform Admin in an App Note (บันทึก). New classes are
67
+ // SQLite (`new_sqlite_classes` only). Uncomment both blocks together:
68
+ //
69
+ // "durable_objects": {
70
+ // "bindings": [{ "name": "COUNTER", "class_name": "Counter" }]
71
+ // },
72
+ // "migrations": [
73
+ // { "tag": "v1", "new_sqlite_classes": ["Counter"] }
74
+ // ],
75
+
62
76
  "vars": {
63
77
  // PPLE ID (identity). The Worker validates bearer tokens against this.
64
78
  "SSO_BASE_URL": "https://id.peoplesparty.or.th",