@micha.bigler/ui-core-micha 4.30.0 → 4.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.32.0 - UCM-PRIV-1
4
+
5
+ Adds opt-in shared privacy choices for hosts on `django-core-micha` >= 3.22.0: `PrivacyProvider`, `usePrivacy`, the
6
+ choice banner, purpose settings, notice/settings links, `createPrivacyApi`, and purpose-aware service lifecycle helpers.
7
+ Adoption is explicit; no privacy dialog is mounted in an app unless the host adopts these exports. `OnboardingProvider`
8
+ and the profile components accept `privacyMode="central"` to replace the legacy privacy/cookie prompts while preserving
9
+ name completion and separate terms acceptance. Legacy exports and default behavior remain available and are deprecated
10
+ where replaced. Adds `Privacy.*` translations and the privacy playground entry.
11
+
12
+ ## 4.31.0 - UCM-BILL-11
13
+
14
+ Contract status, cancellation and withdrawal declarations, and the full-refund withdrawal view, against the django-core-micha
15
+ DCM-BILL-8 endpoints (`contracts/`, `contracts/<reference>/cancel|withdraw/`, `public/declarations/`, `public/declarations/confirm/`).
16
+ New opt-in exports `ContractSummary`, `CancellationDialog` ("Verträge hier kündigen" / "Jetzt kündigen"), `DeclarationForm` (public
17
+ cancellation or withdrawal without login, saveable localised acknowledgement) and `DeclarationConfirm`; `createBillingApi` gains
18
+ `listContracts`, `cancelContract`, `withdrawContract`, `primeDeclarationCsrf`, `submitDeclaration`, `confirmDeclaration`.
19
+ `SubscriptionSection` shows the owner's contracts when the server offers them (a 404 renders nothing). Withdrawal rows and previews with
20
+ `policy: "full"` use the server deadline, the label "Vertrag widerrufen" and show paid, previously refunded and refund amounts plus the
21
+ refund status instead of the time/token breakdown; legacy rows are unchanged. `PlanPicker` shows an annual plan's monthly continuation
22
+ (price plus applicable taxes, allowance, monthly cancellable). Translations only add keys; no existing text changed.
23
+
3
24
  ## 4.30.0 - UCM-CHAT-19
4
25
 
5
26
  `ChatComposer` `layout="compact"` without `context`: the `actions` (the model picker) now sit in the input row before Send/Stop and
package/README.md CHANGED
@@ -16,6 +16,32 @@ Spread `uiCoreTranslations` into the default i18n namespace as the supported agg
16
16
  offer privacy/cookie statement text endpoints; this hides their panels and prevents their requests.
17
17
  The privacy and cookie consent controls and their submitted values remain available.
18
18
 
19
+ ## Shared privacy choices (opt-in)
20
+
21
+ Hosts using `django-core-micha` >= 3.22.0 can adopt `PrivacyProvider`, `PrivacyBanner`, `PrivacySettingsLink` and
22
+ `PrivacyNoticeLink`. Create the API once and pass it to the provider when the host mounts the privacy routes elsewhere:
23
+
24
+ ```jsx
25
+ const privacyApi = createPrivacyApi({}, { apiBase: '/api/privacy/', csrfUrl: '/api/csrf/' });
26
+
27
+ <PrivacyProvider api={privacyApi}>
28
+ <Router>
29
+ <AppShell><PrivacyBanner /><AppRoutes /></AppShell>
30
+ </Router>
31
+ </PrivacyProvider>
32
+ ```
33
+
34
+ Place `PrivacyProvider` above the router content, render one `PrivacyBanner` in the app shell, and put
35
+ `PrivacySettingsLink` in the public footer and account area. The provider owns the settings dialog. Register each app-owned
36
+ optional adapter with `registerPrivacyService({ purposeId, serviceId, activate, deactivate, ownedStorage })`; gate imports,
37
+ requests and callbacks with `useGrantedPurpose`, `guardedImport` or `createPrivacyGuard`. The package never loads vendors.
38
+
39
+ Adoption is explicit. `OnboardingProvider` and `ProfileComponent` / `ProfileStepContent` accept `privacyMode="central"` to
40
+ remove the legacy privacy and convenience-cookie prompts while keeping name completion and actual terms acceptance. The
41
+ default remains `privacyMode="legacy"` during rollout. `CookieConsentStep` remains exported for compatibility and is
42
+ deprecated. The host manifest supplies actual controllers, purpose details, providers, storage and localized notice links;
43
+ empty optional configuration has no choice banner.
44
+
19
45
  ## Account page: extra tabs in a navigation group
20
46
 
21
47
  An entry of `AccountPage`'s `extraTabs` (`{ value, label, render, visible? }`) may carry an optional `group` naming one of
