CASHPOCKET stores everything in one MongoDB replica set. The schema is declared in Prisma, and most code reads and writes through it. The parts that move points use the native driver inside a session. This page lists the collections by area, then the rules the data has to keep and what enforces each one.

Collections by area

AreaCollectionsWhat they holdIndex or rule that matters
Users and sign-inusers, phone verifications, email tokens, identity-check sessions, login events, tier historyAccount, user type and role, tier, the point balance, verified bank account, first-touch UTM dataUnique email. Unique identity-check transaction id
Campaignscampaigns, applications, reviews, bookmarks, deliveries, proofsThe campaign and its status, one application per tester with its own status, ratings on four axes from each evaluator, shipment trackingUnique bookmark per user and campaign. Unique delivery per application, with an index on tracking number and courier
Points and moneypoint ledger, payments, cash-out requests, shop products, purchases, coupon issue logs, deals, deal purchases, game tokens and historyEvery point movement, card orders, withdrawal requests and their admin state, coupon purchasesA partial unique index on the ledger’s idempotency key. A second partial unique index for referral bonuses on reason, user and reference
Notificationsnotifications, device tokens, push campaigns, push deliveries, popups and per-user popup stateIn-app notices, registered devices, scheduled pushes and their delivery rowsUnique device token. Index on push status and scheduled time. Unique popup state per user and announcement
FAQ and chatbotFAQ items, chatbot sessions, chatbot logs, reward-chat progressQuestions with keywords, target audience and an embedding vector. One log row per answerUnique session id. A weighted text index over question, keywords and answer
Trackinguser activity, daily stats, UTM visit logs, app-install clicks, ad campaigns and daily ad metricsVisits with UTM fields, daily aggregates, spend and results per adUnique daily stat per date and metric. A TTL index on activity rows

Older point-history collections from the first version of the product still exist beside the ledger. A migration merged their rows into it, and the kernel writes only to the ledger.

The ledger row

The ledger is the one collection whose shape matters to every money path. This is its shape, not the source.

// point ledger: one row per movement
{
  userId,
  delta,            // signed integer, never zero
  type,             // EARN or USE
  reason,           // e.g. CHARGE, CAMPAIGN_PAYMENT, CASHOUT, POINTS_EXPIRED
  refType, refId,   // what this movement belongs to: an order, a campaign, a purchase
  balanceBefore,
  balanceAfter,     // taken from the user document after the conditional update
  expiresAt,        // created + 180 days, on credits only
  idempotencyKey,   // optional: present on operations that can be retried
  status,
  createdAt
}

The balance itself lives on the user document. The kernel updates it with a condition and inserts the ledger row in the same transaction, so the two cannot disagree after a crash. balanceBefore and balanceAfter make each row checkable against its neighbours: an audit script walks the chain, compares the stored balance with the sum of deltas, and reports any break.

What must not break

RuleWhat enforces it
A balance never goes below zeroThe debit is one conditional update that matches only when the balance covers the amount. No match means nothing is written
The balance and the ledger agree after a crashBoth writes run in one transaction on the replica set. An abort rolls back both
An operation with a key is applied onceA lookup by key before the transaction, and a partial unique index that rejects a second insert when two first attempts race
A referral bonus is paid once per pairIts own partial unique index on reason, user and reference
A card order is confirmed by one requestThe payment row is claimed by a conditional status update before the provider is called. A second request finds it claimed
A cash-out request and its debit exist together or not at allThe debit and the request row are written in the same transaction
An admin action on a withdrawal happens onceEach admin state change is a conditional update on the current state. A race returns a conflict
A campaign reward is paid once per testerA paid-at claim on the application, and a key built from the campaign and the tester
A campaign moves only along allowed transitionsA transition table checked on every manual change. An attempt outside it is rejected, for admins too
One shipment belongs to one applicationThe unique index on deliveries
A device token points at one device rowThe unique index on the token

Several of these rules rest on indexes that the Prisma schema cannot express. The partial unique indexes on the ledger and the TTL indexes are created by scripts kept in the repository. The script for the ledger key checks the existing data for duplicates first, has a dry-run mode, and is meant to run before the code that relies on it is deployed.

Transactions and their scope

MongoDB runs as a replica set because transactions need one. The kernel can either open its own transaction or join the caller’s session. Joining is what lets a route combine a point movement with its own writes:

  • Cash-out: the debit and the request row.
  • Shop purchase: a conditional stock decrement, the debit and the purchase row. Coupons are issued by the provider after the commit, with a compensating refund if issuing fails.
  • Bank-deposit top-up: the claim on the deposit, the matched-transaction row and the credit.
  • Games: the token claim, the history row and the reward.
  • Account withdrawal: forfeiting the remaining balance and flagging the account.

Calls to outside providers stay outside the transaction on purpose. A coupon issue or a card cancellation cannot be rolled back by the database, so those paths are written as a sequence with a compensating step and a key on each step. Notifications are also sent after the commit.

Migration and repair

The ledger replaced three earlier history collections. Four scripts carried that change and keep it checkable.

ScriptWhat it doesSafety
Ledger migration (run once, since removed)Merged the three legacy collections into the ledger and created its indexesSkips a row that already exists with the same user, reference, reason, delta and time
Status and expiry backfillFills in a status on old rows and an expiry date on old creditsDry run by default, applies only with a flag, filters on missing fields so a second run does nothing
Drift auditRead-only. Compares the stored balance with the sum of deltas and reports breaks in the before and after chainWrites nothing
Drift fixProposes a correcting adjustment per user and writes it through the kernelDry run by default. Applying needs a target, a strategy, the operator’s identity and a confirmation that repeats the affected count, and it stays under caps on accounts and total amount

One incident shows why the read path matters as much as the write path. In August 2026 an expression that read the balance fell back to a legacy field whenever the current field was zero, and old balances reappeared on accounts that had spent everything. The fix was a single resolver that every read goes through: the current field wins whenever it is a number, zero included, and the legacy field is consulted only when the current one is absent. A unit test covers the resolver, the zero case included.