@pplethai/cli 0.21.0 → 0.23.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.
Files changed (117) hide show
  1. package/README.md +12 -14
  2. package/dist/bin.js +102 -102
  3. package/package.json +3 -6
  4. package/templates/golden-path/.dev.vars.example +0 -33
  5. package/templates/golden-path/.env.example +0 -10
  6. package/templates/golden-path/.github/workflows/ci.yml +0 -22
  7. package/templates/golden-path/AGENTS.md +0 -1
  8. package/templates/golden-path/CLAUDE.md +0 -187
  9. package/templates/golden-path/README.md +0 -118
  10. package/templates/golden-path/gitignore +0 -17
  11. package/templates/golden-path/index.html +0 -16
  12. package/templates/golden-path/migrations/0001_init.sql +0 -10
  13. package/templates/golden-path/overlay-mtime.mjs +0 -30
  14. package/templates/golden-path/package-lock.json +0 -4318
  15. package/templates/golden-path/package.json +0 -41
  16. package/templates/golden-path/scripts/assert-dev-compiled-out.mjs +0 -45
  17. package/templates/golden-path/shared/api.ts +0 -325
  18. package/templates/golden-path/src/auth.ts +0 -230
  19. package/templates/golden-path/src/call-service.ts +0 -147
  20. package/templates/golden-path/src/dataset-query.ts +0 -470
  21. package/templates/golden-path/src/dataset-schema.ts +0 -398
  22. package/templates/golden-path/src/db.ts +0 -32
  23. package/templates/golden-path/src/dev-call-service.ts +0 -392
  24. package/templates/golden-path/src/dev-personas.ts +0 -186
  25. package/templates/golden-path/src/dev-read-dataset.ts +0 -444
  26. package/templates/golden-path/src/dev-registry.ts +0 -294
  27. package/templates/golden-path/src/email.ts +0 -224
  28. package/templates/golden-path/src/entry-name.ts +0 -114
  29. package/templates/golden-path/src/env.ts +0 -38
  30. package/templates/golden-path/src/files.ts +0 -38
  31. package/templates/golden-path/src/identity-header.ts +0 -17
  32. package/templates/golden-path/src/index.ts +0 -276
  33. package/templates/golden-path/src/legal-identity.ts +0 -180
  34. package/templates/golden-path/src/levels.ts +0 -132
  35. package/templates/golden-path/src/notification-response.ts +0 -55
  36. package/templates/golden-path/src/notify.ts +0 -311
  37. package/templates/golden-path/src/payment.ts +0 -554
  38. package/templates/golden-path/src/read-dataset.ts +0 -490
  39. package/templates/golden-path/src/registry.ts +0 -128
  40. package/templates/golden-path/src/vite-env.d.ts +0 -27
  41. package/templates/golden-path/test/apply-migrations.ts +0 -4
  42. package/templates/golden-path/test/call-service.test.ts +0 -288
  43. package/templates/golden-path/test/dev-call-service.test.ts +0 -455
  44. package/templates/golden-path/test/dev-read-dataset.test.ts +0 -379
  45. package/templates/golden-path/test/dev-registry.test.ts +0 -404
  46. package/templates/golden-path/test/effective-sub.test.ts +0 -101
  47. package/templates/golden-path/test/email-offline.test.ts +0 -51
  48. package/templates/golden-path/test/email.test.ts +0 -117
  49. package/templates/golden-path/test/env.d.ts +0 -17
  50. package/templates/golden-path/test/fixtures/overlay/branch-list/entry.md +0 -85
  51. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/audience.json +0 -3
  52. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/named.json +0 -3
  53. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/offices.json +0 -6
  54. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/roster.json +0 -3
  55. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/summary.json +0 -1
  56. package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +0 -8
  57. package/templates/golden-path/test/fixtures/overlay/catalog/mocks/responses.json +0 -7
  58. package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +0 -11
  59. package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +0 -7
  60. package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +0 -24
  61. package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +0 -1
  62. package/templates/golden-path/test/fixtures/overlay/orders/entry.md +0 -12
  63. package/templates/golden-path/test/fixtures/overlay/orders/mocks/responses.json +0 -36
  64. package/templates/golden-path/test/fixtures/overlay/platform/email/entry.md +0 -12
  65. package/templates/golden-path/test/fixtures/overlay/platform/email/mocks/responses.json +0 -11
  66. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/entry.md +0 -8
  67. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/mocks/responses.json +0 -13
  68. package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +0 -12
  69. package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +0 -71
  70. package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +0 -10
  71. package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +0 -7
  72. package/templates/golden-path/test/fixtures/overlay/score/entry.md +0 -10
  73. package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +0 -7
  74. package/templates/golden-path/test/harness.ts +0 -153
  75. package/templates/golden-path/test/interaction.test.ts +0 -230
  76. package/templates/golden-path/test/legal-identity.test.ts +0 -323
  77. package/templates/golden-path/test/membership.test.ts +0 -105
  78. package/templates/golden-path/test/notification-response.test.ts +0 -79
  79. package/templates/golden-path/test/payment-app.test.ts +0 -210
  80. package/templates/golden-path/test/payment-offline.test.ts +0 -91
  81. package/templates/golden-path/test/payment.test.ts +0 -427
  82. package/templates/golden-path/test/payments-offline.ts +0 -33
  83. package/templates/golden-path/test/read-dataset.test.ts +0 -387
  84. package/templates/golden-path/test/service-call.test.ts +0 -166
  85. package/templates/golden-path/test/smoke.test.ts +0 -464
  86. package/templates/golden-path/tsconfig.json +0 -20
  87. package/templates/golden-path/tsconfig.worker.json +0 -21
  88. package/templates/golden-path/vite.config.ts +0 -12
  89. package/templates/golden-path/vitest.config.ts +0 -28
  90. package/templates/golden-path/web/App.tsx +0 -478
  91. package/templates/golden-path/web/app.css +0 -83
  92. package/templates/golden-path/web/main.tsx +0 -51
  93. package/templates/golden-path/web/pple.ts +0 -124
  94. package/templates/golden-path/web/vite-env.d.ts +0 -10
  95. package/templates/golden-path/wrangler.jsonc +0 -89
  96. package/templates/payment-bridge/.github/workflows/ci.yml +0 -21
  97. package/templates/payment-bridge/CLAUDE.md +0 -9
  98. package/templates/payment-bridge/README.md +0 -57
  99. package/templates/payment-bridge/docs/verify-webhook.md +0 -80
  100. package/templates/payment-bridge/docs/verify-webhook.ts +0 -29
  101. package/templates/payment-bridge/gitignore +0 -5
  102. package/templates/payment-bridge/package-lock.json +0 -4198
  103. package/templates/payment-bridge/package.json +0 -21
  104. package/templates/payment-bridge/src/bridge-key.ts +0 -18
  105. package/templates/payment-bridge/src/env.ts +0 -14
  106. package/templates/payment-bridge/src/index.ts +0 -39
  107. package/templates/payment-bridge/src/platform.ts +0 -49
  108. package/templates/payment-bridge/src/webhook.ts +0 -86
  109. package/templates/payment-bridge/test/docs.test.ts +0 -9
  110. package/templates/payment-bridge/test/fixtures/payments-responses.json +0 -71
  111. package/templates/payment-bridge/test/harness.ts +0 -78
  112. package/templates/payment-bridge/test/inbound.test.ts +0 -138
  113. package/templates/payment-bridge/test/webhook.test.ts +0 -174
  114. package/templates/payment-bridge/tsconfig.json +0 -22
  115. package/templates/payment-bridge/vitest.config.ts +0 -8
  116. package/templates/payment-bridge/wrangler.jsonc +0 -15
  117. package/templates/payment-bridge.version +0 -1
