Skip to content

Commit 13a8245

Browse files
fix(cli): no checkout on an unreadable plan, and a moved balance is priced again
Review on #7085: on Enter, a plan read that failed (timeout, 401, 500) came back null, counted as not done, and opened a second checkout after a browser payment. It now opens nothing and the wait carries on. A partial top-up on the page before Enter kept the old deficit: the price is now worked out from the fresh balance, and when it changed the new price is shown and Enter is asked again before any checkout.
1 parent 17dc9a3 commit 13a8245

2 files changed

Lines changed: 97 additions & 25 deletions

File tree

Lines changed: 58 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,70 @@
11
import { runCommand } from "citty";
22
import { afterEach, describe, expect, it, vi } from "vitest";
33
import { consumeCommandResult } from "../utils/commandResult.js";
4+
import type { Plan } from "../heygen/plan.js";
45

56
const opened = vi.hoisted(() => [] as string[]);
6-
const checkouts = vi.hoisted(() => [] as string[]);
7-
const state = vi.hoisted(() => ({ plans: [] as string[], unattended: true }));
7+
const checkouts = vi.hoisted(() => [] as { kind: string; missing?: number }[]);
8+
const state = vi.hoisted(() => ({ plans: [] as (Plan | null)[], unattended: true, enters: 0 }));
89

