@rangka-os/create 0.5.0-alpha.15 → 0.5.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/package.json +1 -1
  2. package/template/base/apps/grosir_distribusi/app.rk +2 -1
  3. package/template/base/apps/langganan_jasa/app.rk +3 -0
  4. package/template/base/apps/produksi_pabrik/dashboards/produksi_overview.rk +1 -1
  5. package/template/base/apps/ritel_cabang/app.rk +3 -0
  6. package/template/base/connectors/doku/mock/doku_mock.py +16 -5
  7. package/template/base/connectors/moka/mock/moka_mock.py +210 -0
  8. package/template/base/connectors/xendit/mock/xendit_mock.py +231 -0
  9. package/template/base/modules/bank_statement/flows/bank_transaction_booked.rk +12 -0
  10. package/template/base/modules/bank_statement/flows/bank_transaction_booked_released.rk +11 -0
  11. package/template/base/modules/bank_statement/flows/bank_transaction_claim.rk +11 -1
  12. package/template/base/modules/bank_statement/flows/bank_transaction_confirm.rk +23 -5
  13. package/template/base/modules/bank_statement/flows/bank_transaction_suggest.rk +56 -14
  14. package/template/base/modules/bank_statement/models/bank_transaction.rk +27 -4
  15. package/template/base/modules/bank_statement/models/bank_transaction_claim.rk +1 -1
  16. package/template/base/modules/catalogue/models/item_category.rk +2 -0
  17. package/template/base/modules/coretax/module.rk +2 -2
  18. package/template/base/modules/coretax/print/coretax_faktur.rk +1 -1
  19. package/template/base/modules/coretax/print/coretax_faktur.xml +13 -7
  20. package/template/base/modules/delivery/flows/invoice_qty_from_deliveries.rk +1 -1
  21. package/template/base/modules/delivery/module.rk +1 -1
  22. package/template/base/modules/distribution/flows/order_tier_pricing_created.rk +2 -2
  23. package/template/base/modules/distribution/flows/order_tier_pricing_updated.rk +2 -2
  24. package/template/base/modules/distribution/module.rk +1 -1
  25. package/template/base/modules/invoicing/models/sales_invoice.rk +31 -4
  26. package/template/base/modules/invoicing/models/sales_invoice_item.rk +7 -0
  27. package/template/base/modules/invoicing/module.rk +1 -1
  28. package/template/base/modules/invoicing/print/sales_invoice.html +15 -2
  29. package/template/base/modules/orders/models/customer_order.rk +2 -0
  30. package/template/base/modules/orders/models/customer_order_item.rk +10 -0
  31. package/template/base/modules/orders/module.rk +1 -1
  32. package/template/base/modules/payments/flows/payment_refund_from_doku.rk +14 -0
  33. package/template/base/modules/payroll/flows/payroll_close_on_submit.rk +2 -2
  34. package/template/base/modules/payroll/module.rk +2 -2
  35. package/template/base/modules/production/models/production_batch.rk +3 -0
  36. package/template/base/modules/production/module.rk +1 -1
  37. package/template/base/modules/quotation/models/quotation.rk +14 -4
  38. package/template/base/modules/quotation/models/quotation_item.rk +13 -0
  39. package/template/base/modules/quotation/module.rk +1 -1
  40. package/template/base/modules/quotation/print/quotation.html +16 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rangka-os/create",
3
- "version": "0.5.0-alpha.15",
3
+ "version": "0.5.0-alpha.16",
4
4
  "description": "Start a Rangka OS project: npm create @rangka-os@latest my-shop",
5
5
  "license": "Elastic-2.0",
6
6
  "homepage": "https://rangka-os.github.io/rangka-os/guide/quick-start",
@@ -26,13 +26,14 @@ modules:
26
26
  procurement: ^1.0
27
27
  distribution: ^1.0
28
28
  delivery: ^1.0
29
+ bank_statement: ^1.0
29
30
  dashboards: [grosir_overview, grosir_ar]
30
31
  roles: [sales_manager, finance_manager, head_office, field_sales]
31
32
  home: {dashboard: grosir_overview}
32
33
  # recipe is installed with stock but has no menu entry: a distributor sells goods as they are.
33
34
  menu:
34
35
  - group: {id: Penjualan}
35
- items: [customer_order, sales_invoice, payment, giro, bank_account]
36
+ items: [customer_order, sales_invoice, payment, giro, bank_transaction, bank_account]
36
37
  - group: {id: Pengiriman}
37
38
  items: [delivery_note, sales_return, order_fulfilment, return_credit]
38
39
  - group: {id: Gudang}
@@ -20,6 +20,7 @@ modules:
20
20
  payments: ^1.0
21
21
  procurement: ^1.0
22
22
  subscriptions: ^1.0
23
+ bank_statement: ^1.0
23
24
  dashboards: [langganan_ringkas, penagihan_saya]