@@ -1,554 +0,0 @@
1
- // Payments (docs/adr/0037). The helpers below wrap the Private Platform Service
2
- // `platform/payments`: `createPayment`, `getPayment`, `issueReceipt`,
3
- // `rejectPayment`, `createCheckoutPass`, `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. No money moved and
62
- // no legal Receipt will exist for it. A Draft or Beta app's Payments are always
63
- // `test`; a Live app's are `live` unless it created the Payment with
64
- // `test: true`, to try its payment flow in production. So check `payment.mode`
65
- // (the verified payment from `verifyPaymentEvent`, not just the event) before you
66
- // hand over anything real (a membership, goods, access) for a Payment.
67
-
68
- import { callService, platformError, type CallServiceEnv, type PlatformErrorCode } from "./call-service";
69
- import type { Env } from "./env";
70
-
71
- /**
72
- * What the money is for. The party's legal document follows the kind:
73
- *
74
- * - `donation`: a donation (record of donation แบบ พ.ก.10, receipt แบบ พ.ก.11)
75
- * - `sale`: goods or services sold (receipt แบบ พ.ก.9/1, line by line)
76
- * - `fundraising`: a fundraising event, such as a run ticket (receipt แบบ พ.ก.9)
77
- * - `membership_fee`: a party membership fee, annual or lifetime (receipt แบบ พ.ก.9)
78
- */
79
- export type PaymentKind = "donation" | "sale" | "fundraising" | "membership_fee";
80
-
81
- /** One line of a sale: goods or a service. */
82
- export interface SaleItem {
83
- type: "goods" | "service";
84
- /** What it is, as the receipt prints it, e.g. `เสื้อยืดพรรค ไซซ์ M สีส้ม`. 1 to 120 characters. */
85
- name: string;
86
- /** A whole number, 1 or more. */
87
- quantity: number;
88
- /** What the quantity counts, e.g. `ชิ้น`. Up to 20 characters. Leave it out to print none. */
89
- unit?: string | null;
90
- /** The price of one, in satang. 0 or more. */
91
- unitPriceSatang: number;
92
- }
93
-
94
- /** A fundraising event, as the receipt prints it. */
95
- export interface FundraisingEvent {
96
- /** 1 to 200 characters. */
97
- name: string;
98
- /** The event's day, `YYYY-MM-DD` (the receipt prints it in the Buddhist Era). */
99
- date: string;
100
- }
101
-
102
- export type MembershipTerm = "annual" | "lifetime";
103
-
104
- interface PaymentInputBase {
105
- /** 100 satang is 1 baht. A positive integer. */
106
- amountSatang: number;
107
- /** What the Payer sees on the Checkout Page. 1 to 200 characters. */
108
- description: string;
109
- /** Your own id for this payment. It comes back on every event and lookup. 1 to 128 characters. */
110
- reference: string;
111
- /** Where the Checkout Page sends the Payer afterwards. `https` (`http://localhost` locally). */
112
- returnUrl: string;
113
- /**
114
- * Ask for a test Payment: sandbox Gateway, `TEST-…` Receipt, no real money. Allowed
115
- * in every tier, so a Live app can test its flow in production. Leave it out (or
116
- * `false`) for the tier's own mode: `live` at Live, `test` in Draft and Beta (a
117
- * `false` never makes a Draft or Beta Payment live). Check `payment.mode` before
118
- * handing over anything real.
119
- */
120
- test?: boolean;
121
- }
122
-
123
- /**
124
- * What you send to create a Payment. Every field is required except `test`, and each kind
125
- * carries what its receipt prints: a sale its 1 to 12 lines (which must add up to
126
- * `amountSatang` exactly), a fundraising its event, a membership its term. A
127
- * field of another kind is refused (`invalid_payment` naming it).
128
- */
129
- export type CreatePaymentInput =
130
- | (PaymentInputBase & { kind: "donation" })
131
- | (PaymentInputBase & { kind: "sale"; items: SaleItem[] })
132
- | (PaymentInputBase & { kind: "fundraising"; event: FundraisingEvent })
133
- | (PaymentInputBase & { kind: "membership_fee"; term: MembershipTerm });
134
-
135
- /**
136
- * What a Payment carries for its kind, as the platform answers it: `items` on
137
- * a sale (each with `unit` null when none was sent), `event` on a fundraising,
138
- * `term` on a membership. `event` and `term` are null only on a Payment made
139
- * before kinds carried them.
140
- */
141
- export interface PaymentKindDetails {
142
- items?: (SaleItem & { unit: string | null })[];
143
- event?: FundraisingEvent | null;
144
- term?: MembershipTerm | null;
145
- }
146
-
147
- /** Why a call to `platform/payments` did not give you what you asked for. */
148
- export type PaymentReason =
149
- | "not_configured"
150
- | "invalid_app_key"
151
- | "not_granted"
152
- | "needs_beta"
153
- | "invalid_payment"
154
- | "not_found"
155
- | "not_paid"
156
- | "has_receipt"
157
- | "mismatch"
158
- | "user_token_invalid"
159
- | "not_your_payment"
160
- | "not_payable"
161
- | "checkout_unavailable"
162
- | "upstream_unavailable";
163
-
164
- export type PaymentResult<T> =
165
- | ({ ok: true } & T)
166
- | { ok: false; reason: PaymentReason; /** For `invalid_payment`: the field that is missing or wrong. */ field?: string };
167
-
168
- /** The Issuer's Receipt for a Payment. A test Receipt is `TEST-…`, watermarked, and never legal. */
169
- export interface PaymentReceipt {
170
- id: string;
171
- number: string;
172
- isTest: boolean;
173
- /** ISO 8601. */
174
- issuedAt: string;
175
- /** A Replacement Receipt names the Receipt it replaces; null on a first Receipt. */
176
- replaces: { id: string; number: string } | null;
177
- }
178
-
179
- /** The Payment as the platform answers a lookup. */
180
- export interface PaymentRecord extends PaymentKindDetails {
181
- id: string;
182
- kind: PaymentKind;
183
- amountSatang: number;
184
- description: string;
185
- reference: string;
186
- state: "created" | "pending" | "paid" | "refused" | "rejected" | "refunding" | "refunded";
187
- mode: "live" | "test";
188
- payer: { name: string; maskedCitizenId: string } | null;
189
- voucher: { number: string; nameTh: string; isReceipt: false } | null;
190
- receipt: PaymentReceipt | null;
191
- paidAt: string | null;
192
- refusal: { code: string; reasonTh: string } | null;
193
- /** True for a paid Payment neither issued nor rejected within the party's deadline. You can still do either. */
194
- undecided: boolean;
195
- refund: { status: "refunded" | "owed" | "pending" } | null;
196
- }
197
-
198
- interface PaymentsEnv extends CallServiceEnv {
199
- PPLE_SERVICES_URL?: string;
200
- PPLE_APP_KEY?: string;
201
- }
202
-
203
- /**
204
- * Ask the platform for a Payment. Send the Payer to the `checkoutUrl` it
205
- * answers: do not build that address yourself.
206
- */
207
- export async function createPayment(
208
- env: PaymentsEnv,
209
- input: CreatePaymentInput,
210
- fetchImpl?: typeof fetch,
211
- ): Promise<PaymentResult<{ id: string; checkoutUrl: string; state: "created" }>> {
212
- const answer = await callPayments(env, "", fetchImpl, {
213
- method: "POST",
214
- headers: { "content-type": "application/json" },
215
- body: JSON.stringify(input),
216
- });
217
- if (!answer.ok) return answer;
218
- const { id, checkoutUrl } = answer.body;
219
- if (typeof id !== "string" || typeof checkoutUrl !== "string") return refused("upstream_unavailable");
220
- return { ok: true, id, checkoutUrl, state: "created" };
221
- }
222
-
223
- /** Read a Payment back. The platform's answer, not an event, is the truth about its state. */
224
- export async function getPayment(
225
- env: PaymentsEnv,
226
- id: string,
227
- fetchImpl?: typeof fetch,
228
- ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
229
- const answer = await callPayments(env, `/${encodeURIComponent(id)}`, fetchImpl, { method: "GET" });
230
- if (!answer.ok) return answer;
231
- return { ok: true, payment: answer.body as unknown as PaymentRecord };
232
- }
233
-
234
- /**
235
- * Ask the platform to issue the legal Receipt for a paid Payment. Safe to
236
- * repeat: `issuedNow` is false when it was issued before. A test Receipt
237
- * (`isTest`) is never legal.
238
- */
239
- export async function issueReceipt(
240
- env: PaymentsEnv,
241
- id: string,
242
- fetchImpl?: typeof fetch,
243
- ): Promise<PaymentResult<{ receipt: PaymentReceipt; issuedNow: boolean }>> {
244
- const answer = await callPayments(env, `/${encodeURIComponent(id)}/receipt`, fetchImpl, { method: "POST" });
245
- if (!answer.ok) return answer;
246
- const receipt = answer.body.receipt as PaymentReceipt | undefined;
247
- if (!receipt || typeof receipt.id !== "string") return refused("upstream_unavailable");
248
- return { ok: true, receipt, issuedNow: answer.status === 201 };
249
- }
250
-
251
- /**
252
- * Reject a paid Payment that has no Receipt. A card is refunded; money the
253
- * Gateway cannot return (a QR payment) becomes a Refund Owed
254
- * (`payment.refund.status === "owed"`) the Finance Officer pays back by hand.
255
- * Once a Receipt exists this says `has_receipt`.
256
- */
257
- export async function rejectPayment(
258
- env: PaymentsEnv,
259
- id: string,
260
- fetchImpl?: typeof fetch,
261
- ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
262
- const answer = await callPayments(env, `/${encodeURIComponent(id)}/reject`, fetchImpl, { method: "POST" });
263
- if (!answer.ok) return answer;
264
- return { ok: true, payment: answer.body as unknown as PaymentRecord };
265
- }
266
-
267
- /**
268
- * Ask the platform for a **Checkout Pass**: the Checkout Page's address and a
269
- * one-use `pass`. Your page posts `pass` to `checkoutUrl` as a form (the web's
270
- * `goToCheckout` does), and the Payer opens the Checkout Page already signed in
271
- * as themselves, with no PPLE ID screen (ADR-0043). Only a form posted from
272
- * your app's own address redeems it: never put the pass in a link. Prefer it to the bare
273
- * `checkoutUrl` of `createPayment` whenever the Payer is signed in.
274
- *
275
- * Call it when the Payer taps to pay, not when you create the Payment: a pass
276
- * lasts a few minutes and works once, and each call mints a fresh one. Pass the
277
- * Payer's own PPLE ID token (the one your app checked on this request). The
278
- * platform checks it itself and ties the Payment to that Payer.
279
- *
280
- * - `user_token_invalid`: no token, or the platform refused it. Fall back to
281
- * `createPayment`'s `checkoutUrl`: the Payer signs in on the Checkout Page.
282
- * - `not_your_payment` (`409`): the Payment already belongs to another Payer.
283
- * Do not retry: create a new Payment for this Payer, or tell them it is not theirs.
284
- * - `not_payable`: the Payment is already paid or cancelled. Read it with
285
- * `getPayment` and show its state.
286
- * - `not_found`: no such Payment of yours.
287
- */
288
- export async function createCheckoutPass(
289
- env: PaymentsEnv,
290
- id: string,
291
- userToken: string,
292
- fetchImpl?: typeof fetch,
293
- ): Promise<PaymentResult<{ checkoutUrl: string; pass: string }>> {
294
- // Offline a Persona signs the Payer in and there is no token to send.
295
- const offline = import.meta.env.DEV && env.DEV_PERSONA !== "none";
296
- if (!offline && userToken.trim() === "") return refused("user_token_invalid");
297
- const answer = await callPayments(
298
- env,
299
- `/${encodeURIComponent(id)}/checkout-pass`,
300
- fetchImpl,
301
- { method: "POST" },
302
- { userToken, passRefusals: true },
303
- );
304
- if (!answer.ok) return answer;
305
- const { checkoutUrl, pass } = answer.body;
306
- if (typeof checkoutUrl !== "string" || typeof pass !== "string") return refused("upstream_unavailable");
307
- return { ok: true, checkoutUrl, pass };
308
- }
309
-
310
- /** The states a Payment can be in once the platform has sent an event of that type, and any time after. */
311
- const STATES_AFTER: Record<string, readonly PaymentRecord["state"][]> = {
312
- "payment.paid": ["paid", "rejected", "refunding", "refunded"],
313
- // A Finance Officer can refund a Payment after its Receipt (`refunding`, then `refunded`).
314
- "payment.receipt_issued": ["paid", "refunding", "refunded"],
315
- "payment.receipt_voided": ["refunding", "refunded", "paid"],
316
- "payment.refused": ["refused"],
317
- "payment.rejected": ["rejected", "refunded"],
318
- "payment.refunded": ["refunded"],
319
- };
320
-
321
- /**
322
- * Check an event against the platform before you act on money. The platform
323
- * authenticates its own delivery and your handler gets the parsed event only,
324
- * so this reads the Payment back (`getPayment`) and compares the id, kind,
325
- * amount, reference and mode, and that the state is one the event's type can
326
- * lead to. A late event passes: the Payment may have moved on since. Use the
327
- * `payment` it returns, not the event, to decide what to do next.
328
- *
329
- * `mismatch` means the event does not describe that Payment. Answer it with a
330
- * `2xx` and do nothing: a retry cannot make it true. `not_found` and
331
- * `upstream_unavailable` are worth a retry: throw, or return a non-2xx.
332
- */
333
- export async function verifyPaymentEvent(
334
- env: PaymentsEnv,
335
- event: PaymentEvent,
336
- fetchImpl?: typeof fetch,
337
- ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
338
- const read = await getPayment(env, event.payment.id, fetchImpl);
339
- if (!read.ok) return read;
340
- const claimed = event.payment;
341
- const actual = read.payment;
342
- const same =
343
- actual.id === claimed.id &&
344
- actual.kind === claimed.kind &&
345
- actual.amountSatang === claimed.amountSatang &&
346
- actual.reference === claimed.reference &&
347
- actual.mode === claimed.mode;
348
- const allowed = STATES_AFTER[event.type];
349
- if (!same || (allowed !== undefined && !allowed.includes(actual.state))) return refused("mismatch");
350
- return read;
351
- }
352
-
353
- /** One function per event type you handle. Each is called with that type's event. */
354
- export type PaymentHandlers = {
355
- [T in PaymentEvent["type"]]?: (
356
- event: Extract<PaymentEvent, { type: T }>,
357
- env: Env,
358
- ctx: ExecutionContext,
359
- ) => void | Response | Promise<void | Response>;
360
- };
361
-
362
- /**
363
- * Build your `payment` handler: `worker.payment = paymentHandler({ "payment.paid": … })`.
364
- * A type you give no function is answered `2xx` and ignored, which is what the
365
- * platform needs: later outcomes arrive as new types, and an answer that is not
366
- * `2xx` is sent again every few minutes. What your function returns, or throws,
367
- * is what the platform records (see the top of this file).
368
- */
369
- export function paymentHandler(handlers: PaymentHandlers): PaymentHandler {
370
- return (event, env, ctx) => {
371
- const handle = handlers[event.type] as
372
- | ((event: PaymentEvent, env: Env, ctx: ExecutionContext) => void | Response | Promise<void | Response>)
373
- | undefined;
374
- return handle ? handle(event, env, ctx) : undefined;
375
- };
376
- }
377
-
378
- type Answer = { ok: true; status: number; body: Record<string, unknown> } | { ok: false; reason: PaymentReason; field?: string };
379
-
380
- function refused(reason: PaymentReason, field?: string): { ok: false; reason: PaymentReason; field?: string } {
381
- return field === undefined ? { ok: false, reason } : { ok: false, reason, field };
382
- }
383
-
384
- /** The platform's own refusals (`x-pple-error`) a Builder can act on. Anything else is the Service being unavailable. */
385
- function platformReason(code: PlatformErrorCode | null): PaymentReason {
386
- switch (code) {
387
- case "invalid_app_key":
388
- case "not_granted":
389
- case "needs_beta":
390
- case "user_token_invalid":
391
- return code;
392
- default:
393
- return "upstream_unavailable";
394
- }
395
- }
396
-
397
- /** The Service's own answers, by `error` in the body. */
398
- const SERVICE_REASONS = ["invalid_payment", "not_found", "not_paid", "has_receipt", "checkout_unavailable"] as const;
399
-
400
- async function callPayments(
401
- env: PaymentsEnv,
402
- path: string,
403
- fetchImpl: typeof fetch | undefined,
404
- init: RequestInit,
405
- call: {
406
- /** The Payer's PPLE ID token. Only the Checkout Pass call sends one. */
407
- userToken?: string;
408
- /** The Checkout Pass route's own refusals: `user_token_invalid`, `payment_tied_to_another_payer` and `payment_ended`. */
409
- passRefusals?: boolean;
410
- } = {},
411
- ): Promise<Answer> {
412
- // Offline (`npm run dev` with a Persona) `callService` answers from the mocks
413
- // and needs no bindings.
414
- const offline = import.meta.env.DEV && env.DEV_PERSONA !== "none";
415
- if (!offline && (!env.PPLE_SERVICES_URL || !env.PPLE_APP_KEY)) return refused("not_configured");
416
-
417
- let res: Response;
418
- try {
419
- res = await callService(env, "platform/payments", path, init, {
420
- ...(fetchImpl ? { fetchImpl } : {}),
421
- ...(call.userToken !== undefined ? { userToken: call.userToken } : {}),
422
- });
423
- } catch {
424
- return refused("upstream_unavailable");
425
- }
426
-
427
- // A platform refusal carries `x-pple-error`. This Service's own answers do
428
- // not, so a body `error` is trusted only when the header is absent.
429
- if (res.headers.get("x-pple-error")) return refused(platformReason(platformError(res)));
430
-
431
- const body = ((await res.json().catch(() => null)) ?? {}) as Record<string, unknown>;
432
- const error = typeof body.error === "string" ? body.error : undefined;
433
- const reason = SERVICE_REASONS.find((r) => r === error);
434
- if (reason) return refused(reason, typeof body.field === "string" ? body.field : undefined);
435
- if (call.passRefusals && !res.ok) {
436
- if (error === "user_token_invalid") return refused("user_token_invalid");
437
- if (error === "payment_tied_to_another_payer") return refused("not_your_payment");
438
- if (error === "payment_ended") return refused("not_payable");
439
- }
440
- if (!res.ok) return refused("upstream_unavailable");
441
- return { ok: true, status: res.status, body };
442
- }
443
-
444
- export interface PaymentPaidEvent {
445
- type: "payment.paid";
446
- /** The same on every delivery of this outcome. */
447
- id: string;
448
- payment: PaymentKindDetails & {
449
- id: string;
450
- kind: PaymentKind;
451
- /** 100 satang is 1 baht. */
452
- amountSatang: number;
453
- description: string;
454
- /** Your own id, as you sent it. */
455
- reference: string;
456
- mode: "live" | "test";
457
- };
458
- payer: { name: string; maskedCitizenId: string } | null;
459
- /** The platform's acknowledgement that the money arrived. Not a receipt. */
460
- voucher: { number: string; nameTh: string; isReceipt: false } | null;
461
- /** ISO 8601. */
462
- paidAt: string | null;
463
- }
464
-
465
- /**
466
- * The party's finance rules (a smallest or largest amount, or a Payer's yearly
467
- * cap across all apps) refused the Payment. Nothing was charged and the Payment
468
- * has ended: create a new one to let the Payer try again.
469
- */
470
- export interface PaymentRefusedEvent {
471
- type: "payment.refused";
472
- /** The same on every delivery of this outcome. */
473
- id: string;
474
- payment: PaymentPaidEvent["payment"];
475
- /** `reasonTh` is for the Payer: show it as is. */
476
- refusal: { code: "below_minimum" | "above_maximum" | "over_yearly_cap"; reasonTh: string } | null;
477
- /** ISO 8601. */
478
- refusedAt: string | null;
479
- }
480
-
481
- /**
482
- * The platform issued the Receipt you asked for (`POST platform/payments/<id>/receipt`).
483
- * `payer` is what that Receipt prints, as captured at payment.
484
- */
485
- export interface PaymentReceiptIssuedEvent {
486
- type: "payment.receipt_issued";
487
- /** The same on every delivery of this Receipt's event. */
488
- id: string;
489
- payment: PaymentPaidEvent["payment"];
490
- payer: { name: string; maskedCitizenId: string };
491
- receipt: {
492
- id: string;
493
- /** The Issuer's own number, e.g. `2569-000123`. A test Receipt is `TEST-2569-000001`. */
494
- number: string;
495
- /** True for a test Payment's Receipt: watermarked, never a legal number. */
496
- isTest: boolean;
497
- /** ISO 8601. */
498
- issuedAt: string;
499
- /** Set on a Replacement Receipt (a correction): the voided Receipt it replaces. Null on a first Receipt. */
500
- replaces: { id: string; number: string } | null;
501
- };
502
- }
503
-
504
- /** You rejected the Payment (`POST platform/payments/<id>/reject`) and it is recorded. */
505
- export interface PaymentRejectedEvent {
506
- type: "payment.rejected";
507
- /** The same on every delivery of this outcome. */
508
- id: string;
509
- payment: PaymentPaidEvent["payment"];
510
- /** ISO 8601. */
511
- rejectedAt: string | null;
512
- }
513
-
514
- /** A rejected Payment's money is back with the Payer: by the Gateway, or settled by the Finance Officer. */
515
- export interface PaymentRefundedEvent {
516
- type: "payment.refunded";
517
- /** The same on every delivery of this outcome. */
518
- id: string;
519
- payment: PaymentPaidEvent["payment"];
520
- /** ISO 8601. */
521
- refundedAt: string | null;
522
- }
523
-
524
- /**
525
- * A Finance Officer voided a Receipt of your Payment: they refunded it after the
526
- * Receipt (the Payment is `refunding`, and `payment.refunded` follows once the
527
- * money is back), or it is being corrected (the Payment stays `paid` and
528
- * `payment.receipt_issued` follows for the Replacement). The Receipt stays on
529
- * record under its number.
530
- */
531
- export interface PaymentReceiptVoidedEvent {
532
- type: "payment.receipt_voided";
533
- /** The same on every delivery of this Receipt's event. */
534
- id: string;
535
- payment: PaymentPaidEvent["payment"];
536
- receipt: PaymentReceiptIssuedEvent["receipt"] & {
537
- /** ISO 8601. */
538
- voidedAt: string | null;
539
- };
540
- }
541
-
542
- export type PaymentEvent =
543
- | PaymentPaidEvent
544
- | PaymentRefusedEvent
545
- | PaymentReceiptIssuedEvent
546
- | PaymentReceiptVoidedEvent
547
- | PaymentRejectedEvent
548
- | PaymentRefundedEvent;
549
-
550
- export type PaymentHandler = (
551
- event: PaymentEvent,
552
- env: Env,
553
- ctx: ExecutionContext,
554
- ) => void | Response | Promise<void | Response>;