@rangka-os/create 0.5.0-alpha.14 → 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 (94) hide show
  1. package/package.json +1 -1
  2. package/template/base/apps/grosir_distribusi/app.rk +2 -1
  3. package/template/base/apps/jasa_proyek/app.rk +4 -0
  4. package/template/base/apps/jasa_proyek/dashboards/rekap_absen.rk +1 -1
  5. package/template/base/apps/kasir/skills/rangka-app-kasir/SKILL.md +17 -1
  6. package/template/base/apps/kelas_kursus/app.rk +3 -0
  7. package/template/base/apps/langganan_jasa/app.rk +8 -1
  8. package/template/base/apps/produksi_pabrik/dashboards/produksi_overview.rk +1 -1
  9. package/template/base/apps/ritel_cabang/app.rk +3 -0
  10. package/template/base/apps/sewa_alat/app.rk +6 -1
  11. package/template/base/connectors/doku/mock/doku_mock.py +16 -5
  12. package/template/base/connectors/moka/connector.rk +6 -5
  13. package/template/base/connectors/moka/mock/moka_mock.py +210 -0
  14. package/template/base/connectors/xendit/mock/xendit_mock.py +231 -0
  15. package/template/base/modules/bank_statement/flows/bank_transaction_booked.rk +12 -0
  16. package/template/base/modules/bank_statement/flows/bank_transaction_booked_released.rk +11 -0
  17. package/template/base/modules/bank_statement/flows/bank_transaction_claim.rk +11 -1
  18. package/template/base/modules/bank_statement/flows/bank_transaction_confirm.rk +23 -5
  19. package/template/base/modules/bank_statement/flows/bank_transaction_suggest.rk +56 -14
  20. package/template/base/modules/bank_statement/models/bank_transaction.rk +27 -4
  21. package/template/base/modules/bank_statement/models/bank_transaction_claim.rk +1 -1
  22. package/template/base/modules/catalogue/models/item.rk +9 -0
  23. package/template/base/modules/catalogue/models/item_category.rk +2 -0
  24. package/template/base/modules/contacts/models/customer.rk +10 -1
  25. package/template/base/modules/contacts/models/vendor.rk +10 -1
  26. package/template/base/modules/coretax/module.rk +2 -2
  27. package/template/base/modules/coretax/print/coretax_faktur.rk +1 -1
  28. package/template/base/modules/coretax/print/coretax_faktur.xml +13 -7
  29. package/template/base/modules/courses/flows/session_attendance_checked.rk +14 -0
  30. package/template/base/modules/courses/flows/session_of_the_day.rk +34 -0
  31. package/template/base/modules/courses/models/course_attendance.rk +2 -0
  32. package/template/base/modules/courses/models/course_session.rk +1 -0
  33. package/template/base/modules/courses/module.rk +1 -1
  34. package/template/base/modules/courses/screens/absen_kelas.rk +17 -0
  35. package/template/base/modules/delivery/flows/invoice_qty_from_deliveries.rk +1 -1
  36. package/template/base/modules/delivery/module.rk +1 -1
  37. package/template/base/modules/distribution/flows/order_tier_pricing_created.rk +2 -2
  38. package/template/base/modules/distribution/flows/order_tier_pricing_updated.rk +2 -2
  39. package/template/base/modules/distribution/module.rk +1 -1
  40. package/template/base/modules/invoicing/models/sales_invoice.rk +31 -4
  41. package/template/base/modules/invoicing/models/sales_invoice_item.rk +7 -0
  42. package/template/base/modules/invoicing/module.rk +1 -1
  43. package/template/base/modules/invoicing/print/sales_invoice.html +15 -2
  44. package/template/base/modules/orders/models/customer_order.rk +2 -0
  45. package/template/base/modules/orders/models/customer_order_item.rk +10 -0
  46. package/template/base/modules/orders/module.rk +1 -1
  47. package/template/base/modules/outlet_sales/flows/moka_api_opened.rk +30 -0
  48. package/template/base/modules/outlet_sales/flows/moka_held_release.rk +35 -0
  49. package/template/base/modules/outlet_sales/flows/moka_line_mapped.rk +12 -3
  50. package/template/base/modules/outlet_sales/flows/moka_transaction_refused.rk +15 -0
  51. package/template/base/modules/outlet_sales/flows/moka_transaction_staged.rk +31 -11
  52. package/template/base/modules/outlet_sales/models/moka_sale_line.rk +9 -1
  53. package/template/base/modules/outlets/models/outlet.rk +13 -1
  54. package/template/base/modules/payments/flows/payment_refund_from_doku.rk +14 -0
  55. package/template/base/modules/payroll/flows/payroll_close_on_submit.rk +2 -2
  56. package/template/base/modules/payroll/flows/payslip_advance_guard.rk +3 -0
  57. package/template/base/modules/payroll/flows/payslip_from_recap.rk +30 -1
  58. package/template/base/modules/payroll/flows/payslip_ytd_guard.rk +18 -1
  59. package/template/base/modules/payroll/flows/payslip_ytd_on_create.rk +28 -1
  60. package/template/base/modules/payroll/models/payslip.rk +19 -1
  61. package/template/base/modules/payroll/module.rk +2 -2
  62. package/template/base/modules/pos/screens/kasir.rk +1 -1
  63. package/template/base/modules/production/models/production_batch.rk +3 -0
  64. package/template/base/modules/production/module.rk +1 -1
  65. package/template/base/modules/projects/flows/attendance_close_on_submit.rk +6 -2
  66. package/template/base/modules/projects/flows/attendance_log_guard_created.rk +3 -1
  67. package/template/base/modules/projects/flows/attendance_log_guard_submitted.rk +8 -4
  68. package/template/base/modules/projects/flows/attendance_log_guard_updated.rk +2 -1
  69. package/template/base/modules/projects/models/assignment.rk +3 -0
  70. package/template/base/modules/projects/models/attendance_close.rk +4 -0
  71. package/template/base/modules/projects/models/attendance_guard.rk +1 -1
  72. package/template/base/modules/projects/models/attendance_log.rk +63 -66
  73. package/template/base/modules/projects/models/work_site.rk +2 -1
  74. package/template/base/modules/projects/module.rk +1 -1
  75. package/template/base/modules/projects/roles/field_worker.rk +2 -0
  76. package/template/base/modules/projects/screens/absen.rk +21 -0
  77. package/template/base/modules/quotation/models/quotation.rk +14 -4
  78. package/template/base/modules/quotation/models/quotation_item.rk +13 -0
  79. package/template/base/modules/quotation/module.rk +1 -1
  80. package/template/base/modules/quotation/print/quotation.html +16 -2
  81. package/template/base/modules/rental/flows/rental_return_on_cancel.rk +5 -3
  82. package/template/base/modules/rental/models/rental_checkout.rk +10 -15
  83. package/template/base/modules/rental/models/rental_return.rk +3 -11
  84. package/template/base/modules/rental/models/rental_schedule.rk +8 -0
  85. package/template/base/modules/rental/models/rental_unit.rk +7 -0
  86. package/template/base/modules/rental/module.rk +1 -1
  87. package/template/base/modules/rental/screens/alat_keluar.rk +19 -0
  88. package/template/base/modules/rental/screens/alat_kembali.rk +19 -0
  89. package/template/base/modules/rental/screens/jadwal_alat.rk +21 -0
  90. package/template/base/modules/subscriptions/models/collection_visit.rk +47 -0
  91. package/template/base/modules/subscriptions/models/subscription.rk +3 -1
  92. package/template/base/modules/subscriptions/module.rk +1 -1
  93. package/template/base/modules/subscriptions/screens/catat_tagih.rk +18 -0
  94. package/template/base/modules/subscriptions/screens/rute_tagih.rk +25 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rangka-os/create",
