Recheck the agreement before opening the store purchase sheet [skip ci]

This commit is contained in:
Maurice
2026-12-02 16:33:34 +01:00
parent bf6a66d52c
commit e54f954f31
4 changed files with 164 additions and 13 deletions
+28 -12
View File
@@ -7,7 +7,14 @@ import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
import { pageUnderStatusBar } from '../src/native/appBoot';
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from '../src/native/cloudOrders';
import {
isNewCloudPlan,
matchesPurchaseAgreement,
opensSoon,
planForUnclaimedPurchase,
refundedBeforeOpening,
type CloudPurchaseAgreement,
} from '../src/native/cloudOrders';
import { fakeIapClient, getIapClient, productIdFor, type IapProduct, type Purchase } from '../src/native/iap';
import {
APP_STORE_SUBSCRIPTIONS_URL,
@@ -1126,11 +1133,7 @@ async function slugStatus(slug: string): Promise<SlugStatus> {
* (terms § 2 (1a), § 327h BGB), as the control plane words and versions it. The
* app shows the server's text, never its own, and sends back the version it showed.
*/
interface DeviationsConsent {
version: string;
text: string;
}
async function fetchConsent(): Promise<DeviationsConsent | null> {
async function fetchConsent(): Promise<CloudPurchaseAgreement | null> {
try {
const res = await CapacitorHttp.get({
url: `${CLOUD_URL}/api/iap/consent`,
@@ -1285,7 +1288,7 @@ function showClaim(
};
// The § 327h agreement, asked on its own before anything is bought.
let consent: DeviationsConsent | null = null;
let consent: CloudPurchaseAgreement | null = null;
const consentBox = el('input', { type: 'checkbox' });
const consentText = el('span', { className: 'consent-text' }, t('native.claim.consentLoading'));
const consentField = el(
@@ -1294,13 +1297,16 @@ function showClaim(
consentBox,
el('span', {}, el('strong', {}, t('native.claim.consentTitle')), consentText)
);
const loadConsent = async (): Promise<DeviationsConsent | null> => {
const showConsent = (current: CloudPurchaseAgreement | null): void => {
consent = current;
consentBox.checked = false;
consentBox.disabled = true;
consentText.textContent = t('native.claim.consentLoading');
consent = await fetchConsent();
consentBox.disabled = consent === null;
consentText.textContent = consent ? consent.text : t('native.claim.consentUnavailable');
};
const loadConsent = async (): Promise<CloudPurchaseAgreement | null> => {
consentBox.disabled = true;
consentText.textContent = t('native.claim.consentLoading');
showConsent(await fetchConsent());
return consent;
};
void loadConsent();
@@ -1453,7 +1459,8 @@ function showClaim(
consentBox.focus();
return;
}
const consentVersion = consent ? consent.version : null;
const acceptedConsent = consent;
const consentVersion = acceptedConsent?.version ?? null;
void tap(ImpactStyle.Medium);
// The purchase sheet and the progress want the whole screen, not the keyboard.
@@ -1473,6 +1480,15 @@ function showClaim(
};
if (!bought) {
const currentConsent = await fetchConsent();
if (!form.isConnected) return;
if (!matchesPurchaseAgreement(acceptedConsent, currentConsent)) {
restore();
showConsent(currentConsent);
setNotice(error, t(currentConsent ? 'native.claim.consentRequired' : 'native.claim.consentUnavailable'));
if (currentConsent) consentBox.focus();
return;
}
const trialRenewalPrice = opts.freeTrial ? priceLabel : undefined;
const outcome = await iap.purchase(productIdFor(plan.id, interval), trialRenewalPrice);
if (outcome.kind === 'offer-changed') {
+16 -1
View File
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest';
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from './cloudOrders';
import {
isNewCloudPlan,
matchesPurchaseAgreement,
opensSoon,
planForUnclaimedPurchase,
refundedBeforeOpening,
} from './cloudOrders';
describe('opensSoon', () => {
const base = { available: true, closed: true, sandbox: false, onPlay: false };
@@ -35,6 +41,15 @@ describe('refundedBeforeOpening', () => {
});
describe('Cloud catalog and purchase recovery', () => {
it('only carries the accepted agreement into a new purchase if the current version and text still match', () => {
const accepted = { version: '2026-12-01', text: 'Agreed changes' };
expect(matchesPurchaseAgreement(accepted, { ...accepted })).toBe(true);
expect(matchesPurchaseAgreement(accepted, null)).toBe(false);
expect(matchesPurchaseAgreement(null, accepted)).toBe(false);
expect(matchesPurchaseAgreement(accepted, { ...accepted, version: '2026-12-02' })).toBe(false);
expect(matchesPurchaseAgreement(accepted, { ...accepted, text: 'Changed conditions' })).toBe(false);
});
it('only offers Start and Plus even when the server still lists retired plans', () => {
expect(['start', 'basis', 'plus', 'pro'].filter(isNewCloudPlan)).toEqual(['start', 'plus']);
});
+15
View File
@@ -29,6 +29,21 @@ export function isNewCloudPlan(id: string): boolean {
return id === 'start' || id === 'plus';
}
export interface CloudPurchaseAgreement {
version: string;
text: string;
}
/** Recheck the agreement before opening the store sheet. No agreement means no new purchase. */
export function matchesPurchaseAgreement(
accepted: CloudPurchaseAgreement | null,
current: CloudPurchaseAgreement | null
): boolean {
return (
accepted !== null && current !== null && accepted.version === current.version && accepted.text === current.text
);
}
const PLAN_NAMES: Record<string, string> = { start: 'Start', basis: 'Basis', plus: 'Plus', pro: 'Pro' };
/** A verified purchase can predate the current offer and still need its instance set up. */
@@ -0,0 +1,105 @@
import { fireEvent, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
agreement: vi.fn(),
purchase: vi.fn().mockResolvedValue({ kind: 'cancelled' }),
}));
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn() } }));
vi.mock('@capacitor/core', async (importOriginal) => ({
...(await importOriginal<typeof import('@capacitor/core')>()),
CapacitorHttp: { get: mocks.agreement },
}));
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn().mockResolvedValue(undefined) } }));
vi.mock('../../../native-shell/scenery', () => ({
WELCOME_CAMERA: [0, 0],
cameraForPlan: () => [0, 0],
startScenery: () => null,
}));
vi.mock('../../../src/native/trekShell', () => ({
TrekShell: {
getServer: vi.fn().mockResolvedValue({ url: null }),
requestServer: vi.fn(async ({ url }: { url: string }) => ({
status: 200,
url,
data:
new URL(url).pathname === '/api/plans'
? {
ordering: 'open',
plans: [{ id: 'plus', name: 'Plus', storageGb: 50, aiDocumentLimit: null }],
}
: { available: true },
})),
},
}));
vi.mock('../../../src/native/iap', async (importOriginal) => ({
...(await importOriginal<typeof import('../../../src/native/iap')>()),
getIapClient: () => ({
isAvailable: async () => true,
products: async () => new Map([['cloud.plus.monthly', { displayPrice: '$11.99', freeTrial: true }]]),
held: async () => false,
onTransaction: vi.fn(),
unfinished: async () => null,
purchase: mocks.purchase,
}),
}));
const agreement = { status: 200, data: { version: '2026-12-01', deviations: 'First agreement' } };
function element<T extends HTMLElement>(selector: string): T {
const found = document.querySelector<T>(selector);
if (!found) throw new Error(`The app did not show ${selector}`);
return found;
}
afterEach(() => {
vi.unstubAllGlobals();
document.body.replaceChildren();
});
it('keeps the store closed for a withdrawn agreement and asks again when the version changes', async () => {
vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener: vi.fn() }));
vi.stubGlobal('cancelAnimationFrame', vi.fn());
document.body.append(Object.assign(document.createElement('main'), { id: 'shell' }));
const changed = { status: 200, data: { version: '2026-12-02', deviations: 'Updated agreement' } };
mocks.agreement
.mockResolvedValueOnce(agreement)
.mockResolvedValueOnce({ status: 503, data: { code: 'ordering-closed' } })
.mockResolvedValueOnce(agreement)
.mockResolvedValue(changed);
await import('../../../native-shell/main');
await waitFor(() => expect(element<HTMLElement>('.trial-badge').hidden).toBe(false));
fireEvent.click(element('button.discover'));
await waitFor(() => expect(element<HTMLButtonElement>('.dock button.cta').hidden).toBe(false));
fireEvent.click(element('.dock button.cta'));
const consent = await waitFor(() => {
expect(element('.consent-text').textContent).toBe(agreement.data.deviations);
return element<HTMLInputElement>('.consent input');
});
fireEvent.input(element('.form input[type="text"]'), { target: { value: 'sample-journey' } });
fireEvent.input(element('.form input[type="email"]'), { target: { value: 'buyer@example.invalid' } });
fireEvent.input(element('.form input[type="password"]'), { target: { value: 'Training#Pass123' } });
const submit = element<HTMLButtonElement>('.dock button.cta');
fireEvent.click(consent);
fireEvent.click(submit);
await waitFor(() => {
expect(consent.disabled).toBe(true);
expect(consent.checked).toBe(false);
});
expect(mocks.purchase).not.toHaveBeenCalled();
fireEvent.click(submit);
await waitFor(() => expect(element('.consent-text').textContent).toBe(agreement.data.deviations));
fireEvent.click(consent);
fireEvent.click(submit);
await waitFor(() => expect(element('.consent-text').textContent).toBe(changed.data.deviations));
expect(consent.checked).toBe(false);
expect(mocks.purchase).not.toHaveBeenCalled();
fireEvent.click(consent);
fireEvent.click(submit);
await waitFor(() => expect(mocks.purchase).toHaveBeenCalledExactlyOnceWith('cloud.plus.monthly', '$11.99'));
});