910
vi.mock("../auth/browser.js", () => ({
1011
openBrowser: async (url: string) => void opened.push(url),
1112
}));
1213
vi.mock("../utils/attendedTerminal.js", () => ({ isUnattended: () => state.unattended }));
1314
vi.mock("node:readline/promises", () => ({
14-
createInterface: () => ({ question: async () => "", close: () => undefined }),
15+
createInterface: () => ({
16+
question: async () => void state.enters++,
17+
close: () => undefined,
18+
}),
1519
}));
1620
vi.mock("../heygen/plan.js", async (importOriginal) => {
1721
const real = await importOriginal<typeof import("../heygen/plan.js")>();
1822
return {
1923
...real,
20-
readPlan: async () => ({ plan: state.plans.shift() ?? "pro", credits: 0 }),
21-
readOffer: async () => ({ pro: { amount: 2500, currency: "usd" } }),
22-
createCheckout: async (kind: string) => {
23-
checkouts.push(kind);
24+
readPlan: async () => (state.plans.length ? state.plans.shift()! : pro(1_000_000)),
25+
readOffer: async () => ({
26+
pro: { amount: 2500, currency: "usd" },
27+
addon: {
28+
unitsPerBlock: 1000,
29+
unitAmount: 100,
30+
currency: "usd",
31+
min: 1,
32+
max: 100,
33+
recommended: 25,
34+
},
35+
}),
36+
createCheckout: async (kind: string, _offer: unknown, missing?: number) => {
37+
checkouts.push({ kind, missing });
2438
return "https://checkout.stripe.com/c/pay/cs_test_1";
2539
},
2640
};
2741
});
2842

43+
const free: Plan = { plan: "none", credits: 0 };
44+
const pro = (credits: number): Plan => ({ plan: "pro", credits });
45+
2946
const { default: billing } = await import("./billing.js");
3047

3148
afterEach(() => {
3249
opened.length = 0;
3350
checkouts.length = 0;
51+
state.enters = 0;
3452
vi.restoreAllMocks();
3553
consumeCommandResult();
3654
});
3755

38-
async function subscribe(plans: string[], unattended: boolean, rawArgs: string[] = []) {
56+
async function billingRun(
57+
plans: (Plan | null)[],
58+
unattended: boolean,
59+
rawArgs: string[] = ["subscribe"],
60+
) {
3961
state.plans = plans;
4062
state.unattended = unattended;
4163
const logged: string[] = [];
4264
vi.spyOn(console, "log").mockImplementation((line: string) => void logged.push(line));
65+
vi.spyOn(console, "error").mockImplementation(() => undefined);
4366
vi.useFakeTimers();
44-
const done = runCommand(billing, { rawArgs: ["subscribe", ...rawArgs] });
67+
const done = runCommand(billing, { rawArgs });
4568
await vi.advanceTimersByTimeAsync(2000);
4669
await done;
4770
vi.useRealTimers();
@@ -50,28 +73,48 @@ async function subscribe(plans: string[], unattended: boolean, rawArgs: string[]
5073

5174
describe("billing subscribe", () => {
5275
it("opens the plans page credited to the feature and run that sent the person", async () => {
53-
await subscribe(["none", "pro"], true, ["--feature", "reverse", "--session", "rvs_abc"]);
76+
await billingRun([free, pro(0)], true, [
77+
...["subscribe", "--feature", "reverse", "--session", "rvs_abc"],
78+
]);
5479
const url = new URL(opened[0] ?? "");
5580
expect(url.searchParams.get("feature")).toBe("reverse");
5681
expect(url.searchParams.get("rs")).toBe("rvs_abc");
5782
});
5883

5984
it("prints the price and the checkout link when nobody is at the terminal", async () => {
60-
const out = await subscribe(["none", "pro"], true);
85+
const out = await billingRun([free, pro(0)], true);
6186
expect(out).toContain("HyperFrames Pro: $25.00 a month");
6287
expect(out).toContain("https://checkout.stripe.com/c/pay/cs_test_1");
63-
expect(checkouts).toEqual(["plans"]);
88+
expect(checkouts).toEqual([{ kind: "plans" }]);
6489
});
6590

6691
it("opens Stripe's checkout on Enter", async () => {
67-
await subscribe(["none", "none", "pro"], false);
68-
expect(checkouts).toEqual(["plans"]);
92+
await billingRun([free, free, pro(0)], false);
93+
expect(checkouts).toEqual([{ kind: "plans" }]);
6994
expect(opened.at(-1)).toBe("https://checkout.stripe.com/c/pay/cs_test_1");
7095
});
7196

7297
it("opens no second checkout when the person already paid on the page before Enter", async () => {
73-
await subscribe(["none", "pro"], false);
98+
await billingRun([free, pro(0)], false);
7499
expect(checkouts).toEqual([]);
75100
expect(opened).toHaveLength(1);
76101
});
102+
103+
it("opens no checkout when the plan cannot be read on Enter", async () => {
104+
const out = await billingRun([free, null, pro(0)], false);
105+
expect(checkouts).toEqual([]);
106+
expect(out).toContain("Could not read your plan");
107+
});
108+
});
109+
110+
describe("billing top-up", () => {
111+
it("shows the new price and asks again when the balance moved before Enter", async () => {
112+
const out = await billingRun([pro(0), pro(6000), pro(6000), pro(10_000)], false, [
113+
...["top-up", "--needed", "10000"],
114+
]);
115+
expect(out).toContain("10,000 credits: $10.00");
116+
expect(out).toContain("4,000 credits: $4.00");
117+
expect(state.enters).toBe(2);
118+
expect(checkouts).toEqual([{ kind: "credits", missing: 4000 }]);
119+
});
77120
});

‎packages/cli/src/commands/billing.ts‎

Lines changed: 39 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,28 +37,57 @@ function priceLine(
3737
return `${needed ? `This run needs ${needed.toLocaleString("en-US")} credits. ` : ""}${credits} credits: ${price}`;
3838
}
3939

40+
type Done = (p: Plan | null) => boolean;
41+
42+
/** On Enter, reads the plan again: paid on the page meanwhile opens nothing, a plan it cannot read opens nothing
43+
* (the wait carries on), and a balance that moved shows the new price and asks again before any checkout. */
44+
async function payOnEnter(
45+
kind: "plans" | "credits",
46+
offer: Offer,
47+
done: Done,
48+
shown: string | undefined,
49+
needed?: number,
50+
) {
51+
const rl = createInterface({ input: process.stdin, output: process.stdout });
52+
try {
53+
for (;;) {
54+
await rl.question("Press Enter to pay ");
55+
const now = await readPlan();
56+
if (!now || now.mock) {
57+
console.log("Could not read your plan, so no checkout opened. Finish on the page.");
58+
return;
59+
}
60+
if (done(now)) return;
61+
const missing = needed ? needed - now.credits : undefined;
62+
const line = priceLine(kind, offer, missing, needed);
63+
if (line === shown) {
64+
await openBrowser(await createCheckout(kind, offer, missing));
65+
return;
66+
}
67+
if (line) console.log(line);
68+
shown = line;
69+
}
70+
} finally {
71+
rl.close();
72+
}
73+
}
74+
4075
/** Prepares the checkout with the CLI's own token: opens it when a person presses Enter, prints it when nobody can.
41-
* A refusal is printed and the page stays the way to buy. Bought on the page before Enter: no second checkout. */
76+
* A refusal is printed and the page stays the way to buy. */
4277
async function offerCheckout(
4378
kind: "plans" | "credits",
4479
before: Plan | null,
45-
done: (p: Plan | null) => boolean,
80+
done: Done,
4681
needed?: number,
4782
) {
4883
const offer = await readOffer();
4984
const missing = needed ? needed - (before?.credits ?? 0) : undefined;
5085
const line = priceLine(kind, offer, missing, needed);
5186
if (line) console.log(line);
5287
try {
53-
if (isUnattended()) {
88+
if (isUnattended())
5489
console.log(`Checkout link: ${c.accent(await createCheckout(kind, offer, missing))}`);
55-
return;
56-
}
57-
const rl = createInterface({ input: process.stdin, output: process.stdout });
58-
await rl.question("Press Enter to pay ");
59-
rl.close();
60-
if (done(await readPlan())) return;
61-
await openBrowser(await createCheckout(kind, offer, missing));
90+
else await payOnEnter(kind, offer, done, line, needed);
6291
} catch (error) {
6392
console.error(c.error(error instanceof Error ? error.message : String(error)));
6493
}

0 commit comments

Comments
 (0)