3
- "version": "0.5.0-alpha.14",
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}
@@ -30,6 +30,10 @@ dashboards: [jasa_overview, ar_aging, project_margin, absen_saya, rekap_absen]
30
30
  # field_worker and site_supervisor (field attendance, A2) have their role files in the projects module.
31
31
  roles: [sales_manager, finance_manager, purchasing_manager, project_admin, field_worker, site_supervisor]
32
32
  home: {dashboard: jasa_overview}
33
+ # Work screens (contract 0030 §3): the field worker lands on the clock; the site supervisor keeps the rekap_absen
34
+ # dashboard as home (first dashboard of their role) and decides held logs in Persetujuan.
35
+ work:
36
+ - {screen: absen, roles: [field_worker], home: true}
33
37
  menu:
34
38
  - group: {id: Penjualan}
35
39
  items: [quotation, customer_order, sales_invoice]
@@ -12,7 +12,7 @@ widgets:
12
12
  - {name: outside_today, type: number, label: {id: Di luar radius hari ini}, model: attendance_log, filter: work_date == today() && docstatus != 2 && outside_site, compact: true, span: 3, good_when: down}
13
13
  - {name: waiting, type: number, label: {id: Menunggu persetujuan}, description: {id: 'Sudah absen pulang tapi belum sah'}, model: attendance_log, filter: docstatus == 0 && clock_out != '', compact: true, span: 3, good_when: down}
