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