mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 11:06:06 +00:00
feat(mobile): the admin services section gets what the desktop tab has
- Place search and routing as one card, as on the desktop: TREK's own services, today's allowance with a new identity behind a confirm sheet (MAdminServiceQuota), sharing place details (MAdminPlaceContrib), the transit backend and the place search provider as TREK selects, and the search log. - The key card holds Google (with its options and the daily request cap, MAdminGoogleDailyLimit), Unsplash and Amap, in the desktop order. - The logic both views need moves into one place: the transit switch into useAdminSettingsActions, the allowance figures into serviceIdentityModel, and the share-place-details panel into usePlaceContribPanel. - MAdminSettingsSection renders each section in a function of its own. - Tests follow the split admin sections (Save order, 2FA label, field marker).
This commit is contained in:
@@ -1,26 +1,16 @@
|
||||
import type { PlaceContribField, PlaceContribState } from '@trek/shared';
|
||||
import type { PlaceContribState } from '@trek/shared';
|
||||
import { HeartHandshake, Undo2 } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { SettingsCard, StatusPill } from '../Settings/settingsKit';
|
||||
import ToggleSwitch from '../Settings/ToggleSwitch';
|
||||
import ConfirmDialog from '../shared/ConfirmDialog';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { FigureBadge } from '../Tours/paddle/FigureBadge';
|
||||
import PlaceContribLog from './PlaceContribLog';
|
||||
import {
|
||||
contribNote,
|
||||
contribStatus,
|
||||
fieldEntries,
|
||||
fieldLabel,
|
||||
refusalReason,
|
||||
type ContribStatus,
|
||||
} from './placeContribModel';
|
||||
import { contribNote, fieldEntries, fieldLabel, type ContribStatus } from './placeContribModel';
|
||||
import PlaceContribPrompt from './PlaceContribPrompt';
|
||||
import { usePlaceContrib } from './usePlaceContrib';
|
||||
import { usePlaceContribPanel } from './usePlaceContribPanel';
|
||||
|
||||
const PILL_TONE: Record<ContribStatus, 'success' | 'warning' | 'neutral'> = {
|
||||
active: 'success',
|
||||
@@ -61,54 +51,12 @@ function Figures({ state, t }: { state: PlaceContribState; t: TranslationFn }) {
|
||||
* way to take everything back. Turning it on for the first time opens the same
|
||||
* prompt an admin gets on the first visit, so an agreement always comes from it.
|
||||
*/
|
||||
/**
|
||||
* Standing alone (managed settings), a card that can only say "not available"
|
||||
* because the operator switched sharing off is a dead end.
|
||||
*/
|
||||
function hiddenAlone(state: PlaceContribState, alone: boolean): boolean {
|
||||
return alone && state.ineligibleReason === 'env_off';
|
||||
}
|
||||
|
||||
export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const contrib = usePlaceContrib();
|
||||
const { state } = contrib;
|
||||
const [prompting, setPrompting] = useState<boolean | null>(null);
|
||||
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
|
||||
const panel = usePlaceContribPanel({ hideWhenSwitchedOff });
|
||||
const { contrib, state, status, on, confirm, setConfirm, toggleField, withdraw } = panel;
|
||||
|
||||
if (!state) return null;
|
||||
if (hiddenAlone(state, hideWhenSwitchedOff)) return null;
|
||||
const status = contribStatus(state);
|
||||
const agreed = state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
|
||||
// The prompt opens by itself once per visit while the server asks for it.
|
||||
const showPrompt = prompting ?? state.showPrompt;
|
||||
|
||||
const fail = (err: unknown) => {
|
||||
const reason = refusalReason(err);
|
||||
toast.error(
|
||||
reason === 'terms_outdated' || reason === 'no_field'
|
||||
? t(`admin.contribute.refused.${reason}`)
|
||||
: getApiErrorMessage(err, t('common.error'))
|
||||
);
|
||||
};
|
||||
|
||||
const toggleField = (field: PlaceContribField) => {
|
||||
const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };
|
||||
if (!Object.values(fields).some(Boolean)) {
|
||||
setConfirm('off');
|
||||
return;
|
||||
}
|
||||
contrib.decide({ action: 'fields', fields }).catch(fail);
|
||||
};
|
||||
|
||||
const withdraw = () => {
|
||||
setConfirm(null);
|
||||
contrib.withdraw().then((r) => {
|
||||
const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);
|
||||
toast.success(t('admin.contribute.withdrawn', { total }));
|
||||
}, fail);
|
||||
};
|
||||
if (panel.hidden || !state || !status) return null;
|
||||
|
||||
return (
|
||||
<SettingsCard
|
||||
@@ -119,15 +67,15 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid
|
||||
hint={contribNote(t, state)}
|
||||
action={
|
||||
<ToggleSwitch
|
||||
on={agreed && state.consent.enabled}
|
||||
on={on}
|
||||
label={t('admin.contribute.title')}
|
||||
disabled={!state.eligible || contrib.busy}
|
||||
onToggle={() => (agreed && state.consent.enabled ? setConfirm('off') : setPrompting(true))}
|
||||
onToggle={panel.toggleMain}
|
||||
/>
|
||||
}
|
||||
bodyClassName="flex flex-col gap-3 p-4"
|
||||
>
|
||||
{agreed && state.consent.enabled && (
|
||||
{on && (
|
||||
<>
|
||||
<Figures state={state} t={t} />
|
||||
<ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">
|
||||
@@ -151,7 +99,7 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid
|
||||
</>
|
||||
)}
|
||||
|
||||
{(agreed || state.consent.decision === 'off') && (
|
||||
{panel.showLog && (
|
||||
<div className="overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">
|
||||
{/* A plain section head: the settings fold nothing away. */}
|
||||
<div className="flex items-center gap-2.5 px-3.5 py-2.5">
|
||||
@@ -175,16 +123,11 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showPrompt && state.eligible && (
|
||||
<PlaceContribPrompt state={state} contrib={contrib} onClose={() => setPrompting(false)} />
|
||||
)}
|
||||
{panel.showPrompt && <PlaceContribPrompt state={state} contrib={contrib} onClose={panel.closePrompt} />}
|
||||
<ConfirmDialog
|
||||
isOpen={confirm === 'off'}
|
||||
onClose={() => setConfirm(null)}
|
||||
onConfirm={() => {
|
||||
setConfirm(null);
|
||||
contrib.decide({ action: 'off' }).catch(fail);
|
||||
}}
|
||||
onConfirm={panel.switchOff}
|
||||
title={t('admin.contribute.offTitle')}
|
||||
message={t('admin.contribute.offMessage')}
|
||||
confirmLabel={t('admin.contribute.offConfirm')}
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
|
||||
import type { ServiceAllowance, ServiceIdentityState } from '@trek/shared';
|
||||
import { MapPin, RefreshCw, Route, Search, Signal, type LucideIcon } from 'lucide-react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { formatClockTime } from '../../utils/formatters';
|
||||
import { SettingsCard } from '../Settings/settingsKit';
|
||||
import ConfirmDialog from '../shared/ConfirmDialog';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { FigureBadge } from '../Tours/paddle/FigureBadge';
|
||||
import {
|
||||
allowanceNote,
|
||||
canRegenerateKey,
|
||||
identityHint,
|
||||
quotaLevel,
|
||||
quotaResetClock,
|
||||
quotaShare,
|
||||
type QuotaLevel,
|
||||
} from './serviceIdentityModel';
|
||||
import { useServiceIdentity } from './useServiceIdentity';
|
||||
|
||||
const STATE_DOT: Record<ServiceIdentityState, string> = {
|
||||
@@ -23,32 +30,8 @@ const STATE_DOT: Record<ServiceIdentityState, string> = {
|
||||
const SERVICE_ICON: Record<string, LucideIcon> = { places: MapPin, photon: Search, valhalla: Route };
|
||||
|
||||
/** Below a tenth of the day left the bar turns amber, at nothing left red. */
|
||||
function barTone(quota: ServiceQuotaView): string {
|
||||
if (quota.remaining === 0) return 'bg-danger';
|
||||
return quota.remaining < quota.limit / 10 ? 'bg-warning' : 'bg-accent';
|
||||
}
|
||||
|
||||
function figureTone(quota: ServiceQuotaView): string {
|
||||
if (quota.remaining === 0) return 'text-danger';
|
||||
return quota.remaining < quota.limit / 10 ? 'text-warning' : 'text-content';
|
||||
}
|
||||
|
||||
/** The clock time the counts start again, in the user's format; one for all services, which share the day. */
|
||||
function useResetTime(status: ServiceIdentityStatus | null): string | null {
|
||||
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
|
||||
const at = status?.services.find((s) => s.quota)?.quota?.resetAt;
|
||||
if (!at) return null;
|
||||
const reset = new Date(at);
|
||||
return formatClockTime(
|
||||
`${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,
|
||||
is12h
|
||||
);
|
||||
}
|
||||
|
||||
function tileNote(t: TranslationFn, allowance: ServiceAllowance): string | null {
|
||||
if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');
|
||||
return allowance.quota ? null : t('admin.trekApi.quota.unavailable');
|
||||
}
|
||||
const BAR_TONE: Record<QuotaLevel, string> = { ok: 'bg-accent', low: 'bg-warning', out: 'bg-danger' };
|
||||
const FIGURE_TONE: Record<QuotaLevel, string> = { ok: 'text-content', low: 'text-warning', out: 'text-danger' };
|
||||
|
||||
/**
|
||||
* One service under the key, as a tile: what is left today as the figure that
|
||||
@@ -59,10 +42,10 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const number = new Intl.NumberFormat(locale);
|
||||
const name = t(`admin.trekApi.quota.service.${allowance.service}`);
|
||||
const note = tileNote(t, allowance);
|
||||
const note = allowanceNote(t, allowance);
|
||||
const quota = allowance.quota;
|
||||
const Icon = SERVICE_ICON[allowance.service] ?? MapPin;
|
||||
const share = quota && quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;
|
||||
const share = quota ? quotaShare(quota) : 100;
|
||||
|
||||
// One row per service: its name, the day's use as a bar, used of the limit.
|
||||
return (
|
||||
@@ -83,7 +66,7 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
|
||||
className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-surface-tertiary"
|
||||
>
|
||||
<div
|
||||
className={`h-full rounded-full transition-[width] duration-500 ${barTone(quota)}`}
|
||||
className={`h-full rounded-full transition-[width] duration-500 ${BAR_TONE[quotaLevel(quota)]}`}
|
||||
style={{ width: `${share}%` }}
|
||||
/>
|
||||
</div>
|
||||
@@ -91,7 +74,7 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
|
||||
className="flex-none text-caption tabular-nums text-content-faint"
|
||||
title={`${t('admin.trekApi.quota.remaining')}: ${number.format(quota.remaining)}`}
|
||||
>
|
||||
<span className={`font-semibold ${figureTone(quota)}`}>{number.format(quota.used)}</span>
|
||||
<span className={`font-semibold ${FIGURE_TONE[quotaLevel(quota)]}`}>{number.format(quota.used)}</span>
|
||||
{' / '}
|
||||
{number.format(quota.limit)}
|
||||
</span>
|
||||
@@ -103,11 +86,6 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
|
||||
);
|
||||
}
|
||||
|
||||
function stateHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {
|
||||
if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;
|
||||
return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* How this installation stands with the TREK services: whether it has its key,
|
||||
* and for place search, address search and routing today's allowance against
|
||||
@@ -121,7 +99,8 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo
|
||||
const panel = useRef<HTMLDivElement>(null);
|
||||
const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const resetAt = useResetTime(status);
|
||||
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
|
||||
const resetAt = quotaResetClock(status, is12h);
|
||||
|
||||
const confirmRegenerate = async () => {
|
||||
setConfirming(false);
|
||||
@@ -133,8 +112,8 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo
|
||||
}
|
||||
};
|
||||
|
||||
const hint = stateHint(t, status, failed);
|
||||
const canRegenerate = !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';
|
||||
const hint = identityHint(t, status, failed);
|
||||
const canRegenerate = canRegenerateKey(status, managed);
|
||||
|
||||
return (
|
||||
<div ref={panel}>
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// FE-ADMIN-SVCMODEL-001 to FE-ADMIN-SVCMODEL-006
|
||||
import type { ServiceIdentityStatus } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
allowanceNote,
|
||||
canRegenerateKey,
|
||||
identityHint,
|
||||
quotaLevel,
|
||||
quotaResetClock,
|
||||
quotaShare,
|
||||
} from './serviceIdentityModel';
|
||||
|
||||
const t = (key: string) => key;
|
||||
const quota = (used: number, limit: number) => ({
|
||||
used,
|
||||
limit,
|
||||
remaining: limit - used,
|
||||
resetAt: '2026-11-15T01:30:00',
|
||||
});
|
||||
const STATUS: ServiceIdentityStatus = {
|
||||
state: 'connected',
|
||||
tier: 'std',
|
||||
keySource: 'registered',
|
||||
services: [
|
||||
{ service: 'places', inUse: true, quota: quota(10, 100) },
|
||||
{ service: 'photon', inUse: false, quota: null },
|
||||
],
|
||||
lastSeenAt: null,
|
||||
} as ServiceIdentityStatus;
|
||||
|
||||
describe('serviceIdentityModel', () => {
|
||||
it('FE-ADMIN-SVCMODEL-001: a day is ok, low below a tenth left, out at nothing left', () => {
|
||||
expect(quotaLevel(quota(10, 100))).toBe('ok');
|
||||
expect(quotaLevel(quota(95, 100))).toBe('low');
|
||||
expect(quotaLevel(quota(100, 100))).toBe('out');
|
||||
});
|
||||
|
||||
it('FE-ADMIN-SVCMODEL-002: the bar share is capped at the whole and full without a limit', () => {
|
||||
expect(quotaShare(quota(25, 100))).toBe(25);
|
||||
expect(quotaShare({ used: 150, limit: 100, remaining: 0, resetAt: '' })).toBe(100);
|
||||
expect(quotaShare({ used: 0, limit: 0, remaining: 0, resetAt: '' })).toBe(100);
|
||||
});
|
||||
|
||||
it('FE-ADMIN-SVCMODEL-003: the reset reads from the first counted service, in the user format', () => {
|
||||
expect(quotaResetClock(STATUS, false)).toBe('01:30');
|
||||
expect(quotaResetClock(STATUS, true)).toMatch(/1:30/);
|
||||
expect(quotaResetClock(null, false)).toBeNull();
|
||||
expect(quotaResetClock({ ...STATUS, services: [] }, false)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-SVCMODEL-004: a service out of use, or without a count, says so', () => {
|
||||
expect(allowanceNote(t, STATUS.services[1])).toBe('admin.trekApi.quota.notInUse');
|
||||
expect(allowanceNote(t, { service: 'places', inUse: true, quota: null })).toBe('admin.trekApi.quota.unavailable');
|
||||
expect(allowanceNote(t, STATUS.services[0])).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-SVCMODEL-005: the identity line is quiet when connected', () => {
|
||||
expect(identityHint(t, STATUS, false)).toBeNull();
|
||||
expect(identityHint(t, { ...STATUS, state: 'revoked' }, false)).toBe('admin.trekApi.quota.hint.revoked');
|
||||
expect(identityHint(t, null, true)).toBe('admin.trekApi.quota.unavailable');
|
||||
expect(identityHint(t, null, false)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ADMIN-SVCMODEL-006: a new key only where the admin holds the key', () => {
|
||||
expect(canRegenerateKey(STATUS, false)).toBe(true);
|
||||
expect(canRegenerateKey(STATUS, true)).toBe(false);
|
||||
expect(canRegenerateKey({ ...STATUS, keySource: 'env' }, false)).toBe(false);
|
||||
expect(canRegenerateKey({ ...STATUS, state: 'off' }, false)).toBe(false);
|
||||
expect(canRegenerateKey(null, false)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ServiceAllowance, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { formatClockTime } from '../../utils/formatters';
|
||||
|
||||
/**
|
||||
* What the allowance panels (desktop ServiceIdentityPanel, phone MAdminServiceQuota)
|
||||
* read from the service identity status. Pure, so both views show the same thing.
|
||||
*/
|
||||
|
||||
/** How much of a service's day is left: plenty, below a tenth, or nothing. */
|
||||
export type QuotaLevel = 'ok' | 'low' | 'out';
|
||||
|
||||
export function quotaLevel(quota: ServiceQuotaView): QuotaLevel {
|
||||
if (quota.remaining === 0) return 'out';
|
||||
return quota.remaining < quota.limit / 10 ? 'low' : 'ok';
|
||||
}
|
||||
|
||||
/** The share of the day used, for the bar; a quota without a limit reads as full. */
|
||||
export function quotaShare(quota: ServiceQuotaView): number {
|
||||
return quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;
|
||||
}
|
||||
|
||||
/** The clock time the counts start again, in the user's format; one for all services, which share the day. */
|
||||
export function quotaResetClock(status: ServiceIdentityStatus | null, is12h: boolean): string | null {
|
||||
const at = status?.services.find((s) => s.quota)?.quota?.resetAt;
|
||||
if (!at) return null;
|
||||
const reset = new Date(at);
|
||||
return formatClockTime(
|
||||
`${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,
|
||||
is12h
|
||||
);
|
||||
}
|
||||
|
||||
/** A service that is not in use, or whose count the service did not report, says so under its row. */
|
||||
export function allowanceNote(t: TranslationFn, allowance: ServiceAllowance): string | null {
|
||||
if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');
|
||||
return allowance.quota ? null : t('admin.trekApi.quota.unavailable');
|
||||
}
|
||||
|
||||
/** A line about the identity itself, when it is not simply connected (or could not be read). */
|
||||
export function identityHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {
|
||||
if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;
|
||||
return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);
|
||||
}
|
||||
|
||||
/** A new key can be asked for unless the operator holds it (managed, environment) or the services are off. */
|
||||
export function canRegenerateKey(status: ServiceIdentityStatus | null, managed: boolean): boolean {
|
||||
return !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';
|
||||
}
|
||||
@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({
|
||||
updatePlacesDetails: vi.fn(),
|
||||
updatePlacesEnrich: vi.fn(),
|
||||
updatePlaceShadow: vi.fn(),
|
||||
updateTransitProvider: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../api/client', () => ({
|
||||
adminApi: {
|
||||
@@ -22,6 +23,7 @@ vi.mock('../../api/client', () => ({
|
||||
updatePlacesDetails: api.updatePlacesDetails,
|
||||
updatePlacesEnrich: api.updatePlacesEnrich,
|
||||
updatePlaceShadow: api.updatePlaceShadow,
|
||||
updateTransitProvider: api.updateTransitProvider,
|
||||
},
|
||||
authApi: { updateAppSettings: api.updateAppSettings },
|
||||
}));
|
||||
@@ -51,6 +53,9 @@ function host(over: Record<string, unknown> = {}) {
|
||||
setPlacesEnrichEnabled: vi.fn(),
|
||||
setPlaceShadowEnabledState: vi.fn(),
|
||||
setPlaceShadowEnabled: vi.fn(),
|
||||
transitProvider: 'transitous' as const,
|
||||
setTransitProviderState: vi.fn(),
|
||||
setTransitGoogleKeySource: vi.fn(),
|
||||
...over,
|
||||
};
|
||||
}
|
||||
@@ -140,4 +145,30 @@ describe('useAdminSettingsActions', () => {
|
||||
expect(admin.setPlacesDetailsEnabledState).toHaveBeenCalledWith(false);
|
||||
expect(admin.setPlacesEnrichEnabled).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('FE-HOOK-ADMSETACT-T01: switching the transit backend shows it at once and keeps the key source the server reports', async () => {
|
||||
api.updateTransitProvider.mockResolvedValueOnce({ provider: 'google', googleKeySource: 'instance' });
|
||||
const { admin, actions } = mount();
|
||||
await act(() => actions.changeTransitProvider('google'));
|
||||
expect(admin.setTransitProviderState).toHaveBeenCalledWith('google');
|
||||
expect(api.updateTransitProvider).toHaveBeenCalledWith('google');
|
||||
expect(admin.setTransitGoogleKeySource).toHaveBeenCalledWith('instance');
|
||||
});
|
||||
|
||||
it('FE-HOOK-ADMSETACT-T02: picking the backend already set writes nothing', async () => {
|
||||
api.updateTransitProvider.mockClear();
|
||||
const { admin, actions } = mount();
|
||||
await act(() => actions.changeTransitProvider('transitous'));
|
||||
expect(api.updateTransitProvider).not.toHaveBeenCalled();
|
||||
expect(admin.setTransitProviderState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-HOOK-ADMSETACT-T03: a failed save puts the previous backend back and says why', async () => {
|
||||
api.updateTransitProvider.mockRejectedValueOnce(new Error('down'));
|
||||
const { admin, actions } = mount();
|
||||
await act(() => actions.changeTransitProvider('google'));
|
||||
expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(1, 'google');
|
||||
expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(2, 'transitous');
|
||||
expect(admin.toast.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TransitKeySource, TransitProvider } from '@trek/shared';
|
||||
import { adminApi, authApi } from '../../api/client';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../types';
|
||||
@@ -28,6 +29,9 @@ interface SettingsActionsHost {
|
||||
setPlacesEnrichEnabled: Flag;
|
||||
setPlaceShadowEnabledState: Flag;
|
||||
setPlaceShadowEnabled: Flag;
|
||||
transitProvider: TransitProvider;
|
||||
setTransitProviderState: (provider: TransitProvider) => void;
|
||||
setTransitGoogleKeySource: (source: TransitKeySource) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,9 +90,29 @@ export function useAdminSettingsActions(admin: SettingsActionsHost, t: Translati
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* The transit backend (#1699): shown at once, and back to the previous one with a
|
||||
* word when the save fails, so a select that springs back does not read as broken.
|
||||
* A pick of the provider already selected writes nothing: the route is audited.
|
||||
*/
|
||||
const changeTransitProvider = async (value: string) => {
|
||||
if (value === admin.transitProvider) return;
|
||||
const next: TransitProvider = value === 'google' ? 'google' : 'transitous';
|
||||
const previous = admin.transitProvider;
|
||||
admin.setTransitProviderState(next);
|
||||
try {
|
||||
const saved = await adminApi.updateTransitProvider(next);
|
||||
admin.setTransitGoogleKeySource(saved.googleKeySource);
|
||||
} catch (err: unknown) {
|
||||
admin.setTransitProviderState(previous);
|
||||
toast.error(getApiErrorMessage(err, t('common.error')));
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
saveOidc,
|
||||
saveFileTypes,
|
||||
changeTransitProvider,
|
||||
togglePlacesPhotos: placeSwitch(admin.setPlacesPhotosEnabledState, admin.setPlacesPhotosEnabled, (enabled) =>
|
||||
adminApi.updatePlacesPhotos(enabled)
|
||||
),
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { PlaceContribField } from '@trek/shared';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { contribStatus, refusalReason } from './placeContribModel';
|
||||
import { usePlaceContrib } from './usePlaceContrib';
|
||||
|
||||
/**
|
||||
* What the share-place-details panels (desktop PlaceContribPanel, phone
|
||||
* MAdminPlaceContrib) do: the main switch (on asks for consent first, off asks
|
||||
* to confirm), one switch per field (switching the last one off is switching the
|
||||
* whole thing off), withdrawing what was shared, and the words for a refusal.
|
||||
*/
|
||||
export function usePlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const contrib = usePlaceContrib();
|
||||
const { state } = contrib;
|
||||
const [prompting, setPrompting] = useState<boolean | null>(null);
|
||||
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
|
||||
|
||||
const fail = (err: unknown) => {
|
||||
const reason = refusalReason(err);
|
||||
toast.error(
|
||||
reason === 'terms_outdated' || reason === 'no_field'
|
||||
? t(`admin.contribute.refused.${reason}`)
|
||||
: getApiErrorMessage(err, t('common.error'))
|
||||
);
|
||||
};
|
||||
|
||||
// Shown on its own (a managed install), a switch the environment turned off is
|
||||
// no decision of the admin's, so the panel stays away.
|
||||
const hidden = !state || (hideWhenSwitchedOff && state.ineligibleReason === 'env_off');
|
||||
const agreed = !!state && state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
|
||||
const on = agreed && !!state?.consent.enabled;
|
||||
|
||||
const toggleField = (field: PlaceContribField) => {
|
||||
if (!state) return;
|
||||
const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };
|
||||
if (!Object.values(fields).some(Boolean)) {
|
||||
setConfirm('off');
|
||||
return;
|
||||
}
|
||||
contrib.decide({ action: 'fields', fields }).catch(fail);
|
||||
};
|
||||
|
||||
const switchOff = () => {
|
||||
setConfirm(null);
|
||||
contrib.decide({ action: 'off' }).catch(fail);
|
||||
};
|
||||
|
||||
const withdraw = () => {
|
||||
setConfirm(null);
|
||||
contrib.withdraw().then((r) => {
|
||||
const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);
|
||||
toast.success(t('admin.contribute.withdrawn', { total }));
|
||||
}, fail);
|
||||
};
|
||||
|
||||
return {
|
||||
contrib,
|
||||
state,
|
||||
hidden,
|
||||
status: state ? contribStatus(state) : null,
|
||||
agreed,
|
||||
on,
|
||||
/** The log and the withdraw action: once agreed, and still after switching off. */
|
||||
showLog: agreed || state?.consent.decision === 'off',
|
||||
showPrompt: !!state && (prompting ?? state.showPrompt) && state.eligible,
|
||||
toggleMain: () => (on ? setConfirm('off') : setPrompting(true)),
|
||||
closePrompt: () => setPrompting(false),
|
||||
confirm,
|
||||
setConfirm,
|
||||
toggleField,
|
||||
switchOff,
|
||||
withdraw,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user