14
14
  - {name: days_present, type: number, label: {id: Hari hadir sah}, model: attendance_log, filter: docstatus == 1, period: work_date, compact: true, span: 3}
15
- - {name: waiting_list, type: list, label: {id: Absen yang menunggu}, model: attendance_log, filter: docstatus == 0 && clock_out != '', columns: [name, worker_name, work_date, in_site_m, overtime_hours, reason], sort: work_date, limit: 20, span: 12}
15
+ - {name: waiting_list, type: list, label: {id: Absen yang menunggu}, model: attendance_log, filter: docstatus == 0 && clock_out != '', columns: [worker_name, work_date, in_site_m, out_site_m, overtime_hours, reason], sort: work_date, limit: 20, span: 12}
16
16
  - {name: by_worker, type: chart, chart: bar, label: {id: Hari hadir per pekerja}, model: attendance_log, group_by: worker_name, filter: docstatus == 1, period: work_date, sort: -value, span: 6}
17
17
  - {name: by_site, type: chart, chart: bar, label: {id: Hari hadir per lokasi}, model: attendance_log, group_by: work_site, filter: docstatus == 1, period: work_date, sort: -value, span: 6}
18
18
  - {name: today_list, type: list, label: {id: Absen hari ini}, model: attendance_log, filter: work_date == today() && docstatus != 2, columns: [worker_name, work_site, clock_in, clock_out, in_site_m, status], sort: clock_in, limit: 50, span: 12}
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: rangka-app-kasir
3
- description: "Rangka Kasir (app kasir): the browser cashier for shops and F&B outlets, with shifts per outlet, numbered receipts, cash and QRIS, stock and recipes taken out automatically. Use when an owner asks for a cashier or POS (\"mau pakai kasir\", \"tambahin POS\", \"jualan langsung di outlet\"), to explain what it shares with apps they already run, and for what to set up after it is added."
3
+ description: "Rangka Kasir (app kasir): the browser cashier for shops and F&B outlets, with shifts per outlet, numbered receipts, cash and QRIS, stock and recipes taken out automatically. Use when an owner asks for a cashier or POS (\"mau pakai kasir\", \"tambahin POS\", \"jualan langsung di outlet\"), to explain what it shares with apps they already run, for what to set up after it is added, and in the studio interview to decide whether a counter business gets the cashier on its map."
4
4
  metadata: {rangka: {version: 1.0.0, app: kasir, requires: [rangka-compose, rangka-changesets]}}
5
5
  ---
6
6
 
@@ -30,6 +30,22 @@ specific to the cashier.
30
30
  - **Not GoFood, GrabFood or ShopeeFood.** Orders from those apps are not rung up here; see `rangka-compose`, "When
31
31
  nothing fits".
32
32
 
33
+ ## In the studio interview: when the cashier goes on the map
34
+
35
+ For Raka's consultant interview (`rangka-consult`, contract 0042). The deciding fact is the tools the owner uses
36
+ today and whether Juragan replaces them:
37
+
38
+ - A business that serves buyers at a counter (kedai, kafe, restoran, toko) and has **no cashier app yet**, or chose
39
+ **ganti penuh**, gets a piece `{kind: catalogue, ref: kasir}` at the payment stage. Tell the owner the cashier
40
+ screen runs on a tablet or a phone:
41
+
42
+ > Untuk meja kasir aku pasang Kasir. Layarnya jalan di tablet atau HP, jadi tidak perlu mesin kasir khusus.
43
+
44
+ - If the owner keeps their current cashier (**pendamping**, for example Moka or another POS), do not place kasir. Their
45
+ sales come in through the imports from the cashier they already use (check which imports exist with
46
+ `rangka_catalogue` / `rangka_meta` before naming one).
47
+ - If you do not know yet, ask what they use at the counter today before placing anything.
48
+
33
49
  ## Explaining it to an owner who already runs an app
34
50
 
35
51
  Use the catalogue's `shares` and `adds` for `kasir`. On a site running Rangka F&B Cabang it shares items, outlets,
@@ -20,6 +20,9 @@ modules:
20
20
  dashboards: [kursus_ringkas, kelas_saya]
21
21
  roles: [course_admin, instructor, finance_manager]
22
22
  home: {dashboard: kursus_ringkas}
