CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/purchases/charge-amount.ts
Views: 687
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 for weird reasons 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 -- this should never be required,
26
// but sometimes it is, e.g., maybe there is a race condition with purchases
27
// or an admin explicitly increases the minimum balance
28
amountDue += cureAmount;
29
30
const availableCredit = balance - minBalance + cureAmount;
31
const appliedCredit = Math.min(availableCredit, amountDue);
32
if (availableCredit > 0) {
33
// We extend a little bit of credit to this user, because they
34
// have a minBalance below 0:
35
amountDue -= appliedCredit;
36
}
37
38
const minimumPaymentCharge =
39
amountDue > 0 ? Math.max(amountDue, minPayment) - amountDue : 0;
40
41
// amount due can never be negative.
42
// We always round up though -- if the user owes us 1.053 cents and we charge 1.05, then
43
// they still owe 0.003 and the purchase fails!
44
amountDue = Math.max(0, round2up(amountDue));
45
46
// amount you actually have to pay, due to our min payment requirement
47
const chargeAmount = amountDue == 0 ? 0 : Math.max(amountDue, minPayment);
48
49
return {
50
amountDue,
51
chargeAmount,
52
cureAmount,
53
minimumPaymentCharge,
54
};
55
}
56
57