24
25
  roles: [finance_manager, collector]
25
26
  home: {dashboard: langganan_ringkas}
@@ -32,5 +33,7 @@ menu:
32
33
  items: [subscription, subscription_bill, subscription_extra, subscription_status_log]
33
34
  - group: {id: Penagihan lapangan}
34
35
  items: [field_collection, collection_visit, collector_deposit, service_area]
36
+ - group: {id: Bank}
37
+ items: [bank_transaction, bank_account]
35
38
  - group: {id: Pengaturan langganan}
36
39
  items: [subscription_plan, subscription_month]
@@ -88,7 +88,7 @@ widgets:
88
88
  filter: docstatus == 1
89
89
  sort: -production_date
90
90
  limit: 10
91
- columns: [name, item, good_qty, hpp_per_unit, standard_unit_cost, expiry_date]
91
+ columns: [name, item, good_qty, uom, hpp_per_unit, standard_unit_cost]
92
92
  span: 12
93
93
  - name: open_work_orders
94
94
  type: list
@@ -25,6 +25,7 @@ modules:
25
25
  invoicing: ^1.0
26
26
  coretax: ^1.0
27
27
  consignment: ^1.0
28
+ bank_statement: ^1.0
28
29
  dashboards: [ritel_overview, ritel_stock, ritel_tax]
29
30
  roles: [head_office, outlet_staff]
30
31
  home: {dashboard: ritel_overview}
@@ -37,6 +38,8 @@ menu:
37
38
  items: [stock_balance, stock_move, stock_transfer, stock_transfer_receipt, stock_count, stock_adjustment]
38
39
  - group: {id: Pembelian}
39
40
  items: [purchase_request, purchase_order, goods_receipt, vendor_bill, payment]
41
+ - group: {id: Bank}
42
+ items: [bank_transaction, bank_account]
40
43
  - group: {id: Titipan}
41
44
  items: [consignment_settlement]
42
45
  - group: {id: Pembukuan}
@@ -18,8 +18,10 @@ reports/keputusan-riset/doku-connector.md):
18
18
  - GET /checkout-link-v2/<token> a small page standing in for DOKU's payment page (QRIS text and a pay button).
19
19
  - POST /simulate/pay/<token>[?status=FAILED] marks the payment and sends the signed HTTP notification to
20
20
  --notify-url, the way DOKU's sandbox simulator does; answers with the notification's status code.
21
- - POST /simulate/notify body {"invoice_number", "amount", "status"}: a notification for an invoice without Checkout
22
- (a static QRIS paid at the counter).
21
+ - POST /simulate/refund/<token>[?amount=N] a paid payment refunded (all, or N): a notification of transaction.type
22
+ REFUND, status SUCCESS, same original_request_id, as DOKU sends after a refund from Back Office. Not money in.
23
+ - POST /simulate/notify body {"invoice_number", "amount", "status", "type"}: a notification for an invoice without
24
+ Checkout (a static QRIS paid at the counter); type SALE by default, REFUND for a refund.
23
25
  - GET /calls every request it received (for tests).
24
26
 
25
27
  The kernel only sends signed requests over https to api-sandbox.doku.com or api.doku.com (rangka-os contract 0017
@@ -73,11 +75,11 @@ class State:
73
75
  self.lock = threading.Lock()
74
76
 
75
77
 
76
- def notify(state: State, invoice: str, amount: int, status: str, original_request_id: str, channel="QRIS") -> int:
78
+ def notify(state: State, invoice: str, amount: int, status: str, original_request_id: str, channel="QRIS", type_="SALE") -> int:
77
79
  """Send one signed notification to the notify URL, as DOKU does; returns the HTTP status (0 when unreachable)."""
78
80
  body = json.dumps({
79
81
  "order": {"invoice_number": invoice, "amount": amount},
80
- "transaction": {"type": "SALE", "status": status, "date": now_utc(), "original_request_id": original_request_id},
82
+ "transaction": {"type": type_, "status": status, "date": now_utc(), "original_request_id": original_request_id},
81
83
  "service": {"id": "QRIS" if channel == "QRIS" else "VIRTUAL_ACCOUNT"}, "acquirer": {"id": "QRIS"},
82
84
  "channel": {"id": channel}, "additional_info": {"origin": {"product": "CHECKOUT", "source": "doku-mock"}},
83
85
  }, separators=(",", ":")).encode()
@@ -166,11 +168,20 @@ def handler(state: State):
166
168
  p["status"] = status
167
169
  code = notify(state, p["invoice_number"], p["amount"], status, p["request_id"])
168
170
  return self.send(200, {"notified": code, "status": status})
171
+ if u.path.startswith("/simulate/refund/"):
172
+ tok = u.path.rsplit("/", 1)[-1]
173
+ p = state.payments.get(tok)
174
+ if not p or p["status"] != "SUCCESS":
175
+ return self.send(404, {"error": {"code": "not_paid"}})
176
+ amount = int(urllib.parse.parse_qs(u.query).get("amount", [str(p["amount"])])[0])
177
+ code = notify(state, p["invoice_number"], amount, "SUCCESS", p["request_id"], type_="REFUND")
178
+ return self.send(200, {"notified": code, "type": "REFUND", "amount": amount})
169
179
  if u.path == "/simulate/notify":
170
180
  try:
171
181
  req = json.loads(raw or b"{}")
172
182
  code = notify(state, str(req["invoice_number"]), int(req["amount"]), req.get("status", "SUCCESS"),
173
- req.get("original_request_id") or str(uuid.uuid4()), req.get("channel", "QRIS"))
183
+ req.get("original_request_id") or str(uuid.uuid4()), req.get("channel", "QRIS"),
184
+ req.get("type", "SALE"))
174
185
  except (ValueError, KeyError, TypeError):