@@ -0,0 +1,68 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useEffect, useId, useRef, useState } from 'react';
3
+ import { Alert, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, FormControl, FormControlLabel, FormLabel, Radio, RadioGroup, Stack, TextField, Typography } from '@mui/material';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { formatDate } from './format';
6
+ export function CancellationDialog({ open, contract, api, onClose, onCancelled }) {
7
+ const { t, i18n } = useTranslation();
8
+ const [type, setType] = useState('ordinary');
9
+ const [requestedEndDate, setRequestedEndDate] = useState('');
10
+ const [reason, setReason] = useState('');
11
+ const [state, setState] = useState('ready');
12
+ const [result, setResult] = useState(null);
13
+ const [error, setError] = useState(false);
14
+ const guard = useRef(false);
15
+ const typeLabelId = useId();
16
+ const titleId = `contract-cancel-title-${(contract === null || contract === void 0 ? void 0 : contract.reference) || 'dialog'}`;
17
+ useEffect(() => {
18
+ if (!open)
19
+ return;
20
+ setType('ordinary');
21
+ setRequestedEndDate('');
22
+ setReason('');
23
+ setState('ready');
24
+ setResult(null);
25
+ setError(false);
26
+ guard.current = false;
27
+ }, [open, contract === null || contract === void 0 ? void 0 : contract.reference]);
28
+ const submit = async (event) => {
29
+ var _a;
30
+ (_a = event === null || event === void 0 ? void 0 : event.preventDefault) === null || _a === void 0 ? void 0 : _a.call(event);
31
+ if (guard.current || state !== 'ready' && state !== 'error')
32
+ return;
33
+ if (type === 'extraordinary' && !reason.trim()) {
34
+ setError('reason');
35
+ return;
36
+ }
37
+ if (typeof (api === null || api === void 0 ? void 0 : api.cancelContract) !== 'function' || !(contract === null || contract === void 0 ? void 0 : contract.reference)) {
38
+ setError('request');
39
+ setState('error');
40
+ return;
41
+ }
42
+ const body = { cancellation_type: type };
43
+ if (requestedEndDate)
44
+ body.requested_end_date = requestedEndDate;
45
+ if (type === 'extraordinary')
46
+ body.reason = reason.trim();
47
+ guard.current = true;
48
+ setState('submitting');
49
+ setError(false);
50
+ try {
51
+ const response = await api.cancelContract(contract.reference, body);
52
+ setResult((response === null || response === void 0 ? void 0 : response.declaration) || response || {});
53
+ setState('success');
54
+ onCancelled === null || onCancelled === void 0 ? void 0 : onCancelled(response);
55
+ }
56
+ catch (_b) {
57
+ guard.current = false;
58
+ setState('error');
59
+ setError('request');
60
+ }
61
+ };
62
+ const close = () => { if (state !== 'submitting')
63
+ onClose === null || onClose === void 0 ? void 0 : onClose(); };
64
+ const effectiveAt = result === null || result === void 0 ? void 0 : result.effective_at;
65
+ return _jsxs(Dialog, { open: open, onClose: close, disableEscapeKeyDown: state === 'submitting', fullWidth: true, maxWidth: "sm", "aria-labelledby": titleId, children: [_jsx(DialogTitle, { id: titleId, children: t(state === 'success' ? 'Billing.CANCEL_SUCCESS' : 'Billing.CANCEL_TITLE') }), _jsx(DialogContent, { children: state === 'success' ? _jsx(Typography, { role: "status", children: formatDate(effectiveAt, i18n.language) ? t('Billing.CANCEL_SUCCESS_EFFECTIVE', { date: formatDate(effectiveAt, i18n.language) }) : t('Billing.CANCEL_PENDING_REVIEW') }) : _jsxs(Stack, { component: "form", onSubmit: submit, spacing: 1.5, sx: { pt: 1 }, children: [_jsx(Typography, { children: (contract === null || contract === void 0 ? void 0 : contract.plan_name) || (contract === null || contract === void 0 ? void 0 : contract.plan_key) || '' }), _jsxs(FormControl, { children: [_jsx(FormLabel, { id: typeLabelId, children: t('Billing.CANCEL_TYPE_LABEL') }), _jsxs(RadioGroup, { "aria-labelledby": typeLabelId, value: type, onChange: (event) => { setType(event.target.value); setError(false); }, children: [_jsx(FormControlLabel, { value: "ordinary", control: _jsx(Radio, {}), label: t('Billing.CANCEL_ORDINARY') }), _jsx(FormControlLabel, { value: "extraordinary", control: _jsx(Radio, {}), label: t('Billing.CANCEL_EXTRAORDINARY') })] })] }), _jsx(TextField, { type: "date", label: t('Billing.CANCEL_REQUESTED_END_DATE'), value: requestedEndDate, onChange: (event) => setRequestedEndDate(event.target.value), InputLabelProps: { shrink: true } }), type === 'extraordinary' && _jsx(TextField, { label: t('Billing.CANCEL_REASON'), value: reason, onChange: (event) => { setReason(event.target.value); if (event.target.value.trim())
66
+ setError(false); }, required: true, error: error === 'reason', helperText: error === 'reason' ? t('Billing.CANCEL_REASON_REQUIRED') : undefined, inputProps: { maxLength: 2000 }, multiline: true, minRows: 3 }), error === 'request' && _jsx(Alert, { severity: "error", children: t('Billing.CANCEL_ERROR') }), state === 'submitting' && _jsxs(Typography, { role: "status", children: [_jsx(CircularProgress, { size: 16 }), " ", t('Billing.LOADING')] })] }) }), _jsx(DialogActions, { children: state === 'success' ? _jsx(Button, { onClick: close, children: t('Billing.WITHDRAWAL_CLOSE') }) : _jsxs(_Fragment, { children: [_jsx(Button, { onClick: close, disabled: state === 'submitting', children: t('Billing.WITHDRAWAL_CANCEL') }), _jsx(Button, { variant: "contained", onClick: submit, disabled: state === 'submitting', children: t('Billing.CANCEL_SUBMIT') })] }) })] });
67
+ }
68
+ export default CancellationDialog;
@@ -0,0 +1,22 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React from 'react';
3
+ import { Button, Stack, Typography } from '@mui/material';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { formatDate, formatPrice, formatTokens } from './format';
6
+ export const CONTRACT_SUMMARY_CANCEL_BUTTON_SX = { alignSelf: 'flex-start' };
7
+ const REFUND_STATUSES = new Set(['pending', 'requested', 'succeeded', 'failed', 'requires_action', 'cancelled']);
8
+ const statusKey = (status) => REFUND_STATUSES.has(status) ? `Billing.REFUND_STATUS_${status.toUpperCase()}` : 'Billing.REFUND_STATUS_UNKNOWN';
9
+ const DECLARATION_STATUSES = new Set(['received', 'awaiting_confirmation', 'needs_review', 'accepted', 'scheduled', 'effective', 'rejected']);
10
+ const declarationKindKey = (kind) => kind === 'withdrawal' ? 'Billing.DECLARATION_WITHDRAWAL' : 'Billing.DECLARATION_CANCELLATION';
11
+ const declarationStatusKey = (status) => DECLARATION_STATUSES.has(status) ? `Billing.DECLARATION_STATUS_${status.toUpperCase()}` : 'Billing.DECLARATION_STATUS_UNKNOWN';
12
+ export function ContractSummary({ contract, onCancel, sx }) {
13
+ const { t, i18n } = useTranslation();
14
+ if (!contract || typeof contract !== 'object')
15
+ return null;
16
+ const phaseKey = ({ initial: 'Billing.CONTRACT_PHASE_INITIAL', continuation: 'Billing.CONTRACT_PHASE_CONTINUATION', none: 'Billing.CONTRACT_PHASE_NONE' })[contract.phase];
17
+ const statusSuffix = ({ active: 'ACTIVE', cancellation_scheduled: 'CANCELLATION_SCHEDULED', ended: 'ENDED', withdrawn: 'WITHDRAWN' })[contract.status];
18
+ const paidThrough = contract.phase === 'initial' ? contract.initial_term_end : contract.phase === 'continuation' ? contract.current_period_end : null;
19
+ const nextCharge = contract.next_charge;
20
+ return _jsxs(Stack, { sx: sx, spacing: 0.5, children: [_jsx(Typography, { variant: "h6", children: contract.plan_name || contract.plan_key || t('Billing.CONTRACT_TITLE') }), phaseKey && _jsx(Typography, { children: t(phaseKey) }), statusSuffix && _jsx(Typography, { children: t(`Billing.CONTRACT_STATUS_${statusSuffix}`) }), formatDate(contract.started_at, i18n.language) && _jsx(Typography, { children: t('Billing.CONTRACT_STARTED_AT', { date: formatDate(contract.started_at, i18n.language) }) }), formatDate(paidThrough, i18n.language) && _jsx(Typography, { children: t('Billing.CONTRACT_PAID_THROUGH', { date: formatDate(paidThrough, i18n.language) }) }), nextCharge && _jsxs(Stack, { spacing: 0.25, children: [_jsx(Typography, { children: t('Billing.CONTRACT_NEXT_CHARGE', { amount: formatPrice(nextCharge.amount_cents, i18n.language, nextCharge.currency) }) }), formatDate(nextCharge.date, i18n.language) && _jsx(Typography, { children: t('Billing.CONTRACT_NEXT_CHARGE_DATE', { date: formatDate(nextCharge.date, i18n.language) }) }), Number.isFinite(nextCharge.token_allowance) && _jsx(Typography, { children: t('Billing.CONTRACT_NEXT_ALLOWANCE', { tokens: formatTokens(nextCharge.token_allowance, i18n.language) }) })] }), contract.status === 'cancellation_scheduled' && formatDate(contract.cancel_effective_at, i18n.language) && _jsx(Typography, { children: t('Billing.CONTRACT_CANCEL_EFFECTIVE', { date: formatDate(contract.cancel_effective_at, i18n.language) }) }), Array.isArray(contract.declarations) && contract.declarations.map((declaration, index) => _jsx(Typography, { color: "text.secondary", children: t('Billing.CONTRACT_DECLARATION', { kind: t(declarationKindKey(declaration === null || declaration === void 0 ? void 0 : declaration.kind)), status: t(declarationStatusKey(declaration === null || declaration === void 0 ? void 0 : declaration.status)) }) }, (declaration === null || declaration === void 0 ? void 0 : declaration.reference) || index)), Array.isArray(contract.refunds) && contract.refunds.map((refund, index) => _jsxs(Stack, { spacing: 0.25, children: [_jsx(Typography, { children: t(statusKey(refund === null || refund === void 0 ? void 0 : refund.status)) }), Number.isFinite(refund === null || refund === void 0 ? void 0 : refund.amount_cents) && _jsx(Typography, { children: formatPrice(refund.amount_cents, i18n.language, refund.currency) }), formatDate(refund === null || refund === void 0 ? void 0 : refund.due_by, i18n.language) && _jsx(Typography, { children: t('Billing.CONTRACT_REFUND_DUE', { date: formatDate(refund.due_by, i18n.language) }) })] }, `${(refund === null || refund === void 0 ? void 0 : refund.status) || 'refund'}-${index}`)), contract.status === 'active' && onCancel && _jsx(Button, { onClick: onCancel, sx: CONTRACT_SUMMARY_CANCEL_BUTTON_SX, children: t('Billing.CANCEL_OPEN') })] });
21
+ }
22
+ export default ContractSummary;
@@ -0,0 +1,27 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useRef, useState } from 'react';
3
+ import { Alert, Button, CircularProgress, Stack, Typography } from '@mui/material';
4
+ import { useTranslation } from 'react-i18next';
5
+ export function DeclarationConfirm({ api, token, onDone }) {
6
+ const { t } = useTranslation();
7
+ const [state, setState] = useState('ready');
8
+ const [declaration, setDeclaration] = useState(null);
9
+ const posted = useRef(false);
10
+ const confirm = async () => {
11
+ if (posted.current || state !== 'ready')
12
+ return;
13
+ posted.current = true;
14
+ setState('submitting');
15
+ try {
16
+ const response = await api.confirmDeclaration(token);
17
+ setDeclaration((response === null || response === void 0 ? void 0 : response.declaration) || response || {});
18
+ setState('success');
19
+ onDone === null || onDone === void 0 ? void 0 : onDone(response);
20
+ }
21
+ catch (_a) {
22
+ setState('error');
23
+ }
24
+ };
25
+ return _jsxs(Stack, { spacing: 1.5, children: [state === 'ready' && _jsxs(_Fragment, { children: [_jsx(Typography, { children: t('Billing.DECLARATION_CONFIRM_TITLE') }), _jsx(Button, { variant: "contained", onClick: confirm, children: t('Billing.DECLARATION_CONFIRM') })] }), state === 'submitting' && _jsxs(Typography, { role: "status", children: [_jsx(CircularProgress, { size: 16 }), " ", t('Billing.LOADING')] }), state === 'success' && _jsx(Typography, { role: "status", children: t('Billing.DECLARATION_CONFIRM_SUCCESS', { reference: (declaration === null || declaration === void 0 ? void 0 : declaration.reference) || '' }) }), state === 'error' && _jsx(Alert, { severity: "error", children: t('Billing.DECLARATION_CONFIRM_ERROR') })] });
26
+ }
27
+ export default DeclarationConfirm;
@@ -0,0 +1,134 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useEffect, useId, useRef, useState } from 'react';
3
+ import { Alert, Button, FormControl, FormControlLabel, FormLabel, Radio, RadioGroup, Stack, TextField, Typography } from '@mui/material';
4
+ import { useTranslation } from 'react-i18next';
5
+ import { formatDateTime } from './format';
6
+ const LIMITS = { name: 200, email: 254, contract_hint: 200, reason: 2000, message: 2000 };
7
+ const INITIAL_VALUES = { name: '', email: '', contract_hint: '', cancellation_type: 'ordinary', requested_end_date: '', reason: '', message: '' };
8
+ const FIELD_ORDER = ['name', 'email', 'contract_hint', 'reason', 'message'];
9
+ function acknowledgementText(ack, t, language) {
10
+ const { submitted } = ack;
11
+ const lines = [
12
+ t('Billing.DECLARATION_RECEIVED'),
13
+ t('Billing.DECLARATION_REFERENCE', { reference: ack.reference || '' }),
14
+ t('Billing.DECLARATION_RECEIVED_AT', { date: formatDateTime(ack.received_at, language) || ack.received_at || '' }),
15
+ `(${ack.received_at || ''})`,
16
+ t(`Billing.DECLARATION_${submitted.kind.toUpperCase()}`),
17
+ `${t('Billing.DECLARATION_NAME')}: ${submitted.name}`,
18
+ `${t('Billing.DECLARATION_EMAIL')}: ${submitted.email}`,
19
+ ];
20
+ if (submitted.contract_hint)
21
+ lines.push(`${t('Billing.DECLARATION_CONTRACT_HINT')}: ${submitted.contract_hint}`);
22
+ if (submitted.cancellation_type)
23
+ lines.push(t(submitted.cancellation_type === 'ordinary' ? 'Billing.CANCEL_ORDINARY' : 'Billing.CANCEL_EXTRAORDINARY'));
24
+ if (submitted.requested_end_date)
25
+ lines.push(`${t('Billing.DECLARATION_REQUESTED_END_DATE')}: ${submitted.requested_end_date}`);
26
+ if (submitted.reason)
27
+ lines.push(`${t('Billing.DECLARATION_REASON')}: ${submitted.reason}`);
28
+ if (submitted.message)
29
+ lines.push(`${t('Billing.DECLARATION_MESSAGE')}: ${submitted.message}`);
30
+ return lines.join('\n');
31
+ }
32
+ export function DeclarationForm({ api, kind, defaultKind, onSubmitted, legalNotice }) {
33
+ const { t, i18n } = useTranslation();
34
+ const [selectedKind, setSelectedKind] = useState(kind || defaultKind || 'cancellation');
35
+ const [values, setValues] = useState(INITIAL_VALUES);
36
+ const [fieldErrors, setFieldErrors] = useState({});
37
+ const [state, setState] = useState('editing');
38
+ const [ack, setAck] = useState(null);
39
+ const csrfPrimed = useRef(false);
40
+ const csrfRequest = useRef(null);
41
+ const submitGuard = useRef(false);
42
+ const currentKind = kind || selectedKind;
43
+ const fixedKind = kind === 'cancellation' || kind === 'withdrawal';
44
+ const kindLabelId = useId();
45
+ const typeLabelId = useId();
46
+ const formRef = useRef(null);
47
+ const ackHeading = useRef(null);
48
+ useEffect(() => { var _a; if (state === 'acknowledged')
49
+ (_a = ackHeading.current) === null || _a === void 0 ? void 0 : _a.focus(); }, [state]);
50
+ const setField = (name, value) => setValues((current) => (Object.assign(Object.assign({}, current), { [name]: value })));
51
+ const ensureCsrf = async () => {
52
+ if (csrfPrimed.current)
53
+ return;
54
+ if (!csrfRequest.current) {
55
+ csrfRequest.current = Promise.resolve().then(() => {
56
+ if (typeof (api === null || api === void 0 ? void 0 : api.primeDeclarationCsrf) !== 'function')
57
+ throw new Error('csrf_unavailable');
58
+ return api.primeDeclarationCsrf();
59
+ }).then(() => { csrfPrimed.current = true; csrfRequest.current = null; }).catch((error) => { csrfRequest.current = null; throw error; });
60
+ }
61
+ await csrfRequest.current;
62
+ };
63
+ const validate = () => {
64
+ var _a, _b;
65
+ const errors = {};
66
+ if (!values.name.trim())
67
+ errors.name = 'Billing.DECLARATION_REQUIRED';
68
+ if (!values.email.trim())
69
+ errors.email = 'Billing.DECLARATION_REQUIRED';
70
+ else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim()))
71
+ errors.email = 'Billing.DECLARATION_INVALID_EMAIL';
72
+ if (currentKind === 'cancellation' && values.cancellation_type === 'extraordinary' && !values.reason.trim())
73
+ errors.reason = 'Billing.DECLARATION_REASON_REQUIRED';
74
+ for (const [name, limit] of Object.entries(LIMITS))
75
+ if (values[name].length > limit)
76
+ errors[name] = 'Billing.DECLARATION_TOO_LONG';
77
+ setFieldErrors(errors);
78
+ const first = FIELD_ORDER.find((name) => errors[name]);
79
+ if (first)
80
+ (_b = (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(`[name="${first}"]`)) === null || _b === void 0 ? void 0 : _b.focus();
81
+ return Object.keys(errors).length === 0;
82
+ };
83
+ const submit = async (event) => {
84
+ event.preventDefault();
85
+ if (submitGuard.current || state === 'submitting' || state === 'acknowledged' || !validate())
86
+ return;
87
+ const submitted = { kind: currentKind, name: values.name.trim(), email: values.email.trim(), contract_hint: values.contract_hint.trim() };
88
+ if (currentKind === 'cancellation') {
89
+ submitted.cancellation_type = values.cancellation_type;
90
+ if (values.requested_end_date)
91
+ submitted.requested_end_date = values.requested_end_date;
92
+ if (values.cancellation_type === 'extraordinary')
93
+ submitted.reason = values.reason.trim();
94
+ }
95
+ if (values.message.trim())
96
+ submitted.message = values.message.trim();
97
+ submitGuard.current = true;
98
+ setState('submitting');
99
+ setFieldErrors({});
100
+ try {
101
+ await ensureCsrf();
102
+ if (typeof (api === null || api === void 0 ? void 0 : api.submitDeclaration) !== 'function')
103
+ throw new Error('declaration_unavailable');
104
+ const response = await api.submitDeclaration(submitted);
105
+ const receipt = { reference: (response === null || response === void 0 ? void 0 : response.reference) || '', received_at: (response === null || response === void 0 ? void 0 : response.received_at) || '', submitted };
106
+ setAck(receipt);
107
+ setState('acknowledged');
108
+ onSubmitted === null || onSubmitted === void 0 ? void 0 : onSubmitted(response);
109
+ }
110
+ catch (_a) {
111
+ submitGuard.current = false;
112
+ setState('error');
113
+ setFieldErrors({ form: 'Billing.DECLARATION_ERROR' });
114
+ }
115
+ };
116
+ const fieldProps = (name, labelKey, extra = {}) => (Object.assign({ label: t(labelKey), name, value: values[name], onChange: (event) => setField(name, event.target.value), error: Boolean(fieldErrors[name]), helperText: fieldErrors[name] ? t(fieldErrors[name]) : undefined, inputProps: { maxLength: LIMITS[name] } }, extra));
117
+ const save = () => {
118
+ if (!ack || typeof URL.createObjectURL !== 'function')
119
+ return;
120
+ const blob = new Blob([acknowledgementText(ack, t, i18n.language)], { type: 'text/plain;charset=utf-8' });
121
+ const url = URL.createObjectURL(blob);
122
+ const anchor = document.createElement('a');
123
+ anchor.href = url;
124
+ anchor.download = `declaration-${ack.reference || 'acknowledgement'}.txt`;
125
+ document.body.appendChild(anchor);
126
+ anchor.click();
127
+ anchor.remove();
128
+ URL.revokeObjectURL(url);
129
+ };
130
+ if (state === 'acknowledged' && ack)
131
+ return _jsxs(Stack, { spacing: 1.5, role: "status", children: [_jsx(Typography, { variant: "h6", ref: ackHeading, tabIndex: -1, sx: { outline: 'none' }, children: t('Billing.DECLARATION_RECEIVED') }), _jsx(Typography, { children: t('Billing.DECLARATION_REFERENCE', { reference: ack.reference }) }), formatDateTime(ack.received_at, i18n.language) && _jsx(Typography, { children: t('Billing.DECLARATION_RECEIVED_AT', { date: formatDateTime(ack.received_at, i18n.language) }) }), _jsx(Typography, { children: t(`Billing.DECLARATION_${ack.submitted.kind.toUpperCase()}`) }), _jsx(Typography, { children: ack.submitted.name }), _jsx(Typography, { children: ack.submitted.email }), ack.submitted.contract_hint && _jsx(Typography, { children: ack.submitted.contract_hint }), ack.submitted.cancellation_type && _jsx(Typography, { children: t(ack.submitted.cancellation_type === 'ordinary' ? 'Billing.CANCEL_ORDINARY' : 'Billing.CANCEL_EXTRAORDINARY') }), ack.submitted.requested_end_date && _jsx(Typography, { children: ack.submitted.requested_end_date }), ack.submitted.reason && _jsx(Typography, { children: ack.submitted.reason }), ack.submitted.message && _jsx(Typography, { children: ack.submitted.message }), _jsxs(Stack, { direction: { xs: 'column', sm: 'row' }, spacing: 1, alignItems: { xs: 'stretch', sm: 'center' }, children: [_jsx(Button, { onClick: save, children: t('Billing.DECLARATION_SAVE') }), _jsx(Button, { onClick: () => window.print(), children: t('Billing.DECLARATION_PRINT') })] })] });
132
+ return _jsxs(Stack, { component: "form", ref: formRef, noValidate: true, onSubmit: submit, spacing: 1.5, children: [!fixedKind && _jsxs(FormControl, { children: [_jsx(FormLabel, { id: kindLabelId, children: t('Billing.DECLARATION_KIND_LABEL') }), _jsxs(RadioGroup, { row: true, "aria-labelledby": kindLabelId, value: currentKind, onChange: (event) => setSelectedKind(event.target.value), children: [_jsx(FormControlLabel, { value: "cancellation", control: _jsx(Radio, {}), label: t('Billing.DECLARATION_CANCELLATION') }), _jsx(FormControlLabel, { value: "withdrawal", control: _jsx(Radio, {}), label: t('Billing.DECLARATION_WITHDRAWAL') })] })] }), legalNotice && _jsx(Typography, { component: "div", children: legalNotice }), _jsx(TextField, Object.assign({}, fieldProps('name', 'Billing.DECLARATION_NAME'), { required: true })), _jsx(TextField, Object.assign({}, fieldProps('email', 'Billing.DECLARATION_EMAIL', { type: 'email' }), { required: true })), _jsx(TextField, Object.assign({}, fieldProps('contract_hint', 'Billing.DECLARATION_CONTRACT_HINT'))), currentKind === 'cancellation' && _jsxs(_Fragment, { children: [_jsxs(FormControl, { children: [_jsx(FormLabel, { id: typeLabelId, children: t('Billing.CANCEL_TYPE_LABEL') }), _jsxs(RadioGroup, { row: true, "aria-labelledby": typeLabelId, value: values.cancellation_type, onChange: (event) => setField('cancellation_type', event.target.value), children: [_jsx(FormControlLabel, { value: "ordinary", control: _jsx(Radio, {}), label: t('Billing.CANCEL_ORDINARY') }), _jsx(FormControlLabel, { value: "extraordinary", control: _jsx(Radio, {}), label: t('Billing.CANCEL_EXTRAORDINARY') })] })] }), _jsx(TextField, { type: "date", label: t('Billing.DECLARATION_REQUESTED_END_DATE'), value: values.requested_end_date, onChange: (event) => setField('requested_end_date', event.target.value), InputLabelProps: { shrink: true } }), values.cancellation_type === 'extraordinary' && _jsx(TextField, Object.assign({}, fieldProps('reason', 'Billing.DECLARATION_REASON'), { required: true, multiline: true, minRows: 3 }))] }), _jsx(TextField, Object.assign({}, fieldProps('message', 'Billing.DECLARATION_MESSAGE'), { multiline: true, minRows: 3 })), fieldErrors.form && _jsx(Alert, { severity: "error", role: "alert", children: t(fieldErrors.form) }), _jsx(Button, { type: "submit", variant: "contained", disabled: state === 'submitting', children: t(state === 'submitting' ? 'Billing.DECLARATION_SUBMITTING' : 'Billing.DECLARATION_SUBMIT') })] });
133
+ }
134
+ export default DeclarationForm;
@@ -46,7 +46,7 @@ export function PlanPicker({ plans = [], kinds = ['subscription', 'team_package'
46
46
  } }, "aria-label": t('Billing.PLAN_INTERVAL'), children: [_jsx(ToggleButton, { value: "month", children: t('Billing.MONTHLY') }), _jsx(ToggleButton, { value: "year", children: t('Billing.YEARLY') })] }), _jsx(RadioGroup, { row: true, value: effectiveSelected !== null && effectiveSelected !== void 0 ? effectiveSelected : '', onChange: (event) => setSelected(event.target.value), "aria-label": t('Billing.PLANS'), children: _jsx(Stack, { direction: "row", useFlexGap: true, flexWrap: "wrap", spacing: 2, children: filteredPlans.map((plan) => {
47
47
  const active = effectiveSelected === plan.key;
48
48
  const suffix = plan.kind === 'subscription' ? (plan.interval === 'year' ? t('Billing.PER_YEAR') : t('Billing.PER_MONTH')) : '';
49
- return _jsx(Card, { variant: "outlined", sx: [PLAN_PICKER_CARD_SX, active && PLAN_PICKER_SELECTED_CARD_SX], children: _jsx(FormControlLabel, { value: plan.key, control: _jsx(Radio, {}), sx: PLAN_PICKER_LABEL_SX, label: _jsxs(Stack, { spacing: 1, children: [_jsx(Typography, { variant: "h6", children: plan.name }), _jsxs(Typography, { children: [formatPrice(plan.amount_cents, i18n.language), suffix] }), plan.kind === 'team_package' && _jsxs(Typography, { children: [t('Billing.SEATS', { count: plan.seats }), " \u00B7 ", t('Billing.TERM_MONTHS', { count: plan.term_months })] }), Number.isFinite(plan.token_allowance) && plan.token_allowance > 0 && _jsx(Typography, { children: t('Billing.TOKENS_INCLUDED', { tokens: formatTokens(plan.token_allowance, i18n.language) }) }), describePlan === null || describePlan === void 0 ? void 0 : describePlan(plan)] }) }) }, plan.key);
49
+ return _jsx(Card, { variant: "outlined", sx: [PLAN_PICKER_CARD_SX, active && PLAN_PICKER_SELECTED_CARD_SX], children: _jsx(FormControlLabel, { value: plan.key, control: _jsx(Radio, {}), sx: PLAN_PICKER_LABEL_SX, label: _jsxs(Stack, { spacing: 1, children: [_jsx(Typography, { variant: "h6", children: plan.name }), _jsxs(Typography, { children: [formatPrice(plan.amount_cents, i18n.language), suffix] }), plan.kind === 'team_package' && _jsxs(Typography, { children: [t('Billing.SEATS', { count: plan.seats }), " \u00B7 ", t('Billing.TERM_MONTHS', { count: plan.term_months })] }), Number.isFinite(plan.token_allowance) && plan.token_allowance > 0 && _jsx(Typography, { children: t('Billing.TOKENS_INCLUDED', { tokens: formatTokens(plan.token_allowance, i18n.language) }) }), plan.continuation && Number.isFinite(plan.continuation.amount_cents) && Number.isFinite(plan.continuation.token_allowance) && _jsx(Typography, { children: t('Billing.PLAN_CONTINUATION', { amount: formatPrice(plan.continuation.amount_cents, i18n.language), tokens: formatTokens(plan.continuation.token_allowance, i18n.language) }) }), describePlan === null || describePlan === void 0 ? void 0 : describePlan(plan)] }) }) }, plan.key);
50
50
  }) }) }), error && _jsx(Alert, { severity: "error", sx: PLAN_PICKER_ALERT_SX, children: t('Billing.ERROR_CHECKOUT') }), _jsx(Button, { variant: "contained", disabled: effectiveSelected === null || busy, onClick: continueToPayment, children: t('Billing.CONTINUE_TO_PAYMENT') })] });