23
+ # The instructor lands on the class roll (contract 0030 roll); Kelas saya stays their dashboard.
24
+ work:
25
+ - {screen: absen_kelas, roles: [instructor], home: true}
23
26
  menu:
24
27
  - group: {id: Kelas}
25
28
  items: [course_batch, course_session, enrollment]
@@ -20,13 +20,20 @@ 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}
27
+ # The collector lands on the route of the day (contract 0030 route); Penagihan saya stays their dashboard.
28
+ work:
29
+ - {screen: rute_tagih, roles: [collector], home: true}
30
+ - {screen: catat_tagih, roles: [collector]}
26
31
  menu:
27
32
  - group: {id: Langganan}
28
33
  items: [subscription, subscription_bill, subscription_extra, subscription_status_log]
29
34
  - group: {id: Penagihan lapangan}
30
- items: [field_collection, collector_deposit, service_area]
35
+ items: [field_collection, collection_visit, collector_deposit, service_area]
36
+ - group: {id: Bank}
37
+ items: [bank_transaction, bank_account]
31
38
  - group: {id: Pengaturan langganan}
32
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}
@@ -11,7 +11,7 @@ rangka: '>=0.5'
11
11
  # A piece (riset/desain/11-susunan-kepingan.md) for rental businesses (kamera, alat pesta, alat outdoor). The rent
12
12
  # invoices it drafts are collected through faktur_piutang (payments); the deposit journals need pembukuan. Staf gudang
13
13
  # (rental_staff) records equipment out and back per unit with a checklist and prints the BAST; their dashboard is
14
- # alat_hari_ini. The handover screens of contract 0030 (kernel WS8) bind here with work: once the renderer exists.
14
+ # alat_hari_ini; their home is the work screen jadwal_alat (contract 0030), which opens the handover screens.
15
15
  modules:
16
16
  users: ^1.0
17
17
  contacts: ^1.0
@@ -21,6 +21,11 @@ modules:
21
21
  dashboards: [sewa_ringkas, alat_hari_ini]
22
22
  roles: [sales_manager, finance_manager, head_office, rental_staff]
23
23
  home: {dashboard: sewa_ringkas}
24
+ work:
25
+ - {screen: jadwal_alat, roles: [rental_staff], home: true}
26
+ - {screen: jadwal_alat, roles: [sales_manager]}
27
+ - {screen: alat_keluar}
28
+ - {screen: alat_kembali}
24
29
  menu:
25
30
  - group: {id: Sewa alat}
26
31
  items: [rental_booking, rental_checkout, rental_return, rental_schedule]
@@ -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})
@@ -46,11 +46,11 @@ triggers:
46
46
  # what is emitted, kept 30 days); a refunded one emits a new event (payment_refunds, refunded_quantity), and flow
47
47
  # moka_transaction_staged (rangka-apps) books only the quantity refunded since, per checkout uuid.
48
48
  # - A sale synced late from offline mode comes in with its sync time, inside the window.
49
- # - LIMIT until the kernel follows next_url (rangka-os card): one call reads the newest 100 of the window only. More
50
- # than 100 transactions per outlet between two polls lose the oldest of them, and a refund of a transaction past
51
- # the newest 100 is not seen. With next_url followed the whole window is read and nothing in it is lost; a refund
52
- # made more than two days after the sale is outside the window either way (head office books it, or the export).
53
- # An outlet moves from the export file to the API only after that kernel card (Juragan PROGRESS, audit moka H3/M1).
49
+ # - Pages: next: next makes the kernel follow Moka's next_url (on api.mokapos.com only) until it is null (rangka-os
50
+ # contract 0002, refinement 11 Nov 2026; at most 50 pages of 100 per outlet and poll), so the whole window is read
51
+ # and nothing in it is lost. A refund made more than two days after the sale is outside the window (head office
52
+ # books it, or the export). An outlet moves from the export file to the API on the day head office sets its
53
+ # moka_api_from (rangka-apps outlet; until then its API transactions are kept without lines).
54
54
  # To confirm once Moka grants API access: synchronized_at for offline sales, the largest per_page, the offset of
55
55
  # created_at (flows take the day from its first 10 characters, a Z time as WIB).
56
56
  - name: transaction_created
@@ -64,6 +64,7 @@ triggers:
64
64
  since: "(days_between('1970-01-01', today()) - 2) * 86400"
65
65
  time_filter: "'synchronized_at'"
66
66
  reorder_type: "'DESC'"
67
+ next: next
67
68
  for_each: payments[]
68
69
  emit:
69
70
  transaction_id: item.id
@@ -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()