From b211120d8fbd68a3678f87c238ecbef745a4d121 Mon Sep 17 00:00:00 2001 From: alpha Date: Sat, 5 Dec 2026 14:51:13 -0600 Subject: [PATCH] feat: manage billing and the password on the website The app and the website's account area both had checkout, payment history, payment status and a change-password form. Two copies drift (they already showed different status labels), and every checkout change was an admin, backend and client release, with macOS waiting on notarization. The conventional split for a desktop app with a web account is applied: the app keeps what using it needs (sign-in, plan status, the low-balance and expiry warnings, the interview profile) and links to the website for account management. - /payment keeps the current plan and the pass cards with prices from the backend. Choose (or Extend, on the current pass) opens the website's checkout for that pass. Payment history is a link to it. The in-app currency picker, payment creation, history and status tabs are removed, with their IPC channels, API calls, types and copy. - The account page's password form becomes a row that opens the website's security page, or the account overview. - webAccountService.open() asks the backend for a single-use, 60-second handoff code and opens /app-sign-in with it in the URL fragment, in the app's language, so the user arrives signed in and the session token never enters a URL. Without a code the page opens anyway and the website asks the user to sign in. The 5-second health-check ping already refreshes the balance, so a pass bought in the browser shows without anything watching for it. Closes #166 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 + src/main/api/auth.ts | 16 +- src/main/api/payment.ts | 39 +- src/main/consts.ts | 6 + src/main/ipc/account.ts | 6 + src/main/ipc/auth.ts | 8 - src/main/ipc/payment.ts | 55 +- src/main/preload.cts | 8 +- src/main/services/auth.service.ts | 46 +- src/main/services/payment.service.ts | 106 +--- src/main/services/web-account.service.ts | 66 ++ src/main/types/auth.ts | 7 +- src/main/types/payment.ts | 77 +-- src/main/utils/ui-strings.ts | 51 +- .../custom/payment/payment-history-tab.tsx | 194 ------ .../custom/payment/payment-status-tab.tsx | 584 ------------------ .../custom/payment/payment-utils.ts | 53 -- .../custom/payment/subscription-tab.tsx | 211 +------ .../custom/settings/password-section.tsx | 272 -------- src/renderer/hooks/use-auth.ts | 22 - src/renderer/hooks/use-payment.ts | 118 +--- src/renderer/i18n/locales/de.ts | 134 +--- src/renderer/i18n/locales/en.ts | 134 +--- src/renderer/i18n/locales/es.ts | 134 +--- src/renderer/i18n/locales/fr.ts | 134 +--- src/renderer/i18n/locales/ja.ts | 135 +--- src/renderer/i18n/locales/ko.ts | 134 +--- src/renderer/i18n/locales/pt.ts | 134 +--- src/renderer/i18n/locales/ru.ts | 134 +--- src/renderer/i18n/locales/zh.ts | 133 +--- src/renderer/pages/account/index.tsx | 37 +- src/renderer/pages/payment/index.tsx | 99 +-- src/renderer/types/electron-api.d.ts | 32 +- src/renderer/types/payment.ts | 75 --- test/change-password.test.mjs | 70 --- test/run.mjs | 2 +- test/web-account.test.mjs | 78 +++ 37 files changed, 381 insertions(+), 3171 deletions(-) create mode 100644 src/main/services/web-account.service.ts delete mode 100644 src/renderer/components/custom/payment/payment-history-tab.tsx delete mode 100644 src/renderer/components/custom/payment/payment-status-tab.tsx delete mode 100644 src/renderer/components/custom/payment/payment-utils.ts delete mode 100644 src/renderer/components/custom/settings/password-section.tsx delete mode 100644 test/change-password.test.mjs create mode 100644 test/web-account.test.mjs diff --git a/CLAUDE.md b/CLAUDE.md index 0e4850a0..72ff7d3a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -748,6 +748,14 @@ lapses - never for one that lapsed before launch, and never across a sign-out. S also carry `kind=mock` and a per-session `client_session_id`, which the backend uses only to label and group its ledger rows. +### Billing and the password live on the website + +**The app shows the plan; the website's account area manages the account.** `/payment` is the current plan and the three pass cards, with prices from `GET /payment/subscription-plans`, and *Choose* / *Extend* opens the website's checkout for that pass. Payment history, payment status and the password change are on the website too: the app's own checkout, history and status tabs and its change-password form are gone, because two copies drifted and every checkout change was a client release (and, on macOS, a notarization). Signing in, the plan status, the low-balance and expiry warnings and the interview profile stay here, since they are what using the app needs. + +Every link out goes through `webAccountService.open()` ([web-account.service.ts](src/main/services/web-account.service.ts)), over `account:open-web`. It asks the backend for a single-use, 60-second handoff code (`POST /api/auth/handoff`) and opens `WEBSITE_BASE_URL//app-sign-in?next=#code=`: the code rides in the **fragment**, which no server log or Referer sees, and the website trades it for a session of the browser's own. The session token itself never goes into a URL. Without a code (a backend that predates the endpoint, a network blip) the page opens anyway and the website asks the user to sign in, then continues to the same place. The locale prefix follows `uiLanguage`, since the website's locales are the app's. `test/web-account.test.mjs` pins the fragment, the paths, the plan-id check and the fallback. + +Nothing needs to watch for the purchase coming back: the health-check ping refreshes the balance every 5 seconds while signed in. A password changed on the website signs out every other session, this one included, so the app returns to sign-in on the next ping - the same as any other device. + ### Window and Stealth Mode The main window reference is passed to `windowControlService` and `zoomService` after creation. Window bounds persist to Electron Store on `close` and are restored on next launch with minimum-size clamping (`MIN_WIDTH` / `MIN_HEIGHT` from [src/main/consts.ts](src/main/consts.ts)). diff --git a/src/main/api/auth.ts b/src/main/api/auth.ts index b8f5f527..149b5a80 100644 --- a/src/main/api/auth.ts +++ b/src/main/api/auth.ts @@ -5,8 +5,8 @@ import { AuthToken, - ChangePasswordRequest, ForgotPasswordRequest, + HandoffCode, LoginRequest, ResetPasswordRequest, SendVerificationCodeRequest, @@ -38,6 +38,13 @@ export class AuthApi extends ApiClient { return this.post('/api/auth/login', credentials); } + /** + * A single-use code that signs the website in as this account (backend #89) + */ + async createHandoff(): Promise> { + return this.post('/api/auth/handoff', {}); + } + /** * Logout current session */ @@ -52,13 +59,6 @@ export class AuthApi extends ApiClient { return this.post('/api/auth/signup', data); } - /** - * Change user password - */ - async changePassword(data: ChangePasswordRequest): Promise> { - return this.post('/api/auth/change-password', data); - } - /** * Request a password reset code. * diff --git a/src/main/api/payment.ts b/src/main/api/payment.ts index f8f4d82b..f91fffd5 100644 --- a/src/main/api/payment.ts +++ b/src/main/api/payment.ts @@ -1,16 +1,9 @@ /** * Payment API - * Handles payment and credit operations + * The passes on sale. Checkout, status and history are the website's (see web-account.service.ts). */ -import { - AvailableCurrency, - CreatePaymentRequest, - CreatePaymentResponse, - PaymentHistory, - PaymentPlan, - PaymentStatusResponse, -} from '../types/payment.js'; +import { PaymentPlan } from '../types/payment.js'; import { ApiClient, ApiResponse } from './client.js'; export class PaymentApi extends ApiClient { @@ -30,32 +23,4 @@ export class PaymentApi extends ApiClient { > { return this.get('/api/payment/subscription-plans'); } - - /** - * Get available currencies for payment - */ - async getAvailableCurrencies(): Promise> { - return this.get('/api/payment/currencies'); - } - - /** - * Create a new payment - */ - async createPayment(data: CreatePaymentRequest): Promise> { - return this.post('/api/payment/create', data); - } - - /** - * Get payment status - */ - async getPaymentStatus(paymentId: string): Promise> { - return this.get(`/api/payment/status/${paymentId}`); - } - - /** - * Get payment history - */ - async getPaymentHistory(): Promise> { - return this.get('/api/payment/history'); - } } diff --git a/src/main/consts.ts b/src/main/consts.ts index bd82755d..c29737bf 100644 --- a/src/main/consts.ts +++ b/src/main/consts.ts @@ -4,6 +4,12 @@ export const BACKEND_BASE_URL = EnvUtil.isDev() ? 'http://localhost:8080' : 'https://api.powerinterviewai.com'; +// The website, whose account area is where billing, payment history and the password are managed. +// The app links there rather than keeping its own copy (see web-account.service.ts). +export const WEBSITE_BASE_URL = EnvUtil.isDev() + ? 'http://localhost:3000' + : 'https://www.powerinterviewai.com'; + // GitHub repo the release/publish workflow ships to. macOS reads releases from here directly // (see mac-update.util.ts) since Squirrel.Mac's silent update needs real Developer ID signing, // which this app does not have yet. diff --git a/src/main/ipc/account.ts b/src/main/ipc/account.ts index 44c293e6..4f26644f 100644 --- a/src/main/ipc/account.ts +++ b/src/main/ipc/account.ts @@ -1,6 +1,7 @@ import { ipcMain } from 'electron'; import { accountService } from '../services/account.service.js'; +import { WebAccountPage, webAccountService } from '../services/web-account.service.js'; export function registerAccountHandlers(): void { // Push local account config changes (full name, profile, context) to the backend @@ -27,4 +28,9 @@ export function registerAccountHandlers(): void { ipcMain.handle('account:set-onboarding-completed', async (_event, completed: boolean) => { return accountService.setOnboardingCompleted(completed); }); + + // Billing, payment history and the password live on the website; this opens it signed in. + ipcMain.handle('account:open-web', async (_event, page: WebAccountPage, plan?: string) => { + return webAccountService.open(page, plan); + }); } diff --git a/src/main/ipc/auth.ts b/src/main/ipc/auth.ts index 6a5c5fa3..5dcb0ee1 100644 --- a/src/main/ipc/auth.ts +++ b/src/main/ipc/auth.ts @@ -31,14 +31,6 @@ export function registerAuthHandlers(): void { return authService.logout(); }); - // Change password - ipcMain.handle( - 'auth:change-password', - async (_event, currentPassword: string, newPassword: string) => { - return authService.changePassword(currentPassword, newPassword); - } - ); - // Request a password reset code ipcMain.handle('auth:forgot-password', async (_event, email: string) => { return authService.forgotPassword(email); diff --git a/src/main/ipc/payment.ts b/src/main/ipc/payment.ts index 1db1aded..ec6cfefb 100644 --- a/src/main/ipc/payment.ts +++ b/src/main/ipc/payment.ts @@ -6,14 +6,7 @@ import { ipcMain } from 'electron'; import { paymentService } from '../services/payment.service.js'; -import { - AvailableCurrency, - CreatePaymentRequest, - CreatePaymentResponse, - PaymentHistory, - PaymentStatusResponse, - SubscriptionPlanInfo, -} from '../types/payment.js'; +import { SubscriptionPlanInfo } from '../types/payment.js'; export function registerPaymentHandlers(): void { /** @@ -25,50 +18,4 @@ export function registerPaymentHandlers(): void { return paymentService.getPlans(); } ); - - /** - * Get available payment currencies - */ - ipcMain.handle( - 'payment:get-currencies', - async (): Promise<{ success: boolean; data?: AvailableCurrency[]; error?: string }> => { - return paymentService.getAvailableCurrencies(); - } - ); - - /** - * Create a new payment - */ - ipcMain.handle( - 'payment:create', - async ( - _event, - data: CreatePaymentRequest - ): Promise<{ success: boolean; data?: CreatePaymentResponse; error?: string }> => { - return paymentService.createPayment(data); - } - ); - - /** - * Get payment status - */ - ipcMain.handle( - 'payment:get-status', - async ( - _event, - paymentId: string - ): Promise<{ success: boolean; data?: PaymentStatusResponse; error?: string }> => { - return paymentService.getPaymentStatus(paymentId); - } - ); - - /** - * Get payment history - */ - ipcMain.handle( - 'payment:get-history', - async (): Promise<{ success: boolean; data?: PaymentHistory[]; error?: string }> => { - return paymentService.getPaymentHistory(); - } - ); } diff --git a/src/main/preload.cts b/src/main/preload.cts index c13fe03c..d1192068 100644 --- a/src/main/preload.cts +++ b/src/main/preload.cts @@ -64,8 +64,6 @@ const electronApi = { ipcRenderer.invoke('auth:signup', username, email, password, verificationCode), login: (email: string, password: string) => ipcRenderer.invoke('auth:login', email, password), logout: () => ipcRenderer.invoke('auth:logout'), - changePassword: (currentPassword: string, newPassword: string) => - ipcRenderer.invoke('auth:change-password', currentPassword, newPassword), forgotPassword: (email: string) => ipcRenderer.invoke('auth:forgot-password', email), verifyPasswordResetCode: (email: string, code: string) => ipcRenderer.invoke('auth:verify-password-reset-code', email, code), @@ -80,14 +78,12 @@ const electronApi = { get: () => ipcRenderer.invoke('account:get'), setOnboardingCompleted: (completed: boolean) => ipcRenderer.invoke('account:set-onboarding-completed', completed), + openWeb: (page: 'overview' | 'billing' | 'security', plan?: string) => + ipcRenderer.invoke('account:open-web', page, plan), }, payment: { getPlans: () => ipcRenderer.invoke('payment:get-plans'), - getCurrencies: () => ipcRenderer.invoke('payment:get-currencies'), - create: (data: Record) => ipcRenderer.invoke('payment:create', data), - getStatus: (paymentId: string) => ipcRenderer.invoke('payment:get-status', paymentId), - getHistory: () => ipcRenderer.invoke('payment:get-history'), }, appState: { diff --git a/src/main/services/auth.service.ts b/src/main/services/auth.service.ts index 1cd56a0a..61b2478d 100644 --- a/src/main/services/auth.service.ts +++ b/src/main/services/auth.service.ts @@ -11,7 +11,7 @@ import { disableStealth } from './window-control.service.js'; * AuthService * Wrapper around the low-level `AuthApi` client that provides * higher-level methods used by the application (login, signup, - * logout, changePassword). Each method returns a simple result + * logout, password reset). Each method returns a simple result * object with `success` and optional `error` message to keep * caller-side handling straightforward. */ @@ -188,48 +188,6 @@ export class AuthService { } } - /** - * Change the authenticated user's password. - * The API expects `current_password` and `new_password` keys. - */ - async changePassword( - currentPassword: string, - newPassword: string - ): Promise<{ success: boolean; error?: string }> { - try { - const response = await this.client.changePassword({ - current_password: currentPassword, - new_password: newPassword, - }); - if (response.error) { - return { - success: false, - error: response.error.message || uiStrings().authErrors.changePasswordFailed, - }; - } - - // Only persist when the user opted in - login/logout leave the store empty otherwise, - // and writing here would put credentials back behind their back. - // - // Guarded separately from the request, because by this line the password has already - // changed on the server. Letting a disk write decide the return value reports a failure - // for a change that happened, and the dialog then asks the user to try again with a - // current password that is no longer current, so the retry cannot work either. Same - // line `resetPassword` draws, and `login.tsx` before it. - try { - if (configStore.getConfig().rememberMe) { - configStore.updateConfig({ password: newPassword }); - } - } catch (err) { - console.error('Failed to store the new password after change:', err); - } - - return { success: true }; - } catch { - return { success: false, error: uiStrings().authErrors.changePasswordFailed }; - } - } - /** * Request a password reset code for an address. * @@ -298,7 +256,7 @@ export class AuthService { // The login form pre-fills from the store when rememberMe is on, and if what it holds // is this account then the password in it is the one that just stopped working. // - // Two guards, not one. `rememberMe` is the same check changePassword makes: login and + // Two guards, not one. `rememberMe` first: login and // logout leave the store empty when the user did not opt in, and writing here would put // credentials back on disk behind their back. The address check is specific to reset, // which is the only password flow that runs while signed out and can therefore be run diff --git a/src/main/services/payment.service.ts b/src/main/services/payment.service.ts index 1a9d2087..171ab580 100644 --- a/src/main/services/payment.service.ts +++ b/src/main/services/payment.service.ts @@ -1,17 +1,10 @@ /** * PaymentService - * Manages payment and credit operations + * The passes on sale, for the app's plan cards. Buying one happens on the website. */ import { PaymentApi } from '../api/payment.js'; -import { - AvailableCurrency, - CreatePaymentRequest, - CreatePaymentResponse, - PaymentHistory, - PaymentStatusResponse, - SubscriptionPlanInfo, -} from '../types/payment.js'; +import { SubscriptionPlanInfo } from '../types/payment.js'; import { uiStrings } from '../utils/ui-strings.js'; export class PaymentService { @@ -55,101 +48,6 @@ export class PaymentService { return { success: false, error: uiStrings().paymentErrors.getPlans }; } } - - /** - * Get available payment currencies - */ - async getAvailableCurrencies(): Promise<{ - success: boolean; - data?: AvailableCurrency[]; - error?: string; - }> { - try { - const response = await this.api.getAvailableCurrencies(); - if (response.error) { - return { - success: false, - error: response.error.message || uiStrings().paymentErrors.getCurrencies, - }; - } - - return { success: true, data: response.data || [] }; - } catch (error) { - console.error('[PaymentService] Failed to get available currencies:', error); - return { success: false, error: uiStrings().paymentErrors.getCurrencies }; - } - } - - /** - * Create a new payment - */ - async createPayment( - data: CreatePaymentRequest - ): Promise<{ success: boolean; data?: CreatePaymentResponse; error?: string }> { - try { - const response = await this.api.createPayment(data); - - if (response.error) { - return { - success: false, - error: response.error.message || uiStrings().paymentErrors.createPayment, - }; - } - - return { success: true, data: response.data }; - } catch (error) { - console.error('[PaymentService] Failed to create payment:', error); - return { success: false, error: uiStrings().paymentErrors.createPayment }; - } - } - - /** - * Get payment status - */ - async getPaymentStatus( - paymentId: string - ): Promise<{ success: boolean; data?: PaymentStatusResponse; error?: string }> { - try { - const response = await this.api.getPaymentStatus(paymentId); - - if (response.error) { - return { - success: false, - error: response.error.message || uiStrings().paymentErrors.getStatus, - }; - } - - return { success: true, data: response.data }; - } catch (error) { - console.error('[PaymentService] Failed to get payment status:', error); - return { success: false, error: uiStrings().paymentErrors.getStatus }; - } - } - - /** - * Get payment history - */ - async getPaymentHistory(): Promise<{ - success: boolean; - data?: PaymentHistory[]; - error?: string; - }> { - try { - const response = await this.api.getPaymentHistory(); - - if (response.error) { - return { - success: false, - error: response.error.message || uiStrings().paymentErrors.getHistory, - }; - } - - return { success: true, data: response.data || [] }; - } catch (error) { - console.error('[PaymentService] Failed to get payment history:', error); - return { success: false, error: uiStrings().paymentErrors.getHistory }; - } - } } export const paymentService = new PaymentService(); diff --git a/src/main/services/web-account.service.ts b/src/main/services/web-account.service.ts new file mode 100644 index 00000000..814a9317 --- /dev/null +++ b/src/main/services/web-account.service.ts @@ -0,0 +1,66 @@ +import { AuthApi } from '../api/auth.js'; +import { WEBSITE_BASE_URL } from '../consts.js'; +import { openExternally } from '../navigation-guard.js'; +import { configStore } from '../store/config.store.js'; +import { DEFAULT_UI_LANGUAGE } from '../types/ui-language.js'; + +/** The account pages on the website the app links to. */ +export enum WebAccountPage { + Overview = 'overview', + Billing = 'billing', + Security = 'security', +} + +const PAGE_PATHS: Record = { + [WebAccountPage.Overview]: '/account', + [WebAccountPage.Billing]: '/account/billing', + [WebAccountPage.Security]: '/account/security', +}; + +/** Plan ids are lowercase words (`monthly`, `quarterly`, `yearly`); anything else is dropped. */ +const PLAN_ID = /^[a-z]{1,32}$/; + +/** + * Opens the website's account area in the user's browser, signed in as this account. + * + * Billing, payment history and the password are managed on the website, not in the app: one + * implementation, and a pricing or checkout change ships with a web deploy instead of a client + * release. What makes that bearable is arriving signed in. The session token never goes into the + * URL - it is long-lived and would sit in browser history - so the backend swaps it for a + * single-use code that lives a minute, and the website's `/app-sign-in` trades that for a session + * of the browser's own. The code rides in the fragment, which no server or Referer sees. + * + * When the code cannot be had (a backend from before #89, a network blip) the page opens anyway + * and the website asks the user to sign in, then carries on to the same place. + */ +export class WebAccountService { + private client = new AuthApi(); + + buildUrl(page: WebAccountPage, plan?: string, code?: string): string { + const path = PAGE_PATHS[page] ?? PAGE_PATHS[WebAccountPage.Overview]; + const next = plan && PLAN_ID.test(plan) ? `${path}?plan=${plan}` : path; + + // Same language as the app's chrome. The website's locales are the app's, and English is + // unprefixed there. + const language = configStore.getConfig().uiLanguage; + const prefix = language && language !== DEFAULT_UI_LANGUAGE ? `/${language}` : ''; + + if (!code) return `${WEBSITE_BASE_URL}${prefix}${next}`; + const query = new URLSearchParams({ next }); + const fragment = new URLSearchParams({ code }); + return `${WEBSITE_BASE_URL}${prefix}/app-sign-in?${query.toString()}#${fragment.toString()}`; + } + + async open(page: WebAccountPage, plan?: string): Promise<{ success: boolean; error?: string }> { + let code: string | undefined; + try { + const response = await this.client.createHandoff(); + code = response.data?.code; + } catch (error) { + console.warn('[WebAccountService] No handoff code, opening without one:', error); + } + return openExternally(this.buildUrl(page, plan, code)); + } +} + +export const webAccountService = new WebAccountService(); diff --git a/src/main/types/auth.ts b/src/main/types/auth.ts index 436cd31e..c498ec44 100644 --- a/src/main/types/auth.ts +++ b/src/main/types/auth.ts @@ -26,9 +26,10 @@ export interface AuthToken { session_token: string; } -export interface ChangePasswordRequest { - current_password: string; - new_password: string; +/** A single-use code the website trades for a session of its own; `expires_in` is in seconds. */ +export interface HandoffCode { + code: string; + expires_in: number; } export interface ForgotPasswordRequest { diff --git a/src/main/types/payment.ts b/src/main/types/payment.ts index 12d53697..f8069609 100644 --- a/src/main/types/payment.ts +++ b/src/main/types/payment.ts @@ -1,19 +1,7 @@ /** - * Payment Types + * The passes on sale. Paying for one happens on the website's account area. */ -export enum PaymentStatus { - Waiting = 'waiting', - Confirming = 'confirming', - Confirmed = 'confirmed', - Sending = 'sending', - PartiallyPaid = 'partially_paid', - Finished = 'finished', - Failed = 'failed', - Refunded = 'refunded', - Expired = 'expired', -} - /** * What a payment buys. Monthly, quarterly and yearly are the passes on sale; the credit packs * are only here because orders placed before subscriptions carry them. @@ -37,66 +25,3 @@ export interface SubscriptionPlanInfo { pricePerMonthUsd: number; popular: boolean; } - -export interface CreatePaymentRequest { - plan: PaymentPlan; - pay_currency?: string; -} - -export interface CreatePaymentResponse { - payment_id: string; - payment_status: PaymentStatus; - pay_address: string; - pay_amount: number; - pay_currency: string; - price_amount: number; - price_currency: string; - order_id: string; - order_description: string; - payment_url: string; - created_at: string; - updated_at: string; - expiration_estimate_date: string; -} - -export interface PaymentStatusResponse { - payment_id: string; - order_id: string; - payment_status: PaymentStatus; - pay_address: string; - pay_amount: number; - pay_currency: string; - price_amount: number; - price_currency: string; - actually_paid: number | null; - outcome_amount: number | null; - created_at: string | null; - updated_at: string | null; -} - -export interface AvailableCurrency { - code: string; - name: string; - logo_url: string; -} - -export interface PaymentHistory { - payment_id: string | null; - order_id: string; - plan: PaymentPlan; - credits_amount: number; - /** Calendar months a pass buys. */ - months_amount?: number; - /** What the order actually granted once applied, overpay bonus included. */ - days_granted?: number | null; - /** Set on a follow-up payment for the remainder of a partially paid order. */ - root_payment_id?: string | null; - price_amount: number; - pay_address: string | null; - pay_amount: number | null; - pay_currency: string | null; - status: PaymentStatus; - credits_applied: boolean; - created_at: string; - updated_at: string; -} diff --git a/src/main/utils/ui-strings.ts b/src/main/utils/ui-strings.ts index 7e049a77..80b38cfc 100644 --- a/src/main/utils/ui-strings.ts +++ b/src/main/utils/ui-strings.ts @@ -50,7 +50,6 @@ export interface UiStrings { | 'invalidCredentials' | 'loginFailed' | 'logoutFailed' - | 'changePasswordFailed' | 'sendResetCodeFailed' | 'invalidResetCode' | 'resetFailed', @@ -76,10 +75,7 @@ export interface UiStrings { transportErrors: Record<'timedOut' | 'networkFailed', string>; /** Same shape again for the payment service, whose every path sets its own message. */ - paymentErrors: Record< - 'getPlans' | 'getCurrencies' | 'createPayment' | 'getStatus' | 'getHistory', - string - >; + paymentErrors: Record<'getPlans', string>; /** * Written onto a suggestion's `error` field, which the panel renders verbatim on the card the @@ -159,7 +155,6 @@ const STRINGS: Record = { invalidCredentials: 'Invalid email or password', loginFailed: 'Login failed', logoutFailed: 'Logout failed', - changePasswordFailed: 'Change password failed', sendResetCodeFailed: 'Failed to send password reset code', invalidResetCode: 'Invalid or expired reset code', resetFailed: 'Password reset failed', @@ -180,10 +175,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'Failed to get plans', - getCurrencies: 'Failed to get available currencies', - createPayment: 'Failed to create payment', - getStatus: 'Failed to get payment status', - getHistory: 'Failed to get payment history', }, suggestionErrors: { @@ -251,7 +242,6 @@ const STRINGS: Record = { invalidCredentials: 'Неверная почта или пароль', loginFailed: 'Не удалось войти', logoutFailed: 'Не удалось выйти', - changePasswordFailed: 'Не удалось изменить пароль', sendResetCodeFailed: 'Не удалось отправить код сброса пароля', invalidResetCode: 'Код сброса неверен или истёк', resetFailed: 'Не удалось изменить пароль', @@ -272,10 +262,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'Не удалось получить тарифы', - getCurrencies: 'Не удалось получить список доступных валют', - createPayment: 'Не удалось создать платёж', - getStatus: 'Не удалось получить статус платежа', - getHistory: 'Не удалось получить историю платежей', }, suggestionErrors: { @@ -343,7 +329,6 @@ const STRINGS: Record = { invalidCredentials: 'Correo o contraseña incorrectos', loginFailed: 'No se pudo iniciar sesión', logoutFailed: 'No se pudo cerrar sesión', - changePasswordFailed: 'No se pudo cambiar la contraseña', sendResetCodeFailed: 'No se pudo enviar el código de restablecimiento', invalidResetCode: 'Código de restablecimiento no válido o caducado', resetFailed: 'No se pudo restablecer la contraseña', @@ -364,10 +349,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'No se pudieron obtener los planes', - getCurrencies: 'No se pudieron obtener las monedas disponibles', - createPayment: 'No se pudo crear el pago', - getStatus: 'No se pudo obtener el estado del pago', - getHistory: 'No se pudo obtener el historial de pagos', }, suggestionErrors: { @@ -438,7 +419,6 @@ const STRINGS: Record = { invalidCredentials: 'E-mail ou senha incorretos', loginFailed: 'Não foi possível entrar', logoutFailed: 'Não foi possível sair', - changePasswordFailed: 'Não foi possível alterar a senha', sendResetCodeFailed: 'Não foi possível enviar o código de redefinição', invalidResetCode: 'Código de redefinição inválido ou expirado', resetFailed: 'Não foi possível redefinir a senha', @@ -459,10 +439,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'Não foi possível obter os planos', - getCurrencies: 'Não foi possível obter as moedas disponíveis', - createPayment: 'Não foi possível criar o pagamento', - getStatus: 'Não foi possível obter a situação do pagamento', - getHistory: 'Não foi possível obter o histórico de pagamentos', }, suggestionErrors: { @@ -531,7 +507,6 @@ const STRINGS: Record = { invalidCredentials: 'E-Mail oder Passwort ist falsch', loginFailed: 'Anmeldung fehlgeschlagen', logoutFailed: 'Abmeldung fehlgeschlagen', - changePasswordFailed: 'Passwort konnte nicht geändert werden', sendResetCodeFailed: 'Code zum Zurücksetzen konnte nicht gesendet werden', invalidResetCode: 'Ungültiger oder abgelaufener Code zum Zurücksetzen', resetFailed: 'Zurücksetzen des Passworts fehlgeschlagen', @@ -552,10 +527,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'Tarife konnten nicht abgerufen werden', - getCurrencies: 'Verfügbare Währungen konnten nicht abgerufen werden', - createPayment: 'Zahlung konnte nicht erstellt werden', - getStatus: 'Zahlungsstatus konnte nicht abgerufen werden', - getHistory: 'Zahlungsverlauf konnte nicht abgerufen werden', }, suggestionErrors: { @@ -623,7 +594,6 @@ const STRINGS: Record = { invalidCredentials: 'Adresse e-mail ou mot de passe incorrect', loginFailed: 'Échec de la connexion', logoutFailed: 'Échec de la déconnexion', - changePasswordFailed: 'Impossible de modifier le mot de passe', sendResetCodeFailed: 'Impossible d’envoyer le code de réinitialisation', invalidResetCode: 'Code de réinitialisation invalide ou expiré', resetFailed: 'Échec de la réinitialisation du mot de passe', @@ -644,10 +614,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'Impossible d’obtenir les formules', - getCurrencies: 'Impossible d’obtenir les devises disponibles', - createPayment: 'Impossible de créer le paiement', - getStatus: 'Impossible d’obtenir le statut du paiement', - getHistory: 'Impossible d’obtenir l’historique des paiements', }, suggestionErrors: { @@ -717,7 +683,6 @@ const STRINGS: Record = { invalidCredentials: '邮箱或密码错误', loginFailed: '登录失败', logoutFailed: '退出登录失败', - changePasswordFailed: '修改密码失败', sendResetCodeFailed: '重置码发送失败', invalidResetCode: '重置码无效或已过期', resetFailed: '密码重置失败', @@ -738,10 +703,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: '获取套餐失败', - getCurrencies: '获取可用币种失败', - createPayment: '创建支付失败', - getStatus: '获取支付状态失败', - getHistory: '获取支付记录失败', }, suggestionErrors: { @@ -805,7 +766,6 @@ const STRINGS: Record = { invalidCredentials: 'メールアドレスまたはパスワードが正しくありません', loginFailed: 'ログインに失敗しました', logoutFailed: 'ログアウトに失敗しました', - changePasswordFailed: 'パスワードを変更できませんでした', sendResetCodeFailed: 'リセットコードを送信できませんでした', invalidResetCode: 'リセットコードが無効か、有効期限が切れています', resetFailed: 'パスワードの再設定に失敗しました', @@ -826,10 +786,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: 'プランを取得できませんでした', - getCurrencies: '利用できる通貨を取得できませんでした', - createPayment: '支払いを作成できませんでした', - getStatus: '支払いステータスを取得できませんでした', - getHistory: '支払い履歴を取得できませんでした', }, suggestionErrors: { @@ -896,7 +852,6 @@ const STRINGS: Record = { invalidCredentials: '이메일 또는 비밀번호가 올바르지 않습니다', loginFailed: '로그인하지 못했습니다', logoutFailed: '로그아웃하지 못했습니다', - changePasswordFailed: '비밀번호를 변경하지 못했습니다', sendResetCodeFailed: '비밀번호 재설정 코드를 보내지 못했습니다', invalidResetCode: '재설정 코드가 올바르지 않거나 만료되었습니다', resetFailed: '비밀번호를 재설정하지 못했습니다', @@ -917,10 +872,6 @@ const STRINGS: Record = { paymentErrors: { getPlans: '요금제를 가져오지 못했습니다', - getCurrencies: '사용 가능한 통화를 가져오지 못했습니다', - createPayment: '결제를 생성하지 못했습니다', - getStatus: '결제 상태를 가져오지 못했습니다', - getHistory: '결제 내역을 가져오지 못했습니다', }, suggestionErrors: { diff --git a/src/renderer/components/custom/payment/payment-history-tab.tsx b/src/renderer/components/custom/payment/payment-history-tab.tsx deleted file mode 100644 index 80e35400..00000000 --- a/src/renderer/components/custom/payment/payment-history-tab.tsx +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Payment History Tab Component - */ - -import { RefreshCw } from 'lucide-react'; -import { useCallback, useEffect, useRef, useState } from 'react'; - -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Skeleton } from '@/components/ui/skeleton'; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from '@/components/ui/table'; -import { usePayment } from '@/hooks/use-payment'; -import { useT } from '@/i18n'; -import { cn } from '@/lib/utils'; -import type { PaymentHistory } from '@/types/payment'; - -import { getStatusBadgeColor, getStatusLabel } from './payment-utils'; - -interface PaymentHistoryTabProps { - isActive: boolean; - onViewPayment: (paymentId: string) => void; - onSwitchToBuy: () => void; -} - -export default function PaymentHistoryTab({ - isActive, - onViewPayment, - onSwitchToBuy, -}: PaymentHistoryTabProps) { - const t = useT(); - const { getPaymentHistory } = usePayment(); - const [history, setHistory] = useState([]); - const [loading, setLoading] = useState(false); - const [refreshing, setRefreshing] = useState(false); - const [error, setError] = useState(null); - - const historyRef = useRef(history); - useEffect(() => { - historyRef.current = history; - }, [history]); - - const fetchHistory = useCallback( - async (silent = false) => { - if (!silent) setLoading(true); - if (silent) setRefreshing(true); - try { - const result = await getPaymentHistory(); - if (result === null) { - // A failed background poll keeps the list on screen and says nothing. - if (!silent) setError(t.payment.history.loadFailed); - return; - } - setError(null); - // only update state when new data differs from the current list - if (JSON.stringify(result) !== JSON.stringify(historyRef.current)) { - setHistory(result); - } - } catch (err) { - if (!silent) setError(err instanceof Error ? err.message : t.payment.history.loadFailed); - } finally { - if (!silent) setLoading(false); - if (silent) setRefreshing(false); - } - }, - [getPaymentHistory, t] - ); - - useEffect(() => { - let interval: number | null = null; - - if (isActive) { - // load immediately (show spinner on first load) - fetchHistory(); - // background polls are silent - no spinner flash - interval = window.setInterval(() => fetchHistory(true), 5000); - } - - return () => { - if (interval !== null) window.clearInterval(interval); - }; - }, [isActive, fetchHistory]); - - return ( -
- {error && ( -
-

{error}

-
- )} - - {loading ? ( -
- {[0, 1, 2].map((i) => ( - - ))} - - {t.payment.history.loading} - -
- ) : history.length === 0 && error ? null : history.length === 0 ? ( - - - {t.payment.history.emptyTitle} - {t.payment.history.emptyBody} - - - - - - ) : ( -
-
- - - {t.payment.history.refreshing} - -
- - - - {t.payment.history.columns.created} - {t.payment.history.columns.paymentId} - {t.payment.history.columns.purchase} - {t.payment.history.columns.amount} - {t.payment.history.columns.status} - {t.payment.history.columns.action} - - - - {history.slice(0, 30).map((payment) => ( - - - {new Date(payment.created_at).toLocaleDateString()}{' '} - {new Date(payment.created_at).toLocaleTimeString()} - - {payment.payment_id} - - {payment.root_payment_id - ? t.payment.history.remainder - : t.payment.history.grant( - payment.months_amount ?? 0, - payment.days_granted ?? 0, - payment.credits_amount - )} - - - {payment.pay_amount && payment.pay_currency - ? `${payment.pay_amount} ${payment.pay_currency.toUpperCase()}` - : t.payment.history.notAvailable} -
${payment.price_amount} USD
-
- - - {getStatusLabel(t, payment.status)} - - - - - -
- ))} -
-
-
- )} -
- ); -} diff --git a/src/renderer/components/custom/payment/payment-status-tab.tsx b/src/renderer/components/custom/payment/payment-status-tab.tsx deleted file mode 100644 index 3398d9d4..00000000 --- a/src/renderer/components/custom/payment/payment-status-tab.tsx +++ /dev/null @@ -1,584 +0,0 @@ -/** - * Payment Status Tab Component - */ - -import { - CircleCheck, - Copy, - CopyCheck, - FileIcon, - FolderOpenIcon, - RefreshCw, - XIcon, -} from 'lucide-react'; -import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { QrcodeCanvas, useQrcodeDownload } from 'react-qrcode-pretty'; -import { toast } from 'sonner'; - -import logoQr from '/logo-qr.png'; -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Input } from '@/components/ui/input'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; -import { usePayment } from '@/hooks/use-payment'; -import { type Translation, useT } from '@/i18n'; -import { cn, getElectron } from '@/lib/utils'; -import type { PaymentStatusResponse } from '@/types/payment'; -import { PaymentStatus } from '@/types/payment'; - -import { getStatusBadgeColor, getStatusLabel } from './payment-utils'; - -// separate memoized QR canvas to avoid redraws when parent re-renders -interface MemoQrProps { - /** The dictionary, so the memo comparison below can treat a language change as a change. */ - t: Translation; - paymentUri: string; - setQrcode: (canvas: HTMLCanvasElement | SVGSVGElement) => void; - isQrcodeReady: boolean; - orderId: string; // memo comparison only - onDownload: () => void; -} - -const QrComponent: React.FC = ({ - t, - paymentUri, - setQrcode, - isQrcodeReady, - onDownload, -}) => ( - <> - - - -); - -const MemoQr = memo( - QrComponent, - (prev, next) => - prev.t === next.t && - prev.paymentUri === next.paymentUri && - prev.isQrcodeReady === next.isQrcodeReady && - prev.orderId === next.orderId -); - -interface PaymentStatusTabProps { - initialPaymentId?: string; -} - -const TERMINAL_STATUSES: readonly PaymentStatus[] = [ - PaymentStatus.Finished, - PaymentStatus.Failed, - PaymentStatus.Expired, - PaymentStatus.Refunded, -]; - -// The money has arrived, so an address and amount on screen would invite paying a second time. -const FUNDS_RECEIVED_STATUSES: readonly PaymentStatus[] = [ - PaymentStatus.Confirming, - PaymentStatus.Confirmed, - PaymentStatus.Sending, -]; - -export default function PaymentStatusTab({ initialPaymentId = '' }: PaymentStatusTabProps) { - const t = useT(); - const { getPaymentStatus } = usePayment(); - const [paymentId, setPaymentId] = useState(initialPaymentId); - // What is polled. Separate from the input, so a half-typed id is never sent to the backend. - const [watchedId, setWatchedId] = useState(initialPaymentId); - const [paymentStatus, setPaymentStatus] = useState(null); - const [loading, setLoading] = useState(false); - const [refreshing, setRefreshing] = useState(false); - const [error, setError] = useState(null); - const [setQrcode, , isQrcodeReady] = useQrcodeDownload('payment'); - const canvasRef = useRef(null); - - const handleQrcodeReady = useCallback( - (canvas: HTMLCanvasElement | SVGSVGElement) => { - setQrcode(canvas); - if (canvas instanceof HTMLCanvasElement) canvasRef.current = canvas; - }, - [setQrcode] - ); - - const handleDownloadQr = useCallback(async () => { - const canvas = canvasRef.current; - if (!canvas) return; - const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); - if (!blob) return; - const data = Array.from(new Uint8Array(await blob.arrayBuffer())); - const filename = `payment-${paymentStatus?.order_id ?? 'qr'}.png`; - const result = await getElectron()?.tools.saveImage({ filename, data }); - const filePath = result?.filePath; - if (!filePath) return; - const electron = getElectron(); - const toastId = `qr-${Date.now()}`; - toast.custom( - () => ( -
- - {t.payment.status.qrSaved} -
- - - - - {t.exportToast.openFile} - - - - - - {t.exportToast.showInFolder} - - - - - - {t.exportToast.dismiss} - -
-
- ), - { id: toastId, duration: 10_000, style: { width: 'var(--width, 356px)' } } - ); - }, [paymentStatus?.order_id, t]); - - const paymentStatusRef = React.useRef(null); - // The id on screen, and the one asked for last: a poll of the old payment that answers after - // the user asked for another must not put the old one back. - const watchedIdRef = useRef(initialPaymentId); - const requestedIdRef = useRef(initialPaymentId); - - const handleCheckStatus = useCallback( - async (checkId: string, silent = false) => { - if (!checkId) return; - - if (silent) { - setRefreshing(true); - } else { - requestedIdRef.current = checkId; - setLoading(true); - setError(null); - } - try { - const status = await getPaymentStatus(checkId); - if (checkId !== requestedIdRef.current) return; - if (status) { - watchedIdRef.current = checkId; - setError(null); - setWatchedId(checkId); - // only update state if the object really changed - const prev = paymentStatusRef.current; - if (JSON.stringify(prev) !== JSON.stringify(status)) { - setPaymentStatus(status); - paymentStatusRef.current = status; - } - } else if (!silent) { - // A background check that fails says nothing: the payment on screen is still valid. - requestedIdRef.current = watchedIdRef.current; - setError(t.payment.status.notFound); - } - } catch (err) { - if (!silent) { - requestedIdRef.current = watchedIdRef.current; - setError(err instanceof Error ? err.message : t.payment.status.fetchFailed); - } - } finally { - if (!silent) setLoading(false); - if (silent) setRefreshing(false); - } - }, - [getPaymentStatus, t] - ); - - type CopyField = 'address' | 'amount' | 'currency'; - const [copiedField, setCopiedField] = useState(null); - const copiedFieldTimeoutRef = useRef(null); - - useEffect( - () => () => { - if (copiedFieldTimeoutRef.current) window.clearTimeout(copiedFieldTimeoutRef.current); - }, - [] - ); - - const copyToClipboard = useCallback((text: string, field: CopyField, message: string) => { - navigator.clipboard.writeText(text); - toast.success(message); - setCopiedField(field); - if (copiedFieldTimeoutRef.current) window.clearTimeout(copiedFieldTimeoutRef.current); - copiedFieldTimeoutRef.current = window.setTimeout(() => setCopiedField(null), 1500); - }, []); - - const handleCopyAddress = useCallback(() => { - if (paymentStatus?.pay_address) { - copyToClipboard(paymentStatus.pay_address, 'address', t.payment.status.addressCopied); - } - }, [paymentStatus, copyToClipboard, t]); - - const handleCopyAmount = useCallback(() => { - if (paymentStatus?.pay_amount != null) { - copyToClipboard(String(paymentStatus.pay_amount), 'amount', t.payment.status.amountCopied); - } - }, [paymentStatus, copyToClipboard, t]); - - const handleCopyCurrency = useCallback(() => { - if (paymentStatus?.pay_currency) { - copyToClipboard( - paymentStatus.pay_currency.toUpperCase(), - 'currency', - t.payment.status.currencyCopied - ); - } - }, [paymentStatus, copyToClipboard, t]); - - // Generate payment URI for wallet apps (includes amount) - // memoized so it only recalculates when status changes - const paymentUri = useMemo(() => { - if (!paymentStatus) return ''; - - const { pay_address, pay_amount, pay_currency } = paymentStatus; - const currency = pay_currency.toLowerCase(); - - // For most cryptocurrencies, the format is: currency:address?amount=value - // This is BIP21 for Bitcoin and similar standards for other cryptos - return `${currency}:${pay_address}?amount=${pay_amount}`; - }, [paymentStatus]); - - // Auto-check if initialPaymentId changes - useEffect(() => { - if (!initialPaymentId) return; - setPaymentId(initialPaymentId); - const timer = window.setTimeout(() => handleCheckStatus(initialPaymentId), 100); - return () => window.clearTimeout(timer); - }, [initialPaymentId, handleCheckStatus]); - - const isTerminal = - paymentStatus !== null && TERMINAL_STATUSES.includes(paymentStatus.payment_status); - const fundsReceived = - paymentStatus !== null && FUNDS_RECEIVED_STATUSES.includes(paymentStatus.payment_status); - const closedNotice = - paymentStatus?.payment_status === PaymentStatus.Expired - ? { title: t.payment.status.expiredTitle, body: t.payment.status.expiredBody } - : paymentStatus?.payment_status === PaymentStatus.Refunded - ? { title: t.payment.status.refundedTitle, body: t.payment.status.refundedBody } - : paymentStatus?.payment_status === PaymentStatus.Failed - ? { title: t.payment.status.failedTitle, body: t.payment.status.failedBody } - : null; - - // poll for status every 5 seconds while we have an ID and the payment - // hasn't reached a terminal state. this keeps the UI up‑to‑date without - // requiring manual clicks. - useEffect(() => { - let interval: number | null = null; - - // only poll when there's an ID and the payment hasn't reached a final state - if (watchedId && !isTerminal) { - interval = window.setInterval(() => handleCheckStatus(watchedId, true), 5000); - } - - return () => { - if (interval !== null) window.clearInterval(interval); - }; - }, [watchedId, isTerminal, handleCheckStatus]); - - return ( -
- - - {t.payment.status.title} - {t.payment.status.description} - - -
- setPaymentId(e.target.value)} - className="max-w-40" - maxLength={100} - /> - -
-
-
- - {error && ( -
-

{error}

-
- )} - - {paymentStatus && ( - - -
-
- - - {getStatusLabel(t, paymentStatus.payment_status)} - - - - {t.payment.status.order(paymentStatus.order_id)} - -
- - - {t.payment.status.refreshing} - -
-
- -
-
-

{t.payment.status.amountToPay}

-

- {paymentStatus.pay_amount} {paymentStatus.pay_currency.toUpperCase()} -

-
-
-

{t.payment.status.priceUsd}

-

- ${paymentStatus.price_amount} {paymentStatus.price_currency} -

-
- {paymentStatus.actually_paid != null && paymentStatus.actually_paid > 0 && ( -
-

{t.payment.status.actuallyPaid}

-

- {paymentStatus.actually_paid} {paymentStatus.pay_currency.toUpperCase()} -

-
- )} -
- - {/* A top-up to the original address is not matched to the order, so its QR and - address must not stay on screen once a payment is partial. */} - {paymentStatus.payment_status === PaymentStatus.PartiallyPaid && ( -
-

- {t.payment.status.partialTitle} -

-

- {t.payment.status.partialBody} -

-
- )} - - {fundsReceived && ( -
-

- {t.payment.status.receivedTitle} -

-

- {t.payment.status.receivedBody} -

-
- )} - - {!isTerminal && - !fundsReceived && - paymentStatus.payment_status !== PaymentStatus.PartiallyPaid && ( - <> -
-

{t.payment.status.paymentMethods}

- - - {t.payment.status.qrTab} - {t.payment.status.addressTab} - - - -
- -

- {t.payment.status.scanWithWallet} -

-

- {t.payment.status.qrIncludes( - `${paymentStatus.pay_amount} ${paymentStatus.pay_currency.toUpperCase()}` - )} -

-
-
- - -
-
-

- {t.payment.status.paymentAddress} -

-
- - - {paymentStatus.pay_address} - -
-
-
-

- {t.payment.status.amountToSend} -

-
-
- - - {paymentStatus.pay_amount} - -
-
- - - {paymentStatus.pay_currency.toUpperCase()} - -
-
-
-

- {t.payment.status.sendExactly} -

-
-
-
-
- - )} - - {paymentStatus.payment_status === PaymentStatus.Finished && ( -
-

- {t.payment.status.successTitle} -

-

- {t.payment.status.successBody} -

-
- )} - - {closedNotice && ( -
-

- {closedNotice.title} -

-

{closedNotice.body}

-
- )} - - {(paymentStatus.created_at || paymentStatus.updated_at) && ( -
- {paymentStatus.created_at && ( -
- {t.payment.status.created} - {new Date(paymentStatus.created_at).toLocaleString()} -
- )} - {paymentStatus.updated_at && ( -
- {t.payment.status.updated} - {new Date(paymentStatus.updated_at).toLocaleString()} -
- )} -
- )} -
-
- )} -
- ); -} diff --git a/src/renderer/components/custom/payment/payment-utils.ts b/src/renderer/components/custom/payment/payment-utils.ts deleted file mode 100644 index bf1c7789..00000000 --- a/src/renderer/components/custom/payment/payment-utils.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Payment utility functions - */ - -import type { Translation } from '@/i18n'; -import { PaymentStatus } from '@/types/payment'; - -export function getStatusBadgeColor(status: PaymentStatus): string { - switch (status) { - case PaymentStatus.Finished: - return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100'; - case PaymentStatus.Failed: - case PaymentStatus.Expired: - return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-100'; - case PaymentStatus.Waiting: - case PaymentStatus.Confirming: - return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-100'; - default: - return 'bg-muted text-muted-foreground'; - } -} - -/** - * Takes the dictionary rather than calling `useT`, because this is reached from a table cell's - * render as well as from a memoised card - a plain function either way, not a component. - * - * The fallback is the raw status string, which is what a backend ahead of this build sends: an - * untranslated code on screen is poor, and a blank badge where the status should be is worse. - */ -export function getStatusLabel(t: Translation, status: PaymentStatus): string { - switch (status) { - case PaymentStatus.Waiting: - return t.payment.statusLabels.waiting; - case PaymentStatus.Confirming: - return t.payment.statusLabels.confirming; - case PaymentStatus.Confirmed: - return t.payment.statusLabels.confirmed; - case PaymentStatus.Sending: - return t.payment.statusLabels.sending; - case PaymentStatus.PartiallyPaid: - return t.payment.statusLabels.partiallyPaid; - case PaymentStatus.Finished: - return t.payment.statusLabels.finished; - case PaymentStatus.Failed: - return t.payment.statusLabels.failed; - case PaymentStatus.Refunded: - return t.payment.statusLabels.refunded; - case PaymentStatus.Expired: - return t.payment.statusLabels.expired; - default: - return status; - } -} diff --git a/src/renderer/components/custom/payment/subscription-tab.tsx b/src/renderer/components/custom/payment/subscription-tab.tsx index 9cbb2521..af53f906 100644 --- a/src/renderer/components/custom/payment/subscription-tab.tsx +++ b/src/renderer/components/custom/payment/subscription-tab.tsx @@ -1,17 +1,10 @@ -import { Check, Search } from 'lucide-react'; -import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { Check, ExternalLink as ExternalLinkIcon, Loader2 } from 'lucide-react'; +import { useState } from 'react'; +import { toast } from 'sonner'; import ExternalLink from '@/components/custom/external-link'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Input } from '@/components/ui/input'; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from '@/components/ui/select'; import { Skeleton } from '@/components/ui/skeleton'; import { useNow } from '@/hooks/use-now'; import { usePayment } from '@/hooks/use-payment'; @@ -24,7 +17,7 @@ import { type SubscriptionSummary, } from '@/lib/subscription'; import { cn } from '@/lib/utils'; -import type { AvailableCurrency, SubscriptionPlanInfo } from '@/types/payment'; +import type { SubscriptionPlanInfo } from '@/types/payment'; interface SubscriptionTabProps { /** The free-tier balance, in credits. */ @@ -32,7 +25,6 @@ interface SubscriptionTabProps { subscription: SubscriptionSummary; /** From the backend ping; falls back to the compiled-in mirror while that has not arrived. */ creditsPerMinute?: number; - onPaymentCreated: (paymentId: string) => void; } /** How much cheaper a pass is per month than the dearest one on offer, in whole percent. */ @@ -46,43 +38,11 @@ export default function SubscriptionTab({ credits, subscription, creditsPerMinute, - onPaymentCreated, }: SubscriptionTabProps) { const t = useT(); - const { plans, currencies, loading, error, createPayment } = usePayment(); - const [selectedPlan, setSelectedPlan] = useState(null); - const [selectedCurrency, setSelectedCurrency] = useState(''); - const [creating, setCreating] = useState(false); - const [currencySearch, setCurrencySearch] = useState(''); - const [currencySelectOpen, setCurrencySelectOpen] = useState(false); - const paymentDetailsRef = useRef(null); - const currencySearchInputRef = useRef(null); - - const currencyMatches = useCallback( - (currency: AvailableCurrency) => { - const terms = currencySearch.trim().toLowerCase().split(/\s+/).filter(Boolean); - if (terms.length === 0) return true; - const haystack = `${currency.name} ${currency.code}`.toLowerCase(); - return terms.every((term) => haystack.includes(term)); - }, - [currencySearch] - ); - - const hasVisibleCurrency = useMemo( - () => currencies.some((currency) => currencyMatches(currency)), - [currencies, currencyMatches] - ); - - useEffect(() => { - if (!currencySelectOpen) return; - const id = setTimeout(() => currencySearchInputRef.current?.focus(), 0); - return () => clearTimeout(id); - }, [currencySelectOpen]); - - const handleCurrencySelectOpenChange = useCallback((open: boolean) => { - setCurrencySelectOpen(open); - if (!open) setCurrencySearch(''); - }, []); + const { plans, loading, error } = usePayment(); + // The pass whose checkout is being opened: the handoff code is a round trip to the backend. + const [opening, setOpening] = useState(null); const now = useNow(); const freeMinutes = minutesCovered(credits, creditsPerMinute); @@ -94,32 +54,19 @@ export default function SubscriptionTab({ return key === 'other' ? plan.plan : t.creditsDisplay.planNames[key]; }; - const handleSelectPlan = useCallback((plan: SubscriptionPlanInfo) => { - setSelectedPlan(plan); - setTimeout(() => { - paymentDetailsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); - }, 100); - }, []); - - const handleCreatePayment = useCallback(async () => { - if (!selectedPlan) return; - - setCreating(true); + // Checkout is the website's: it opens on that pass, signed in, and the ping picks up the new + // subscription within seconds of the payment confirming. + const openCheckout = async (plan: SubscriptionPlanInfo) => { + setOpening(plan.plan); try { - const payment = await createPayment({ - plan: selectedPlan.plan, - pay_currency: selectedCurrency || undefined, - }); - - if (payment) { - onPaymentCreated(payment.payment_id); - } - } catch (err) { - console.error('Failed to create payment:', err); + const result = await window.electronAPI?.account.openWeb('billing', plan.plan); + if (!result?.success) toast.error(t.payment.buy.openFailed); + } catch { + toast.error(t.payment.buy.openFailed); } finally { - setCreating(false); + setOpening(null); } - }, [selectedPlan, selectedCurrency, createPayment, onPaymentCreated]); + }; return (
@@ -206,7 +153,8 @@ export default function SubscriptionTab({
{plans.map((plan) => { const isPopular = plan.popular; - const isSelected = selectedPlan?.plan === plan.plan; + const isCurrent = active && subscription.plan === plan.plan; + const isOpening = opening === plan.plan; const key = planKey(plan.plan); const planName = planNameOf(plan); const planDescription = key === 'other' ? '' : t.payment.buy.planDescriptions[key]; @@ -220,17 +168,9 @@ export default function SubscriptionTab({ isPopular ? 'border-primary/60 bg-linear-to-b from-primary/10 to-card shadow-lg hover:shadow-xl' : 'shadow-sm hover:shadow-lg', - isSelected - ? 'ring-2 ring-primary bg-primary/5 shadow-xl -translate-y-0.5' - : 'hover:-translate-y-0.5' + 'hover:-translate-y-0.5' )} > - {isSelected && ( -
- -
- )} - {isPopular && (
@@ -263,27 +203,21 @@ export default function SubscriptionTab({ @@ -293,7 +227,7 @@ export default function SubscriptionTab({

- {t.payment.buy.prepaid} {t.payment.buy.refundPrompt}{' '} + {t.payment.buy.checkoutOnWeb} {t.payment.buy.prepaid} {t.payment.buy.refundPrompt}{' '}

- - {selectedPlan && ( - - - {t.payment.buy.detailsTitle} - - {t.payment.buy.detailsLead} - {planNameOf(selectedPlan)} - {t.payment.buy.detailsFor} - ${selectedPlan.priceUsd} USD - - - -
- - setCurrencySearch(e.target.value)} - onKeyDown={(e) => { - if (e.key !== 'Escape') e.stopPropagation(); - }} - placeholder={t.payment.buy.currencySearchPlaceholder} - className="h-8 pl-7 text-xs" - /> -
-
- {!hasVisibleCurrency ? ( -
- {t.payment.buy.noCurrency} -
- ) : ( - currencies.map((currency: AvailableCurrency) => ( - -
- {currency.name} - - {currency.name} ({currency.code.toUpperCase()}) - -
-
- )) - )} - - -
- - - - - )} )} diff --git a/src/renderer/components/custom/settings/password-section.tsx b/src/renderer/components/custom/settings/password-section.tsx deleted file mode 100644 index 344e7181..00000000 --- a/src/renderer/components/custom/settings/password-section.tsx +++ /dev/null @@ -1,272 +0,0 @@ -import { KeyRound } from 'lucide-react'; -import { useState } from 'react'; -import { toast } from 'sonner'; - -import { InputPassword } from '@/components/custom/input-password'; -import { Button } from '@/components/ui/button'; -import { Textarea } from '@/components/ui/textarea'; -import useAuth from '@/hooks/use-auth'; -import { useSaveHistoryGuard } from '@/hooks/use-save-history-guard'; -import { useT } from '@/i18n'; - -type Mode = 'idle' | 'change' | 'reset'; - -/** - * The password row of the account card, opening in place rather than in a dialog. - * - * It carries its own forgotten-password path because the signed-out one cannot be reached from - * here: `AuthLayout` sends a signed-in user straight back home, so a signed-in user who did not - * remember the current password had no way forward at all. - */ -export function PasswordSection({ email }: { email: string }) { - const t = useT(); - const { changePassword, forgotPassword, resetPassword, logout, loading, error, setError } = - useAuth(); - const { confirmDiscard } = useSaveHistoryGuard(); - - const [mode, setMode] = useState('idle'); - const [currentPassword, setCurrentPassword] = useState(''); - const [code, setCode] = useState(''); - const [newPassword, setNewPassword] = useState(''); - const [confirmPassword, setConfirmPassword] = useState(''); - // `loading` is shared by every request this hook makes, so it cannot say which one is running. - const [sendingCode, setSendingCode] = useState(false); - - const close = () => { - setMode('idle'); - setCurrentPassword(''); - setCode(''); - setNewPassword(''); - setConfirmPassword(''); - setError(null); - }; - - // A stale server error ("current password is incorrect") stays on screen while the user is - // correcting the very field it is about, unless editing clears it. - const edit = (setter: (value: string) => void) => (value: string) => { - setter(value); - if (error) setError(null); - }; - - // Both new fields are masked, so a mismatch is the one condition the user cannot see for - // themselves. Held back until the confirm field has something in it. - const passwordsMismatch = confirmPassword !== '' && newPassword !== confirmPassword; - const newPasswordReady = newPassword !== '' && confirmPassword !== '' && !passwordsMismatch; - const canSubmit = - newPasswordReady && (mode === 'change' ? currentPassword !== '' : code.trim() !== ''); - - // A failure is reported by the inline `error`, which carries the server's reason; a toast - // beside it would repeat it. - const sendCode = async () => { - setError(null); - setSendingCode(true); - try { - return await forgotPassword(email); - } finally { - setSendingCode(false); - } - }; - - const startReset = async () => { - if (await sendCode()) { - setCurrentPassword(''); - setMode('reset'); - } - }; - - const submit = async (e: React.FormEvent) => { - e.preventDefault(); - if (!canSubmit || loading) return; - - if (mode === 'change') { - if (await changePassword(currentPassword, newPassword)) { - toast.success(t.changePassword.succeeded); - close(); - } - return; - } - - // A reset ends every session on the account, this one included, so it is a sign-out and is - // asked about like one - before the request, while declining still leaves everything intact. - if (!(await confirmDiscard('signout'))) return; - if (!(await resetPassword(email, code.trim(), newPassword))) return; - - toast.success(t.auth.reset.succeeded); - // The token is already dead on the server. Signing out here takes the user to the sign-in - // form now, rather than leaving them on a page whose next request fails as an expiry. - // Main clears the local session even when the backend call fails, so its error is moot. - try { - await logout(); - } catch (err) { - console.warn('Sign out after password reset failed:', err); - } - }; - - if (mode === 'idle') { - return ( -
-
-
-
-

{t.account.password.title}

-

{t.account.password.description}

-
- -
- ); - } - - return ( -
-
-
-
-
-

{t.changePassword.title}

-

- {mode === 'change' ? t.changePassword.description : t.account.password.codeSent(email)} -

-
-
- - {mode === 'change' ? ( -
-
- - -
- edit(setCurrentPassword)(e.target.value)} - placeholder={t.changePassword.currentPlaceholder} - maxLength={128} - disabled={loading} - /> -
- ) : ( -
-
- - -
-