frontend phase 3: geography — addresses, map-pin picker & nurse coverage areas

Three domain services (mirroring the patients/nurse template): services/geography
(cached province→city→district lookups; Infinity staleTime + shared geographyKeys),
services/addresses (address book CRUD + set-primary; single-primary invariant), and
services/serviceAreas (coverage add/remove; areaExists dup-guard, districtId=null = whole city).

Four tested composites in src/components/geography: CascadingRegionSelect (drives the
cascade queries), AddressMapPicker (map-pin stand-in emitting real lat/lng), AddressForm,
AddressCard. Screens: customer address book (/addresses, reached from the profile hub) and
nurse coverage editor (/nurse/coverage, new sidebar tab, inline duplicate block + 409).

Adds geo/address/coverage i18n namespaces (both locales), location/delete/coverage icons,
ADDRESSES/NURSE_COVERAGE routes. Consumes the b4 geography-addresses contract; filed REQ-008
(accept the map pin on create/update) and REQ-009 (provinceId on CustomerAddressDto) for gaps.

Gate: npm run check + npm run test:ci (129, +17) + npm run build all green. A 5-dimension
adversarial review fixed 3 findings (map-marker RTL transform, page_size→pageSize pagination
casing, coverage districts-scope dead-end on district-less cities).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamid
2026-07-05 14:50:41 +03:30
parent 1c266523bc
commit b8934f531d
56 changed files with 2627 additions and 3 deletions
@@ -0,0 +1,216 @@
'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import {
Box,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Paper,
Skeleton,
Stack,
Typography,
} from '@mui/material';
import { AppButton, AppIcon } from '@/components';
import { AddressCard, AddressForm } from '@/components/geography';
import {
useAddresses,
useCreateAddress,
useUpdateAddress,
useDeleteAddress,
useSetPrimaryAddress,
} from '@/services/addresses';
import type { CreateAddressInput, CustomerAddress } from '@/services/addresses/types';
/**
* The customer address book — a cached, invalidate-on-mutation list of the customer's saved
* addresses with add/edit (the cascading dropdowns + map pin in a dialog), soft-delete (confirm),
* and set-primary (exactly one badge). Loading skeleton + empty state both handled. The chosen
* address later feeds the f7 booking request.
*/
export default function AddressesPage() {
const t = useTranslations('address');
const tc = useTranslations('common');
const locale = useLocale();
const { enqueueSnackbar } = useSnackbar();
const { data, isLoading } = useAddresses();
const createAddress = useCreateAddress();
const updateAddress = useUpdateAddress();
const deleteAddress = useDeleteAddress();
const setPrimary = useSetPrimaryAddress();
const [formOpen, setFormOpen] = useState(false);
const [editing, setEditing] = useState<CustomerAddress | null>(null);
const [deleteTarget, setDeleteTarget] = useState<CustomerAddress | null>(null);
const openAdd = () => {
setEditing(null);
setFormOpen(true);
};
const openEdit = (address: CustomerAddress) => {
setEditing(address);
setFormOpen(true);
};
const closeForm = () => setFormOpen(false);
// Address district is optional granularity: show "city · district" when set, else just the city.
const regionLabel = (address: CustomerAddress) => {
const city = locale === 'en' ? address.cityNameEn : address.cityNameFa;
if (address.districtId == null) return city;
const district = locale === 'en' ? address.districtNameEn : address.districtNameFa;
return `${city} · ${district}`;
};
const handleSubmit = (input: CreateAddressInput) => {
const onSuccess = () => {
closeForm();
enqueueSnackbar(t('saved'), { variant: 'success' });
};
const onError = () => enqueueSnackbar(t('save_error'), { variant: 'error' });
if (editing) {
updateAddress.mutate({ id: editing.id, input }, { onSuccess, onError });
} else {
createAddress.mutate(input, { onSuccess, onError });
}
};
const confirmDelete = () => {
if (!deleteTarget) return;
const id = deleteTarget.id;
setDeleteTarget(null);
deleteAddress.mutate(id, {
onSuccess: () => enqueueSnackbar(t('deleted'), { variant: 'success' }),
onError: () => enqueueSnackbar(t('unavailable'), { variant: 'error' }),
});
};
const addresses = data?.items ?? [];
const isEmpty = !isLoading && addresses.length === 0;
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
<Stack direction="row" sx={{ alignItems: 'flex-start', justifyContent: 'space-between', gap: 2 }}>
<Box>
<Typography variant="h5" component="h1">
{t('title')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('subtitle')}
</Typography>
</Box>
{!isEmpty ? (
<AppButton color="primary" variant="contained" startIcon="add" onClick={openAdd} sx={{ m: 0, flexShrink: 0 }}>
{t('add')}
</AppButton>
) : null}
</Stack>
{isLoading ? (
<Stack sx={{ gap: 1.5 }}>
{[0, 1].map((key) => (
<Skeleton key={key} variant="rounded" height={104} />
))}
</Stack>
) : isEmpty ? (
<Paper
elevation={0}
sx={{
p: 4,
textAlign: 'center',
border: '1px dashed',
borderColor: 'divider',
borderRadius: 2,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 1.5,
}}
>
<AppIcon icon="location" size={40} color="var(--bal-primary)" />
<Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
{t('empty_title')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('empty_body')}
</Typography>
<AppButton color="primary" variant="contained" startIcon="add" onClick={openAdd} sx={{ mt: 1 }}>
{t('add')}
</AppButton>
</Paper>
) : (
<Stack sx={{ gap: 1.5 }}>
{addresses.map((address) => (
<AddressCard
key={address.id}
title={address.title}
regionLabel={regionLabel(address)}
addressLine={address.addressLine}
isPrimary={address.isPrimary}
primaryLabel={t('primary')}
onEdit={() => openEdit(address)}
onDelete={() => setDeleteTarget(address)}
onSetPrimary={() =>
setPrimary.mutate(address.id, {
onSuccess: () => enqueueSnackbar(t('primary_set'), { variant: 'success' }),
onError: () => enqueueSnackbar(t('unavailable'), { variant: 'error' }),
})
}
settingPrimary={setPrimary.isPending}
editLabel={t('edit')}
deleteLabel={t('delete')}
setPrimaryLabel={t('set_primary')}
/>
))}
</Stack>
)}
<Dialog open={formOpen} onClose={closeForm} fullWidth maxWidth="sm">
<DialogTitle>{editing ? t('edit_title') : t('add_title')}</DialogTitle>
<DialogContent>
<Box sx={{ pt: 1 }}>
<AddressForm
key={editing?.id ?? 'new'}
initial={
editing
? {
title: editing.title,
provinceId: editing.provinceId,
cityId: editing.cityId,
districtId: editing.districtId,
addressLine: editing.addressLine,
latitude: editing.latitude,
longitude: editing.longitude,
isPrimary: editing.isPrimary,
}
: undefined
}
submitting={createAddress.isPending || updateAddress.isPending}
onSubmit={handleSubmit}
onCancel={closeForm}
/>
</Box>
</DialogContent>
</Dialog>
<Dialog open={Boolean(deleteTarget)} onClose={() => setDeleteTarget(null)}>
<DialogTitle>{t('delete_title')}</DialogTitle>
<DialogContent>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('delete_body')}
</Typography>
</DialogContent>
<DialogActions>
<AppButton variant="text" onClick={() => setDeleteTarget(null)}>
{tc('cancel')}
</AppButton>
<AppButton color="error" variant="contained" onClick={confirmDelete}>
{t('delete_confirm')}
</AppButton>
</DialogActions>
</Dialog>
</Box>
);
}
@@ -1,10 +1,11 @@
'use client';
import { FunctionComponent, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useLocale, useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import { Box, Divider, MenuItem, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppLoading, PhoneNumberField } from '@/components';
import { Box, Divider, MenuItem, Paper, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppIcon, AppLoading, PhoneNumberField } from '@/components';
import { isIranianMobile } from '@/components/PhoneNumberField';
import { ROUTES } from '@/constants';
import { digitsOnly } from '@/utils';
import { useCustomerProfile, useUpsertCustomerProfile } from '@/services/profiles';
import type { CustomerProfile } from '@/services/profiles/types';
@@ -18,7 +19,9 @@ export default function CustomerProfilePage() {
const CustomerProfileForm: FunctionComponent<{ initial: CustomerProfile | null }> = ({ initial }) => {
const t = useTranslations('profile');
const ta = useTranslations('address');
const tc = useTranslations('common');
const locale = useLocale();
const { enqueueSnackbar } = useSnackbar();
const upsert = useUpsertCustomerProfile();
@@ -123,6 +126,33 @@ const CustomerProfileForm: FunctionComponent<{ initial: CustomerProfile | null }
>
{upsert.isPending ? tc('saving') : t('save')}
</AppButton>
<Divider />
{/* Address book lives alongside the profile in the customer area; a booking (f7) needs a
chosen address, so the entry point is surfaced here on the settings hub. */}
<Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2, display: 'flex', gap: 2 }}>
<AppIcon icon="location" size={28} color="var(--bal-primary)" />
<Stack sx={{ gap: 1, flexGrow: 1 }}>
<Box>
<Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
{ta('manage_title')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{ta('manage_body')}
</Typography>
</Box>
<AppButton
color="primary"
variant="outlined"
startIcon="location"
to={`/${locale}${ROUTES.ADDRESSES}`}
sx={{ m: 0, alignSelf: 'flex-start' }}
>
{ta('manage_cta')}
</AppButton>
</Stack>
</Paper>
</Box>
);
};
@@ -0,0 +1,265 @@
'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import {
Box,
Chip,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Paper,
Skeleton,
Stack,
ToggleButton,
ToggleButtonGroup,
Typography,
} from '@mui/material';
import { AppButton, AppIcon } from '@/components';
import { CascadingRegionSelect, type CascadingRegionValue } from '@/components/geography';
import { ApiError } from '@/lib/api/errors';
import { useDistricts } from '@/services/geography';
import { useServiceAreas, useAddServiceArea, useRemoveServiceArea } from '@/services/serviceAreas';
import { areaExists, type NurseServiceArea } from '@/services/serviceAreas/types';
type Scope = 'whole_city' | 'districts';
const EMPTY_REGION: CascadingRegionValue = { provinceId: null, cityId: null, districtId: null };
/**
* The nurse coverage-area editor — the cities/districts a nurse will travel to, so search (f6)
* can fan them out geographically. Areas render as chips (whole-city shown explicitly); the add
* control is the cascading dropdowns + a whole-city vs specific-districts scope toggle. A
* duplicate `(city, district)` is blocked inline before the request (and the server's 409 maps to
* the same message). Empty → a warning that the nurse won't appear in search.
*/
export default function NurseCoveragePage() {
const t = useTranslations('coverage');
const tc = useTranslations('common');
const locale = useLocale();
const { enqueueSnackbar } = useSnackbar();
const { data, isLoading } = useServiceAreas();
const addArea = useAddServiceArea();
const removeArea = useRemoveServiceArea();
const [region, setRegion] = useState<CascadingRegionValue>(EMPTY_REGION);
const [scope, setScope] = useState<Scope>('whole_city');
const [cityError, setCityError] = useState(false);
const [districtError, setDistrictError] = useState(false);
const [duplicate, setDuplicate] = useState(false);
const [removeTarget, setRemoveTarget] = useState<NurseServiceArea | null>(null);
const areas = data?.items ?? [];
// A whole-city-only city (no districts, e.g. Mashhad) can't satisfy "specific districts" — reads the
// same cached districts query the cascade uses to force whole-city, so the toggle never dead-ends on a
// district that cannot exist.
const districtsQuery = useDistricts(region.cityId);
const cityHasNoDistricts =
region.cityId != null && districtsQuery.isSuccess && (districtsQuery.data?.length ?? 0) === 0;
const effectiveScope: Scope = cityHasNoDistricts ? 'whole_city' : scope;
const chipLabel = (area: NurseServiceArea) => {
const city = locale === 'en' ? area.cityNameEn : area.cityNameFa;
if (area.isWholeCity) return `${city} · ${t('whole_city_chip')}`;
const district = locale === 'en' ? area.districtNameEn : area.districtNameFa;
return `${city} · ${district}`;
};
const changeScope = (next: Scope | null) => {
if (!next) return;
setScope(next);
setDistrictError(false);
setDuplicate(false);
// Whole-city ignores any picked district — clear it so the submitted pair is unambiguous.
if (next === 'whole_city') setRegion((prev) => ({ ...prev, districtId: null }));
};
const resetForm = () => {
setRegion(EMPTY_REGION);
setScope('whole_city');
setCityError(false);
setDistrictError(false);
setDuplicate(false);
};
const handleAdd = () => {
const cityInvalid = region.cityId == null;
const districtInvalid = effectiveScope === 'districts' && region.districtId == null;
setCityError(cityInvalid);
setDistrictError(districtInvalid);
setDuplicate(false);
if (cityInvalid || districtInvalid) return;
const cityId = region.cityId as number;
const districtId = effectiveScope === 'whole_city' ? null : region.districtId;
// Fast path: block a duplicate before firing (null district treated as a real value).
if (areaExists(areas, cityId, districtId)) {
setDuplicate(true);
return;
}
addArea.mutate(
{ cityId, districtId },
{
onSuccess: () => {
resetForm();
enqueueSnackbar(t('added'), { variant: 'success' });
},
onError: (error) => {
// Belt-and-braces: the server's UNIQUE 409 maps to the same inline duplicate message.
if (error instanceof ApiError && error.status === 409) setDuplicate(true);
else enqueueSnackbar(t('add_error'), { variant: 'error' });
},
},
);
};
const confirmRemove = () => {
if (!removeTarget) return;
const id = removeTarget.id;
setRemoveTarget(null);
removeArea.mutate(id, {
onSuccess: () => enqueueSnackbar(t('removed'), { variant: 'success' }),
});
};
return (
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 560 }}>
<Box>
<Typography variant="h5" component="h1">
{t('title')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('subtitle')}
</Typography>
</Box>
{isLoading ? (
<Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
{[0, 1].map((key) => (
<Skeleton key={key} variant="rounded" width={160} height={32} />
))}
</Stack>
) : areas.length > 0 ? (
<Stack sx={{ gap: 1 }}>
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
{t('areas_heading')}
</Typography>
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
{areas.map((area) => (
<Chip
key={area.id}
label={chipLabel(area)}
onDelete={() => setRemoveTarget(area)}
sx={{ bgcolor: 'var(--bal-primary-soft)', fontWeight: 600 }}
/>
))}
</Box>
</Stack>
) : (
<Paper
elevation={0}
sx={{
p: 2,
borderRadius: 2,
border: '1px solid',
borderColor: 'divider',
borderInlineStartWidth: 4,
borderInlineStartColor: 'var(--bal-warning)',
}}
>
<Stack direction="row" sx={{ gap: 1.5, alignItems: 'flex-start' }}>
<AppIcon icon="warning" size={24} color="var(--bal-warning)" />
<Box>
<Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
{t('empty_title')}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('empty_warning')}
</Typography>
</Box>
</Stack>
</Paper>
)}
<Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
<Stack sx={{ gap: 2 }}>
<Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
{t('add_title')}
</Typography>
<Stack sx={{ gap: 1 }}>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('scope_label')}
</Typography>
<ToggleButtonGroup
exclusive
size="small"
color="primary"
value={effectiveScope}
onChange={(_event, next: Scope | null) => changeScope(next)}
>
<ToggleButton value="whole_city">{t('scope_whole_city')}</ToggleButton>
{/* A district-less city forces whole-city — disable the option rather than dead-end on it. */}
<ToggleButton value="districts" disabled={cityHasNoDistricts}>
{t('scope_districts')}
</ToggleButton>
</ToggleButtonGroup>
</Stack>
<CascadingRegionSelect
value={region}
onChange={(next) => {
setRegion(next);
if (cityError && next.cityId != null) setCityError(false);
if (districtError && next.districtId != null) setDistrictError(false);
setDuplicate(false);
}}
includeDistrict={effectiveScope === 'districts'}
cityError={cityError}
cityErrorText={t('city_required')}
districtError={districtError}
districtErrorText={t('district_required')}
/>
{duplicate ? (
<Typography variant="caption" sx={{ color: 'var(--bal-error)' }}>
{t('duplicate')}
</Typography>
) : null}
<AppButton
color="primary"
variant="contained"
startIcon="add"
onClick={handleAdd}
disabled={addArea.isPending}
sx={{ m: 0, alignSelf: 'flex-start' }}
>
{addArea.isPending ? t('adding') : t('add')}
</AppButton>
</Stack>
</Paper>
<Dialog open={Boolean(removeTarget)} onClose={() => setRemoveTarget(null)}>
<DialogTitle>{t('remove_title')}</DialogTitle>
<DialogContent>
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
{t('remove_body')}
</Typography>
</DialogContent>
<DialogActions>
<AppButton variant="text" onClick={() => setRemoveTarget(null)}>
{tc('cancel')}
</AppButton>
<AppButton color="error" variant="contained" onClick={confirmRemove}>
{t('remove_confirm')}
</AppButton>
</DialogActions>
</Dialog>
</Box>
);
}