@pplethai/cli 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pplethai/cli",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -65,7 +65,7 @@ Where the token comes from:
65
65
  - `callService` takes the entry's full name: a bare name such as `branch-list`,
66
66
  a Namespace (กลุ่มชื่อ) name such as `election/2027/score`, or one of the
67
67
  platform's own entries, which all sit under `platform`: `platform/sms`,
68
- `platform/legal-identity`. A bare `sms` names nothing, and `platform` on its
68
+ `platform/email`, `platform/legal-identity`. A bare `sms` names nothing, and `platform` on its
69
69
  own is refused. Locally it answers from
70
70
  `.pple/registry/<full name>/mocks/responses.json` (nested folders for a
71
71
  Namespace) as the active persona (`x-pple-mock` names the entry). A `userToken: required`
@@ -114,6 +114,21 @@ Where the token comes from:
114
114
  `event.responder.sub` only. Try the question with `pple notify test` (it
115
115
  reaches only you; its answers reach no handler). Full guide: the
116
116
  `pple-platform` Skill, mini-app reference.
117
+ - **Payments**: take a donation or membership fee through the Private Platform
118
+ Service `platform/payments` (Use Grant needed; Beta or Live). `src/payment.ts`
119
+ has `createPayment` (send the Payer to its `checkoutUrl`; never build a card
120
+ form), `getPayment`, `issueReceipt`, `rejectPayment`, `verifyPaymentEvent`
121
+ and `paymentHandler`. The outcome arrives at `payment` on the default export
122
+ (`createPaymentHandler` in `src/index.ts` is the starting point): it verifies
123
+ the event and **does not issue a Receipt**: you choose, issue at payment or
124
+ verify first and then issue or reject (both are in the Skill's payments reference).
125
+ Gate the button on `actor.kyc.verified`. You only ever see `maskedCitizenId`:
126
+ never show, log or store a full citizen ID. Only Live takes real money, and a
127
+ rejected QR payment becomes a Refund Owed. Offline, the mocks pay
128
+ for every Persona; `unverified` and `kyc-pending` are stopped by your own
129
+ `actor.kyc.verified` gate (see `test/payment-app.test.ts`). A system outside the
130
+ platform needs a stub app: the `pple-platform` Skill's payments reference has the
131
+ recipe (it is not in this template).
117
132
  - **Mobile-first layout** uses the layout classes in `web/app.css`.
118
133
  - **Add a DB table** by writing a new migration and running
119
134
  `npm run db:migrate:local`.
@@ -18,6 +18,7 @@ what you want to your AI coding agent and edit the demo cards. See
18
18
  | **Database** | D1, `src/db.ts` + `migrations/` | the Notes card |
19
19
  | **Files** | R2, `src/files.ts` | the Files card |
20
20
  | **Notifications** | `src/notify.ts` | the Notify card (Broadcast or Direct; optional `linkPath`) |
21
+ | **Payments** | `src/payment.ts`, `POST /api/payments` | donations and membership fees through the platform's Checkout Page, with a Receipt (needs the `platform/payments` Use Grant; offline with `DEV_PERSONA`, see `test/payment-app.test.ts`) |
21
22
  | **Design system** | `@pplethai/components` | every screen |
22
23
 
23
24
  One Worker serves the API under `/api/*` and the React app (`web/`) for
@@ -98,4 +99,14 @@ you, so a freshly created app is ready to `npm run dev` straight away.)
98
99
  in `test/notification-response.test.ts`. `pple notify test <file.json | ->`
99
100
  shows the question on your own phone; its answers reach no handler.
100
101
 
