@pplethai/cli 0.15.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,427 @@
1
+ // Payments (docs/adr/0037). The helpers below wrap the Private Platform Service
2
+ // `platform/payments`: `createPayment`, `getPayment`, `issueReceipt`,
3
+ // `rejectPayment`, `verifyPaymentEvent` and `paymentHandler`. Each answers
4
+ // `{ ok: true, … }` or `{ ok: false, reason }`. Offline (`npm run dev` with a
5
+ // Persona) they answer from the entry's mocks. The rest of this comment is the
6
+ // outcome the platform sends you.
7
+ //
8
+ // A Payment's outcome. You created the Payment with the
9
+ // Private Platform Service `platform/payments` and sent the Payer to its
10
+ // `checkoutUrl`. When the Payer has paid, the platform calls
11
+ // `payment(event, env, ctx)` on the Worker default export, beside `fetch`.
12
+ // Define it on `worker` in `src/index.ts`.
13
+ //
14
+ // What your handler returns is what the platform records:
15
+ //
16
+ // - not defined: the platform records "not delivered"
17
+ // - returns nothing, or a `2xx` Response: delivered
18
+ // - any other status, or throws: not delivered. The Payment is still paid,
19
+ // and the platform tells you again the next time it hears from the Gateway
20
+ //
21
+ // Delivery is at-least-once. Dedupe on `event.payment.id` (the event's own
22
+ // `id` is the same on every attempt). You can always read a Payment back with
23
+ // `GET platform/payments/<id>`. Switch on `event.type` and answer `2xx` to a
24
+ // type you do not handle: later outcomes arrive as new types.
25
+ //
26
+ // A paid Payment has a Payment Voucher, which is not a receipt. The legal
27
+ // Receipt is issued when YOU ask: `POST platform/payments/<id>/receipt`, from
28
+ // this handler or after your own checks. Asking twice is safe. The platform
29
+ // then calls you with `payment.receipt_issued`.
30
+ //
31
+ // The event carries what the Receipt will print and no more: the Payer's full
32
+ // name and a masked citizen ID. You never receive the full citizen ID, and you
33
+ // need no Use Grant of `platform/legal-identity` to take a payment.
34
+ //
35
+ // The party's finance rules are checked at checkout for every app together. A
36
+ // Payment they refuse is not paid: you get a `payment.refused` event instead
37
+ // (switch on `event.type`).
38
+ //
39
+ // If your own checks fail, reject a paid Payment that has no Receipt yet:
40
+ // `POST platform/payments/<id>/reject`. A card is refunded and you get
41
+ // `payment.rejected` then `payment.refunded`; money the Gateway cannot return
42
+ // (a QR payment) becomes a Refund Owed the Finance Officer pays back by hand,
43
+ // and you get `payment.rejected` only (`payment.refunded` follows when they
44
+ // have). Once a Receipt exists you cannot reject: only a Finance Officer can
45
+ // refund it. A paid Payment you neither issue nor reject within the party's
46
+ // deadline goes to the Finance Officer as Undecided; you can still do either.
47
+ // An event you did not answer `2xx` is sent again every few minutes.
48
+ //
49
+ // A Finance Officer may refund a Payment after its Receipt was issued: the
50
+ // Receipt is voided (it stays on record under its number) and you hear
51
+ // `payment.receipt_voided`, then `payment.refunded` once the money is back. A
52
+ // Refund Owed the Finance Officer keeps as a donation brings the Payment back
53
+ // to `paid` as a donation with a new Receipt: you hear `payment.receipt_issued`.
54
+ //
55
+ // A Receipt is never edited. A Payer asks for a correction (or a Finance Officer
56
+ // makes one) and the Receipt is voided and a Replacement issued under a new
57
+ // number: you hear `payment.receipt_voided`, then `payment.receipt_issued` for
58
+ // the Replacement, whose `receipt.replaces` names the Receipt it replaces. The
59
+ // Payment stays `paid`; its lookup's `receipt` is now the Replacement.
60
+ //
61
+ // A `paid` event with `mode: "test"` is a sandbox payment from a Draft or Beta
62
+ // app. No money moved and no legal Receipt will exist for it. Only a Live
63
+ // app's Payments are `live`.
64
+
65
+ import { callService, platformError, type CallServiceEnv, type PlatformErrorCode } from "./call-service";
66
+ import type { Env } from "./env";
67
+
68
+ /** What you send to create a Payment. Every field is required. */
69
+ export interface CreatePaymentInput {
70
+ kind: "donation" | "membership_fee";
71
+ /** 100 satang is 1 baht. A positive integer. */
72
+ amountSatang: number;
73
+ /** What the Payer sees on the Checkout Page. 1 to 200 characters. */
74
+ description: string;
75
+ /** Your own id for this payment. It comes back on every event and lookup. 1 to 128 characters. */
76
+ reference: string;
77
+ /** Where the Checkout Page sends the Payer afterwards. `https` (`http://localhost` locally). */
78
+ returnUrl: string;
79
+ }
80
+
81
+ /** Why a call to `platform/payments` did not give you what you asked for. */
82
+ export type PaymentReason =
83
+ | "not_configured"
84
+ | "invalid_app_key"
85
+ | "not_granted"
86
+ | "needs_beta"
87
+ | "invalid_payment"
88
+ | "not_found"
89
+ | "not_paid"
90
+ | "has_receipt"
91
+ | "mismatch"
92
+ | "checkout_unavailable"
93
+ | "upstream_unavailable";
94
+
95
+ export type PaymentResult<T> =
96
+ | ({ ok: true } & T)
97
+ | { ok: false; reason: PaymentReason; /** For `invalid_payment`: the field that is missing or wrong. */ field?: string };
98
+
99
+ /** The Issuer's Receipt for a Payment. A test Receipt is `TEST-…`, watermarked, and never legal. */
100
+ export interface PaymentReceipt {
101
+ id: string;
102
+ number: string;
103
+ isTest: boolean;
104
+ /** ISO 8601. */
105
+ issuedAt: string;
106
+ /** A Replacement Receipt names the Receipt it replaces; null on a first Receipt. */
107
+ replaces: { id: string; number: string } | null;
108
+ }
109
+
110
+ /** The Payment as the platform answers a lookup. */
111
+ export interface PaymentRecord {
112
+ id: string;
113
+ kind: "donation" | "membership_fee";
114
+ amountSatang: number;
115
+ description: string;
116
+ reference: string;
117
+ state: "created" | "pending" | "paid" | "refused" | "rejected" | "refunding" | "refunded";
118
+ mode: "live" | "test";
119
+ payer: { name: string; maskedCitizenId: string } | null;
120
+ voucher: { number: string; nameTh: string; isReceipt: false } | null;
121
+ receipt: PaymentReceipt | null;
122
+ paidAt: string | null;
123
+ refusal: { code: string; reasonTh: string } | null;
124
+ /** True for a paid Payment neither issued nor rejected within the party's deadline. You can still do either. */
125
+ undecided: boolean;
126
+ refund: { status: "refunded" | "owed" | "pending" } | null;
127
+ }
128
+
129
+ interface PaymentsEnv extends CallServiceEnv {
130
+ PPLE_SERVICES_URL?: string;
131
+ PPLE_APP_KEY?: string;
132
+ }
133
+
134
+ /**
135
+ * Ask the platform for a Payment. Send the Payer to the `checkoutUrl` it
136
+ * answers: do not build that address yourself.
137
+ */
138
+ export async function createPayment(
139
+ env: PaymentsEnv,
140
+ input: CreatePaymentInput,
141
+ fetchImpl?: typeof fetch,
142
+ ): Promise<PaymentResult<{ id: string; checkoutUrl: string; state: "created" }>> {
143
+ const answer = await callPayments(env, "", fetchImpl, {
144
+ method: "POST",
145
+ headers: { "content-type": "application/json" },
146
+ body: JSON.stringify(input),
147
+ });
148
+ if (!answer.ok) return answer;
149
+ const { id, checkoutUrl } = answer.body;
150
+ if (typeof id !== "string" || typeof checkoutUrl !== "string") return refused("upstream_unavailable");
151
+ return { ok: true, id, checkoutUrl, state: "created" };
152
+ }
153
+
154
+ /** Read a Payment back. The platform's answer, not an event, is the truth about its state. */
155
+ export async function getPayment(
156
+ env: PaymentsEnv,
157
+ id: string,
158
+ fetchImpl?: typeof fetch,
159
+ ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
160
+ const answer = await callPayments(env, `/${encodeURIComponent(id)}`, fetchImpl, { method: "GET" });
161
+ if (!answer.ok) return answer;
162
+ return { ok: true, payment: answer.body as unknown as PaymentRecord };
163
+ }
164
+
165
+ /**
166
+ * Ask the platform to issue the legal Receipt for a paid Payment. Safe to
167
+ * repeat: `issuedNow` is false when it was issued before. A test Receipt
168
+ * (`isTest`) is never legal.
169
+ */
170
+ export async function issueReceipt(
171
+ env: PaymentsEnv,
172
+ id: string,
173
+ fetchImpl?: typeof fetch,
174
+ ): Promise<PaymentResult<{ receipt: PaymentReceipt; issuedNow: boolean }>> {
175
+ const answer = await callPayments(env, `/${encodeURIComponent(id)}/receipt`, fetchImpl, { method: "POST" });
176
+ if (!answer.ok) return answer;
177
+ const receipt = answer.body.receipt as PaymentReceipt | undefined;
178
+ if (!receipt || typeof receipt.id !== "string") return refused("upstream_unavailable");
179
+ return { ok: true, receipt, issuedNow: answer.status === 201 };
180
+ }
181
+
182
+ /**
183
+ * Reject a paid Payment that has no Receipt. A card is refunded; money the
184
+ * Gateway cannot return (a QR payment) becomes a Refund Owed
185
+ * (`payment.refund.status === "owed"`) the Finance Officer pays back by hand.
186
+ * Once a Receipt exists this says `has_receipt`.
187
+ */
188
+ export async function rejectPayment(
189
+ env: PaymentsEnv,
190
+ id: string,
191
+ fetchImpl?: typeof fetch,
192
+ ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
193
+ const answer = await callPayments(env, `/${encodeURIComponent(id)}/reject`, fetchImpl, { method: "POST" });
194
+ if (!answer.ok) return answer;
195
+ return { ok: true, payment: answer.body as unknown as PaymentRecord };
196
+ }
197
+
198
+ /** The states a Payment can be in once the platform has sent an event of that type, and any time after. */
199
+ const STATES_AFTER: Record<string, readonly PaymentRecord["state"][]> = {
200
+ "payment.paid": ["paid", "rejected", "refunding", "refunded"],
201
+ // A Finance Officer can refund a Payment after its Receipt (`refunding`, then `refunded`).
202
+ "payment.receipt_issued": ["paid", "refunding", "refunded"],
203
+ "payment.receipt_voided": ["refunding", "refunded", "paid"],
204
+ "payment.refused": ["refused"],
205
+ "payment.rejected": ["rejected", "refunded"],
206
+ "payment.refunded": ["refunded"],
207
+ };
208
+
209
+ /**
210
+ * Check an event against the platform before you act on money. The platform
211
+ * authenticates its own delivery and your handler gets the parsed event only,
212
+ * so this reads the Payment back (`getPayment`) and compares the id, kind,
213
+ * amount, reference and mode, and that the state is one the event's type can
214
+ * lead to. A late event passes: the Payment may have moved on since. Use the
215
+ * `payment` it returns, not the event, to decide what to do next.
216
+ *
217
+ * `mismatch` means the event does not describe that Payment. Answer it with a
218
+ * `2xx` and do nothing: a retry cannot make it true. `not_found` and
219
+ * `upstream_unavailable` are worth a retry: throw, or return a non-2xx.
220
+ */
221
+ export async function verifyPaymentEvent(
222
+ env: PaymentsEnv,
223
+ event: PaymentEvent,
224
+ fetchImpl?: typeof fetch,
225
+ ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
226
+ const read = await getPayment(env, event.payment.id, fetchImpl);
227
+ if (!read.ok) return read;
228
+ const claimed = event.payment;
229
+ const actual = read.payment;
230
+ const same =
231
+ actual.id === claimed.id &&
232
+ actual.kind === claimed.kind &&
233
+ actual.amountSatang === claimed.amountSatang &&
234
+ actual.reference === claimed.reference &&
235
+ actual.mode === claimed.mode;
236
+ const allowed = STATES_AFTER[event.type];
237
+ if (!same || (allowed !== undefined && !allowed.includes(actual.state))) return refused("mismatch");
238
+ return read;
239
+ }
240
+
241
+ /** One function per event type you handle. Each is called with that type's event. */
242
+ export type PaymentHandlers = {
243
+ [T in PaymentEvent["type"]]?: (
244
+ event: Extract<PaymentEvent, { type: T }>,
245
+ env: Env,
246
+ ctx: ExecutionContext,
247
+ ) => void | Response | Promise<void | Response>;
248
+ };
249
+
250
+ /**
251
+ * Build your `payment` handler: `worker.payment = paymentHandler({ "payment.paid": … })`.
252
+ * A type you give no function is answered `2xx` and ignored, which is what the
253
+ * platform needs: later outcomes arrive as new types, and an answer that is not
254
+ * `2xx` is sent again every few minutes. What your function returns, or throws,
255
+ * is what the platform records (see the top of this file).
256
+ */
257
+ export function paymentHandler(handlers: PaymentHandlers): PaymentHandler {
258
+ return (event, env, ctx) => {
259
+ const handle = handlers[event.type] as
260
+ | ((event: PaymentEvent, env: Env, ctx: ExecutionContext) => void | Response | Promise<void | Response>)
261
+ | undefined;
262
+ return handle ? handle(event, env, ctx) : undefined;
263
+ };
264
+ }
265
+
266
+ type Answer = { ok: true; status: number; body: Record<string, unknown> } | { ok: false; reason: PaymentReason; field?: string };
267
+
268
+ function refused(reason: PaymentReason, field?: string): { ok: false; reason: PaymentReason; field?: string } {
269
+ return field === undefined ? { ok: false, reason } : { ok: false, reason, field };
270
+ }
271
+
272
+ /** The platform's own refusals (`x-pple-error`) a Builder can act on. Anything else is the Service being unavailable. */
273
+ function platformReason(code: PlatformErrorCode | null): PaymentReason {
274
+ switch (code) {
275
+ case "invalid_app_key":
276
+ case "not_granted":
277
+ case "needs_beta":
278
+ return code;
279
+ default:
280
+ return "upstream_unavailable";
281
+ }
282
+ }
283
+
284
+ /** The Service's own answers, by `error` in the body. */
285
+ const SERVICE_REASONS = ["invalid_payment", "not_found", "not_paid", "has_receipt", "checkout_unavailable"] as const;
286
+
287
+ async function callPayments(
288
+ env: PaymentsEnv,
289
+ path: string,
290
+ fetchImpl: typeof fetch | undefined,
291
+ init: RequestInit,
292
+ ): Promise<Answer> {
293
+ // Offline (`npm run dev` with a Persona) `callService` answers from the mocks
294
+ // and needs no bindings.
295
+ const offline = import.meta.env.DEV && env.DEV_PERSONA !== "none";
296
+ if (!offline && (!env.PPLE_SERVICES_URL || !env.PPLE_APP_KEY)) return refused("not_configured");
297
+
298
+ let res: Response;
299
+ try {
300
+ res = await callService(env, "platform/payments", path, init, fetchImpl ? { fetchImpl } : {});
301
+ } catch {
302
+ return refused("upstream_unavailable");
303
+ }
304
+
305
+ // A platform refusal carries `x-pple-error`. This Service's own answers do
306
+ // not, so a body `error` is trusted only when the header is absent.
307
+ if (res.headers.get("x-pple-error")) return refused(platformReason(platformError(res)));
308
+
309
+ const body = ((await res.json().catch(() => null)) ?? {}) as Record<string, unknown>;
310
+ const error = typeof body.error === "string" ? body.error : undefined;
311
+ const reason = SERVICE_REASONS.find((r) => r === error);
312
+ if (reason) return refused(reason, typeof body.field === "string" ? body.field : undefined);
313
+ if (!res.ok) return refused("upstream_unavailable");
314
+ return { ok: true, status: res.status, body };
315
+ }
316
+
317
+ export interface PaymentPaidEvent {
318
+ type: "payment.paid";
319
+ /** The same on every delivery of this outcome. */
320
+ id: string;
321
+ payment: {
322
+ id: string;
323
+ kind: "donation" | "membership_fee";
324
+ /** 100 satang is 1 baht. */
325
+ amountSatang: number;
326
+ description: string;
327
+ /** Your own id, as you sent it. */
328
+ reference: string;
329
+ mode: "live" | "test";
330
+ };
331
+ payer: { name: string; maskedCitizenId: string } | null;
332
+ /** The platform's acknowledgement that the money arrived. Not a receipt. */
333
+ voucher: { number: string; nameTh: string; isReceipt: false } | null;
334
+ /** ISO 8601. */
335
+ paidAt: string | null;
336
+ }
337
+
338
+ /**
339
+ * The party's finance rules (a smallest or largest amount, or a Payer's yearly
340
+ * cap across all apps) refused the Payment. Nothing was charged and the Payment
341
+ * has ended: create a new one to let the Payer try again.
342
+ */
343
+ export interface PaymentRefusedEvent {
344
+ type: "payment.refused";
345
+ /** The same on every delivery of this outcome. */
346
+ id: string;
347
+ payment: PaymentPaidEvent["payment"];
348
+ /** `reasonTh` is for the Payer: show it as is. */
349
+ refusal: { code: "below_minimum" | "above_maximum" | "over_yearly_cap"; reasonTh: string } | null;
350
+ /** ISO 8601. */
351
+ refusedAt: string | null;
352
+ }
353
+
354
+ /**
355
+ * The platform issued the Receipt you asked for (`POST platform/payments/<id>/receipt`).
356
+ * `payer` is what that Receipt prints, as captured at payment.
357
+ */
358
+ export interface PaymentReceiptIssuedEvent {
359
+ type: "payment.receipt_issued";
360
+ /** The same on every delivery of this Receipt's event. */
361
+ id: string;
362
+ payment: PaymentPaidEvent["payment"];
363
+ payer: { name: string; maskedCitizenId: string };
364
+ receipt: {
365
+ id: string;
366
+ /** The Issuer's own number, e.g. `2569-000123`. A test Receipt is `TEST-2569-000001`. */
367
+ number: string;
368
+ /** True for a Draft or Beta app's Receipt: watermarked, never a legal number. */
369
+ isTest: boolean;
370
+ /** ISO 8601. */
371
+ issuedAt: string;
372
+ /** Set on a Replacement Receipt (a correction): the voided Receipt it replaces. Null on a first Receipt. */
373
+ replaces: { id: string; number: string } | null;
374
+ };
375
+ }
376
+
377
+ /** You rejected the Payment (`POST platform/payments/<id>/reject`) and it is recorded. */
378
+ export interface PaymentRejectedEvent {
379
+ type: "payment.rejected";
380
+ /** The same on every delivery of this outcome. */
381
+ id: string;
382
+ payment: PaymentPaidEvent["payment"];
383
+ /** ISO 8601. */
384
+ rejectedAt: string | null;
385
+ }
386
+
387
+ /** A rejected Payment's money is back with the Payer: by the Gateway, or settled by the Finance Officer. */
388
+ export interface PaymentRefundedEvent {
389
+ type: "payment.refunded";
390
+ /** The same on every delivery of this outcome. */
391
+ id: string;
392
+ payment: PaymentPaidEvent["payment"];
393
+ /** ISO 8601. */
394
+ refundedAt: string | null;
395
+ }
396
+
397
+ /**
398
+ * A Finance Officer voided a Receipt of your Payment: they refunded it after the
399
+ * Receipt (the Payment is `refunding`, and `payment.refunded` follows once the
400
+ * money is back), or it is being corrected (the Payment stays `paid` and
401
+ * `payment.receipt_issued` follows for the Replacement). The Receipt stays on
402
+ * record under its number.
403
+ */
404
+ export interface PaymentReceiptVoidedEvent {
405
+ type: "payment.receipt_voided";
406
+ /** The same on every delivery of this Receipt's event. */
407
+ id: string;
408
+ payment: PaymentPaidEvent["payment"];
409
+ receipt: PaymentReceiptIssuedEvent["receipt"] & {
410
+ /** ISO 8601. */
411
+ voidedAt: string | null;
412
+ };
413
+ }
414
+
415
+ export type PaymentEvent =
416
+ | PaymentPaidEvent
417
+ | PaymentRefusedEvent
418
+ | PaymentReceiptIssuedEvent
419
+ | PaymentReceiptVoidedEvent
420
+ | PaymentRejectedEvent
421
+ | PaymentRefundedEvent;
422
+
423
+ export type PaymentHandler = (
424
+ event: PaymentEvent,
425
+ env: Env,
426
+ ctx: ExecutionContext,
427
+ ) => void | Response | Promise<void | Response>;
@@ -15,6 +15,7 @@
15
15
  import { IdentitySchema, type Identity } from "../shared/api";
16
16
  import type { Env } from "./env";
17
17
  import type { NotificationResponseHandler } from "./notification-response";
18
+ import type { PaymentHandler } from "./payment";
18
19
 
19
20
  export const CONSUMER_HEADER = "x-pple-consumer";
20
21
  export const ENTRY_HEADER = "x-pple-entry";
@@ -92,6 +93,8 @@ export interface PpleWorker {
92
93
  registry?: RegistryMap;
93
94
  /** Answers to your Interactive Notifications. See `./notification-response`. */
94
95
  notificationResponse?: NotificationResponseHandler;
96
+ /** What happened to a Payment you created. See `./payment`. */
97
+ payment?: PaymentHandler;
95
98
  }
96
99
 
97
100
  function decodeIdentity(value: string): Identity | null {
@@ -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
+ });