Arthur Foo

Case study · Loyalty & points

Loyalty Program System

A points programme for staff and members, where every balance change goes through one atomic ledger.

Solo full-stack 2025 build, 2026 hardening Lumen 10 · Vue 3 · MariaDB 10.4 428 tests passed

01 · Summary

Points behave like money, so one ledger owns every balance change

I built the system solo in 2025 while working as a full-stack developer for a previous employer, then hardened it in 2026 with AI-assisted code review.

A Lumen 10 API serves a Vue 3 admin console and a member portal backed by MariaDB. One atomic ledger handles balances and transaction history.

02 · Problem & constraints

Staff operate it at the counter and members use it on their own

The business needed members to earn on purchases, climb tiers, redeem vouchers and gifts, and join campaigns. A lost update or a double refund represents a real liability, so the balance and its history have to agree.

The system had to run on MariaDB 10.4 and support CSV/Excel import and export for admin lists. I was the only developer.

03 · My role

Schema, API, both front ends and the business rules

2025 · Build

I designed the schema (20 tables, 51 migrations), built the REST API and both front ends, and wrote the rules for earning, tiers, expiry, redemption and refunds.

2026 · Hardening

I audited the code with Claude Code and Codex. Fixes were merged through pull requests #1–#38, most of them with a regression test.

04 · Architecture & critical path

For a debit, one statement checks and updates the balance

The Vue SPA sends a JWT to Lumen. Middleware checks the route's role allow-list or member token domain, then the controller calls PointsLedger. The balance update and history row are written in one MariaDB transaction.

Vue SPA 把 JWT 交给 Lumen。中间件根据路由检查后台角色白名单或会员 token 域,再由控制器调用 PointsLedger。余额变动和流水在同一个 MariaDB 事务里写入。

Debit through the ledger

Simplified
PointsLedger debit path The controller opens a transaction, locks the member row, then debits through PointsLedger. One affected row records history and commits. Zero affected rows roll back and return 422. ONE DB TRANSACTION · MariaDB 10.4 CLIENT Vue 3 SPA admin + member portal ROUTE + GUARD routes/web.php member.auth / admin.auth CONTROLLER processRedemption() opens the transaction LEDGER PointsLedger::debit(n) one balance write path JWT authorised debit(n) ① LOCK Member::lockForUpdate() member row first then child rows ② CONDITIONAL DEBIT UPDATE members SET points_balance = points_balance − n WHERE id = ? AND points_balance >= n 1 row ③ HISTORY ROW Insert the history row read back the balance store the snapshot COMMIT Balance and history agree 0 rows THROW → ROLLBACK Balance and history stay intact RESPONSE 422 Insufficient points balance
Normal debit. The conditional UPDATE affects one row, the history row records the balance read back from the database, and the transaction commits. 正常扣分。 条件 UPDATE 影响一行,从数据库读回余额、写入流水,然后提交事务。
Refused overspend. The balance cannot cover the debit, so the UPDATE affects zero rows, the transaction rolls back and the client receives 422 Insufficient points balance, as measured with demo data. 拒绝超额扣分。 余额不足,UPDATE 影响零行,事务回滚,客户端收到 422 Insufficient points balance,这个响应已在演示数据上实测。
  1. The Vue 3 client sends a redemption.Vue 3 客户端发出兑换请求。
  2. The controller opens a transaction.控制器开启事务。
  3. The member row is locked first.先锁住会员行。
  4. PointsLedger runs the conditional debit.PointsLedger 执行条件扣分。
  5. One affected row: the history row is written and the transaction commits.影响一行:写入流水并提交事务。
  6. Zero affected rows: the transaction rolls back and the response is 422.影响零行:回滚事务并返回 422。
Fig 04.1 A debit and its history commit together, so an unaffordable debit leaves both unchanged.
Ledger methods
credit, debit, reverse, returnSpend, removeEntry are the entry points for balance changes.
余额变动统一由 credit、debit、reverse、returnSpend、removeEntry 处理。
Lock order
Redemption, refunds, expiry and history edits lock the member row first to avoid deadlocks from upgrading a lock on that row.
兑换、退款、过期和流水编辑都先锁会员行,避免升级该行的锁时发生死锁。
MariaDB
MariaDB counts changed rows, so zero-point movements need separate handling.
Race tests
PointsLedgerRaceTest, RewardRedeemLockTest and GiftRedeemTrustTest use DB::listen to inject a concurrent write after the pre-check.
PointsLedgerRaceTest、RewardRedeemLockTest 和 GiftRedeemTrustTest 用 DB::listen 在预检查之后插入并发写。
Conditional debit Simplified
UPDATE members
   SET points_balance = points_balance - :n
 WHERE id = :member_id
   AND points_balance >= :n;

