Files
co-lite/solvway-admin-portal/app/lib/walletAmounts.ts
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

137 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Wallet amount validation and cap helpers for the per-wallet checkout flow.
// No next/* imports — used by routes and the page.
import type { MemberCheckoutPreviewResult } from "@/app/lib/types";
export const WALLET_ORDER = ["GIFT", "ACORN", "PRODUCT", "APPLE"] as const;
export const WALLET_REFUSAL_CODES = [
"WalletAmountOverBalance",
"AcornsOverYellowLabel",
"WalletAmountsOverDue",
"WalletAmountInvalid",
"WalletLegsDisabled",
] as const;
/** Valid wallet type codes. */
const VALID_CODES = new Set(WALLET_ORDER);
/**
* Validate and parse a wallet amounts value from an untrusted source.
* `undefined` → `{}` (absent means no wallet usage).
* A plain object whose every key is one of GIFT/ACORN/PRODUCT/APPLE and every value
* a finite number ≥ 0 with at most 2 decimals → that object.
* Anything else (array, null, string, unknown code, NaN, Infinity) → `null`.
*/
export function parseWalletAmounts(raw: unknown): Record<string, number> | null {
if (raw === null) return null;
if (raw === undefined) return {};
if (typeof raw !== "object") return null;
if (Array.isArray(raw)) return null;
const obj = raw as Record<string, unknown>;
const result: Record<string, number> = {};
for (const [key, value] of Object.entries(obj)) {
if (!VALID_CODES.has(key as typeof WALLET_ORDER[number])) return null;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null;
// At most 2 decimal places: check in integer sense.
if (Math.abs(value * 100 - Math.round(value * 100)) >= 1e-9) return null;
result[key] = value;
}
return result;
}
/**
* Compute the maximum amount this wallet may contribute right now.
* = min(option.max, due − sum of OTHER wallets' amounts), floored at 0.
* Computed in integer-sense (cents) and returned as an RM number with 2dp.
*/
export function walletCap(
option: { walletTypeCode: string; max: number },
due: number,
amounts: Record<string, number>,
): number {
// Sum of OTHER wallets' amounts (exclude the option's own code from the sum).
const others = Object.entries(amounts)
.filter(([key]) => key !== option.walletTypeCode)
.reduce((sum, [, v]) => sum + v, 0);
const cents = Math.round((Math.min(option.max, due - others) * 100));
return Math.max(0, Math.round(cents)) / 100;
}
/** Check if a parsed response body is a wallet refusal. */
export function isWalletRefusal(body: unknown): body is { code: string } {
if (!body || typeof body !== "object") return false;
const obj = body as Record<string, unknown>;
return typeof obj.code === "string" && WALLET_REFUSAL_CODES.includes(obj.code as typeof WALLET_REFUSAL_CODES[number]);
}
/**
* Extract the wallet type code from a refusal body.
* Tries `details.walletTypeCode` first, then `walletTypeCode` at the top level.
*/
export function refusalWallet(data: unknown): string | null {
if (!data || typeof data !== "object") return null;
const obj = data as Record<string, unknown>;
if (obj.details && typeof obj.details === "object") {
const d = obj.details as Record<string, unknown>;
if (typeof d.walletTypeCode === "string") return d.walletTypeCode;
}
if (typeof obj.walletTypeCode === "string") return obj.walletTypeCode;
return null;
}
// Keys the retired single-wallet flow sent; never forwarded.
const RETIRED_KEYS = new Set(["election", "walletAmount", "splitWalletAmount"]);
/**
* The body to forward upstream: the retired single-wallet keys (`walletAmount`, `splitWalletAmount`, the Apple pick) removed and
* `walletAmounts` replaced by the validated map. `null` when `walletAmounts` is invalid (answer 400 and do
* not call upstream).
*/
export function withWalletAmounts(body: unknown): Record<string, unknown> | null {
const input = body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>) : {};
const rest = Object.fromEntries(Object.entries(input).filter(([k]) => !RETIRED_KEYS.has(k)));
const walletAmounts = parseWalletAmounts(rest.walletAmounts);
return walletAmounts ? { ...rest, walletAmounts } : null;
}
/** Stable, order-independent key of the non-zero wallet amounts (`CODE=amount` 2dp, sorted) for client keys. */
export function walletAmountsKey(amounts: Record<string, number>): string {
return Object.entries(amounts)
.filter(([, v]) => v > 0)
.map(([k, v]) => `${k}=${v.toFixed(2)}`)
.sort()
.join(",");
}
/** Clamp entered amounts to the wallets' caps; drop wallets no longer offered. Same object back when nothing moved. */
export function clampWalletAmounts(
prev: Record<string, number>,
options: { walletTypeCode: string; balance: number; max: number }[],
): Record<string, number> {
const kept: Record<string, number> = {};
for (const [code, v] of Object.entries(prev)) {
const o = options.find((x) => x.walletTypeCode === code && x.balance > 0);
const clamped = o ? Math.min(v, o.max) : 0;
if (clamped > 0) kept[code] = clamped;
}
const same =
Object.keys(kept).length === Object.keys(prev).length && Object.entries(kept).every(([c, v]) => prev[c] === v);
return same ? prev : kept;
}
/** The receipt's per-wallet breakdown: what the operator entered, not the pre-entry preview. */
export function receiptPreview(preview: MemberCheckoutPreviewResult, amounts: Record<string, number>): MemberCheckoutPreviewResult {
return {
...preview,
giftWalletPaid: amounts.GIFT ?? 0,
acornPaid: amounts.ACORN ?? 0,
productPaid: amounts.PRODUCT ?? 0,
applePaid: amounts.APPLE ?? 0,
gatewayResidual: 0,
};
}