Path: blob/master/src/packages/util/purchases/charge-amount.ts
5836 views
import { round2up } from "@cocalc/util/misc";12export default function getChargeAmount({3cost,4balance,5minBalance,6minPayment,7}: {8cost: number;9balance: number;10minBalance: number;11minPayment: number;12}): {13amountDue: number;14chargeAmount: number;15cureAmount: number;16minimumPaymentCharge: number;17} {18// Figure out what the amount due is, not worrying about the minPayment (we do that below).19let amountDue = cost;2021// Sometimes the balance goes below the minimum allowed balance,22// so if that happens we correct that here.23const cureAmount = Math.max(minBalance - balance, 0);24// get back up to the minimum balance:25amountDue += cureAmount;2627const availableCredit = balance - minBalance + cureAmount;28const appliedCredit = Math.min(availableCredit, amountDue);29if (availableCredit > 0) {30// We extend a little bit of credit to this user, because they31// have a minBalance below 0:32amountDue -= appliedCredit;33}3435const minimumPaymentCharge =36amountDue > 0 ? Math.max(amountDue, minPayment) - amountDue : 0;3738// amount due can never be negative.39// We always round up though -- if the user owes us 1.053 cents and we charge 1.05, then40// they still owe 0.003 and the purchase fails!41amountDue = Math.max(0, round2up(amountDue));4243// amount you actually have to pay, due to our min payment requirement44const chargeAmount = amountDue == 0 ? 0 : Math.max(amountDue, minPayment);4546return {47amountDue,48chargeAmount,49cureAmount,50minimumPaymentCharge,51};52}535455