175
186
  return self.send(400, {"error": {"code": "invalid_request"}})
176
187
  return self.send(200, {"notified": code})
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env python3
2
+ """A local stand-in for the Moka Connect API, and a poller that does what the kernel's poll trigger does, for demos and
3
+ tests without Moka API access (Moka grants it per partner; see moka/connector.rk).
4
+
5
+ python3 moka/mock/moka_mock.py serve --port 8911 --fixtures moka/fixtures [--token demo-token] [--day 2026-11-04]
6
+ python3 moka/mock/moka_mock.py poll --moka http://127.0.0.1:8911 --rangka http://127.0.0.1:8101 \
7
+ [--today 2026-11-06] # the Rangka API token comes from RANGKA_TOKEN (not argv, which `ps` shows)
8
+
9
+ serve answers, in Moka's formats, from the fixtures folder (latest_transactions.json, list_outlets.json):
10
+ - GET /v1/businesses/outlets -> list_outlets.json
11
+ - GET /v3/outlets/<id>/reports/get_latest_transactions -> that outlet's payments whose synchronized_at (or
12
+ created_at / updated_at, time_filter) is at or after `since` (epoch seconds), newest first (reorder_type DESC, the
13
+ default) or oldest first (ASC), `per_page` per page, the next page in data.next_url (null on the last page)
14
+ - GET /calls -> every request it received (for tests)
15
+ A request without `Authorization: Bearer <token>` is 401, as Moka answers. --day D moves every transaction to day D
16
+ (created_at, synchronized_at, refunded_date and the refunds keep their time of day; a refund made a later day than its
17
+ sale stays that many days later), so one fixture serves any demo date.
18
+
19
+ poll reads the mock the way the kernel's trigger moka.transaction_created does (contract 0002 §A.1, moka/connector.rk):
20
+ list_outlets first, then per outlet get_latest_transactions since two days before today with time_filter
21
+ synchronized_at, DESC, following next_url until it is null, and for each payment the trigger's emit mapping. Each event
22
+ goes to the tenant's flow moka_transaction_staged (POST /api/v1/flows/moka_transaction_staged/run), which is where the
23
+ kernel would start it. The kernel's own drop of a repeated event (hash kept 30 days) is not reproduced: the flow's
24
+ idempotency key (transaction and refunded quantity) is what keeps a repeated poll from booking twice, and the demo
25
+ polls twice to show it.
26
+
27
+ Why not let the kernel poll the mock: connector actions call https://api.mokapos.com (fixed in connector.rk) and the
28
+ kernel has no per-host override; a mock on 127.0.0.1 would need one. Until then the poller stands in for the kernel's
29
+ poll job, and only the HTTP leg between them is skipped.
30
+
31
+ Synthetic data only. Stdlib only.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import json
37
+ import os
38
+ import re
39
+ import sys
40
+ import threading
41
+ import urllib.error
42
+ import urllib.parse
43
+ import urllib.request
44
+ from datetime import date, datetime, timedelta, timezone
45
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
46
+
47
+ WIB = timezone(timedelta(hours=7))
48
+
49
+
50
+ def parse_ts(s: str) -> datetime:
51
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
52
+
53
+
54
+ def shift_day(s, base: date, day: date):
55
+ """s moved from its sale day `base` to `day`, keeping the time of day and the offset (and any days after the sale)."""
56
+ if not s:
57
+ return s
58
+ t = parse_ts(s)
59
+ return (t + timedelta(days=(day - base).days)).isoformat()
60
+
61
+
62
+ def load(fixtures: str, day: str | None):
63
+ pays = json.load(open(os.path.join(fixtures, "latest_transactions.json")))["data"]["payments"]
64
+ outlets = json.load(open(os.path.join(fixtures, "list_outlets.json")))
65
+ if day:
66
+ d = date.fromisoformat(day)
67
+ moved = []
68
+ for p in pays:
69
+ base = parse_ts(p["created_at"]).date()
70
+ q = dict(p)
71
+ for k in ("created_at", "synchronized_at", "updated_at", "refunded_date"):
72
+ if q.get(k):
73
+ q[k] = shift_day(q[k], base, d)
74
+ q["payment_refunds"] = [dict(r, created_at=shift_day(r.get("created_at"), base, d)) for r in (p.get("payment_refunds") or [])]
75
+ moved.append(q)
76
+ pays = moved
77
+ return pays, outlets
78
+
79
+
80
+ class Mock:
81
+ def __init__(self, fixtures: str, token: str, day: str | None = None):
82
+ self.payments, self.outlets = load(fixtures, day)
83
+ self.token = token
84
+ self.calls: list[dict] = []
85
+ self.lock = threading.Lock()
86
+
87
+ def latest(self, outlet_id: str, q: dict, base: str) -> dict:
88
+ since = int(q.get("since", ["0"])[0] or 0)
89
+ field = q.get("time_filter", ["synchronized_at"])[0]
90
+ if field not in ("created_at", "updated_at", "synchronized_at"):
91
+ field = "synchronized_at"
92
+ order = q.get("reorder_type", ["DESC"])[0].upper()
93
+ per = max(1, min(100, int(q.get("per_page", ["100"])[0] or 100)))
94
+ page = max(1, int(q.get("page", ["1"])[0] or 1))
95
+
96
+ def when(p):
97
+ return parse_ts(p.get(field) or p["created_at"]).timestamp()
98
+
99
+ rows = [p for p in self.payments if str(p["outlet_id"]) == str(outlet_id) and when(p) >= since]
100
+ rows.sort(key=when, reverse=order != "ASC")
101
+ chunk = rows[(page - 1) * per: page * per]
102
+ nxt = None
103
+ if page * per < len(rows):
104
+ qq = {k: v[0] for k, v in q.items()}
105
+ qq["page"] = str(page + 1)
106
+ nxt = f"{base}/v3/outlets/{outlet_id}/reports/get_latest_transactions?{urllib.parse.urlencode(qq)}"
107
+ return {"data": {"completed": nxt is None, "next_url": nxt, "payments": chunk}}
108
+
109
+
110
+ def handler(m: Mock):
111
+ class H(BaseHTTPRequestHandler):
112
+ def log_message(self, *a):
113
+ pass
114
+
115
+ def send(self, code, obj):
116
+ b = json.dumps(obj).encode()
117
+ self.send_response(code)
118
+ self.send_header("Content-Type", "application/json")
119
+ self.send_header("Content-Length", str(len(b)))
120
+ self.end_headers()
121
+ self.wfile.write(b)
122
+
123
+ def do_GET(self):
124
+ u = urllib.parse.urlsplit(self.path)
125
+ with m.lock:
126
+ m.calls.append({"path": u.path, "query": u.query})
127
+ if u.path == "/calls":
128
+ return self.send(200, m.calls)
129
+ if self.headers.get("Authorization") != f"Bearer {m.token}":
130
+ return self.send(401, {"meta": {"code": 401, "error_type": "unauthorized", "error_message": "invalid access token"}})
131
+ if u.path == "/v1/businesses/outlets":
132
+ return self.send(200, m.outlets)
133
+ mt = re.fullmatch(r"/v3/outlets/([^/]+)/reports/get_latest_transactions", u.path)
134
+ if mt:
135
+ base = f"http://{self.headers.get('Host')}"
136
+ return self.send(200, m.latest(mt.group(1), urllib.parse.parse_qs(u.query), base))
137
+ self.send(404, {"meta": {"code": 404, "error_message": "not found"}})
138
+
139
+ return H
140
+
141
+
142
+ def get(url: str, token: str) -> dict:
143
+ req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
144
+ with urllib.request.urlopen(req, timeout=30) as r:
145
+ return json.loads(r.read())
146
+
147
+
148
+ def emit(p: dict, outlet: dict) -> dict:
149
+ """The emit mapping of trigger transaction_created (moka/connector.rk), item = p, outlet = the list_outlets row."""
150
+ return {
151
+ "transaction_id": p.get("id"), "outlet_id": p.get("outlet_id"), "outlet_name": outlet.get("name"),
152
+ "receipt_no": p.get("payment_no"), "created_at": p.get("created_at"), "synchronized_at": p.get("synchronized_at"),
153
+ "is_refunded": p.get("is_refunded"), "refunded_date": p.get("refunded_date"), "payment_refunds": p.get("payment_refunds"),
154
+ "checkouts": p.get("checkouts"), "payment_type": p.get("payment_type"), "total_collected": p.get("total_collected"),
155
+ }
156
+
157
+
158
+ def poll(moka: str, moka_token: str, rangka: str, rangka_token: str, today: str, max_pages: int = 50) -> dict:
159
+ """One poll as the kernel runs it; returns {events, delivered, refused, pages}."""
160
+ since = int((datetime.combine(date.fromisoformat(today), datetime.min.time(), WIB) - timedelta(days=2)).timestamp())
161
+ out = {"events": 0, "delivered": 0, "refused": [], "pages": 0}
162
+ for o in get(f"{moka}/v1/businesses/outlets", moka_token).get("data", []):
163
+ url = f"{moka}/v3/outlets/{o['id']}/reports/get_latest_transactions?" + urllib.parse.urlencode(
164
+ {"since": since, "time_filter": "synchronized_at", "reorder_type": "DESC", "per_page": "100"})
165
+ for _ in range(max_pages):
166
+ page = get(url, moka_token)["data"]
167
+ out["pages"] += 1
168
+ for p in page.get("payments") or []:
169
+ out["events"] += 1
170
+ body = json.dumps({"event": emit(p, o)}).encode()
171
+ req = urllib.request.Request(f"{rangka}/api/v1/flows/moka_transaction_staged/run", data=body, method="POST",
172
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {rangka_token}"})
173
+ try:
174
+ with urllib.request.urlopen(req, timeout=60) as r:
175
+ out["delivered"] += r.status == 200
176
+ except urllib.error.HTTPError as e:
177
+ out["refused"].append({"transaction": p.get("id"), "status": e.code, "body": e.read()[:300].decode(errors="replace")})
178
+ url = page.get("next_url")
179
+ if not url:
180
+ break
181
+ return out
182
+
183
+
184
+ def main(argv=None):
185
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
186
+ sub = ap.add_subparsers(dest="cmd", required=True)
187
+ s = sub.add_parser("serve")
188
+ s.add_argument("--port", type=int, default=8911)
189
+ s.add_argument("--fixtures", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "fixtures"))
190
+ s.add_argument("--token", default=os.environ.get("MOKA_MOCK_TOKEN", "demo-moka-token"))
191
+ s.add_argument("--day", default=None, help="move every transaction to this day (YYYY-MM-DD)")
192
+ p = sub.add_parser("poll")
193
+ p.add_argument("--moka", required=True)
194
+ p.add_argument("--rangka", required=True)
195
+ p.add_argument("--today", default=datetime.now(WIB).date().isoformat())
196
+ p.add_argument("--moka-token", default=os.environ.get("MOKA_MOCK_TOKEN", "demo-moka-token"))
197
+ a = ap.parse_args(argv)
198
+ if a.cmd == "serve":
199
+ srv = ThreadingHTTPServer(("127.0.0.1", a.port), handler(Mock(a.fixtures, a.token, a.day)))
200
+ print(f"moka mock: http://127.0.0.1:{srv.server_address[1]}", flush=True)
201
+ srv.serve_forever()
202
+ else:
203
+ tok = os.environ.get("RANGKA_TOKEN", "")
204
+ if not tok:
205
+ sys.exit("set RANGKA_TOKEN (an API token of the tenant's owner or head office)")
206
+ print(json.dumps(poll(a.moka, a.moka_token, a.rangka, tok, a.today)))
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env python3
2
+ """A local stand-in for Xendit in test mode (fixed virtual accounts and dynamic QRIS), for demos and tests without a
3
+ Xendit account.
4
+
5
+ XENDIT_MOCK_SECRET_KEY=xnd_development_dummy_demo XENDIT_MOCK_CALLBACK_TOKEN=dummy-cb-demo \
6
+ python3 xendit/mock/xendit_mock.py --port 8902 \
7
+ --va-callback-url http://127.0.0.1:8790/api/xendit/va_paid --qr-callback-url http://127.0.0.1:8790/api/xendit/qr_paid
8
+
9
+ Dummy keys only: the key must start with xnd_development_ and say it is a dummy (a part "dummy" or "test" between
10
+ - _ or .), and the callback token too. Keys come from the environment, never argv (`ps` shows argv). It listens on
11
+ 127.0.0.1 only.
12
+
13
+ Stdlib only. The request and callback shapes follow Xendit's API and the connector `xendit` (connector.rk):
14
+
15
+ - POST /callback_virtual_accounts (Basic auth: secret key, empty password): a fixed VA. A second request with the same
16
+ external_id answers the VA it already made (one VA per invoice), so a retried request makes no second VA.
17
+ - POST /qr_codes (Basic auth): a dynamic QRIS, reference_id = the invoice number.
18
+ - POST /callback_virtual_accounts/external_id=<id>/simulate_payment {amount}: the payer pays the VA (Xendit test
19
+ mode has the same endpoint). The mock sends the VA callback (x-callback-token header) and answers with the callback's
20
+ HTTP status. A closed VA refuses another amount (400 INVALID_AMOUNT).
21
+ - POST /qr_codes/<qr id>/payments/simulate {amount}: the payer pays the QRIS; sends the qr.payment callback.
22
+ - POST /simulate/redeliver/<payment id>[?token=<other>]: sends a callback that was already sent once more (Xendit
23
+ retries a callback that did not get a 2xx), optionally with another token, to test the receiver's idempotency and
24
+ its token check.
25
+ - GET /calls: every request it received (Authorization redacted), for tests. GET /healthz.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import base64
31
+ import hmac
32
+ import json
33
+ import os
34
+ import re
35
+ import sys
36
+ import threading
37
+ import urllib.error
38
+ import urllib.parse
39
+ import urllib.request
40
+ import uuid
41
+ from datetime import datetime, timedelta, timezone
42
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
43
+
44
+ BANKS = {"BCA": "39108", "BNI": "8808", "BRI": "26215", "MANDIRI": "88908", "PERMATA": "8214", "BSI": "6059", "CIMB": "93490"}
45
+
46
+
47
+ def now_iso() -> str:
48
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
49
+
50
+
51
+ class State:
52
+ def __init__(self, secret, token, va_url, qr_url, owner_id="5f0000000000000000000001"):
53
+ self.secret, self.token, self.va_url, self.qr_url, self.owner_id = secret, token, va_url, qr_url, owner_id
54
+ self.vas = {} # external_id -> VA
55
+ self.qrs = {} # qr id -> QR
56
+ self.sent = {} # payment id -> (kind, payload)
57
+ self.calls = []
58
+ self.seq = 0
59
+ self.lock = threading.Lock()
60
+
61
+
62
+ def deliver(state: State, kind: str, payload: dict, token: str | None = None) -> int:
63
+ """POST one callback with the x-callback-token header; the HTTP status, 0 when unreachable."""
64
+ url = state.va_url if kind == "va" else state.qr_url
65
+ if not url:
66
+ return 0
67
+ req = urllib.request.Request(url, data=json.dumps(payload).encode(), method="POST",
68
+ headers={"Content-Type": "application/json", "x-callback-token": token or state.token})
69
+ try:
70
+ with urllib.request.urlopen(req, timeout=15) as r:
71
+ return r.status
72
+ except urllib.error.HTTPError as e:
73
+ return e.code
74
+ except OSError:
75
+ return 0
76
+
77
+
78
+ def handler(state: State):
79
+ class H(BaseHTTPRequestHandler):
80
+ def log_message(self, *a):
81
+ pass
82
+
83
+ def send(self, code, obj):
84
+ raw = json.dumps(obj).encode()
85
+ self.send_response(code)
86
+ self.send_header("Content-Type", "application/json")
87
+ self.send_header("Content-Length", str(len(raw)))
88
+ self.end_headers()
89
+ self.wfile.write(raw)
90
+
91
+ def authed(self) -> bool:
92
+ h = self.headers.get("Authorization", "")
93
+ want = "Basic " + base64.b64encode((state.secret + ":").encode()).decode()
94
+ return hmac.compare_digest(h, want)
95
+
96
+ def json_body(self, raw):
97
+ try:
98
+ return json.loads(raw or b"{}")
99
+ except ValueError:
100
+ return None
101
+
102
+ def do_GET(self):
103
+ path = urllib.parse.urlparse(self.path).path
104
+ if path == "/healthz":
105
+ return self.send(200, {"ok": True})
106
+ if path == "/calls":
107
+ with state.lock:
108
+ return self.send(200, state.calls)
109
+ self.send(404, {"error_code": "NOT_FOUND"})
110
+
111
+ def do_POST(self):
112
+ u = urllib.parse.urlparse(self.path)
113
+ raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
114
+ with state.lock:
115
+ state.calls.append({"method": "POST", "path": u.path, "body": raw.decode(errors="replace"),
116
+ "headers": {k: ("[redacted]" if k.lower() == "authorization" else v) for k, v in self.headers.items()}})
117
+ body = self.json_body(raw)
118
+ if body is None:
119
+ return self.send(400, {"error_code": "API_VALIDATION_ERROR", "message": "body is not JSON"})
120
+
121
+ if u.path == "/callback_virtual_accounts":
122
+ if not self.authed():
123
+ return self.send(401, {"error_code": "INVALID_API_KEY"})
124
+ ext, bank = str(body.get("external_id") or ""), str(body.get("bank_code") or "")
125
+ if not ext or bank not in BANKS:
126
+ return self.send(400, {"error_code": "API_VALIDATION_ERROR", "message": "external_id and a known bank_code are required"})
127
+ with state.lock:
128
+ va = state.vas.get(ext)
129
+ if va is None:
130
+ state.seq += 1
131
+ amount = int(body.get("expected_amount") or 0)
132
+ va = {"id": uuid.uuid4().hex[:24], "owner_id": state.owner_id, "external_id": ext, "bank_code": bank,
133
+ "merchant_code": BANKS[bank], "name": str(body.get("name") or ""), "account_number": BANKS[bank] + f"{state.seq:011d}",
134
+ "expected_amount": amount, "is_closed": bool(body.get("is_closed", amount > 0)),
135
+ "is_single_use": bool(body.get("is_single_use", False)), "status": "PENDING", "currency": "IDR",
136
+ "expiration_date": body.get("expiration_date") or (datetime.now(timezone.utc) + timedelta(days=31)).strftime("%Y-%m-%dT%H:%M:%S.000Z")}
137
+ state.vas[ext] = va
138
+ return self.send(200, va)
139
+
140
+ if u.path == "/qr_codes":
141
+ if not self.authed():
142
+ return self.send(401, {"error_code": "INVALID_API_KEY"})
143
+ ref, amount = str(body.get("reference_id") or ""), int(body.get("amount") or 0)
144
+ if not ref or amount <= 0:
145
+ return self.send(400, {"error_code": "API_VALIDATION_ERROR", "message": "reference_id and amount are required"})
146
+ qid = "qr_" + uuid.uuid4().hex[:24]
147
+ qr = {"id": qid, "reference_id": ref, "business_id": state.owner_id, "type": "DYNAMIC", "currency": "IDR", "amount": amount,
148
+ "channel_code": "ID_DANA", "status": "ACTIVE", "qr_string": f"00020101021226660014ID.CO.QRIS.WWW0215ID{qid[3:19]}5204599953033605404{amount}5802ID6304MOCK",
149
+ "expires_at": body.get("expires_at") or (datetime.now(timezone.utc) + timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%S.000Z"), "created": now_iso()}
150
+ with state.lock:
151
+ state.qrs[qid] = qr
152
+ return self.send(201, qr)
153
+
154
+ m = re.fullmatch(r"/callback_virtual_accounts/external_id=([^/]+)/simulate_payment", u.path)
155
+ if m:
156
+ ext = urllib.parse.unquote(m.group(1))
157
+ va = state.vas.get(ext)
158
+ if not va:
159
+ return self.send(404, {"error_code": "CALLBACK_VIRTUAL_ACCOUNT_NOT_FOUND_ERROR"})
160
+ if va["status"] != "PENDING":
161
+ return self.send(400, {"error_code": "INACTIVE_VIRTUAL_ACCOUNT_ERROR", "message": "a single-use VA is paid once"})
162
+ amount = int(body.get("amount") or va["expected_amount"])
163
+ if va["is_closed"] and amount != va["expected_amount"]:
164
+ return self.send(400, {"error_code": "INVALID_AMOUNT", "message": "a closed VA takes exactly its expected amount"})
165
+ pid = uuid.uuid4().hex[:24]
166
+ payload = {"id": uuid.uuid4().hex[:24], "payment_id": pid, "callback_virtual_account_id": va["id"], "owner_id": va["owner_id"],
167
+ "external_id": ext, "account_number": va["account_number"], "bank_code": va["bank_code"], "amount": amount,
168
+ "transaction_timestamp": now_iso(), "merchant_code": va["merchant_code"], "currency": "IDR"}
169
+ with state.lock:
170
+ state.sent[pid] = ("va", payload)
171
+ if va["is_single_use"]:
172
+ va["status"] = "INACTIVE"
173
+ return self.send(200, {"payment_id": pid, "callback_status": deliver(state, "va", payload)})
174
+
175
+ m = re.fullmatch(r"/qr_codes/([^/]+)/payments/simulate", u.path)
176
+ if m:
177
+ qr = state.qrs.get(m.group(1))
178
+ if not qr:
179
+ return self.send(404, {"error_code": "DATA_NOT_FOUND"})
180
+ if qr["status"] != "ACTIVE":
181
+ return self.send(400, {"error_code": "INACTIVE_QR_CODE", "message": "a dynamic QR is paid once"})
182
+ amount = int(body.get("amount") or qr["amount"])
183
+ pid = "qrpy_" + uuid.uuid4().hex[:24]
184
+ payload = {"event": "qr.payment", "business_id": qr["business_id"], "created": now_iso(),
185
+ "data": {"id": pid, "qr_id": qr["id"], "reference_id": qr["reference_id"], "type": "DYNAMIC", "currency": "IDR",
186
+ "amount": amount, "channel_code": qr["channel_code"], "status": "SUCCEEDED", "created": now_iso()}}
187
+ with state.lock:
188
+ state.sent[pid] = ("qr", payload)
189
+ qr["status"] = "INACTIVE"
190
+ return self.send(200, {"payment_id": pid, "callback_status": deliver(state, "qr", payload)})
191
+
192
+ m = re.fullmatch(r"/simulate/redeliver/([^/]+)", u.path)
193
+ if m:
194
+ sent = state.sent.get(m.group(1))
195
+ if not sent:
196
+ return self.send(404, {"error_code": "NOT_FOUND"})
197
+ token = urllib.parse.parse_qs(u.query).get("token", [None])[0]
198
+ return self.send(200, {"callback_status": deliver(state, sent[0], sent[1], token)})
199
+
200
+ self.send(404, {"error_code": "NOT_FOUND"})
201
+ return H
202
+
203
+
204
+ def dummy(value: str) -> bool:
205
+ """True for a value that says it is a dummy (a part dummy or test): a real key or token must never reach the mock."""
206
+ return bool(re.search(r"(^|[-_.])(dummy|test)([-_.]|$)", value, re.IGNORECASE))
207
+
208
+
209
+ def main(argv=None):
210
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
211
+ ap.add_argument("--port", type=int, default=8902)
212
+ ap.add_argument("--va-callback-url", default="", help="where VA callbacks go (the receiver's va_paid hook)")
213
+ ap.add_argument("--qr-callback-url", default="", help="where QRIS callbacks go (the receiver's qr_paid hook)")
214
+ a = ap.parse_args(argv)
215
+ secret = os.environ.get("XENDIT_MOCK_SECRET_KEY", "")
216
+ token = os.environ.get("XENDIT_MOCK_CALLBACK_TOKEN", "")
217
+ if not (secret.startswith("xnd_development_") and dummy(secret)):
218
+ ap.error("set XENDIT_MOCK_SECRET_KEY to a dummy test key (xnd_development_ and a part dummy, e.g. xnd_development_dummy_demo); never a real key")
219
+ if not dummy(token):
220
+ ap.error("set XENDIT_MOCK_CALLBACK_TOKEN to a dummy token (a part dummy or test, e.g. dummy-cb-demo)")
221
+ srv = ThreadingHTTPServer(("127.0.0.1", a.port), handler(State(secret, token, a.va_callback_url, a.qr_callback_url)))
222
+ print(f"xendit mock on http://127.0.0.1:{srv.server_address[1]} (VA callbacks to {a.va_callback_url or '-'}, QRIS to {a.qr_callback_url or '-'})", flush=True)
223
+ try:
224
+ srv.serve_forever()
225
+ except KeyboardInterrupt:
226
+ pass
227
+ return 0
228
+
229
+
230
+ if __name__ == "__main__":
231
+ sys.exit(main())
@@ -0,0 +1,12 @@
1
+ # yaml-language-server: $schema=https://rangka-os.github.io/rangka-os/schema/0.5/flow.json
2
+ # The owner confirms a line that is money already on the books (booked_payment): the line is "Sudah tercatat" against
3
+ # that payment. Nothing is drafted or paid: the money was booked when the payment was submitted (giro received, gateway
4
+ # notification). booked_payment is unique, so one payment is on one line only.
5
+ name: bank_transaction_booked
6
+ label: {id: Mutasi dikonfirmasi sebagai uang yang sudah tercatat}
7
+ on: bank_transaction.updated
8
+ if: event.status == 'confirmed' && event.booked_payment != '' && event.payment == ''
9
+ steps:
10
+ - {find: bank_transaction, where: name == event.name, as: line}
11
+ - update: line
12
+ set: {status: "'booked'", suggested_invoice: "''"}
@@ -0,0 +1,11 @@
1
+ # yaml-language-server: $schema=https://rangka-os.github.io/rangka-os/schema/0.5/flow.json
2
+ # The payment a line was booked against is cancelled (a giro bounced, a gateway payment reversed): the line goes back
3
+ # to unmatched, without the payment, and can be matched again.
4
+ name: bank_transaction_booked_released
5
+ label: {id: Mutasi kembali belum cocok saat pembayaran tercatatnya dibatalkan}
6
+ on: payment.cancelled
7
+ steps:
8
+ - {find: bank_transaction, where: booked_payment == event.name, as: line}
9
+ - update: line
10
+ if: line != null
11
+ set: {status: "'unmatched'", booked_payment: "''"}
@@ -12,8 +12,18 @@ steps:
12
12
  - find: payment
13
13
  where: "event.amended_from != '' && name == event.amended_from && bank_transaction == event.bank_transaction"
14
14
  as: source
15
+ # Checked again at the moment the money is booked (audit rel-uang-e2e r8 H11): another received payment of this amount
16
+ # from the same customer, submitted and held by no statement line, may be this very money (an instalment finance
17
+ # booked after the line was confirmed). Then the submit is refused; the owner sets the line against that payment.
18
+ - {find_all: bank_transaction, where: "status == 'booked'", as: held}
19
+ - find_all: payment
20
+ where: >-
21
+ docstatus == 1 && direction == 'receive' && method != 'sales_return' && amount == event.amount &&
22
+ customer == event.customer && bank_transaction == '' && name != event.name &&
23
+ !(name in held.map(l, l.booked_payment))
24
+ as: same
15
25
  - create: bank_transaction_claim
16
26
  set:
17
27
  bank_transaction: event.bank_transaction
18
28
  payment: event.name
19
- valid: "line != null && line.amount == event.amount && (line.draft_payment == event.before.name || source != null)"
29
+ valid: "line != null && line.amount == event.amount && (line.draft_payment == event.before.name || source != null) && size(same) == 0"