Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/purchases/charge-amount.ts
5836 views
1
import { round2up } from "@cocalc/util/misc";
2
3
export default function getChargeAmount({
4
cost,
5
balance,
6
minBalance,
7
minPayment,
8
}: {
9
cost: number;
10
balance: number;
11
minBalance: number;
12
minPayment: number;
13
}): {
14
amountDue: number;
15
chargeAmount: number;
16
cureAmount: number;
17
minimumPaymentCharge: number;
18
} {
19
// Figure out what the amount due is, not worrying about the minPayment (we do that below).
20
let amountDue = cost;
21
22
// Sometimes the balance goes below the minimum allowed balance,
23
// so if that happens we correct that here.
24
const cureAmount = Math.max(minBalance - balance, 0);
25
// get back up to the minimum balance:
26
amountDue += cureAmount;
27
28
const availableCredit = balance - minBalance + cureAmount;
29
const appliedCredit = Math.min(availableCredit, amountDue);
30
if (availableCredit > 0) {
31
// We extend a little bit of credit to this user, because they
32
// have a minBalance below 0:
33
amountDue -= appliedCredit;
34
}
35
36
const minimumPaymentCharge =
37
amountDue > 0 ? Math.max(amountDue, minPayment) - amountDue : 0;
38
39
// amount due can never be negative.
40
// We always round up though -- if the user owes us 1.053 cents and we charge 1.05, then
41
// they still owe 0.003 and the purchase fails!
42
amountDue = Math.max(0, round2up(amountDue));
43
44
// amount you actually have to pay, due to our min payment requirement
45
const chargeAmount = amountDue == 0 ? 0 : Math.max(amountDue, minPayment);
46
47
return {
48
amountDue,
49
chargeAmount,
50
cureAmount,
51
minimumPaymentCharge,
52
};
53
}
54
55