LibreChat/api/server/controllers/Balance.js
Danny Avila 57ab67cbac
📏 fix: Measure Usage Percent Against the Allowance Each Period Granted (#17850)
* 📏 fix: Measure Usage Percent Against the Allowance Each Period Granted

Store the credits granted at the start of each balance period on the record and measure the usage percent against it, so changing refillAmount or startBalance no longer moves a user's percent until their next grant. Legacy records fall back to the configured amount.

* 🕰️ fix: Ignore a Stored Allotment a Later Refill Has Replaced

Stamp each stored allotment with the time of its grant and measure against it only while no refill is more recent, so a refill by a replica that predates the field falls back to the configured amount instead of reporting usage against the prior period's allowance.

* 🔒 fix: Write the Allotment Grant Atomically and Return Its Period Start

Insert lastRefill with the credit, allotment and grant time when a balance record is created, so a racing creator never moves another's period start past its grant. Return lastRefill even without auto-refill so the client can place a stored allotment in its period, and fall back when it cannot.
2026-11-09 08:27:13 -05:00

27 lines
681 B
JavaScript

const { findBalanceByUser } = require('~/models');
async function balanceController(req, res) {
const balanceLocals = res.locals || {};
if (balanceLocals.balanceConfigEnabled === false) {
return res.sendStatus(204);
}
const balanceData = balanceLocals.balanceData ?? (await findBalanceByUser(req.user.id));
if (!balanceData) {
return res.status(404).json({ error: 'Balance not found' });
}
const { _id: _, ...result } = balanceData;
if (!result.autoRefillEnabled) {
delete result.refillIntervalValue;
delete result.refillIntervalUnit;
delete result.refillAmount;
}
res.status(200).json(result);
}
module.exports = balanceController;