Skip to content

A local-first personal finance app

Select the user's current country as default when opening bank sync, instead of no value (uses browser locale) (#6054)

Henri Cooka2fa74ca8dd3
diff --git a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
new file mode 100644
index 0000000000..73b007b920
--- /dev/null
+++ b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.test.tsx
@@ -0,0 +1,138 @@
+import { render, screen } from '@testing-library/react';
+import { vi } from 'vitest';
+
+import { GoCardlessExternalMsgModal } from './GoCardlessExternalMsgModal';
+
+import { TestProvider } from '@desktop-client/redux/mock';
+
+vi.mock('@desktop-client/hooks/useGlobalPref', () => ({
+ useGlobalPref: () => [null],
+}));
+
+vi.mock('@desktop-client/hooks/useGoCardlessStatus', () => ({
+ useGoCardlessStatus: () => ({
+ configuredGoCardless: true,
+ isLoading: false,
+ }),
+}));
+
+describe('GoCardlessExternalMsgModal - Country Auto-selection', () => {
+ const mockProps = {
+ onMoveExternal: vi.fn(),
+ onSuccess: vi.fn(),
+ onClose: vi.fn(),
+ };
+
+ const originalIntl = global.Intl;
+ const originalNavigator = global.navigator;
+
+ afterEach(() => {
+ global.Intl = originalIntl;
+ Object.defineProperty(global, 'navigator', {
+ value: originalNavigator,
+ writable: true,
+ });
+ vi.clearAllMocks();
+ });
+
+ it('should pre-select country based on browser timezone', () => {
+ // Mock timezone to Germany
+ global.Intl = {
+ ...originalIntl,
+ DateTimeFormat: vi.fn(() => ({
+ resolvedOptions: () => ({ timeZone: 'Europe/Berlin' }),
+ })) as unknown as typeof Intl.DateTimeFormat,
+ } as typeof Intl;
+
+ Object.defineProperty(global, 'navigator', {
+ value: { language: 'en' },
+ writable: true,
+ });
+
+ render(
+ <TestProvider>
+ <GoCardlessExternalMsgModal {...mockProps} />
+ </TestProvider>,
+ );
+
+ const countryInput = screen.getByPlaceholderText('(please select)');
+ // The Autocomplete component displays the country name, not the code
+ expect(countryInput).toHaveValue('Germany');
+ });
+
+ it('should pre-select country based on locale when timezone is not in EU', () => {
+ // Mock timezone to US (not supported)
+ global.Intl = {
+ ...originalIntl,
+ DateTimeFormat: vi.fn(() => ({
+ resolvedOptions: () => ({ timeZone: 'America/New_York' }),
+ })) as unknown as typeof Intl.DateTimeFormat,
+ } as typeof Intl;
+
+ // But locale is UK
+ Object.defineProperty(global, 'navigator', {
+ value: { language: 'en-GB' },
+ writable: true,
+ });
+
+ render(
+ <TestProvider>
+ <GoCardlessExternalMsgModal {...mockProps} />
+ </TestProvider>,
+ );
+
+ const countryInput = screen.getByPlaceholderText('(please select)');
+ expect(countryInput).toHaveValue('United Kingdom');
+ });
+
+ it('should leave country empty when neither timezone nor locale match', () => {
+ // Mock timezone to US
+ global.Intl = {
+ ...originalIntl,
+ DateTimeFormat: vi.fn(() => ({
+ resolvedOptions: () => ({ timeZone: 'America/New_York' }),
+ })) as unknown as typeof Intl.DateTimeFormat,
+ } as typeof Intl;
+
+ // Locale is also US
+ Object.defineProperty(global, 'navigator', {
+ value: { language: 'en-US' },
+ writable: true,
+ });
+
+ render(
+ <TestProvider>
+ <GoCardlessExternalMsgModal {...mockProps} />
+ </TestProvider>,
+ );
+
+ const countryInput = screen.getByPlaceholderText('(please select)');
+ expect(countryInput).toHaveValue('');
+ });
+
+ it('should prioritize timezone over locale', () => {
+ // Mock timezone to France
+ global.Intl = {
+ ...originalIntl,
+ DateTimeFormat: vi.fn(() => ({
+ resolvedOptions: () => ({ timeZone: 'Europe/Paris' }),
+ })) as unknown as typeof Intl.DateTimeFormat,
+ } as typeof Intl;
+
+ // Locale is German
+ Object.defineProperty(global, 'navigator', {
+ value: { language: 'de-DE' },
+ writable: true,
+ });
+
+ render(
+ <TestProvider>
+ <GoCardlessExternalMsgModal {...mockProps} />
+ </TestProvider>,
+ );
+
+ const countryInput = screen.getByPlaceholderText('(please select)');
+ // Should select France from timezone, not Germany from locale
+ expect(countryInput).toHaveValue('France');
+ });
+});
diff --git a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
index b86eb4d49f..bea6fa5810 100644
--- a/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
+++ b/packages/desktop-client/src/components/modals/GoCardlessExternalMsgModal.tsx
@@ -24,6 +24,8 @@ import {
} from '@desktop-client/components/common/Modal';
import { FormField, FormLabel } from '@desktop-client/components/forms';
import { COUNTRY_OPTIONS } from '@desktop-client/components/util/countries';
+import { getCountryFromBrowser } from '@desktop-client/components/util/localeToCountry';
+import { useGlobalPref } from '@desktop-client/hooks/useGlobalPref';
import { useGoCardlessStatus } from '@desktop-client/hooks/useGoCardlessStatus';
import {
type Modal as ModalType,
@@ -99,11 +101,21 @@ export function GoCardlessExternalMsgModal({
const { t } = useTranslation();
const dispatch = useDispatch();
+ const [language] = useGlobalPref('language');
+
+ const browserTimezone =
+ Intl.DateTimeFormat().resolvedOptions().timeZone || '';
+ const browserLocale = language || navigator.language || 'en-US';
+ const detectedCountry = getCountryFromBrowser(
+ browserTimezone,
+ browserLocale,
+ COUNTRY_OPTIONS,
+ );
const [waiting, setWaiting] = useState<string | null>(null);
const [success, setSuccess] = useState<boolean>(false);
const [institutionId, setInstitutionId] = useState<string>();
- const [country, setCountry] = useState<string>();
+ const [country, setCountry] = useState<string | undefined>(detectedCountry);
const [error, setError] = useState<{
code: 'unknown' | 'timeout';
message?: string;
diff --git a/packages/desktop-client/src/components/util/localeToCountry.ts b/packages/desktop-client/src/components/util/localeToCountry.ts
new file mode 100644
index 0000000000..917ee2b631
--- /dev/null
+++ b/packages/desktop-client/src/components/util/localeToCountry.ts
@@ -0,0 +1,134 @@
+export type CountryOption = {
+ id: string;
+ name: string;
+};
+
+/**
+ * Mapping of IANA timezone identifiers to ISO 3166-1 alpha-2 country codes
+ * for European countries supported by GoCardless.
+ *
+ * Note: We use a manual mapping instead of a library (e.g., countries-and-timezones)
+ * because GoCardless only supports 30 European countries. A manual mapping is ~2KB
+ * vs 316KB+ for worldwide timezone libraries. This keeps the bundle size small and
+ * makes the mapping explicit, type-safe, and easy to audit.
+ */
+const TIMEZONE_TO_COUNTRY: Record<string, string> = {
+ // Austria
+ 'Europe/Vienna': 'AT',
+ // Belgium
+ 'Europe/Brussels': 'BE',
+ // Bulgaria
+ 'Europe/Sofia': 'BG',
+ // Croatia
+ 'Europe/Zagreb': 'HR',
+ // Cyprus
+ 'Asia/Nicosia': 'CY',
+ 'Europe/Nicosia': 'CY',
+ // Czechia
+ 'Europe/Prague': 'CZ',
+ // Denmark
+ 'Europe/Copenhagen': 'DK',
+ // Estonia
+ 'Europe/Tallinn': 'EE',
+ // Finland
+ 'Europe/Helsinki': 'FI',
+ 'Europe/Mariehamn': 'FI',
+ // France
+ 'Europe/Paris': 'FR',
+ // Germany
+ 'Europe/Berlin': 'DE',
+ 'Europe/Busingen': 'DE',
+ // Greece
+ 'Europe/Athens': 'GR',
+ // Hungary
+ 'Europe/Budapest': 'HU',
+ // Iceland
+ 'Atlantic/Reykjavik': 'IS',
+ // Ireland
+ 'Europe/Dublin': 'IE',
+ // Italy
+ 'Europe/Rome': 'IT',
+ // Latvia
+ 'Europe/Riga': 'LV',
+ // Liechtenstein
+ 'Europe/Vaduz': 'LI',
+ // Lithuania
+ 'Europe/Vilnius': 'LT',
+ // Luxembourg
+ 'Europe/Luxembourg': 'LU',
+ // Malta
+ 'Europe/Malta': 'MT',
+ // Netherlands
+ 'Europe/Amsterdam': 'NL',
+ // Norway
+ 'Europe/Oslo': 'NO',
+ // Poland
+ 'Europe/Warsaw': 'PL',
+ // Portugal
+ 'Europe/Lisbon': 'PT',
+ 'Atlantic/Madeira': 'PT',
+ 'Atlantic/Azores': 'PT',
+ // Romania
+ 'Europe/Bucharest': 'RO',
+ // Slovakia
+ 'Europe/Bratislava': 'SK',
+ // Slovenia
+ 'Europe/Ljubljana': 'SI',
+ // Spain
+ 'Europe/Madrid': 'ES',
+ 'Africa/Ceuta': 'ES',
+ 'Atlantic/Canary': 'ES',
+ // Sweden
+ 'Europe/Stockholm': 'SE',
+ // United Kingdom
+ 'Europe/London': 'GB',
+};
+
+/**
+ * Detects a country code based on browser timezone and locale, prioritizing
+ * timezone as it's a better indicator of physical location.
+ *
+ * @param timezone - Browser timezone (e.g., "Europe/Berlin")
+ * @param locale - Browser locale string (e.g., "en-GB", "de-DE")
+ * @param supportedCountries - Array of country options with id (ISO 3166-1 alpha-2 codes)
+ * @returns The country code if found and supported, undefined otherwise
+ *
+ * @example
+ * getCountryFromBrowser("Europe/Berlin", "en", countries) // Returns "DE" (timezone wins)
+ * getCountryFromBrowser("America/New_York", "en-GB", countries) // Returns "GB" (locale fallback)
+ * getCountryFromBrowser("America/New_York", "en-US", countries) // Returns undefined (neither match)
+ */
+export function getCountryFromBrowser(
+ timezone: string,
+ locale: string,
+ supportedCountries: CountryOption[],
+): string | undefined {
+ // Try timezone first - it's the most accurate indicator of physical location
+ if (timezone) {
+ const countryFromTimezone = TIMEZONE_TO_COUNTRY[timezone];
+ if (
+ countryFromTimezone &&
+ supportedCountries.some(country => country.id === countryFromTimezone)
+ ) {
+ return countryFromTimezone;
+ }
+ }
+
+ // Fall back to locale detection (language setting)
+ // Parse from the end to handle BCP 47 locales with script subtags (e.g., en-Latn-GB)
+ if (locale) {
+ const parts = locale.split(/[-_]/);
+ for (let index = parts.length - 1; index >= 1; index -= 1) {
+ const part = parts[index];
+ if (/^[A-Za-z]{2}$/.test(part)) {
+ const countryCode = part.toUpperCase();
+ if (supportedCountries.some(country => country.id === countryCode)) {
+ return countryCode;
+ }
+ break;
+ }
+ }
+ }
+
+ return undefined;
+}
diff --git a/upcoming-release-notes/6054.md b/upcoming-release-notes/6054.md
new file mode 100644
index 0000000000..cd7876f655
--- /dev/null
+++ b/upcoming-release-notes/6054.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [henricook]
+---
+
+Auto-select country in GoCardless bank sync based on browser timezone and locale