51
51
  }
52
52
  export default PlanPicker;
@@ -11,6 +11,8 @@ import { TokenBalanceBadge } from './TokenBalanceBadge';
11
11
  import { AccessEndedBanner } from './AccessEndedBanner';
12
12
  import { WithdrawalSection } from './WithdrawalSection';
13
13
  import { TokenOriginTable } from './TokenOriginTable';
14
+ import { ContractSummary } from './ContractSummary';
15
+ import { CancellationDialog } from './CancellationDialog';
14
16
  export const SUBSCRIPTION_SECTION_ALERT_SX = { width: '100%' };
15
17
  export const SUBSCRIPTION_SECTION_SEAT_SELECT_SX = { flex: '1 1 auto', minWidth: 0 };
16
18
  // The seat button keeps its width and its single line next to a shrinking select (375 px).
@@ -31,6 +33,10 @@ export function SubscriptionSection({ api = defaultBillingApi, redirect = (url)
31
33
  const [seatInput, setSeatInput] = useState('');
32
34
  const [busy, setBusy] = useState(false);
33
35
  const [actionError, setActionError] = useState(null);
36
+ const [contracts, setContracts] = useState([]);
37
+ const [contractLoadError, setContractLoadError] = useState(false);
38
+ const [selectedContract, setSelectedContract] = useState(null);
39
+ const [reloadAfterCancellation, setReloadAfterCancellation] = useState(false);
34
40
  const renewalPickerRef = useRef(null);
35
41
  useEffect(() => {
36
42
  var _a;
@@ -50,6 +56,27 @@ export function SubscriptionSection({ api = defaultBillingApi, redirect = (url)
50
56
  }
51
57
  return () => { live = false; };
52
58
  }, [api, state, me]);
59
+ useEffect(() => {
60
+ if (state !== 'ready')
61
+ return undefined;
62
+ let live = true;
63
+ setContractLoadError(false);
64
+ // `me.contract` names only the current subscription's contract; the owner may hold more, so the list wins when it exists.
65
+ const embedded = (me === null || me === void 0 ? void 0 : me.contract) && typeof me.contract === 'object' && !Array.isArray(me.contract) ? [me.contract] : [];
66
+ setContracts(embedded);
67
+ if (typeof (api === null || api === void 0 ? void 0 : api.listContracts) !== 'function')
68
+ return () => { live = false; };
69
+ Promise.resolve().then(() => api.listContracts()).then((result) => {
70
+ if (live)
71
+ setContracts(Array.isArray(result === null || result === void 0 ? void 0 : result.contracts) ? result.contracts.filter((item) => item && typeof item === 'object') : embedded);
72
+ }).catch((error) => {
73
+ if (!live)
74
+ return;
75
+ if (!isStatus(error, 404))
76
+ setContractLoadError(true);
77
+ });
78
+ return () => { live = false; };
79
+ }, [api, state, me]);
53
80
  const safeRedirect = async (operation, errorKey) => {
54
81
  setBusy(true);
55
82
  setActionError(null);
@@ -82,6 +109,13 @@ export function SubscriptionSection({ api = defaultBillingApi, redirect = (url)
82
109
  setBusy(false);
83
110
  }
84
111
  };
112
+ const closeCancellation = () => {
113
+ setSelectedContract(null);
114
+ if (reloadAfterCancellation) {
115
+ setReloadAfterCancellation(false);
116
+ reload();
117
+ }
118
+ };
85
119
  if (state === 'loading')
86
120
  return _jsxs(Stack, { sx: sx, role: "status", direction: "row", spacing: 1, alignItems: "center", children: [_jsx(CircularProgress, { size: 20 }), _jsx(Typography, { children: t('Billing.LOADING') })] });
87
121
  if (state === 'error' || !(me === null || me === void 0 ? void 0 : me.access))
@@ -115,7 +149,7 @@ export function SubscriptionSection({ api = defaultBillingApi, redirect = (url)
115
149
  return selectedSeatCandidate ? api.addSeat({ userId: selectedSeatCandidate.id }) : undefined;
116
150
  }
117
151
  return seatInput.includes('@') ? api.addSeat({ email: seatInput.trim() }) : api.addSeat({ userId: seatInput.trim() });
118
- }), children: t('Billing.SEATS_ADD') })] }), seatError && _jsx(Alert, { severity: "error", sx: SUBSCRIPTION_SECTION_ALERT_SX, children: typeof seatError === 'string' ? t(seatError) : t('Billing.ERROR_LOAD') })] }), actionError && _jsx(Alert, { severity: "error", sx: SUBSCRIPTION_SECTION_ALERT_SX, children: t(actionError) }), me.seat && typeof me.seat === 'object' && formatDate(me.seat.ends_at, i18n.language) && _jsxs(Stack, { spacing: 0.25, children: [_jsx(Typography, { children: t('Billing.OP_SEAT_UNTIL', { date: formatDate(me.seat.ends_at, i18n.language) }) }), typeof me.seat.payer_name === 'string' && me.seat.payer_name.trim() && _jsx(Typography, { color: "text.secondary", children: t('Billing.SEAT_PAYER', { name: me.seat.payer_name }) })] })] }), _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", children: [_jsx(Typography, { children: t('Billing.BALANCE_LABEL') }), _jsx(TokenBalanceBadge, { balance: tokens.balance })] }), _jsx(Typography, { children: t('Billing.BALANCE', { tokens: formatTokens(tokens.balance, i18n.language) }) }), _jsx(TokenOriginTable, { tokens: tokens }), packagePlans.length > 0 && _jsxs(Stack, { spacing: 1, children: [_jsx(Typography, { variant: "h6", children: t('Billing.BUY_PACKAGE') }), packagePlans.map((plan) => _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", children: [_jsxs(Typography, { children: [formatPrice(plan.amount_cents, i18n.language), " \u00B7 ", t('Billing.PACKAGE_TOKENS', { tokens: formatTokens(plan.tokens, i18n.language) })] }), _jsx(Button, { disabled: busy, onClick: () => safeRedirect(() => api.startCheckout(plan.key), 'Billing.ERROR_CHECKOUT'), children: t('Billing.PACKAGE_BUY') })] }, plan.key))] }), withdrawal && _jsx(WithdrawalSection, { api: api, plans: me.plans, sessionWithdrawals: withdrawnPurchases, onWithdrawn: (result, purchase) => {
152
+ }), children: t('Billing.SEATS_ADD') })] }), seatError && _jsx(Alert, { severity: "error", sx: SUBSCRIPTION_SECTION_ALERT_SX, children: typeof seatError === 'string' ? t(seatError) : t('Billing.ERROR_LOAD') })] }), actionError && _jsx(Alert, { severity: "error", sx: SUBSCRIPTION_SECTION_ALERT_SX, children: t(actionError) }), me.seat && typeof me.seat === 'object' && formatDate(me.seat.ends_at, i18n.language) && _jsxs(Stack, { spacing: 0.25, children: [_jsx(Typography, { children: t('Billing.OP_SEAT_UNTIL', { date: formatDate(me.seat.ends_at, i18n.language) }) }), typeof me.seat.payer_name === 'string' && me.seat.payer_name.trim() && _jsx(Typography, { color: "text.secondary", children: t('Billing.SEAT_PAYER', { name: me.seat.payer_name }) })] })] }), contracts.length > 0 && _jsx(Stack, { spacing: 1, children: contracts.map((contract) => _jsx(ContractSummary, { contract: contract, onCancel: () => setSelectedContract(contract) }, contract.reference || contract.plan_key)) }), contractLoadError && _jsx(Alert, { severity: "error", sx: SUBSCRIPTION_SECTION_ALERT_SX, children: t('Billing.CONTRACT_LOAD_ERROR') }), _jsx(CancellationDialog, { open: Boolean(selectedContract), contract: selectedContract, api: api, onClose: closeCancellation, onCancelled: () => setReloadAfterCancellation(true) }), _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", children: [_jsx(Typography, { children: t('Billing.BALANCE_LABEL') }), _jsx(TokenBalanceBadge, { balance: tokens.balance })] }), _jsx(Typography, { children: t('Billing.BALANCE', { tokens: formatTokens(tokens.balance, i18n.language) }) }), _jsx(TokenOriginTable, { tokens: tokens }), packagePlans.length > 0 && _jsxs(Stack, { spacing: 1, children: [_jsx(Typography, { variant: "h6", children: t('Billing.BUY_PACKAGE') }), packagePlans.map((plan) => _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", children: [_jsxs(Typography, { children: [formatPrice(plan.amount_cents, i18n.language), " \u00B7 ", t('Billing.PACKAGE_TOKENS', { tokens: formatTokens(plan.tokens, i18n.language) })] }), _jsx(Button, { disabled: busy, onClick: () => safeRedirect(() => api.startCheckout(plan.key), 'Billing.ERROR_CHECKOUT'), children: t('Billing.PACKAGE_BUY') })] }, plan.key))] }), withdrawal && _jsx(WithdrawalSection, { api: api, plans: me.plans, sessionWithdrawals: withdrawnPurchases, onWithdrawn: (result, purchase) => {
119
153
  if ((purchase === null || purchase === void 0 ? void 0 : purchase.id) != null)
120
154
  setWithdrawnPurchases((current) => (Object.assign(Object.assign({}, current), { [purchase.id]: { result, purchase } })));
121
155
  reload();
@@ -4,6 +4,8 @@ import { Alert, Button, CircularProgress, Dialog, DialogActions, DialogContent,
4
4
  import { useTranslation } from 'react-i18next';
5
5
  import { formatDateTime, formatPrice } from './format';
6
6
  export const WITHDRAWAL_DIALOG_ALERT_SX = { width: '100%' };
7
+ const refundStatusKey = (status) => ['pending', 'requested', 'succeeded', 'failed', 'requires_action', 'cancelled'].includes(status)
8
+ ? `Billing.REFUND_STATUS_${status.toUpperCase()}` : 'Billing.REFUND_STATUS_UNKNOWN';
7
9
  export function describeCalculation(preview, t, language) {
8
10
  const currency = (preview === null || preview === void 0 ? void 0 : preview.currency) || 'USD';
9
11
  const price = (value) => formatPrice(value, language, currency);
@@ -90,6 +92,7 @@ export function WithdrawalDialog({ open, purchase, api, onClose, onWithdrawn })
90
92
  onClose === null || onClose === void 0 ? void 0 : onClose(); };
91
93
  const amount = formatPrice(preview === null || preview === void 0 ? void 0 : preview.refund_cents, i18n.language, preview === null || preview === void 0 ? void 0 : preview.currency);
92
94
  const none = !(Number(preview === null || preview === void 0 ? void 0 : preview.refund_cents) > 0);
93
- return _jsxs(Dialog, { open: open, onClose: close, disableEscapeKeyDown: state === 'submitting', fullWidth: true, maxWidth: "sm", "aria-labelledby": titleId, children: [_jsx(DialogTitle, { id: titleId, children: t(state === 'success' ? 'Billing.WITHDRAWAL_DONE' : 'Billing.WITHDRAWAL_TITLE') }), _jsxs(DialogContent, { children: [state === 'loading' && _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", role: "status", children: [_jsx(CircularProgress, { size: 20 }), _jsx(Typography, { children: t('Billing.LOADING') })] }), state === 'preview_error' && _jsx(Alert, { severity: "error", sx: WITHDRAWAL_DIALOG_ALERT_SX, children: t('Billing.WITHDRAWAL_PREVIEW_ERROR') }), (state === 'not_possible') && _jsx(Alert, { severity: "info", children: t('Billing.WITHDRAWAL_NOT_POSSIBLE') }), (state === 'ready' || state === 'submitting' || state === 'confirm_error') && _jsxs(Stack, { spacing: 1, children: [_jsx(Typography, { children: t((purchase === null || purchase === void 0 ? void 0 : purchase.kind) === 'token_package' ? 'Billing.WITHDRAWAL_EFFECT_TOKENS' : 'Billing.WITHDRAWAL_EFFECT') }), _jsx(Typography, { children: none ? t('Billing.WITHDRAWAL_REFUND_NONE') : t('Billing.WITHDRAWAL_REFUND', { amount }) }), _jsx(Typography, { children: t('Billing.WITHDRAWAL_CALCULATION', { explanation: describeCalculation(Object.assign(Object.assign({}, preview), { kind: purchase === null || purchase === void 0 ? void 0 : purchase.kind }), t, i18n.language) }) }), state === 'confirm_error' && _jsx(Alert, { severity: "error", sx: WITHDRAWAL_DIALOG_ALERT_SX, children: t('Billing.WITHDRAWAL_ERROR') }), state === 'submitting' && _jsxs(Typography, { role: "status", children: [_jsx(CircularProgress, { size: 16 }), " ", t('Billing.LOADING')] })] }), state === 'success' && _jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE_DETAIL', { date: formatDateTime(result === null || result === void 0 ? void 0 : result.withdrawn_at, i18n.language) }) })] }), _jsx(DialogActions, { children: state === 'ready' || state === 'confirm_error' ? _jsxs(_Fragment, { children: [_jsx(Button, { onClick: close, disabled: state === 'submitting', children: t('Billing.WITHDRAWAL_CANCEL') }), _jsx(Button, { variant: "contained", onClick: confirm, disabled: state === 'submitting', children: t('Billing.WITHDRAWAL_CONFIRM') })] }) : state === 'preview_error' ? _jsxs(_Fragment, { children: [_jsx(Button, { onClick: close, children: t('Billing.WITHDRAWAL_CLOSE') }), _jsx(Button, { onClick: () => setAttempt((n) => n + 1), children: t('Billing.RETRY') })] }) : (state === 'success' || state === 'not_possible') && _jsx(Button, { onClick: close, children: t('Billing.WITHDRAWAL_CLOSE') }) })] });
95
+ const fullRefund = (preview === null || preview === void 0 ? void 0 : preview.policy) === 'full' || (purchase === null || purchase === void 0 ? void 0 : purchase.policy) === 'full';
96
+ return _jsxs(Dialog, { open: open, onClose: close, disableEscapeKeyDown: state === 'submitting', fullWidth: true, maxWidth: "sm", "aria-labelledby": titleId, children: [_jsx(DialogTitle, { id: titleId, children: t(state === 'success' ? 'Billing.WITHDRAWAL_DONE' : 'Billing.WITHDRAWAL_TITLE') }), _jsxs(DialogContent, { children: [state === 'loading' && _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", role: "status", children: [_jsx(CircularProgress, { size: 20 }), _jsx(Typography, { children: t('Billing.LOADING') })] }), state === 'preview_error' && _jsx(Alert, { severity: "error", sx: WITHDRAWAL_DIALOG_ALERT_SX, children: t('Billing.WITHDRAWAL_PREVIEW_ERROR') }), (state === 'not_possible') && _jsx(Alert, { severity: "info", children: t('Billing.WITHDRAWAL_NOT_POSSIBLE') }), (state === 'ready' || state === 'submitting' || state === 'confirm_error') && _jsxs(Stack, { spacing: 1, children: [_jsx(Typography, { children: t((purchase === null || purchase === void 0 ? void 0 : purchase.kind) === 'token_package' ? 'Billing.WITHDRAWAL_EFFECT_TOKENS' : 'Billing.WITHDRAWAL_EFFECT') }), _jsx(Typography, { children: fullRefund ? t('Billing.WITHDRAWAL_REFUND', { amount }) : none ? t('Billing.WITHDRAWAL_REFUND_NONE') : t('Billing.WITHDRAWAL_REFUND', { amount }) }), fullRefund ? _jsxs(_Fragment, { children: [_jsx(Typography, { children: t('Billing.WITHDRAWAL_PAID_TOTAL', { amount: formatPrice(preview === null || preview === void 0 ? void 0 : preview.amount_paid_cents, i18n.language, preview === null || preview === void 0 ? void 0 : preview.currency) }) }), _jsx(Typography, { children: t('Billing.WITHDRAWAL_REFUNDED_BEFORE', { amount: formatPrice(preview === null || preview === void 0 ? void 0 : preview.refunded_cents, i18n.language, preview === null || preview === void 0 ? void 0 : preview.currency) }) })] }) : _jsx(Typography, { children: t('Billing.WITHDRAWAL_CALCULATION', { explanation: describeCalculation(Object.assign(Object.assign({}, preview), { kind: purchase === null || purchase === void 0 ? void 0 : purchase.kind }), t, i18n.language) }) }), state === 'confirm_error' && _jsx(Alert, { severity: "error", sx: WITHDRAWAL_DIALOG_ALERT_SX, children: t('Billing.WITHDRAWAL_ERROR') }), state === 'submitting' && _jsxs(Typography, { role: "status", children: [_jsx(CircularProgress, { size: 16 }), " ", t('Billing.LOADING')] })] }), state === 'success' && _jsxs(Stack, { spacing: 0.5, children: [_jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE_DETAIL', { date: formatDateTime(result === null || result === void 0 ? void 0 : result.withdrawn_at, i18n.language) }) }), (result === null || result === void 0 ? void 0 : result.refund_status) && _jsx(Typography, { children: t(refundStatusKey(result.refund_status)) })] })] }), _jsx(DialogActions, { children: state === 'ready' || state === 'confirm_error' ? _jsxs(_Fragment, { children: [_jsx(Button, { onClick: close, disabled: state === 'submitting', children: t('Billing.WITHDRAWAL_CANCEL') }), _jsx(Button, { variant: "contained", onClick: confirm, disabled: state === 'submitting', children: t('Billing.WITHDRAWAL_CONFIRM') })] }) : state === 'preview_error' ? _jsxs(_Fragment, { children: [_jsx(Button, { onClick: close, children: t('Billing.WITHDRAWAL_CLOSE') }), _jsx(Button, { onClick: () => setAttempt((n) => n + 1), children: t('Billing.RETRY') })] }) : (state === 'success' || state === 'not_possible') && _jsx(Button, { onClick: close, children: t('Billing.WITHDRAWAL_CLOSE') }) })] });
94
97
  }
95
98
  export default WithdrawalDialog;
@@ -6,13 +6,16 @@ import { formatDate, formatDateTime, formatPrice } from './format';
6
6
  import { WithdrawalDialog } from './WithdrawalDialog';
7
7
  export const WITHDRAWAL_SECTION_ALERT_SX = { width: '100%' };
8
8
  const is404 = (error) => { var _a; return ((_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.status) === 404; };
9
- const deadline = (purchase) => {
9
+ const legacyDeadline = (purchase) => {
10
10
  const date = new Date(purchase.purchased_at);
11
11
  if (!Number.isFinite(date.getTime()))
12
12
  return '';
13
13
  date.setUTCDate(date.getUTCDate() + 14);
14
14
  return date.toISOString();
15
15
  };
16
+ const deadline = (purchase) => (purchase === null || purchase === void 0 ? void 0 : purchase.deadline) !== undefined && (purchase === null || purchase === void 0 ? void 0 : purchase.deadline) !== null ? purchase.deadline : legacyDeadline(purchase);
17
+ const refundStatusKey = (status) => ['pending', 'requested', 'succeeded', 'failed', 'requires_action', 'cancelled'].includes(status)
18
+ ? `Billing.REFUND_STATUS_${status.toUpperCase()}` : 'Billing.REFUND_STATUS_UNKNOWN';
16
19
  export function WithdrawalSection({ api, plans = [], onWithdrawn, sessionWithdrawals = {}, sx }) {
17
20
  const { t, i18n } = useTranslation();
18
21
  const [purchases, setPurchases] = useState([]);
@@ -49,7 +52,7 @@ export function WithdrawalSection({ api, plans = [], onWithdrawn, sessionWithdra
49
52
  };
50
53
  const successful = Object.assign(Object.assign({}, sessionWithdrawals), withdrawn);
51
54
  if (loadError)
52
- return _jsxs(Stack, { sx: sx, spacing: 1, children: [_jsx(Alert, { severity: "error", sx: WITHDRAWAL_SECTION_ALERT_SX, children: t('Billing.WITHDRAWAL_LOAD_ERROR') }), _jsx(Button, { onClick: () => setReload((count) => count + 1), children: t('Billing.RETRY') }), Object.entries(successful).map(([id, entry]) => { var _a; return _jsxs(Stack, { spacing: 0.5, role: "status", children: [_jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE') }), _jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE_DETAIL', { date: formatDateTime((_a = ((entry === null || entry === void 0 ? void 0 : entry.result) || entry)) === null || _a === void 0 ? void 0 : _a.withdrawn_at, i18n.language) }) })] }, id); })] });
55
+ return _jsxs(Stack, { sx: sx, spacing: 1, children: [_jsx(Alert, { severity: "error", sx: WITHDRAWAL_SECTION_ALERT_SX, children: t('Billing.WITHDRAWAL_LOAD_ERROR') }), _jsx(Button, { onClick: () => setReload((count) => count + 1), children: t('Billing.RETRY') }), Object.entries(successful).map(([id, entry]) => { var _a, _b; return _jsxs(Stack, { spacing: 0.5, role: "status", children: [_jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE') }), _jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE_DETAIL', { date: formatDateTime((_a = ((entry === null || entry === void 0 ? void 0 : entry.result) || entry)) === null || _a === void 0 ? void 0 : _a.withdrawn_at, i18n.language) }) }), ((_b = ((entry === null || entry === void 0 ? void 0 : entry.result) || entry)) === null || _b === void 0 ? void 0 : _b.refund_status) && _jsx(Typography, { children: t(refundStatusKey(((entry === null || entry === void 0 ? void 0 : entry.result) || entry).refund_status)) })] }, id); })] });
53
56
  if (!purchases.length && !Object.keys(successful).length)
54
57
  return null;
55
58
  const findPlan = (key) => { var _a; return ((_a = plans.find((plan) => (plan === null || plan === void 0 ? void 0 : plan.key) === key)) === null || _a === void 0 ? void 0 : _a.name) || key; };
@@ -62,10 +65,10 @@ export function WithdrawalSection({ api, plans = [], onWithdrawn, sessionWithdra
62
65
  if (withdrawnAt)
63
66
  status = _jsx(Typography, { color: "text.secondary", children: t('Billing.WITHDRAWN_ON', { date: formatDate(withdrawnAt, i18n.language) }) });
64
67
  else if (purchase.eligible === true)
65
- status = _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", flexWrap: "wrap", children: [_jsx(Button, { onClick: () => setSelected(purchase), children: t('Billing.WITHDRAWAL_BUTTON') }), deadlineText && _jsx(Typography, { color: "text.secondary", children: t('Billing.WITHDRAWAL_UNTIL', { date: deadlineText }) })] });
68
+ status = _jsxs(Stack, { direction: "row", spacing: 1, alignItems: "center", flexWrap: "wrap", children: [_jsx(Button, { onClick: () => setSelected(purchase), children: t(purchase.policy === 'full' ? 'Billing.WITHDRAW_CONTRACT' : 'Billing.WITHDRAWAL_BUTTON') }), deadlineText && _jsx(Typography, { color: "text.secondary", children: t('Billing.WITHDRAWAL_UNTIL', { date: deadlineText }) })] });
66
69
  else if (purchase.reason === 'period_over')
67
70
  status = _jsx(Typography, { color: "text.secondary", children: t('Billing.WITHDRAWAL_PERIOD_OVER') });
68
71
  return _jsxs(Stack, { direction: "row", spacing: 1, justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", sx: { borderBottom: '1px solid', borderColor: 'divider', py: 1 }, children: [_jsxs(Stack, { sx: { minWidth: 0, flex: '1 1 auto' }, children: [_jsx(Typography, { children: findPlan(purchase.plan_key) }), _jsxs(Typography, { variant: "body2", color: "text.secondary", children: [formatDate(purchase.purchased_at, i18n.language), " \u00B7 ", formatPrice(purchase.amount_paid_cents, i18n.language, purchase.currency)] })] }), status] }, purchase.id);
69
- }), Object.entries(successful).map(([id, entry]) => { var _a; return _jsxs(Stack, { spacing: 0.5, role: "status", children: [_jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE') }), _jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE_DETAIL', { date: formatDateTime((_a = ((entry === null || entry === void 0 ? void 0 : entry.result) || entry)) === null || _a === void 0 ? void 0 : _a.withdrawn_at, i18n.language) }) })] }, id); }), _jsx(WithdrawalDialog, { open: Boolean(selected), purchase: selected, api: api, onClose: () => setSelected(null), onWithdrawn: (result) => selected && handleWithdrawn(selected.id, result) })] });
72
+ }), Object.entries(successful).map(([id, entry]) => { var _a, _b; return _jsxs(Stack, { spacing: 0.5, role: "status", children: [_jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE') }), _jsx(Typography, { children: t('Billing.WITHDRAWAL_DONE_DETAIL', { date: formatDateTime((_a = ((entry === null || entry === void 0 ? void 0 : entry.result) || entry)) === null || _a === void 0 ? void 0 : _a.withdrawn_at, i18n.language) }) }), ((_b = ((entry === null || entry === void 0 ? void 0 : entry.result) || entry)) === null || _b === void 0 ? void 0 : _b.refund_status) && _jsx(Typography, { children: t(refundStatusKey(((entry === null || entry === void 0 ? void 0 : entry.result) || entry).refund_status)) })] }, id); }), _jsx(WithdrawalDialog, { open: Boolean(selected), purchase: selected, api: api, onClose: () => setSelected(null), onWithdrawn: (result) => selected && handleWithdrawn(selected.id, result) })] });
70
73
  }
71
74
  export default WithdrawalSection;
@@ -30,6 +30,12 @@ export function createBillingApi(overrides = {}, { apiBase = '/api/billing/' } =
30
30
  listWithdrawals: () => data(apiClient.get(urls.withdrawals)),
31
31
  previewWithdrawal: (id) => data(apiClient.get(urls.withdrawalPreview(id))),
32
32
  confirmWithdrawal: (id) => data(apiClient.post(urls.withdrawalConfirm(id), { confirm: true })),
33
+ listContracts: () => data(apiClient.get(urls.contracts)),
34
+ cancelContract: (reference, body) => data(apiClient.post(urls.contractCancel(reference), body)),
35
+ withdrawContract: (reference) => data(apiClient.post(urls.contractWithdraw(reference), { confirm: true })),
36
+ primeDeclarationCsrf: () => data(apiClient.get(urls.declarationCsrf)),
37
+ submitDeclaration: (body) => data(apiClient.post(urls.declarations, body)),
38
+ confirmDeclaration: (token) => data(apiClient.post(urls.declarationConfirm, { token })),
33
39
  getOperatorOverview: ({ month } = {}) => data(month === undefined ? apiClient.get(urls.operatorOverview) : apiClient.get(urls.operatorOverview, { params: { month } })),
34
40
  listOperatorAccounts: ({ q, page, pageSize } = {}) => {
35
41
  const params = {};
@@ -15,6 +15,12 @@ export const billingApiUrls = (base = '/api/billing/') => {
15
15
  withdrawals: root + 'withdrawal/',
16
16
  withdrawalPreview: (id) => root + `withdrawal/${encodeURIComponent(id)}/preview/`,
17
17
  withdrawalConfirm: (id) => root + `withdrawal/${encodeURIComponent(id)}/`,
18
+ contracts: root + 'contracts/',
19
+ contractCancel: (reference) => root + `contracts/${encodeURIComponent(reference)}/cancel/`,
20
+ contractWithdraw: (reference) => root + `contracts/${encodeURIComponent(reference)}/withdraw/`,
21
+ declarationCsrf: root + 'public/declarations/csrf/',
22
+ declarations: root + 'public/declarations/',
23
+ declarationConfirm: root + 'public/declarations/confirm/',
18
24
  operatorOverview: root + 'operator/overview/',
19
25
  operatorAccounts: root + 'operator/accounts/',
20
26
  operatorFreeAccess: (id) => root + `operator/accounts/${encodeURIComponent(id)}/free-access/`,