102
+ - **Take a payment:** `createPayment` in `src/payment.ts` asks the platform's
103
+ `platform/payments` Service for a Payment; send the Payer to the
104
+ `checkoutUrl` it returns (never build a card form). The outcome arrives at
105
+ `payment` on the default export, where `verifyPaymentEvent` checks it and
106
+ your code decides: `issueReceipt` or `rejectPayment`. The starter handler only
107
+ verifies and does not issue a Receipt for you. You only ever see a masked
108
+ citizen ID. Only a Live app takes real money. A system outside the platform
109
+ needs a stub app: the `pple-platform` Skill has the recipe (it is not part of
110
+ this template).
111
+
101
112
  The demo cards (Notes / Files / Notify) are examples — replace them.
@@ -9,6 +9,9 @@ dist/
9
9
  .cursor/rules/pple-platform.mdc
10
10
  .pple/rules.md
11
11
  .pple/guidance.json
12
+ .claude/skills/pple-durable-objects/
13
+ .agents/skills/pple-durable-objects/
14
+ .pple/durable-object-guidance.json
12
15
  .pple/registry/
13
16
  .pple/registry.json
14
17
  .pple/registry-check.json
@@ -98,6 +98,16 @@ export const CreateNoteSchema = z.object({
98
98
  });
99
99
  export type CreateNote = z.infer<typeof CreateNoteSchema>;
100
100
 
101
+ /**
102
+ * Body for starting a donation (the payments demo). The amount is in satang
103
+ * (100 satang is 1 baht) and must be a positive whole number. The platform
104
+ * checks the party's own limits at checkout, not here.
105
+ */
106
+ export const CreateDonationSchema = z.object({
107
+ amountSatang: z.number().int().positive().max(100_000_000),
108
+ });
109
+ export type CreateDonation = z.infer<typeof CreateDonationSchema>;
110
+
101
111
  /** An uploaded file's metadata (the R2 demo). */
102
112
  export const UploadedFileSchema = z.object({
103
113
  key: z.string(),
@@ -5,13 +5,21 @@
5
5
  import { Hono } from "hono";
6
6
  import type { ContentfulStatusCode } from "hono/utils/http-status";
7
7
  import type { Identity } from "../shared/api";
8
- import { CreateNoteSchema, NotificationSchema } from "../shared/api";
8
+ import { CreateDonationSchema, CreateNoteSchema, NotificationSchema } from "../shared/api";
9
9
  import { authenticate } from "./auth";
10
10
  import { addNote, listNotes } from "./db";
11
11
  import type { Env } from "./env";
12
12
  import { devWorkerFetch } from "./dev-registry";
13
13
  import { getFile, listFiles, putFile } from "./files";
14
14
  import { closeInteraction, sendNotification } from "./notify";
15
+ import {
16
+ createPayment,
17
+ getPayment,
18
+ paymentHandler,
19
+ verifyPaymentEvent,
20
+ type PaymentHandler,
21
+ type PaymentReason,
22
+ } from "./payment";
15
23
  import type { PpleWorker, RegistryFetch, RegistryMap } from "./registry";
16
24
 
17
25
  /** Test seam: real fetch by default, an injected fake in tests. */
@@ -128,9 +136,93 @@ export function createApp(overrides: AppOverrides = {}) {
128
136
  return c.json({ ok: true, ...(result.closedAt ? { closedAt: result.closedAt } : {}) });
129
137
  });
130
138
 
139
+ // --- Payments demo: take a donation through the platform's Checkout Page ---
140
+ // Replace this with your own. The Payer must be KYC-verified, or the
141
+ // Checkout Page turns them away, so the app says so first. The Payer pays on
142
+ // the platform's page: you send them to `checkoutUrl` and never see card
143
+ // data or a full citizen ID. The outcome arrives at `payment` on the
144
+ // default export (below). Needs the Use Grant of `platform/payments`.
145
+ app.post("/payments", async (c) => {
146
+ if (!c.get("identity").actor.kyc.verified) return c.json({ error: "kyc_required" }, 403);
147
+ const parsed = CreateDonationSchema.safeParse(await c.req.json().catch(() => null));
148
+ if (!parsed.success) return c.json({ error: "invalid_body" }, 400);
149
+ const created = await createPayment(
150
+ c.env,
151
+ {
152
+ kind: "donation",
153
+ amountSatang: parsed.data.amountSatang,
154
+ description: "บริจาคสนับสนุนพรรค",
155
+ // Your own id for this payment: it comes back on every event. Use the
156
+ // id of your own order or record here.
157
+ reference: crypto.randomUUID(),
158
+ returnUrl: new URL("/", c.req.url).toString(),
159
+ },
160
+ fetchImpl,
161
+ );
162
+ if (!created.ok) return c.json({ error: created.reason }, paymentStatus(created.reason));
163
+ return c.json({ id: created.id, checkoutUrl: created.checkoutUrl }, 201);
164
+ });
165
+
166
+ app.get("/payments/:id", async (c) => {
167
+ const read = await getPayment(c.env, c.req.param("id"), fetchImpl);
168
+ if (!read.ok) return c.json({ error: read.reason }, paymentStatus(read.reason));
169
+ return c.json({ payment: read.payment });
170
+ });
171
+
131
172
  return app;
132
173
  }
