@rangka-os/create 0.5.0-alpha.27 → 0.5.0-alpha.28
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 +1 -1
- package/template/base/apps/absen_karyawan/app.rk +37 -0
- package/template/base/apps/absen_karyawan/dashboards/absen_hari_ini.rk +20 -0
- package/template/base/apps/absen_karyawan/dashboards/absen_karyawan_saya.rk +14 -0
- package/template/base/apps/absen_karyawan/dashboards/rekap_absen_karyawan.rk +12 -0
- package/template/base/apps/jasa_proyek/app.rk +1 -1
- package/template/base/apps/kasir/app.rk +5 -1
- package/template/base/apps/kasir/dashboards/kasir_ringkas.rk +4 -0
- package/template/base/apps/kasir/skills/rangka-app-kasir/SKILL.md +20 -0
- package/template/base/connectors/midtrans/connector.rk +249 -0
- package/template/base/connectors/midtrans/fixtures/charge_gopay.json +34 -0
- package/template/base/connectors/midtrans/fixtures/charge_qris.json +23 -0
- package/template/base/connectors/midtrans/fixtures/charge_va.json +20 -0
- package/template/base/connectors/midtrans/fixtures/create_snap.json +4 -0
- package/template/base/connectors/midtrans/fixtures/expect.json +88 -0
- package/template/base/connectors/midtrans/fixtures/get_status.json +15 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified.json +28 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_challenge.json +24 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_expire.json +24 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_other_amount.json +28 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_partial_refund.json +34 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_pending.json +31 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_refund.json +34 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_relabelled.json +28 -0
- package/template/base/connectors/midtrans/fixtures/payment_notified_va.json +32 -0
- package/template/base/connectors/midtrans/fixtures/signature_vector.txt +3 -0
- package/template/base/connectors/midtrans/mock/midtrans_mock.py +335 -0
- package/template/base/connectors/rangka_whatsapp/README.md +105 -0
- package/template/base/connectors/rangka_whatsapp/connector.rk +141 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/expect.json +9 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/message_received.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/message_status.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/message_status_refused.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/opted_out.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/send_template.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/send_template_duplicate.json +1 -0
- package/template/base/connectors/rangka_whatsapp/fixtures/set_opt_out.json +1 -0
- package/template/base/connectors/rangka_whatsapp/mock/rangka_whatsapp_mock.py +354 -0
- package/template/base/connectors/shopee/connector.rk +360 -0
- package/template/base/connectors/shopee/fixtures/expect.json +119 -0
- package/template/base/connectors/shopee/fixtures/get_models.json +52 -0
- package/template/base/connectors/shopee/fixtures/get_order_detail.json +396 -0
- package/template/base/connectors/shopee/fixtures/get_settlement.json +90 -0
- package/template/base/connectors/shopee/fixtures/get_tracking.json +13 -0
- package/template/base/connectors/shopee/fixtures/list_items.json +29 -0
- package/template/base/connectors/shopee/fixtures/list_orders.json +31 -0
- package/template/base/connectors/shopee/fixtures/list_settlements.json +15 -0
- package/template/base/connectors/shopee/fixtures/order_changed.json +101 -0
- package/template/base/connectors/shopee/fixtures/order_changed_cancelled.json +72 -0
- package/template/base/connectors/shopee/fixtures/order_changed_completed.json +101 -0
- package/template/base/connectors/shopee/fixtures/order_changed_in_cancel.json +72 -0
- package/template/base/connectors/shopee/fixtures/order_changed_unpaid.json +71 -0
- package/template/base/connectors/shopee/fixtures/order_settled.json +92 -0
- package/template/base/connectors/shopee/fixtures/push_received.json +12 -0
- package/template/base/connectors/shopee/fixtures/push_received_tracking.json +11 -0
- package/template/base/connectors/shopee/fixtures/update_stock.json +15 -0
- package/template/base/connectors/shopee/mock/shopee_mock.py +894 -0
- package/template/base/connectors/tiktok_shop/connector.rk +300 -0
- package/template/base/connectors/tiktok_shop/fixtures/expect.json +105 -0
- package/template/base/connectors/tiktok_shop/fixtures/get_order_detail.json +136 -0
- package/template/base/connectors/tiktok_shop/fixtures/get_settlement.json +83 -0
- package/template/base/connectors/tiktok_shop/fixtures/get_tracking.json +28 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_orders.json +242 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_products.json +77 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_settlements.json +22 -0
- package/template/base/connectors/tiktok_shop/fixtures/list_shops.json +17 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed.json +129 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_cancelled.json +81 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_completed.json +106 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_on_hold.json +104 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_tokopedia.json +106 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_changed_unpaid.json +79 -0
- package/template/base/connectors/tiktok_shop/fixtures/order_settled.json +73 -0
- package/template/base/connectors/tiktok_shop/fixtures/update_stock.json +6 -0
- package/template/base/connectors/tiktok_shop/fixtures/webhook_received.json +12 -0
- package/template/base/connectors/tiktok_shop/fixtures/webhook_received_cancellation.json +13 -0
- package/template/base/connectors/tiktok_shop/mock/tiktok_shop_mock.py +819 -0
- package/template/base/connectors/whatsapp_business/connector.rk +3 -1
- package/template/base/connectors/whatsapp_business/templates.md +13 -1
- package/template/base/modules/attendance/flows/attendance_missing_digest.rk +30 -0
- package/template/base/modules/attendance/flows/attendance_period_on_cancel.rk +15 -0
- package/template/base/modules/attendance/flows/attendance_period_on_submit.rk +60 -0
- package/template/base/modules/attendance/flows/staff_attendance_cancel_guard.rk +14 -0
- package/template/base/modules/attendance/flows/staff_attendance_guard_created.rk +16 -0
- package/template/base/modules/attendance/flows/staff_attendance_guard_submitted.rk +37 -0
- package/template/base/modules/attendance/flows/staff_attendance_guard_updated.rk +14 -0
- package/template/base/modules/attendance/models/attendance_period.rk +62 -0
- package/template/base/modules/attendance/models/attendance_summary.rk +37 -0
- package/template/base/modules/attendance/models/staff_attendance.rk +281 -0
- package/template/base/modules/attendance/models/staff_attendance_guard.rk +50 -0
- package/template/base/modules/attendance/module.rk +18 -0
- package/template/base/modules/attendance/screens/absen_outlet.rk +22 -0
- package/template/base/modules/catalogue/models/item.rk +69 -0
- package/template/base/modules/catalogue/module.rk +1 -1
- package/template/base/modules/contacts/models/customer.rk +43 -19
- package/template/base/modules/contacts/module.rk +1 -1
- package/template/base/modules/coretax/module.rk +1 -1
- package/template/base/modules/coretax/print/coretax_faktur.rk +3 -2
- package/template/base/modules/coretax/print/coretax_faktur.xml +3 -1
- package/template/base/modules/coretax/print/rekap_ppn.html +9 -7
- package/template/base/modules/courses/flows/charge_invoice_on_submit.rk +15 -0
- package/template/base/modules/courses/module.rk +1 -1
- package/template/base/modules/courses/screens/absen_kelas.rk +1 -0
- package/template/base/modules/invoicing/flows/invoice_due_digest.rk +45 -7
- package/template/base/modules/invoicing/models/sales_invoice_item.rk +4 -1
- package/template/base/modules/invoicing/module.rk +15 -2
- package/template/base/modules/kitchen/screens/dapur.rk +1 -0
- package/template/base/modules/outlets/models/outlet.rk +69 -0
- package/template/base/modules/outlets/module.rk +1 -1
- package/template/base/modules/payments/flows/payment_from_midtrans.rk +85 -0
- package/template/base/modules/payments/flows/payment_refund_from_midtrans.rk +22 -0
- package/template/base/modules/payments/models/payment.rk +2 -1
- package/template/base/modules/payments/module.rk +1 -1
- package/template/base/modules/payroll/flows/payroll_close_on_cancel.rk +8 -5
- package/template/base/modules/payroll/flows/payroll_close_on_submit.rk +8 -5
- package/template/base/modules/payroll/flows/payroll_reminder.rk +106 -0
- package/template/base/modules/payroll/flows/payroll_run_overlap_guard_created.rk +5 -3
- package/template/base/modules/payroll/flows/payroll_run_overlap_guard_updated.rk +5 -3
- package/template/base/modules/payroll/flows/payslip_from_recap.rk +1 -1
- package/template/base/modules/payroll/imports/payroll_profile_list.rk +27 -0
- package/template/base/modules/payroll/models/payroll_close.rk +10 -6
- package/template/base/modules/payroll/models/payroll_run.rk +64 -15
- package/template/base/modules/payroll/models/payslip.rk +48 -9
- package/template/base/modules/payroll/module.rk +22 -5
- package/template/base/modules/payroll/print/payslip.html +4 -1
- package/template/base/modules/pos/models/pos_sale.rk +136 -9
- package/template/base/modules/pos/models/pos_sale_item.rk +33 -1
- package/template/base/modules/pos/module.rk +5 -3
- package/template/base/modules/pos/print/pos_receipt.html +7 -3
- package/template/base/modules/pos/screens/kasir.rk +7 -2
- package/template/base/modules/procurement/flows/reorder_draft_po.rk +57 -0
- package/template/base/modules/procurement/models/vendor_bill.rk +14 -1
- package/template/base/modules/procurement/module.rk +11 -2
- package/template/base/modules/projects/screens/absen.rk +1 -0
- package/template/base/modules/promotions/flows/promo_code_batch_on_submit.rk +26 -0
- package/template/base/modules/promotions/flows/promotion_apply.rk +110 -0
- package/template/base/modules/promotions/flows/promotion_apply_on_create.rk +110 -0
- package/template/base/modules/promotions/flows/promotion_apply_on_delete.rk +111 -0
- package/template/base/modules/promotions/flows/promotion_apply_on_update.rk +110 -0
- package/template/base/modules/promotions/flows/promotion_on_sale.rk +95 -0
- package/template/base/modules/promotions/flows/promotion_on_sale_cancel.rk +43 -0
- package/template/base/modules/promotions/models/promo_code.rk +27 -0
- package/template/base/modules/promotions/models/promo_code_batch.rk +36 -0
- package/template/base/modules/promotions/models/promo_guard.rk +44 -0
- package/template/base/modules/promotions/models/promotion.rk +197 -0
- package/template/base/modules/promotions/models/promotion_ledger.rk +35 -0
- package/template/base/modules/promotions/module.rk +20 -0
- package/template/base/modules/rental/screens/alat_keluar.rk +1 -0
- package/template/base/modules/rental/screens/alat_kembali.rk +1 -0
- package/template/base/modules/rental/screens/jadwal_alat.rk +1 -0
- package/template/base/modules/stock/flows/stock_low_alert.rk +65 -0
- package/template/base/modules/stock/flows/stock_negative_alert.rk +14 -5
- package/template/base/modules/stock/models/stock_reorder.rk +34 -0
- package/template/base/modules/stock/module.rk +17 -2
- package/template/base/modules/subscriptions/screens/catat_tagih.rk +1 -0
- package/template/base/modules/subscriptions/screens/rute_tagih.rk +1 -0
- package/template/base/modules/users/flows/summary_daily.rk +83 -0
- package/template/base/modules/users/flows/summary_monthly.rk +83 -0
- package/template/base/modules/users/flows/summary_weekly.rk +83 -0
- package/template/base/modules/users/models/business_summary.rk +67 -0
- package/template/base/modules/users/models/summary_setting.rk +35 -0
- package/template/base/modules/users/models/user.rk +11 -3
- package/template/base/modules/users/module.rk +21 -2
- package/template/base/modules/users/roles/employee.rk +8 -0
- package/template/base/modules/users/roles/outlet_supervisor.rk +7 -0
- package/template/base/modules/whatsapp/flows/whatsapp_customer_opt_out.rk +16 -0
- package/template/base/modules/whatsapp/flows/whatsapp_customer_opt_out_new.rk +17 -0
- package/template/base/modules/whatsapp/flows/whatsapp_message_status.rk +24 -0
- package/template/base/modules/whatsapp/flows/whatsapp_opted_out.rk +26 -0
- package/template/base/modules/whatsapp/models/whatsapp_message.rk +99 -0
- package/template/base/modules/whatsapp/models/whatsapp_opt_out.rk +44 -0
- package/template/base/modules/whatsapp/module.rk +23 -0
- package/template/base/modules/whatsapp_booking/flows/whatsapp_booking_tomorrow.rk +48 -0
- package/template/base/modules/whatsapp_booking/module.rk +13 -0
- package/template/base/modules/whatsapp_order_ready/flows/whatsapp_pickup_on_sale.rk +19 -0
- package/template/base/modules/whatsapp_order_ready/flows/whatsapp_ticket_ready.rk +40 -0
- package/template/base/modules/whatsapp_order_ready/models/whatsapp_pickup.rk +22 -0
- package/template/base/modules/whatsapp_order_ready/module.rk +14 -0
- package/template/base/modules/whatsapp_receipt/flows/whatsapp_receipt_on_sale.rk +43 -0
- package/template/base/modules/whatsapp_receipt/module.rk +13 -0
- package/template/base/modules/whatsapp_reminder/flows/whatsapp_invoice_overdue.rk +64 -0
- package/template/base/modules/whatsapp_reminder/module.rk +15 -0
- package/template/base/modules/workforce/imports/worker_list.rk +4 -1
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# rangka_whatsapp: WhatsApp from Rangka Cloud
|
|
2
|
+
|
|
3
|
+
A **host connector** (rangka-os contract 0063 §2 and §7): the business sends WhatsApp template messages from its own
|
|
4
|
+
number, which Rangka Cloud provides under Rangka's Meta setup. The owner signs up with nobody and enters no key: every
|
|
5
|
+
auth field is written by the host with a `secrets:host` token, and a kernel serves the connector only when whoever runs
|
|
6
|
+
it names it in `RANGKA_HOST_CONNECTORS`. A self-hosted owner uses [`whatsapp_business`](../whatsapp_business) with
|
|
7
|
+
their own Meta account instead.
|
|
8
|
+
|
|
9
|
+
**Status: spec, tested against a local mock only.** Rangka has no Meta account yet; no message can be sent. `hosts:`
|
|
10
|
+
is a placeholder under the reserved `.example` domain until Rangka Cloud has a public service address, so no bearer can
|
|
11
|
+
leave for a real host before then.
|
|
12
|
+
|
|
13
|
+
## How it works (option B: host relay)
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
flow ─ call rangka_whatsapp.send_template ─► kernel job ─► POST https://{api_host}/svc/whatsapp/v1/messages
|
|
17
|
+
│ Rangka Cloud: kill switch → service state → message
|
|
18
|
+
│ type → template approved → opt-out → daily cap →
|
|
19
|
+
│ number throttle → send once per idempotency_key
|
|
20
|
+
▼
|
|
21
|
+
Meta
|
|
22
|
+
kernel /hooks/<org>/rangka_whatsapp/{message_status|message_received|opted_out} ◄── Rangka Cloud, signed per business
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
What the kernel holds works for this business only and is not Meta's:
|
|
26
|
+
|
|
27
|
+
| Field | What | Secret |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| `api_host` | Rangka Cloud's service host | no |
|
|
30
|
+
| `service_token` | the business's relay bearer | yes |
|
|
31
|
+
| `webhook_key` | the key the host signs this business's events with | yes |
|
|
32
|
+
|
|
33
|
+
## Actions
|
|
34
|
+
|
|
35
|
+
`send_template {to, template, type, components, idempotency_key}` → `{message_id, status}`.
|
|
36
|
+
|
|
37
|
+
- `type` is the business's message type: `receipt`, `reminder`, `order_ready`, `appointment`. Each can be switched off
|
|
38
|
+
on its own.
|
|
39
|
+
- `components` is one body component with text parameters, in the template's order. The host rebuilds what goes to
|
|
40
|
+
Meta from them; a header, a button or media is refused.
|
|
41
|
+
- `idempotency_key` is `<document>:<type>:<step>`, for example `STRK-KPI-2611-00142:receipt:1`. A key is sent once: the
|
|
42
|
+
kernel never queues the same key twice, and the host answers a repeat with the first message (`duplicate: true`)
|
|
43
|
+
without asking Meta.
|
|
44
|
+
|
|
45
|
+
`set_opt_out {phone}` → `{status: recorded | already}`. The business marked the customer "Tidak mau dikirimi WA". It
|
|
46
|
+
only ever adds to the host's list.
|
|
47
|
+
|
|
48
|
+
## Refusals
|
|
49
|
+
|
|
50
|
+
Every refusal is `{"error": {"code": "...", "field": "..."}}`. The connector retries **only** 429 and 5xx; every other
|
|
51
|
+
code is final and arrives at the kernel again as a `message_status` event with `status: failed` and the code in `error`,
|
|
52
|
+
so the document can say why nothing was sent.
|
|
53
|
+
|
|
54
|
+
| HTTP | Code | Meaning | Retried |
|
|
55
|
+
| --- | --- | --- | --- |
|
|
56
|
+
| 400 | `bad_request` (+ `field`) | malformed: `to`, `type`, `template`, `components`, `idempotency_key`, `body` | no |
|
|
57
|
+
| 401 | `unauthenticated` | no bearer, a wrong one, or a revoked one (switch-off) | no |
|
|
58
|
+
| 403 | `service_stopped` | Rangka stopped the service (kill switch), it is switched off or not provisioned yet | no |
|
|
59
|
+
| 403 | `service_paused` | held: a low quality rating, a re-categorised template, or this message type is off | no |
|
|
60
|
+
| 403 | `quota_exceeded` | the business's daily cap is used up | no |
|
|
61
|
+
| 409 | `template_not_approved` | no approved Utility version of this template for the business | no |
|
|
62
|
+
| 409 | `in_progress` | the same key is being sent right now | no |
|
|
63
|
+
| 409 | `delivery_uncertain` | an earlier send of this key got no answer from Meta: it may have arrived, so it is never sent again | no |
|
|
64
|
+
| 422 | `recipient_opted_out` | the customer asked this business to stop | no |
|
|
65
|
+
| 422 | `send_failed` | Meta refused the message for good (for example the number is not on WhatsApp) | no |
|
|
66
|
+
| 429 | `rate_limited` | try again after `Retry-After` | yes |
|
|
67
|
+
| 502 | `upstream_unavailable` | Meta is down or unreachable; nothing was sent | yes |
|
|
68
|
+
| 503 | `unavailable` | the host could not check (its store or the kill switch) | yes |
|
|
69
|
+
|
|
70
|
+
## Triggers
|
|
71
|
+
|
|
72
|
+
Every event is one JSON object, signed over the raw body: `X-Rangka-Signature: sha256=<hex HMAC-SHA256 with webhook_key>`.
|
|
73
|
+
|
|
74
|
+
| Trigger | Fields | When |
|
|
75
|
+
| --- | --- | --- |
|
|
76
|
+
| `message_status` | `message_id`, `idempotency_key`, `type`, `status` (`sent`, `delivered`, `read`, `failed`), `at`, `error` | Meta reported a status, or the host refused a send (`failed`, `message_id` empty, the code in `error`) |
|
|
77
|
+
| `message_received` | `message_id`, `from`, `text`, `profile_name`, `at` | a customer wrote to the number (it only sends in phase 1) |
|
|
78
|
+
| `opted_out` | `phone`, `at`, `source` (`keyword`, `meta`, `staff`) | a customer replied `BERHENTI` or `STOP`, or Meta reported a block |
|
|
79
|
+
|
|
80
|
+
A status never carries the phone: the flow finds its document by `idempotency_key`.
|
|
81
|
+
|
|
82
|
+
## Templates
|
|
83
|
+
|
|
84
|
+
The canonical library is Rangka Cloud's (`internal/whatsapp/templates/library.yaml`); all are category Utility,
|
|
85
|
+
language `id`, and end with *Balas BERHENTI untuk berhenti menerima pesan.*
|
|
86
|
+
|
|
87
|
+
| Name | Type | Body (`{{n}}` = parameter) |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| `struk_pembayaran` | `receipt` | Terima kasih, {{1}}. Struk {{2}} dari {{3}}: {{4}}. Total {{5}}, dibayar {{6}}. |
|
|
90
|
+
| `tagihan_terbit` | `reminder` | Halo {{1}}, berikut tagihan {{2}} no. {{3}} sebesar {{4}}, jatuh tempo {{5}}. Pembayaran ke {{6}}. Mohon tulis {{3}} di berita transfer. Terima kasih. |
|
|
91
|
+
| `pengingat_jatuh_tempo` | `reminder` | Halo {{1}}, kami mengingatkan faktur {{2}} sebesar {{3}} sudah lewat {{4}} hari dari jatuh tempo ({{5}}). Pembayaran ke {{6}}. Mohon tulis {{2}} di berita transfer. Abaikan pesan ini kalau sudah membayar. Terima kasih. |
|
|
92
|
+
| `terima_kasih_lunas` | `reminder` | Halo {{1}}, terima kasih. Pembayaran faktur {{2}} sudah kami terima dan faktur ini sudah lunas. |
|
|
93
|
+
| `pesanan_siap` | `order_ready` | Halo {{1}}, pesanan {{2}} di {{3}} sudah siap diambil. Sebutkan nomor pesanan saat mengambil. Terima kasih. |
|
|
94
|
+
| `pengingat_janji` | `appointment` | Halo {{1}}, kami mengingatkan {{2}} di {{3}} pada {{4}}. Kalau perlu mengubah jadwal, hubungi kami sebelum waktunya. Terima kasih. |
|
|
95
|
+
|
|
96
|
+
## Local mock
|
|
97
|
+
|
|
98
|
+
`mock/rangka_whatsapp_mock.py` stands in for the relay (dummy keys only, from `RANGKA_WHATSAPP_MOCK_TOKEN` and
|
|
99
|
+
`RANGKA_WHATSAPP_MOCK_WEBHOOK_KEY`; 127.0.0.1 only; stdlib). It answers both actions with every refusal above, sends a
|
|
100
|
+
key once, and posts signed events to `--hook-url`; `/simulate/*` routes change statuses, send inbound messages
|
|
101
|
+
(`BERHENTI` opts out), stop or pause the service, unapprove a template, queue a rate limit or an outage, and redeliver
|
|
102
|
+
the last event. `python3 tests/check_rangka_whatsapp_mock.py` (needs PyYAML) builds the requests from `connector.rk`
|
|
103
|
+
itself and checks every answer and event against it.
|
|
104
|
+
|
|
105
|
+
Rangka Cloud has its own stand-in with the real relay code behind a fake Meta: `rangka-cloud wa-dev`.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# yaml-language-server: $schema=https://rangka-os.github.io/rangka-os/schema/0.5/connector.json
|
|
2
|
+
# WhatsApp from Rangka Cloud: a host connector (rangka-os contract 0063 §2 and §7). The business gets its own
|
|
3
|
+
# WhatsApp number under Rangka's Meta setup; the owner signs up with nobody and enters no key.
|
|
4
|
+
# - Every auth field is written by the host with a secrets:host token. A kernel serves this connector only when
|
|
5
|
+
# whoever runs it names it in RANGKA_HOST_CONNECTORS; a self-hosted kernel uses `whatsapp_business` instead.
|
|
6
|
+
# - Sends go to the host's relay, never to Meta (option B of the WhatsApp plan): the relay checks the kill switch,
|
|
7
|
+
# the service's state, the message type, the template's approval, the customer's opt-out and the caps before it
|
|
8
|
+
# asks Meta, and sends a key once. What the kernel holds works for this business only and is not Meta's.
|
|
9
|
+
# - Events come from the host, signed with this business's own key: delivery statuses (and refusals, as status
|
|
10
|
+
# failed with the relay's code), inbound messages, and opt-outs.
|
|
11
|
+
# README.md has the refusal codes; fixtures/ are synthetic.
|
|
12
|
+
name: rangka_whatsapp
|
|
13
|
+
label: {id: WhatsApp dari Rangka Cloud, en: WhatsApp from Rangka Cloud}
|
|
14
|
+
summary:
|
|
15
|
+
id: Kirim struk, pengingat tagihan dan kabar pesanan ke pelanggan dari nomor WhatsApp bisnismu yang disediakan Rangka Cloud.
|
|
16
|
+
en: Send receipts, payment reminders and order updates to customers from the WhatsApp number Rangka Cloud provides for your business.
|
|
17
|
+
category: messaging
|
|
18
|
+
icon: send-plane-line
|
|
19
|
+
version: 0.1.0
|
|
20
|
+
vendor: Rangka Cloud
|
|
21
|
+
docs: https://github.com/rangka-os/rangka-connectors/blob/main/rangka_whatsapp/README.md
|
|
22
|
+
# The host's public service address. A placeholder under the reserved .example domain until Rangka Cloud has one:
|
|
23
|
+
# no bearer can leave for a real host before this line names it (rangka-os contract 0017 §5).
|
|
24
|
+
hosts: [cloud.rangka.example]
|
|
25
|
+
experimental:
|
|
26
|
+
provided_by: host
|
|
27
|
+
auth:
|
|
28
|
+
type: token
|
|
29
|
+
fields:
|
|
30
|
+
- name: api_host
|
|
31
|
+
label: {id: Alamat layanan Rangka Cloud, en: Rangka Cloud service host}
|
|
32
|
+
- name: service_token
|
|
33
|
+
label: {id: Token layanan, en: Service token}
|
|
34
|
+
secret: true
|
|
35
|
+
- name: webhook_key
|
|
36
|
+
label: {id: Kunci tanda tangan kabar, en: Event signing key}
|
|
37
|
+
secret: true
|
|
38
|
+
triggers:
|
|
39
|
+
# What happened to a message this business sent: sent, delivered, read or failed. A send the host refused
|
|
40
|
+
# arrives as failed with the refusal's code in `error` and no message_id. `idempotency_key` is the key the flow
|
|
41
|
+
# sent, so the flow finds its document without knowing any id of Meta's.
|
|
42
|
+
- name: message_status
|
|
43
|
+
label: {id: Status pesan terkirim, en: Sent message status}
|
|
44
|
+
via: webhook
|
|
45
|
+
verify:
|
|
46
|
+
signature:
|
|
47
|
+
header: X-Rangka-Signature
|
|
48
|
+
prefix: sha256=
|
|
49
|
+
alg: hmac-sha256
|
|
50
|
+
key: auth.webhook_key
|
|
51
|
+
emit:
|
|
52
|
+
message_id: message_id
|
|
53
|
+
idempotency_key: idempotency_key
|
|
54
|
+
type: type
|
|
55
|
+
status: status
|
|
56
|
+
at: at
|
|
57
|
+
error: error
|
|
58
|
+
# A customer wrote to the number. The number only sends (phase 1), so this is for the business to see.
|
|
59
|
+
- name: message_received
|
|
60
|
+
label: {id: Pesan masuk, en: Incoming message}
|
|
61
|
+
via: webhook
|
|
62
|
+
verify:
|
|
63
|
+
signature:
|
|
64
|
+
header: X-Rangka-Signature
|
|
65
|
+
prefix: sha256=
|
|
66
|
+
alg: hmac-sha256
|
|
67
|
+
key: auth.webhook_key
|
|
68
|
+
emit:
|
|
69
|
+
message_id: message_id
|
|
70
|
+
from: from
|
|
71
|
+
text: text
|
|
72
|
+
profile_name: profile_name
|
|
73
|
+
at: at
|
|
74
|
+
# A customer asked to stop (they replied BERHENTI or STOP, or Meta reported a block). The host already refuses
|
|
75
|
+
# sends to them; the flow marks the customer so staff see it.
|
|
76
|
+
- name: opted_out
|
|
77
|
+
label: {id: Pelanggan minta berhenti, en: Customer opted out}
|
|
78
|
+
via: webhook
|
|
79
|
+
verify:
|
|
80
|
+
signature:
|
|
81
|
+
header: X-Rangka-Signature
|
|
82
|
+
prefix: sha256=
|
|
83
|
+
alg: hmac-sha256
|
|
84
|
+
key: auth.webhook_key
|
|
85
|
+
emit:
|
|
86
|
+
phone: phone
|
|
87
|
+
at: at
|
|
88
|
+
source: source
|
|
89
|
+
actions:
|
|
90
|
+
- name: send_template
|
|
91
|
+
label: {id: Kirim pesan template, en: Send a template message}
|
|
92
|
+
request:
|
|
93
|
+
method: POST
|
|
94
|
+
url: https://{auth.api_host}/svc/whatsapp/v1/messages
|
|
95
|
+
headers: {Authorization: 'Bearer {auth.service_token}'}
|
|
96
|
+
body:
|
|
97
|
+
to: '{input.to}'
|
|
98
|
+
template: '{input.template}'
|
|
99
|
+
type: '{input.type}'
|
|
100
|
+
components: '{input.components}'
|
|
101
|
+
idempotency_key: '{input.idempotency_key}'
|
|
102
|
+
input:
|
|
103
|
+
- {name: to, type: phone, required: true}
|
|
104
|
+
- {name: template, type: data, required: true}
|
|
105
|
+
# receipt | reminder | order_ready | appointment: which of the business's message types this is
|
|
106
|
+
- {name: type, type: data, required: true}
|
|
107
|
+
- {name: components, type: json}
|
|
108
|
+
# <document>:<type>:<step>, e.g. STRK-KPI-2611-00142:receipt:1. The same key is sent once, by the kernel
|
|
109
|
+
# (the job's unique key) and again by the host.
|
|
110
|
+
- {name: idempotency_key, type: data, required: true}
|
|
111
|
+
output:
|
|
112
|
+
message_id: message_id
|
|
113
|
+
status: status
|
|
114
|
+
# Only rate_limited (429) and a host or Meta outage (5xx) are worth another try. Every other refusal is final:
|
|
115
|
+
# recipient_opted_out, template_not_approved, service_stopped, service_paused, quota_exceeded, send_failed.
|
|
116
|
+
retry:
|
|
117
|
+
max: 5
|
|
118
|
+
backoff: exponential
|
|
119
|
+
on: [429, 500, 502, 503, 504]
|
|
120
|
+
idempotency: input.idempotency_key
|
|
121
|
+
# The business marked a customer "Tidak mau dikirimi WA". It only ever adds to the host's list: a customer comes
|
|
122
|
+
# off it by their own action, never by a call from here.
|
|
123
|
+
- name: set_opt_out
|
|
124
|
+
label: {id: Catat pelanggan yang tidak mau dikirimi WA, en: Record a customer who opted out}
|
|
125
|
+
request:
|
|
126
|
+
method: POST
|
|
127
|
+
url: https://{auth.api_host}/svc/whatsapp/v1/opt-outs
|
|
128
|
+
headers: {Authorization: 'Bearer {auth.service_token}'}
|
|
129
|
+
body:
|
|
130
|
+
phone: '{input.phone}'
|
|
131
|
+
input:
|
|
132
|
+
- {name: phone, type: phone, required: true}
|
|
133
|
+
output:
|
|
134
|
+
status: status
|
|
135
|
+
retry:
|
|
136
|
+
max: 5
|
|
137
|
+
backoff: exponential
|
|
138
|
+
on: [429, 500, 502, 503, 504]
|
|
139
|
+
limits:
|
|
140
|
+
rate: The host throttles each number below Meta's limit and caps each business per day
|
|
141
|
+
note: {id: 'Biaya per pesan: belum ditetapkan', en: 'Fee per message: not set yet'}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"message_status.json": {"message_id": "wam_contoh0001", "idempotency_key": "STRK-KPI-2611-00142:receipt:1", "type": "receipt", "status": "read", "error": ""},
|
|
3
|
+
"message_status_refused.json": {"message_id": "", "idempotency_key": "INV-2026-00031:reminder:7", "status": "failed", "error": "recipient_opted_out"},
|
|
4
|
+
"message_received.json": {"from": "+6281200000001", "text": "Terima kasih", "profile_name": "Pelanggan Contoh"},
|
|
5
|
+
"opted_out.json": {"phone": "+6281200000001", "source": "keyword"},
|
|
6
|
+
"send_template.json": {"message_id": "wam_contoh0001", "status": "accepted"},
|
|
7
|
+
"send_template_duplicate.json": {"message_id": "wam_contoh0001", "status": "delivered"},
|
|
8
|
+
"set_opt_out.json": {"status": "recorded"}
|
|
9
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"message_id": "wamid.CONTOH0002", "from": "+6281200000001", "text": "Terima kasih", "profile_name": "Pelanggan Contoh", "at": "2026-11-19T03:05:00Z"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"message_id": "wam_contoh0001", "idempotency_key": "STRK-KPI-2611-00142:receipt:1", "type": "receipt", "status": "read", "at": "2026-11-19T03:04:05Z", "error": ""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"message_id": "", "idempotency_key": "INV-2026-00031:reminder:7", "type": "reminder", "status": "failed", "at": "2026-11-19T03:04:05Z", "error": "recipient_opted_out"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"phone": "+6281200000001", "at": "2026-11-19T03:06:00Z", "source": "keyword"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"message_id": "wam_contoh0001", "status": "accepted"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"message_id": "wam_contoh0001", "status": "delivered", "duplicate": true}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"status": "recorded"}
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""A local stand-in for Rangka Cloud's WhatsApp relay (the host side of connector `rangka_whatsapp`), for demos and
|
|
3
|
+
tests without Rangka Cloud and without a Meta account. Nothing is sent anywhere: a "sent" message is a row in memory.
|
|
4
|
+
|
|
5
|
+
RANGKA_WHATSAPP_MOCK_TOKEN=dummy-wa-token-demo RANGKA_WHATSAPP_MOCK_WEBHOOK_KEY=dummy-wa-hook-demo \
|
|
6
|
+
python3 rangka_whatsapp/mock/rangka_whatsapp_mock.py --port 8904 \
|
|
7
|
+
--hook-url http://127.0.0.1:8080/hooks/demo/rangka_whatsapp
|
|
8
|
+
|
|
9
|
+
Dummy keys only: the token and the webhook key must say they are a dummy (a part "dummy" or "test" between - _ or .).
|
|
10
|
+
Keys come from the environment, never argv (`ps` shows argv). It listens on 127.0.0.1 only.
|
|
11
|
+
|
|
12
|
+
Stdlib only. The request, answer and event shapes follow connector.rk and README.md:
|
|
13
|
+
|
|
14
|
+
- POST /svc/whatsapp/v1/messages (Bearer token) {to, template, type, components, idempotency_key}: 200 {message_id,
|
|
15
|
+
status}. The same idempotency_key again answers the first message with duplicate: true and sends nothing. Refusals,
|
|
16
|
+
in the relay's order: service_stopped (403), service_paused (403), template_not_approved (409),
|
|
17
|
+
recipient_opted_out (422), quota_exceeded (403), rate_limited (429 with Retry-After).
|
|
18
|
+
- POST /svc/whatsapp/v1/opt-outs (Bearer token) {phone}: 200 {status: recorded | already}.
|
|
19
|
+
- POST /simulate/status {message_id | idempotency_key, status, error}: the message's status changes (sent, delivered,
|
|
20
|
+
read, failed) and the mock posts the message_status event to --hook-url/message_status, signed.
|
|
21
|
+
- POST /simulate/inbound {from, text}: a customer writes. BERHENTI or STOP opts them out and posts opted_out; anything
|
|
22
|
+
else posts message_received.
|
|
23
|
+
- POST /simulate/redeliver[?key=<other>]: posts the last event again (the host retries an event that got no 2xx),
|
|
24
|
+
optionally signed with another key, to test the receiver's dedupe and its signature check.
|
|
25
|
+
- POST /simulate/service {state: active | stopped | paused}, POST /simulate/template {name, approved: true | false},
|
|
26
|
+
POST /simulate/next {results: [rate_limited, upstream_unavailable]}, POST /simulate/cap {daily: n}.
|
|
27
|
+
- GET /calls: every request it received (Authorization redacted), for tests. GET /messages. GET /healthz.
|
|
28
|
+
|
|
29
|
+
A refusal the kernel does not retry is also posted as a message_status event with status failed and the code in
|
|
30
|
+
`error`, as the host does, so a flow can show on the document why nothing was sent.
|
|
31
|
+
"""
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import argparse
|
|
35
|
+
import hashlib
|
|
36
|
+
import hmac
|
|
37
|
+
import json
|
|
38
|
+
import os
|
|
39
|
+
import re
|
|
40
|
+
import sys
|
|
41
|
+
import threading
|
|
42
|
+
import urllib.error
|
|
43
|
+
import urllib.parse
|
|
44
|
+
import urllib.request
|
|
45
|
+
import uuid
|
|
46
|
+
from datetime import datetime, timezone
|
|
47
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
48
|
+
|
|
49
|
+
# name -> (message type, number of parameters); the same library as Rangka Cloud's (README.md "Templates").
|
|
50
|
+
TEMPLATES = {
|
|
51
|
+
"struk_pembayaran": ("receipt", 6),
|
|
52
|
+
"tagihan_terbit": ("reminder", 6),
|
|
53
|
+
"pengingat_jatuh_tempo": ("reminder", 6),
|
|
54
|
+
"terima_kasih_lunas": ("reminder", 2),
|
|
55
|
+
"pesanan_siap": ("order_ready", 3),
|
|
56
|
+
"pengingat_janji": ("appointment", 4),
|
|
57
|
+
}
|
|
58
|
+
TYPES = {"receipt", "reminder", "order_ready", "appointment"}
|
|
59
|
+
STOP_WORDS = {"BERHENTI", "STOP"}
|
|
60
|
+
KEY_RE = re.compile(r"^[A-Za-z0-9._:/-]{1,200}$")
|
|
61
|
+
SIGNATURE_HEADER = "X-Rangka-Signature"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def now_iso() -> str:
|
|
65
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_dummy(value: str) -> bool:
|
|
69
|
+
return any(p in ("dummy", "test") for p in re.split(r"[-_.]", value.lower()))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def normalize_phone(s) -> str | None:
|
|
73
|
+
"""Rangka Cloud's rule: '0812-0000-0001', '812 0000 0001', '62812…', '+62 0812…' -> '+6281200000001'; with a plus
|
|
74
|
+
the country code is as written; None when it is not a phone."""
|
|
75
|
+
s = str(s or "").strip()
|
|
76
|
+
plus = s.startswith("+")
|
|
77
|
+
if not re.fullmatch(r"\+?[0-9 .()\-]+", s):
|
|
78
|
+
return None
|
|
79
|
+
d = re.sub(r"[^0-9]", "", s)
|
|
80
|
+
if not plus:
|
|
81
|
+
if d.startswith("8"):
|
|
82
|
+
d = "62" + d
|
|
83
|
+
elif d.startswith("00"):
|
|
84
|
+
d = d[2:]
|
|
85
|
+
elif d.startswith("0"):
|
|
86
|
+
d = "62" + d[1:]
|
|
87
|
+
if d.startswith("620"):
|
|
88
|
+
d = "62" + d[3:]
|
|
89
|
+
if not 8 <= len(d) <= 15 or d.startswith("0"):
|
|
90
|
+
return None
|
|
91
|
+
return "+" + d
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def sign(key: str, body: bytes) -> str:
|
|
95
|
+
return "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class State:
|
|
99
|
+
def __init__(self, token, webhook_key, hook_url):
|
|
100
|
+
self.token, self.webhook_key, self.hook_url = token, webhook_key, (hook_url or "").rstrip("/")
|
|
101
|
+
self.service = "active"
|
|
102
|
+
self.approved = set(TEMPLATES)
|
|
103
|
+
self.opt_outs = set()
|
|
104
|
+
self.messages = {} # idempotency_key -> message
|
|
105
|
+
self.next = [] # results of the next sends
|
|
106
|
+
self.daily_cap = 500
|
|
107
|
+
self.calls = []
|
|
108
|
+
self.events = [] # (trigger, body bytes, http status)
|
|
109
|
+
self.lock = threading.Lock()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def deliver(state: State, trigger: str, event: dict, key: str | None = None, body: bytes | None = None) -> int:
|
|
113
|
+
"""POST one event to <hook-url>/<trigger>, signed over the raw body; the HTTP status, 0 when unreachable."""
|
|
114
|
+
body = body if body is not None else json.dumps(event, separators=(",", ":")).encode()
|
|
115
|
+
status = 0
|
|
116
|
+
if state.hook_url:
|
|
117
|
+
req = urllib.request.Request(f"{state.hook_url}/{trigger}", data=body, method="POST",
|
|
118
|
+
headers={"Content-Type": "application/json", SIGNATURE_HEADER: sign(key or state.webhook_key, body)})
|
|
119
|
+
try:
|
|
120
|
+
with urllib.request.urlopen(req, timeout=15) as r:
|
|
121
|
+
status = r.status
|
|
122
|
+
except urllib.error.HTTPError as e:
|
|
123
|
+
status = e.code
|
|
124
|
+
except OSError:
|
|
125
|
+
status = 0
|
|
126
|
+
with state.lock:
|
|
127
|
+
state.events.append((trigger, body, status))
|
|
128
|
+
return status
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def body_params(components):
|
|
132
|
+
"""[{type: body, parameters: [{type: text, text}]}] -> the texts, or None when it is anything else."""
|
|
133
|
+
if components in (None, "", []):
|
|
134
|
+
return []
|
|
135
|
+
if isinstance(components, str):
|
|
136
|
+
try:
|
|
137
|
+
components = json.loads(components)
|
|
138
|
+
except ValueError:
|
|
139
|
+
return None
|
|
140
|
+
if not isinstance(components, list) or len(components) != 1 or not isinstance(components[0], dict):
|
|
141
|
+
return None
|
|
142
|
+
c = components[0]
|
|
143
|
+
if str(c.get("type", "")).lower() != "body" or not isinstance(c.get("parameters", []), list):
|
|
144
|
+
return None
|
|
145
|
+
out = []
|
|
146
|
+
for p in c.get("parameters", []):
|
|
147
|
+
if not isinstance(p, dict) or p.get("type") != "text":
|
|
148
|
+
return None
|
|
149
|
+
t = re.sub(r"\s+", " ", str(p.get("text", ""))).strip()
|
|
150
|
+
if not t or len(t) > 512:
|
|
151
|
+
return None
|
|
152
|
+
out.append(t)
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def handler(state: State):
|
|
157
|
+
class H(BaseHTTPRequestHandler):
|
|
158
|
+
def log_message(self, *a):
|
|
159
|
+
pass
|
|
160
|
+
|
|
161
|
+
def _json(self, status, obj, headers=None):
|
|
162
|
+
raw = json.dumps(obj).encode()
|
|
163
|
+
self.send_response(status)
|
|
164
|
+
self.send_header("Content-Type", "application/json")
|
|
165
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
166
|
+
for k, v in (headers or {}).items():
|
|
167
|
+
self.send_header(k, v)
|
|
168
|
+
self.end_headers()
|
|
169
|
+
self.wfile.write(raw)
|
|
170
|
+
|
|
171
|
+
def _refuse(self, status, code, field=None, retry_after=None, notify=None):
|
|
172
|
+
err = {"code": code}
|
|
173
|
+
if field:
|
|
174
|
+
err["field"] = field
|
|
175
|
+
# The event goes first, so a caller that reads the answer finds the event already delivered.
|
|
176
|
+
if notify:
|
|
177
|
+
deliver(state, "message_status", {"message_id": "", "idempotency_key": notify["idempotency_key"], "type": notify["type"],
|
|
178
|
+
"status": "failed", "at": now_iso(), "error": code})
|
|
179
|
+
self._json(status, {"error": err}, {"Retry-After": str(retry_after)} if retry_after else None)
|
|
180
|
+
|
|
181
|
+
def _body(self):
|
|
182
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
183
|
+
raw = self.rfile.read(n) if n else b""
|
|
184
|
+
try:
|
|
185
|
+
return json.loads(raw or b"{}")
|
|
186
|
+
except ValueError:
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
def _authed(self):
|
|
190
|
+
got = self.headers.get("Authorization", "")
|
|
191
|
+
return hmac.compare_digest(got, "Bearer " + state.token)
|
|
192
|
+
|
|
193
|
+
def do_GET(self):
|
|
194
|
+
path = urllib.parse.urlparse(self.path).path
|
|
195
|
+
if path == "/healthz":
|
|
196
|
+
return self._json(200, {"ok": True})
|
|
197
|
+
if path == "/calls":
|
|
198
|
+
with state.lock:
|
|
199
|
+
return self._json(200, {"calls": list(state.calls)})
|
|
200
|
+
if path == "/messages":
|
|
201
|
+
with state.lock:
|
|
202
|
+
return self._json(200, {"messages": list(state.messages.values()), "opt_outs": len(state.opt_outs)})
|
|
203
|
+
self._json(404, {"error": {"code": "not_found"}})
|
|
204
|
+
|
|
205
|
+
def do_POST(self):
|
|
206
|
+
url = urllib.parse.urlparse(self.path)
|
|
207
|
+
path = url.path
|
|
208
|
+
body = self._body()
|
|
209
|
+
with state.lock:
|
|
210
|
+
state.calls.append({"path": path, "authorization": "REDACTED" if self.headers.get("Authorization") else "", "body": body})
|
|
211
|
+
if path.startswith("/svc/"):
|
|
212
|
+
if not self._authed():
|
|
213
|
+
return self._refuse(401, "unauthenticated")
|
|
214
|
+
if not isinstance(body, dict):
|
|
215
|
+
return self._refuse(400, "bad_request", "body")
|
|
216
|
+
if path == "/svc/whatsapp/v1/messages":
|
|
217
|
+
return self.send_message(body)
|
|
218
|
+
if path == "/svc/whatsapp/v1/opt-outs":
|
|
219
|
+
return self.opt_out(body)
|
|
220
|
+
if path.startswith("/simulate/") and isinstance(body, dict):
|
|
221
|
+
return self.simulate(path[len("/simulate/"):], body, urllib.parse.parse_qs(url.query))
|
|
222
|
+
self._json(404, {"error": {"code": "not_found"}})
|
|
223
|
+
|
|
224
|
+
def send_message(self, b):
|
|
225
|
+
to = normalize_phone(b.get("to"))
|
|
226
|
+
if not to:
|
|
227
|
+
return self._refuse(400, "bad_request", "to")
|
|
228
|
+
typ, tpl, key = b.get("type"), b.get("template"), b.get("idempotency_key")
|
|
229
|
+
if typ not in TYPES:
|
|
230
|
+
return self._refuse(400, "bad_request", "type")
|
|
231
|
+
if not isinstance(key, str) or not KEY_RE.match(key):
|
|
232
|
+
return self._refuse(400, "bad_request", "idempotency_key")
|
|
233
|
+
if tpl not in TEMPLATES:
|
|
234
|
+
return self._refuse(400, "bad_request", "template")
|
|
235
|
+
params = body_params(b.get("components"))
|
|
236
|
+
if params is None or TEMPLATES[tpl][0] != typ or len(params) != TEMPLATES[tpl][1]:
|
|
237
|
+
return self._refuse(400, "bad_request", "components" if TEMPLATES[tpl][0] == typ else "type")
|
|
238
|
+
note = {"idempotency_key": key, "type": typ}
|
|
239
|
+
with state.lock:
|
|
240
|
+
service, approved, opted = state.service, tpl in state.approved, to in state.opt_outs
|
|
241
|
+
held = state.messages.get(key)
|
|
242
|
+
count = len(state.messages)
|
|
243
|
+
result = "ok"
|
|
244
|
+
if service == "active" and approved and not opted and not held and count < state.daily_cap and state.next:
|
|
245
|
+
result = state.next.pop(0)
|
|
246
|
+
if service == "stopped":
|
|
247
|
+
return self._refuse(403, "service_stopped", notify=note)
|
|
248
|
+
if service == "paused":
|
|
249
|
+
return self._refuse(403, "service_paused", notify=note)
|
|
250
|
+
if not approved:
|
|
251
|
+
return self._refuse(409, "template_not_approved", notify=note)
|
|
252
|
+
if opted:
|
|
253
|
+
return self._refuse(422, "recipient_opted_out", notify=note)
|
|
254
|
+
if held:
|
|
255
|
+
return self._json(200, {"message_id": held["message_id"], "status": held["status"], "duplicate": True})
|
|
256
|
+
if count >= state.daily_cap:
|
|
257
|
+
return self._refuse(403, "quota_exceeded", notify=note)
|
|
258
|
+
if result == "rate_limited":
|
|
259
|
+
return self._refuse(429, "rate_limited", retry_after=2)
|
|
260
|
+
if result == "upstream_unavailable":
|
|
261
|
+
return self._refuse(502, "upstream_unavailable")
|
|
262
|
+
msg = {"message_id": "wam_" + uuid.uuid4().hex[:20], "idempotency_key": key, "type": typ, "template": tpl,
|
|
263
|
+
"to": to, "params": params, "status": "accepted", "at": now_iso()}
|
|
264
|
+
with state.lock:
|
|
265
|
+
first = state.messages.setdefault(key, msg)
|
|
266
|
+
if first is not msg:
|
|
267
|
+
return self._json(200, {"message_id": first["message_id"], "status": first["status"], "duplicate": True})
|
|
268
|
+
self._json(200, {"message_id": msg["message_id"], "status": "accepted"})
|
|
269
|
+
|
|
270
|
+
def opt_out(self, b):
|
|
271
|
+
phone = normalize_phone(b.get("phone"))
|
|
272
|
+
if not phone:
|
|
273
|
+
return self._refuse(400, "bad_request", "phone")
|
|
274
|
+
with state.lock:
|
|
275
|
+
new = phone not in state.opt_outs
|
|
276
|
+
state.opt_outs.add(phone)
|
|
277
|
+
self._json(200, {"status": "recorded" if new else "already"})
|
|
278
|
+
|
|
279
|
+
def simulate(self, what, b, query):
|
|
280
|
+
if what == "status":
|
|
281
|
+
with state.lock:
|
|
282
|
+
msg = state.messages.get(b.get("idempotency_key")) or next(
|
|
283
|
+
(m for m in state.messages.values() if m["message_id"] == b.get("message_id")), None)
|
|
284
|
+
if msg and b.get("status") in ("sent", "delivered", "read", "failed"):
|
|
285
|
+
msg["status"] = b["status"]
|
|
286
|
+
if not msg or b.get("status") not in ("sent", "delivered", "read", "failed"):
|
|
287
|
+
return self._json(404, {"error": {"code": "not_found"}})
|
|
288
|
+
code = deliver(state, "message_status", {"message_id": msg["message_id"], "idempotency_key": msg["idempotency_key"],
|
|
289
|
+
"type": msg["type"], "status": b["status"], "at": now_iso(), "error": str(b.get("error") or "")})
|
|
290
|
+
return self._json(200, {"hook_status": code})
|
|
291
|
+
if what == "inbound":
|
|
292
|
+
phone = normalize_phone(b.get("from"))
|
|
293
|
+
if not phone:
|
|
294
|
+
return self._json(400, {"error": {"code": "bad_request", "field": "from"}})
|
|
295
|
+
text = str(b.get("text") or "")
|
|
296
|
+
if text.strip().upper() in STOP_WORDS:
|
|
297
|
+
with state.lock:
|
|
298
|
+
state.opt_outs.add(phone)
|
|
299
|
+
code = deliver(state, "opted_out", {"phone": phone, "at": now_iso(), "source": "keyword"})
|
|
300
|
+
else:
|
|
301
|
+
code = deliver(state, "message_received", {"message_id": "wamid.IN" + uuid.uuid4().hex[:12], "from": phone, "text": text,
|
|
302
|
+
"profile_name": str(b.get("profile_name") or "Pelanggan Contoh"), "at": now_iso()})
|
|
303
|
+
return self._json(200, {"hook_status": code})
|
|
304
|
+
if what == "redeliver":
|
|
305
|
+
with state.lock:
|
|
306
|
+
last = state.events[-1] if state.events else None
|
|
307
|
+
if not last:
|
|
308
|
+
return self._json(404, {"error": {"code": "not_found"}})
|
|
309
|
+
code = deliver(state, last[0], {}, key=(query.get("key") or [None])[0], body=last[1])
|
|
310
|
+
return self._json(200, {"hook_status": code})
|
|
311
|
+
if what == "service" and b.get("state") in ("active", "stopped", "paused"):
|
|
312
|
+
with state.lock:
|
|
313
|
+
state.service = b["state"]
|
|
314
|
+
return self._json(200, {"state": b["state"]})
|
|
315
|
+
if what == "template" and b.get("name") in TEMPLATES:
|
|
316
|
+
with state.lock:
|
|
317
|
+
(state.approved.add if b.get("approved") else state.approved.discard)(b["name"])
|
|
318
|
+
return self._json(200, {"name": b["name"], "approved": bool(b.get("approved"))})
|
|
319
|
+
if what == "next" and isinstance(b.get("results"), list):
|
|
320
|
+
with state.lock:
|
|
321
|
+
state.next.extend(str(r) for r in b["results"])
|
|
322
|
+
return self._json(200, {"queued": len(b["results"])})
|
|
323
|
+
if what == "cap" and isinstance(b.get("daily"), int):
|
|
324
|
+
with state.lock:
|
|
325
|
+
state.daily_cap = b["daily"]
|
|
326
|
+
return self._json(200, {"daily": b["daily"]})
|
|
327
|
+
self._json(400, {"error": {"code": "bad_request"}})
|
|
328
|
+
|
|
329
|
+
return H
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def make_server(port: int, token: str, webhook_key: str, hook_url: str | None):
|
|
333
|
+
if not is_dummy(token) or not is_dummy(webhook_key):
|
|
334
|
+
raise ValueError("the mock takes dummy keys only: the token and the webhook key must have a part 'dummy' or 'test'")
|
|
335
|
+
state = State(token, webhook_key, hook_url)
|
|
336
|
+
return ThreadingHTTPServer(("127.0.0.1", port), handler(state)), state
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def main():
|
|
340
|
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
341
|
+
ap.add_argument("--port", type=int, default=8904)
|
|
342
|
+
ap.add_argument("--hook-url", default="", help="where events go: <kernel>/hooks/<org>/rangka_whatsapp (the trigger name is appended)")
|
|
343
|
+
a = ap.parse_args()
|
|
344
|
+
token, key = os.environ.get("RANGKA_WHATSAPP_MOCK_TOKEN", ""), os.environ.get("RANGKA_WHATSAPP_MOCK_WEBHOOK_KEY", "")
|
|
345
|
+
try:
|
|
346
|
+
srv, _ = make_server(a.port, token, key, a.hook_url)
|
|
347
|
+
except ValueError as e:
|
|
348
|
+
sys.exit(f"rangka_whatsapp_mock: {e}")
|
|
349
|
+
print(f"rangka_whatsapp mock on http://127.0.0.1:{a.port} (events to {a.hook_url or 'nowhere'})", file=sys.stderr)
|
|
350
|
+
srv.serve_forever()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
if __name__ == "__main__":
|
|
354
|
+
main()
|