Route the game's `money.delta` events into the web banking system so a player's personal bank account tracks their in-game wallet. - New `processMoneyEvent` (src/lib/arma-bridge/money.ts) applies a parsed money delta to the player's personal account: debits go to the unit treasury (or leave if no treasury), refunds hit the treasury first and fall back to a plain deposit, and rewards/grants deposit directly. - Wire the handler into ArmaSyncEvents and add a `POST /api/arma/v1/balances` route (get_balances) that returns personal balances for Steam IDs, omitting unlinked IDs so the game keeps its own stored value. - Events dedupe by serverId+eventId so a retried delivery never double-charges, and the whole path never throws.
164 lines
6.2 KiB
TypeScript
164 lines
6.2 KiB
TypeScript
import type { Payload } from "payload";
|
|
import type { BankAccount } from "@/payload-types";
|
|
import { applyTransaction, ensurePersonalAccount, getTreasuryAccountId } from "@/lib/banking";
|
|
|
|
/**
|
|
* In-game shop money <-> personal bank account sync (Arma bridge).
|
|
*
|
|
* The game queues a `money.delta` event for every balance change it makes;
|
|
* the events route dedupes by `serverId:eventId`, so a retried delivery never
|
|
* double-charges. Money flow (agreed economy rules):
|
|
* - purchase (negative) -> personal account pays the unit treasury
|
|
* - other negative (dialogue/Zeus) -> personal account pays the unit treasury
|
|
* - refund (positive) -> treasury pays the personal account back
|
|
* (created new if the treasury can't cover it)
|
|
* - reward / grant (positive) -> created new (plain deposit)
|
|
* Players whose Steam ID is not linked to a web user keep a game-only balance:
|
|
* their events are stored as evidence and skipped here.
|
|
*/
|
|
|
|
export interface MoneyDelta {
|
|
steamId: string;
|
|
delta: number;
|
|
reason: string;
|
|
detail: string;
|
|
}
|
|
|
|
/** Payload shape from ptf_shop_fnc_setMoney: [steamId, delta, reason, detail]. */
|
|
export function parseMoneyDelta(payload: unknown): MoneyDelta | null {
|
|
if (!Array.isArray(payload) || payload.length < 3) return null;
|
|
const steamId = typeof payload[0] === "string" ? payload[0].trim() : "";
|
|
const rawDelta = payload[1];
|
|
const delta = typeof rawDelta === "number" && Number.isFinite(rawDelta) ? Math.round(rawDelta) : 0;
|
|
const reason = typeof payload[2] === "string" ? payload[2].trim().toLowerCase() : "";
|
|
const detail = typeof payload[3] === "string" ? payload[3].slice(0, 200) : "";
|
|
if (!steamId || steamId.length > 64 || delta === 0 || !reason) return null;
|
|
return { steamId, delta, reason, detail };
|
|
}
|
|
|
|
async function findUserIdBySteamId(payload: Payload, steamId: string): Promise<number | null> {
|
|
const users = await payload.find({
|
|
collection: "users",
|
|
where: { steamId: { equals: steamId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
return users.docs[0]?.id ?? null;
|
|
}
|
|
|
|
/**
|
|
* Applies one `money.delta` event to the player's personal account. Never
|
|
* throws: a failure (unlinked player, insufficient funds, frozen account) is
|
|
* logged, and the game's next balance pull corrects its displayed value.
|
|
*/
|
|
export async function processMoneyEvent(
|
|
payload: Payload,
|
|
raw: { eventId: string; payload: unknown },
|
|
): Promise<void> {
|
|
try {
|
|
const money = parseMoneyDelta(raw.payload);
|
|
if (!money) {
|
|
payload.logger.warn(`[ShopMoney] Money event ${raw.eventId} has a malformed payload; skipping`);
|
|
return;
|
|
}
|
|
|
|
const userId = await findUserIdBySteamId(payload, money.steamId);
|
|
if (!userId) {
|
|
payload.logger.info(
|
|
`[ShopMoney] Steam ID ${money.steamId} is not linked to a user; game-only balance, event ${raw.eventId} skipped`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
const account = await ensurePersonalAccount(payload, userId);
|
|
const treasuryId = await getTreasuryAccountId(payload);
|
|
const amount = Math.abs(money.delta);
|
|
const memo = `In-game ${money.reason}${money.detail ? `: ${money.detail}` : ""} [${raw.eventId}]`;
|
|
|
|
if (money.delta < 0) {
|
|
// Money leaving the player goes to the unit treasury (like NPC vendor
|
|
// sales in the web market); without a treasury it simply leaves.
|
|
await applyTransaction(
|
|
payload,
|
|
treasuryId
|
|
? { type: "payment", fromAccountId: account.id, toAccountId: treasuryId, amount, memo }
|
|
: { type: "withdrawal", fromAccountId: account.id, amount, memo },
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (money.reason === "refund" && treasuryId) {
|
|
try {
|
|
await applyTransaction(payload, {
|
|
type: "transfer",
|
|
fromAccountId: treasuryId,
|
|
toAccountId: account.id,
|
|
amount,
|
|
memo,
|
|
});
|
|
return;
|
|
} catch (err) {
|
|
// A refund must never be lost: fall through to a plain deposit.
|
|
payload.logger.warn(`[ShopMoney] Treasury could not cover refund ${raw.eventId} (${err}); depositing instead`);
|
|
}
|
|
}
|
|
|
|
await applyTransaction(payload, { type: "deposit", toAccountId: account.id, amount, memo });
|
|
} catch (err) {
|
|
payload.logger.error(`[ShopMoney] Failed to apply money event ${raw.eventId}: ${err}`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Personal account balances for the given Steam IDs. Only linked players are
|
|
* returned (a linked player without an account yet reads as 0); unlinked
|
|
* Steam IDs are omitted so the game falls back to its own stored value.
|
|
* Read-only: accounts are created lazily by the first money event.
|
|
*/
|
|
export async function getBalancesBySteamId(
|
|
payload: Payload,
|
|
steamIds: string[],
|
|
): Promise<Record<string, number>> {
|
|
const wanted = [...new Set(steamIds.map((id) => id.trim()).filter((id) => id.length > 0 && id.length <= 64))];
|
|
if (wanted.length === 0) return {};
|
|
|
|
const users = await payload.find({
|
|
collection: "users",
|
|
where: { steamId: { in: wanted } },
|
|
limit: wanted.length * 2,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const userBySteamId = new Map<string, number>();
|
|
for (const user of users.docs) {
|
|
const steamId = user.steamId?.trim();
|
|
if (steamId && !userBySteamId.has(steamId)) userBySteamId.set(steamId, user.id);
|
|
}
|
|
if (userBySteamId.size === 0) return {};
|
|
|
|
const accounts = (await payload.find({
|
|
collection: "bank-accounts",
|
|
where: {
|
|
and: [
|
|
{ accountType: { equals: "personal" } },
|
|
{ ownerUser: { in: [...userBySteamId.values()] } },
|
|
],
|
|
},
|
|
limit: userBySteamId.size * 4,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as { docs: BankAccount[] };
|
|
const balanceByUser = new Map<number, number>();
|
|
for (const acc of accounts.docs) {
|
|
const owner = typeof acc.ownerUser === "number" ? acc.ownerUser : acc.ownerUser?.id;
|
|
// First personal account wins, matching ensurePersonalAccount.
|
|
if (owner != null && !balanceByUser.has(owner)) balanceByUser.set(owner, acc.balance ?? 0);
|
|
}
|
|
|
|
const balances: Record<string, number> = {};
|
|
for (const [steamId, userId] of userBySteamId) {
|
|
balances[steamId] = Math.round((balanceByUser.get(userId) ?? 0) * 100) / 100;
|
|
}
|
|
return balances;
|
|
}
|