Files
Doormilexpress_console/src/components/nearle_components/LocationAutocomplete.js
2026-08-17 17:14:51 +05:30

107 lines
4.2 KiB
JavaScript

import PropTypes from 'prop-types';
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { Selector } from '@astryxdesign/core/Selector';
import { fetchAppLocations } from 'pages/api/api';
// ==============================|| ZONE PICKER ||============================== //
// Astryx `Selector` over the hub-derived zone list.
//
// Migration notes: the MUI version carried a `pill` variant plus
// `accentColor` / `icon` / `paperComponent` / `sx` / `textfieldSx` props so
// each page could restyle the field itself. Astryx's Selector owns that
// styling, so all of those are gone and the picker now looks identical
// everywhere. `width` is the one layout prop kept, since call sites genuinely
// differ (220px on pricing, 280px elsewhere).
//
// `ref` still works: three pages (deliveries, ordersDetails, ordersSummary)
// call `locationRef.current.focus()` to pull the operator back to the zone
// picker after a "select your zone first" toast. Selector doesn't forward a
// ref, so we expose `focus()` ourselves and drive its trigger button.
const LocationAutocomplete = forwardRef(({ locaName, setAppId, setLocoName, setPage, placeholder = 'Select Zone', width = 280 }, ref) => {
// Tenant-scoped cache key — fetchAppLocations() now narrows the hub list
// to the logged-in tenant's own city, so caching under one shared flat
// key would leak a previous tenant's list into a different tenant's
// session on the same browser if it ever skipped a full logout clear.
const applocationsCacheKey = `applocations_${localStorage.getItem('tenantid') || 'staff'}`;
const [locations, setLocations] = useState(JSON.parse(localStorage.getItem(applocationsCacheKey) || '[]'));
const wrapRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => wrapRef.current?.querySelector('button')?.focus()
}));
useEffect(() => {
// Zones are derived from GET /admin/hubs (the new API has no dedicated
// zones resource) — see fetchAppLocations in pages/api/api.js.
const fetchLocations = async () => {
try {
const updatedLocations = await fetchAppLocations();
localStorage.setItem(applocationsCacheKey, JSON.stringify(updatedLocations));
setLocations(updatedLocations);
} catch (err) {
console.error('Error fetching locations in LocationAutocomplete:', err);
}
};
if (locations.length === 0) {
fetchLocations();
}
}, [locations.length, applocationsCacheKey]);
const options = useMemo(() => (locations || []).map((l) => ({ value: l.locationname, label: l.locationname })), [locations]);
const handleChange = (value) => {
if (!value) {
// null (not 0) — 0 is a real, meaningful selection here: the synthetic
// "All" option (fetchAppLocations in api.js appends
// { locationname: 'All', applocationid: 0 }). Callers that gate other
// pickers on "has a zone been chosen yet" (e.g. deliveries.js's
// Tenant/Rider dropdowns) need to tell "nothing picked" apart from
// "deliberately picked All" — both used to collapse to the same falsy 0,
// so choosing All incorrectly still tripped the "select a zone first" gate.
setAppId?.(null);
setLocoName?.('');
setPage?.(0);
return;
}
const picked = (locations || []).find((l) => l.locationname === value);
if (picked) {
setAppId?.(picked.applocationid);
setLocoName?.(picked.locationname);
setPage?.(0);
}
};
return (
<div ref={wrapRef} style={{ width, maxWidth: '100%' }}>
<Selector
label="Zone"
isLabelHidden
placeholder={placeholder}
options={options}
value={locaName || undefined}
onChange={handleChange}
hasClear
hasSearch
searchPlaceholder="Search zones…"
/>
</div>
);
});
LocationAutocomplete.displayName = 'LocationAutocomplete';
LocationAutocomplete.propTypes = {
locaName: PropTypes.string,
setAppId: PropTypes.func,
setLocoName: PropTypes.func,
setPage: PropTypes.func,
placeholder: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
export default LocationAutocomplete;