removed unneccesary files
This commit is contained in:
@@ -297,6 +297,7 @@ async function getInputs(
|
||||
currentFundedCents: true,
|
||||
dueOn: true,
|
||||
priority: true,
|
||||
fundingMode: true,
|
||||
needsFundingThisPeriod: true,
|
||||
paymentSchedule: true,
|
||||
autoPayEnabled: true,
|
||||
@@ -328,7 +329,8 @@ export function buildPlanStates(
|
||||
userIncomeType?: string,
|
||||
isScheduledIncome?: boolean
|
||||
): PlanState[] {
|
||||
const timezone = config.timezone;
|
||||
const timezone = config.timezone ?? "UTC";
|
||||
const firstIncomeDate = config.firstIncomeDate ?? null;
|
||||
const freqDays = frequencyDays[config.incomeFrequency];
|
||||
|
||||
// Only handle regular income frequencies
|
||||
@@ -342,7 +344,8 @@ export function buildPlanStates(
|
||||
const remainingCents = Math.max(0, total - funded);
|
||||
const hasPaymentSchedule = p.paymentSchedule !== null && p.paymentSchedule !== undefined;
|
||||
const needsFundingThisPeriod = p.needsFundingThisPeriod ?? true;
|
||||
const autoFundEnabled = !!p.autoPayEnabled;
|
||||
const autoFundEnabled =
|
||||
!p.fundingMode || String(p.fundingMode).toLowerCase() !== "manual";
|
||||
|
||||
// Calculate preliminary crisis status to determine if we should override funding restrictions
|
||||
// Use timezone-aware date comparison
|
||||
@@ -357,14 +360,14 @@ export function buildPlanStates(
|
||||
let isPrelimCrisis = false;
|
||||
let dueBeforeNextPayday = false;
|
||||
let daysUntilPayday = 0;
|
||||
if (isPaymentPlanUser && config.firstIncomeDate) {
|
||||
const nextPayday = calculateNextPayday(config.firstIncomeDate, config.incomeFrequency, now, timezone);
|
||||
if (isPaymentPlanUser && firstIncomeDate) {
|
||||
const nextPayday = calculateNextPayday(firstIncomeDate, config.incomeFrequency, now, timezone);
|
||||
const normalizedNextPayday = getUserMidnight(timezone, nextPayday);
|
||||
daysUntilPayday = Math.max(0, Math.ceil((normalizedNextPayday.getTime() - userNow.getTime()) / DAY_MS));
|
||||
dueBeforeNextPayday = userDueDate.getTime() < normalizedNextPayday.getTime();
|
||||
}
|
||||
if (remainingCents >= CRISIS_MINIMUM_CENTS) {
|
||||
if (isPaymentPlanUser && config.firstIncomeDate) {
|
||||
if (isPaymentPlanUser && firstIncomeDate) {
|
||||
isPrelimCrisis = daysUntilDuePrelim < daysUntilPayday && fundedPercent < 90;
|
||||
} else {
|
||||
isPrelimCrisis = fundedPercent < 70 && daysUntilDuePrelim <= 14;
|
||||
@@ -430,10 +433,10 @@ export function buildPlanStates(
|
||||
|
||||
// Calculate payment periods more accurately using firstIncomeDate
|
||||
let cyclesLeft: number;
|
||||
if (config.firstIncomeDate) {
|
||||
if (firstIncomeDate) {
|
||||
// Count actual pay dates between now and due date based on the recurring pattern
|
||||
// established by firstIncomeDate (pass timezone for correct date handling)
|
||||
cyclesLeft = countPayPeriodsBetween(userNow, userDueDate, config.firstIncomeDate, config.incomeFrequency, timezone);
|
||||
cyclesLeft = countPayPeriodsBetween(userNow, userDueDate, firstIncomeDate, config.incomeFrequency, timezone);
|
||||
} else {
|
||||
// Fallback to old calculation if firstIncomeDate not set
|
||||
cyclesLeft = Math.max(1, Math.ceil(daysUntilDue / freqDays));
|
||||
@@ -1377,7 +1380,9 @@ function computeBudgetAllocation(
|
||||
const availableBudget = inputs.availableBefore;
|
||||
const totalPool = availableBudget + newIncome;
|
||||
|
||||
const eligiblePlans = inputs.plans.filter((plan) => plan.autoPayEnabled);
|
||||
const eligiblePlans = inputs.plans.filter(
|
||||
(plan) => !plan.fundingMode || String(plan.fundingMode).toLowerCase() !== "manual"
|
||||
);
|
||||
const planStates = buildBudgetPlanStates(eligiblePlans, now, inputs.config.timezone);
|
||||
|
||||
// Calculate total remaining needed across all fixed plans
|
||||
@@ -1505,7 +1510,8 @@ function buildBudgetPlanStates(
|
||||
const userDueDate = getUserMidnightFromDateOnly(timezone, p.dueOn);
|
||||
const daysUntilDue = Math.max(0, Math.ceil((userDueDate.getTime() - userNow.getTime()) / DAY_MS));
|
||||
const hasPaymentSchedule = p.paymentSchedule !== null && p.paymentSchedule !== undefined;
|
||||
const autoFundEnabled = !!p.autoPayEnabled;
|
||||
const autoFundEnabled =
|
||||
!p.fundingMode || String(p.fundingMode).toLowerCase() !== "manual";
|
||||
const needsFundingThisPeriod = p.needsFundingThisPeriod ?? true;
|
||||
|
||||
// For irregular income, crisis mode triggers earlier (14 days)
|
||||
|
||||
@@ -196,64 +196,64 @@ export function calculateNextPaymentDate(
|
||||
timezone: string
|
||||
): Date {
|
||||
const next = toZonedTime(currentDate, timezone);
|
||||
const hours = next.getUTCHours();
|
||||
const minutes = next.getUTCMinutes();
|
||||
const seconds = next.getUTCSeconds();
|
||||
const ms = next.getUTCMilliseconds();
|
||||
const hours = next.getHours();
|
||||
const minutes = next.getMinutes();
|
||||
const seconds = next.getSeconds();
|
||||
const ms = next.getMilliseconds();
|
||||
|
||||
switch (schedule.frequency) {
|
||||
case "daily":
|
||||
next.setUTCDate(next.getUTCDate() + 1);
|
||||
next.setDate(next.getDate() + 1);
|
||||
break;
|
||||
|
||||
case "weekly":
|
||||
// Move to next occurrence of specified day of week
|
||||
{
|
||||
const targetDay = schedule.dayOfWeek ?? 0;
|
||||
const currentDay = next.getUTCDay();
|
||||
const currentDay = next.getDay();
|
||||
const daysUntilTarget = (targetDay - currentDay + 7) % 7;
|
||||
next.setUTCDate(next.getUTCDate() + (daysUntilTarget || 7));
|
||||
next.setDate(next.getDate() + (daysUntilTarget || 7));
|
||||
}
|
||||
break;
|
||||
|
||||
case "biweekly":
|
||||
{
|
||||
const targetDay = schedule.dayOfWeek ?? next.getUTCDay();
|
||||
const currentDay = next.getUTCDay();
|
||||
const targetDay = schedule.dayOfWeek ?? next.getDay();
|
||||
const currentDay = next.getDay();
|
||||
let daysUntilTarget = (targetDay - currentDay + 7) % 7;
|
||||
// ensure at least one full week gap to make it biweekly
|
||||
daysUntilTarget = daysUntilTarget === 0 ? 14 : daysUntilTarget + 7;
|
||||
next.setUTCDate(next.getUTCDate() + daysUntilTarget);
|
||||
next.setDate(next.getDate() + daysUntilTarget);
|
||||
}
|
||||
break;
|
||||
|
||||
case "monthly":
|
||||
{
|
||||
const targetDay = schedule.dayOfMonth ?? next.getUTCDate();
|
||||
const targetDay = schedule.dayOfMonth ?? next.getDate();
|
||||
// Avoid month overflow (e.g., Jan 31 -> Feb) by resetting to day 1 before adding months.
|
||||
next.setUTCDate(1);
|
||||
next.setUTCMonth(next.getUTCMonth() + 1);
|
||||
next.setDate(1);
|
||||
next.setMonth(next.getMonth() + 1);
|
||||
const lastDay = getLastDayOfMonth(next);
|
||||
next.setUTCDate(Math.min(targetDay, lastDay));
|
||||
next.setDate(Math.min(targetDay, lastDay));
|
||||
}
|
||||
break;
|
||||
|
||||
case "custom":
|
||||
{
|
||||
const days = schedule.everyNDays && schedule.everyNDays > 0 ? schedule.everyNDays : periodDays;
|
||||
next.setUTCDate(next.getUTCDate() + days);
|
||||
next.setDate(next.getDate() + days);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Fallback to periodDays
|
||||
next.setUTCDate(next.getUTCDate() + periodDays);
|
||||
next.setDate(next.getDate() + periodDays);
|
||||
}
|
||||
|
||||
next.setUTCHours(hours, minutes, seconds, ms);
|
||||
next.setHours(hours, minutes, seconds, ms);
|
||||
return fromZonedTime(next, timezone);
|
||||
}
|
||||
|
||||
function getLastDayOfMonth(date: Date): number {
|
||||
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();
|
||||
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import { getUserMidnight, getUserMidnightFromDateOnly } from "../allocator.js";
|
||||
|
||||
const addDaysInTimezone = (date: Date, days: number, timezone: string) => {
|
||||
const zoned = toZonedTime(date, timezone);
|
||||
zoned.setUTCDate(zoned.getUTCDate() + days);
|
||||
zoned.setUTCHours(0, 0, 0, 0);
|
||||
// Advance by calendar days in the user's local timezone, then normalize
|
||||
// to local midnight before converting back to UTC for storage.
|
||||
zoned.setDate(zoned.getDate() + days);
|
||||
zoned.setHours(0, 0, 0, 0);
|
||||
return fromZonedTime(zoned, timezone);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import { getUserMidnightFromDateOnly } from "../allocator.js";
|
||||
import { getUserTimezone } from "../services/user-context.js";
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
@@ -273,9 +274,7 @@ const dashboardRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get("/crisis-status", async (req) => {
|
||||
const userId = req.userId;
|
||||
const now = new Date();
|
||||
const userTimezone =
|
||||
(await app.prisma.user.findUnique({ where: { id: userId }, select: { timezone: true } }))?.timezone ??
|
||||
"America/New_York";
|
||||
const userTimezone = await getUserTimezone(app.prisma, userId);
|
||||
const { getUserMidnight } = await import("../allocator.js");
|
||||
const userNow = getUserMidnight(userTimezone, now);
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
getUserMidnight,
|
||||
getUserMidnightFromDateOnly,
|
||||
} from "../allocator.js";
|
||||
import { getUserTimezone } from "../services/user-context.js";
|
||||
|
||||
type RateLimitRouteOptions = {
|
||||
config: {
|
||||
@@ -90,9 +91,7 @@ const fixedPlansRoutes: FastifyPluginAsync<FixedPlansRoutesOptions> = async (
|
||||
if (!plan) {
|
||||
return reply.code(404).send({ message: "Plan not found" });
|
||||
}
|
||||
const userTimezone =
|
||||
(await app.prisma.user.findUnique({ where: { id: userId }, select: { timezone: true } }))?.timezone ??
|
||||
"America/New_York";
|
||||
const userTimezone = await getUserTimezone(app.prisma, userId);
|
||||
|
||||
await app.prisma.fixedPlan.update({
|
||||
where: { id: planId },
|
||||
@@ -662,9 +661,7 @@ const fixedPlansRoutes: FastifyPluginAsync<FixedPlansRoutesOptions> = async (
|
||||
return reply.code(400).send({ message: "Invalid payload" });
|
||||
}
|
||||
const userId = req.userId;
|
||||
const userTimezone =
|
||||
(await app.prisma.user.findUnique({ where: { id: userId }, select: { timezone: true } }))?.timezone ??
|
||||
"America/New_York";
|
||||
const userTimezone = await getUserTimezone(app.prisma, userId);
|
||||
|
||||
const amountMode = parsed.data.amountMode ?? "fixed";
|
||||
if (amountMode === "estimated" && parsed.data.estimatedCents === undefined) {
|
||||
@@ -751,9 +748,7 @@ const fixedPlansRoutes: FastifyPluginAsync<FixedPlansRoutesOptions> = async (
|
||||
}
|
||||
const id = String((req.params as any).id);
|
||||
const userId = req.userId;
|
||||
const userTimezone =
|
||||
(await app.prisma.user.findUnique({ where: { id: userId }, select: { timezone: true } }))?.timezone ??
|
||||
"America/New_York";
|
||||
const userTimezone = await getUserTimezone(app.prisma, userId);
|
||||
|
||||
const plan = await app.prisma.fixedPlan.findFirst({
|
||||
where: { id, userId },
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FastifyPluginAsync, FastifyInstance } from "fastify";
|
||||
import type { FastifyPluginAsync } from "fastify";
|
||||
import type { Prisma, PrismaClient } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { ensureBudgetSessionAvailableSynced } from "../services/budget-session.js";
|
||||
|
||||
type RateLimitRouteOptions = {
|
||||
config: {
|
||||
@@ -76,52 +77,6 @@ async function assertPercentTotal(
|
||||
}
|
||||
}
|
||||
|
||||
async function getLatestBudgetSession(app: FastifyInstance, userId: string) {
|
||||
return app.prisma.budgetSession.findFirst({
|
||||
where: { userId },
|
||||
orderBy: { periodStart: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureBudgetSession(
|
||||
app: FastifyInstance,
|
||||
userId: string,
|
||||
fallbackAvailableCents = 0
|
||||
) {
|
||||
const existing = await getLatestBudgetSession(app, userId);
|
||||
if (existing) return existing;
|
||||
|
||||
const now = new Date();
|
||||
const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0));
|
||||
const end = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, 0));
|
||||
|
||||
return app.prisma.budgetSession.create({
|
||||
data: {
|
||||
userId,
|
||||
periodStart: start,
|
||||
periodEnd: end,
|
||||
totalBudgetCents: BigInt(Math.max(0, fallbackAvailableCents)),
|
||||
allocatedCents: 0n,
|
||||
fundedCents: 0n,
|
||||
availableCents: BigInt(Math.max(0, fallbackAvailableCents)),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureBudgetSessionAvailableSynced(
|
||||
app: FastifyInstance,
|
||||
userId: string,
|
||||
availableCents: number
|
||||
) {
|
||||
const normalizedAvailableCents = BigInt(Math.max(0, Math.trunc(availableCents)));
|
||||
const session = await ensureBudgetSession(app, userId, Number(normalizedAvailableCents));
|
||||
if ((session.availableCents ?? 0n) === normalizedAvailableCents) return session;
|
||||
return app.prisma.budgetSession.update({
|
||||
where: { id: session.id },
|
||||
data: { availableCents: normalizedAvailableCents },
|
||||
});
|
||||
}
|
||||
|
||||
const variableCategoriesRoutes: FastifyPluginAsync<VariableCategoriesRoutesOptions> = async (
|
||||
app,
|
||||
opts
|
||||
@@ -132,15 +87,7 @@ const variableCategoriesRoutes: FastifyPluginAsync<VariableCategoriesRoutesOptio
|
||||
return reply.code(400).send({ message: "Invalid payload" });
|
||||
}
|
||||
const userId = req.userId;
|
||||
const userTimezone =
|
||||
(
|
||||
await app.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { timezone: true },
|
||||
})
|
||||
)?.timezone ?? "America/New_York";
|
||||
const normalizedName = parsed.data.name.trim().toLowerCase();
|
||||
void userTimezone;
|
||||
|
||||
return await app.prisma.$transaction(async (tx) => {
|
||||
try {
|
||||
@@ -169,18 +116,10 @@ const variableCategoriesRoutes: FastifyPluginAsync<VariableCategoriesRoutesOptio
|
||||
}
|
||||
const id = String((req.params as any).id);
|
||||
const userId = req.userId;
|
||||
const userTimezone =
|
||||
(
|
||||
await app.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { timezone: true },
|
||||
})
|
||||
)?.timezone ?? "America/New_York";
|
||||
const updateData = {
|
||||
...patch.data,
|
||||
...(patch.data.name !== undefined ? { name: patch.data.name.trim().toLowerCase() } : {}),
|
||||
};
|
||||
void userTimezone;
|
||||
|
||||
return await app.prisma.$transaction(async (tx) => {
|
||||
const exists = await tx.variableCategory.findFirst({
|
||||
@@ -271,7 +210,7 @@ const variableCategoriesRoutes: FastifyPluginAsync<VariableCategoriesRoutesOptio
|
||||
select: { id: true, name: true, percent: true, isSavings: true, balanceCents: true },
|
||||
});
|
||||
const totalBalance = cats.reduce((s, c) => s + Number(c.balanceCents ?? 0n), 0);
|
||||
await ensureBudgetSessionAvailableSynced(app, userId, totalBalance);
|
||||
await ensureBudgetSessionAvailableSynced(app.prisma, userId, totalBalance);
|
||||
|
||||
return reply.send({
|
||||
ok: true,
|
||||
@@ -296,7 +235,7 @@ const variableCategoriesRoutes: FastifyPluginAsync<VariableCategoriesRoutesOptio
|
||||
|
||||
const totalBalance = cats.reduce((s, c) => s + Number(c.balanceCents ?? 0n), 0);
|
||||
const availableCents = totalBalance;
|
||||
await ensureBudgetSessionAvailableSynced(app, userId, availableCents);
|
||||
await ensureBudgetSessionAvailableSynced(app.prisma, userId, availableCents);
|
||||
|
||||
const targetMap = new Map<string, number>();
|
||||
for (const t of parsed.data.targets) {
|
||||
|
||||
@@ -10,6 +10,11 @@ import { PrismaClient } from "@prisma/client";
|
||||
import { z } from "zod";
|
||||
import { getUserMidnightFromDateOnly } from "./allocator.js";
|
||||
import { fromZonedTime, toZonedTime } from "date-fns-tz";
|
||||
import {
|
||||
computeDepositShares,
|
||||
computeOverdraftShares,
|
||||
computeWithdrawShares,
|
||||
} from "./services/category-shares.js";
|
||||
import healthRoutes from "./routes/health.js";
|
||||
import sessionRoutes from "./routes/session.js";
|
||||
import userRoutes from "./routes/user.js";
|
||||
@@ -429,199 +434,26 @@ function calculateNextDueDate(currentDueDate: Date, frequency: string, timezone:
|
||||
|
||||
switch (frequency) {
|
||||
case "weekly":
|
||||
zoned.setUTCDate(zoned.getUTCDate() + 7);
|
||||
zoned.setDate(zoned.getDate() + 7);
|
||||
break;
|
||||
case "biweekly":
|
||||
zoned.setUTCDate(zoned.getUTCDate() + 14);
|
||||
zoned.setDate(zoned.getDate() + 14);
|
||||
break;
|
||||
case "monthly": {
|
||||
const targetDay = zoned.getUTCDate();
|
||||
const nextMonth = zoned.getUTCMonth() + 1;
|
||||
const nextYear = zoned.getUTCFullYear() + Math.floor(nextMonth / 12);
|
||||
const nextMonthIndex = nextMonth % 12;
|
||||
const lastDay = new Date(Date.UTC(nextYear, nextMonthIndex + 1, 0)).getUTCDate();
|
||||
zoned.setUTCFullYear(nextYear, nextMonthIndex, Math.min(targetDay, lastDay));
|
||||
const targetDay = zoned.getDate();
|
||||
zoned.setDate(1);
|
||||
zoned.setMonth(zoned.getMonth() + 1);
|
||||
const lastDay = new Date(zoned.getFullYear(), zoned.getMonth() + 1, 0).getDate();
|
||||
zoned.setDate(Math.min(targetDay, lastDay));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return base;
|
||||
}
|
||||
|
||||
zoned.setUTCHours(0, 0, 0, 0);
|
||||
zoned.setHours(0, 0, 0, 0);
|
||||
return fromZonedTime(zoned, timezone);
|
||||
}
|
||||
function jsonBigIntSafe(obj: unknown) {
|
||||
return JSON.parse(
|
||||
JSON.stringify(obj, (_k, v) => (typeof v === "bigint" ? Number(v) : v))
|
||||
);
|
||||
}
|
||||
|
||||
type PercentCategory = {
|
||||
id: string;
|
||||
percent: number;
|
||||
balanceCents: bigint | null;
|
||||
};
|
||||
|
||||
function computePercentShares(categories: PercentCategory[], amountCents: number) {
|
||||
const percentTotal = categories.reduce((sum, cat) => sum + cat.percent, 0);
|
||||
if (percentTotal <= 0) return { ok: false as const, reason: "no_percent" };
|
||||
|
||||
const shares = categories.map((cat) => {
|
||||
const raw = (amountCents * cat.percent) / percentTotal;
|
||||
const floored = Math.floor(raw);
|
||||
return {
|
||||
id: cat.id,
|
||||
balanceCents: Number(cat.balanceCents ?? 0n),
|
||||
share: floored,
|
||||
frac: raw - floored,
|
||||
};
|
||||
});
|
||||
|
||||
let remainder = amountCents - shares.reduce((sum, s) => sum + s.share, 0);
|
||||
shares
|
||||
.slice()
|
||||
.sort((a, b) => b.frac - a.frac)
|
||||
.forEach((s) => {
|
||||
if (remainder > 0) {
|
||||
s.share += 1;
|
||||
remainder -= 1;
|
||||
}
|
||||
});
|
||||
|
||||
if (shares.some((s) => s.share > s.balanceCents)) {
|
||||
return { ok: false as const, reason: "insufficient_balances" };
|
||||
}
|
||||
|
||||
return { ok: true as const, shares };
|
||||
}
|
||||
|
||||
function computeWithdrawShares(categories: PercentCategory[], amountCents: number) {
|
||||
const percentTotal = categories.reduce((sum, cat) => sum + cat.percent, 0);
|
||||
if (percentTotal <= 0) return { ok: false as const, reason: "no_percent" };
|
||||
|
||||
const working = categories.map((cat) => ({
|
||||
id: cat.id,
|
||||
percent: cat.percent,
|
||||
balanceCents: Number(cat.balanceCents ?? 0n),
|
||||
share: 0,
|
||||
}));
|
||||
|
||||
let remaining = Math.max(0, Math.floor(amountCents));
|
||||
let safety = 0;
|
||||
|
||||
while (remaining > 0 && safety < 1000) {
|
||||
safety += 1;
|
||||
const eligible = working.filter((c) => c.balanceCents > 0 && c.percent > 0);
|
||||
if (eligible.length === 0) break;
|
||||
|
||||
const totalPercent = eligible.reduce((sum, cat) => sum + cat.percent, 0);
|
||||
if (totalPercent <= 0) break;
|
||||
|
||||
const provisional = eligible.map((cat) => {
|
||||
const raw = (remaining * cat.percent) / totalPercent;
|
||||
const floored = Math.floor(raw);
|
||||
return {
|
||||
id: cat.id,
|
||||
raw,
|
||||
floored,
|
||||
remainder: raw - floored,
|
||||
};
|
||||
});
|
||||
|
||||
let sumBase = provisional.reduce((sum, p) => sum + p.floored, 0);
|
||||
let leftovers = remaining - sumBase;
|
||||
provisional
|
||||
.slice()
|
||||
.sort((a, b) => b.remainder - a.remainder)
|
||||
.forEach((p) => {
|
||||
if (leftovers > 0) {
|
||||
p.floored += 1;
|
||||
leftovers -= 1;
|
||||
}
|
||||
});
|
||||
|
||||
let allocatedThisRound = 0;
|
||||
for (const p of provisional) {
|
||||
const entry = working.find((w) => w.id === p.id);
|
||||
if (!entry) continue;
|
||||
const take = Math.min(p.floored, entry.balanceCents);
|
||||
if (take > 0) {
|
||||
entry.balanceCents -= take;
|
||||
entry.share += take;
|
||||
allocatedThisRound += take;
|
||||
}
|
||||
}
|
||||
|
||||
remaining -= allocatedThisRound;
|
||||
if (allocatedThisRound === 0) break;
|
||||
}
|
||||
|
||||
if (remaining > 0) {
|
||||
return { ok: false as const, reason: "insufficient_balances" };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true as const,
|
||||
shares: working.map((c) => ({ id: c.id, share: c.share })),
|
||||
};
|
||||
}
|
||||
|
||||
function computeOverdraftShares(categories: PercentCategory[], amountCents: number) {
|
||||
const percentTotal = categories.reduce((sum, cat) => sum + cat.percent, 0);
|
||||
if (percentTotal <= 0) return { ok: false as const, reason: "no_percent" };
|
||||
|
||||
const shares = categories.map((cat) => {
|
||||
const raw = (amountCents * cat.percent) / percentTotal;
|
||||
const floored = Math.floor(raw);
|
||||
return {
|
||||
id: cat.id,
|
||||
share: floored,
|
||||
frac: raw - floored,
|
||||
};
|
||||
});
|
||||
|
||||
let remainder = amountCents - shares.reduce((sum, s) => sum + s.share, 0);
|
||||
shares
|
||||
.slice()
|
||||
.sort((a, b) => b.frac - a.frac)
|
||||
.forEach((s) => {
|
||||
if (remainder > 0) {
|
||||
s.share += 1;
|
||||
remainder -= 1;
|
||||
}
|
||||
});
|
||||
|
||||
return { ok: true as const, shares };
|
||||
}
|
||||
|
||||
function computeDepositShares(categories: PercentCategory[], amountCents: number) {
|
||||
const percentTotal = categories.reduce((sum, cat) => sum + cat.percent, 0);
|
||||
if (percentTotal <= 0) return { ok: false as const, reason: "no_percent" };
|
||||
|
||||
const shares = categories.map((cat) => {
|
||||
const raw = (amountCents * cat.percent) / percentTotal;
|
||||
const floored = Math.floor(raw);
|
||||
return {
|
||||
id: cat.id,
|
||||
share: floored,
|
||||
frac: raw - floored,
|
||||
};
|
||||
});
|
||||
|
||||
let remainder = amountCents - shares.reduce((sum, s) => sum + s.share, 0);
|
||||
shares
|
||||
.slice()
|
||||
.sort((a, b) => b.frac - a.frac)
|
||||
.forEach((s) => {
|
||||
if (remainder > 0) {
|
||||
s.share += 1;
|
||||
remainder -= 1;
|
||||
}
|
||||
});
|
||||
|
||||
return { ok: true as const, shares };
|
||||
}
|
||||
|
||||
const DEFAULT_VARIABLE_CATEGORIES = [
|
||||
{ name: "Essentials", percent: 50, priority: 10, isSavings: false },
|
||||
{ name: "Savings", percent: 30, priority: 20, isSavings: true },
|
||||
|
||||
Reference in New Issue
Block a user