@rangka-os/create 0.5.0-alpha.26 → 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/email/connector.rk +144 -0
- package/template/base/connectors/email/fixtures/email_received.json +33 -0
- package/template/base/connectors/email/fixtures/email_received_reply.json +31 -0
- package/template/base/connectors/email/fixtures/expect.json +20 -0
- package/template/base/connectors/email/fixtures/fetch_email.json +66 -0
- package/template/base/connectors/email/fixtures/send_email.json +4 -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,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()
|