How a purchase earns points

The server applies tier benefits and vouchers, rounds the discounted amount down to whole ringgit and multiplies it by the member’s highest enrolled bonus multiplier. Daily jobs update reward and campaign statuses, recalculate tiers and expire points after six months.

Points for a demo purchase

Demo data
PaymentRM 412.60
Tier discount (5%)−RM 20.63
Total, rounded downRM 391.97 → 391
Highest enrolled bonus× 2
PointsLedger::credit+782
Fig 04.2 The RM 391.97 demo purchase earns 782 points, matching the member’s history in Fig 06.2. Check these 782 points in the history ↓

05 · Technical choices & trade-offs

Balance updates, lock order, token boundaries and business rules

  1. One ledger for every balance change

    A relative UPDATE with a balance condition leaves the check and write to the database.

    使用带余额条件的相对 UPDATE,由数据库在同一语句检查并写入。

    Trade-off Every caller had to migrate to the ledger, and zero-change updates needed separate handling on MariaDB.

    取舍 所有调用点都要迁移,且需要单独处理 MariaDB 的零分变动。

  2. Lock the member before child rows

    A fixed lock order avoids lock-upgrade deadlocks during concurrent redemptions.

    Trade-off Requests for the same member may wait for the lock.

    取舍 同一会员的请求可能需要等锁。

  3. Separate admin and member token domains

    Member tokens carry a dom=member claim, and admin routes enforce roles. A suspended member’s current token is blocked with 403.

    会员 token 带 dom=member 声明,后台路由强制校验角色。已停用会员的现有 token 会被拦下并返回 403。

    Trade-off Old tokens had to be invalidated and users had to sign in again.

    取舍 旧 token 失效,用户需要重新登录。

  4. Encode agreed business rules as tests

    Refunds require enough points to reverse the credit, spend entries are kept, and each gift is limited to one per member.

    Trade-off A member who already spent the points may be refused a refund.

    取舍 会员已经花掉积分时,退款可能被拒。

06 · Interface evidence

A console for the counter, a portal for the member

The admin console covers members, the points ledger, tiers, rewards, campaigns, audit logs with redo and reports. These screenshots show fictional demo data.

Admin transaction history with filters for earned points, redeemed points, tier and date, above the matched rows
Fig 06.1 Demo data Staff can filter the transaction history by points earned, points redeemed, tier and date.
Member history shows a bonus campaign followed by the RM 412.60 demo purchase, its RM 20.63 discount and 782 points earned
Fig 06.2 Demo data The member’s history records the same demo purchase and 782-point credit shown in Fig 04.2. Back to the points calculation ↑
Member portal showing a fictional balance of 5,800 points, reward code entry and gift QR scanning
Fig 06.3 Demo data Members can check their balance and redeem using a code or QR scan in the portal.

07 · Results & verification

Automated tests and local MariaDB verification

PHPUnit covers redemption, gift and ledger races, refund rules, authentication boundaries, upload hardening and response hygiene. There are 169 registered routes. The admin side has public, authenticated and admin-only routes.

The overspend, repeat refund and staff access checks ran locally against seeded demo data on MariaDB 10.4.

CheckResultSource
Backend suite 428 tests · 2,712 assertions · OK Measured PHPUnit · 2026-11-20
Overspend 422 Insufficient points balance Local API · demo data
Second refund 400 This transaction has already been refunded. Local API · demo data
Staff request to an admin-only route 403 Denied Local API · demo data

08 · Limits & next steps

Prototype limits and planned work

This is a prototype with no production deployment on record. Usage and transaction volume are unverified.

  • Admin login still uses the account name.
  • Some report and dashboard figures use the wrong currency.
  • Tier promotion also requires a spending threshold, which is still under review.
  • Pagination runs client-side and some template content remains.

Planned features include tier-specific expiry rules, digital member cards and a points-liability report.