133
174
 
175
+ function paymentStatus(reason: PaymentReason): ContentfulStatusCode {
176
+ switch (reason) {
177
+ case "not_found":
178
+ return 404;
179
+ case "invalid_payment":
180
+ return 400;
181
+ case "not_paid":
182
+ case "has_receipt":
183
+ case "mismatch":
184
+ return 409;
185
+ default:
186
+ // Not granted, still Draft, no Checkout Page, platform down: not the
187
+ // Payer's doing, and not something they can fix.
188
+ return 502;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * What to do when the platform tells the app about a Payment. This default
194
+ * only checks the event against the platform and stops: **it does not issue
195
+ * the legal Receipt.** Issuing is your decision, and a Receipt is never edited,
196
+ * only voided and replaced, so an app should not do it by habit. A paid Payment
197
+ * you neither issue nor reject within the party's deadline goes to the Finance
198
+ * Officer as Undecided. Pick one of the two patterns (the `pple-platform`
199
+ * Skill's payments reference has both in full):
200
+ *
201
+ * Issue at payment: there is nothing more to check (a donation). After the
202
+ * verify below, add:
203
+ *
204
+ * const issued = await issueReceipt(env, event.payment.id, fetchImpl);
205
+ * if (!issued.ok && issued.reason !== "not_paid") return tryAgain();
206
+ *
207
+ * Verify first: your app must check something (an order in stock, a
208
+ * membership that exists). Do the check, then `issueReceipt` when it passes
209
+ * or `rejectPayment(env, event.payment.id, fetchImpl)` when it does not.
210
+ */
211
+ export function createPaymentHandler(overrides: AppOverrides = {}): PaymentHandler {
212
+ const fetchImpl = overrides.fetchImpl;
213
+ // Answer `2xx` and the platform stops; anything else, or a throw, is sent
214
+ // again every few minutes. Retry only what a retry can fix.
215
+ const tryAgain = () => new Response(null, { status: 503 });
216
+ return paymentHandler({
217
+ "payment.paid": async (event, env) => {
218
+ const verified = await verifyPaymentEvent(env, event, fetchImpl);
219
+ if (!verified.ok) return verified.reason === "mismatch" ? undefined : tryAgain();
220
+ if (verified.payment.state !== "paid") return;
221
+ // Decide here: issue at payment, or verify first (see above). Until you do, nothing is issued.
222
+ },
223
+ });
224
+ }
225
+
134
226
  const api = createApp();
135
227
 
136
228
  const registry: RegistryMap = {};
@@ -158,6 +250,7 @@ const worker: PpleWorker = {
158
250
  return appFetch(request, env, ctx);
159
251
  },
160
252
  registry,
253
+ payment: createPaymentHandler(),
161
254
  };
162
255
 
163
256
  export default worker;
@@ -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 {