Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: cleanup & optimize, add autocomplete to LocationForm

edsammy3a96fd5a21d5
diff --git a/apps/erp/app/components/Form/AddressAutocomplete.tsx b/apps/erp/app/components/Form/AddressAutocomplete.tsx
index 9b95df0b1c..30f14b3f2f 100644
--- a/apps/erp/app/components/Form/AddressAutocomplete.tsx
+++ b/apps/erp/app/components/Form/AddressAutocomplete.tsx
@@ -8,7 +8,7 @@ import {
useDebounce,
VStack,
} from "@carbon/react";
-import { useEffect, useState, useCallback, useRef } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useGooglePlaces } from "~/hooks/useGooglePlaces";
import { Input } from ".";
import Country from "./Country";
@@ -66,9 +66,8 @@ const AddressAutocomplete = ({
const [open, setOpen] = useState(false);
const [justSelected, setJustSelected] = useState(false);
const [userInteracted, setUserInteracted] = useState(false);
- const containerRef = useRef<HTMLDivElement>(null);
- // Refs to access the input elements directly
+ const containerRef = useRef<HTMLDivElement>(null);
const addressLine2Ref = useRef<HTMLInputElement>(null);
const cityRef = useRef<HTMLInputElement>(null);
const stateProvinceRef = useRef<HTMLInputElement>(null);
@@ -83,7 +82,6 @@ const AddressAutocomplete = ({
clearSuggestions,
} = useGooglePlaces();
- // Memoize the callback to prevent recreating the debounced function
const handleInputChange = useCallback(
(input: string) => {
if (input && !justSelected && userInteracted) {
@@ -97,10 +95,8 @@ const AddressAutocomplete = ({
[getSuggestions, clearSuggestions, justSelected, userInteracted]
);
- // Debounce the API calls to avoid excessive requests
const debouncedGetSuggestions = useDebounce(handleInputChange, 300);
- // Watch for changes to trigger API calls (only after user interaction)
useEffect(() => {
if (userInteracted) {
debouncedGetSuggestions(value || "");
@@ -108,8 +104,9 @@ const AddressAutocomplete = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value, userInteracted]);
- // Handle clicks outside the component
useEffect(() => {
+ if (!open) return;
+
const handleClickOutside = (event: MouseEvent) => {
if (
containerRef.current &&
@@ -119,28 +116,22 @@ const AddressAutocomplete = ({
}
};
- if (open) {
- document.addEventListener("mousedown", handleClickOutside);
- }
-
- return () => {
- document.removeEventListener("mousedown", handleClickOutside);
- };
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => document.removeEventListener("mousedown", handleClickOutside);
}, [open]);
- const handleSelect = async (placeId: string) => {
- // Close dropdown and clear suggestions immediately
- setOpen(false);
- clearSuggestions();
- setJustSelected(true);
+ const handleSelect = useCallback(
+ async (placeId: string) => {
+ setOpen(false);
+ clearSuggestions();
+ setJustSelected(true);
- const address = await selectPlace(placeId);
+ const address = await selectPlace(placeId);
+ if (!address) return;
- if (address) {
- // Populate all address fields
setValue(address.addressLine1);
- // Set values directly on the input elements
+ // Populate remaining address fields via refs
if (addressLine2Ref.current)
addressLine2Ref.current.value = address.addressLine2;
if (cityRef.current) cityRef.current.value = address.city;
@@ -150,7 +141,6 @@ const AddressAutocomplete = ({
postalCodeRef.current.value = address.postalCode;
if (countryRef.current) countryRef.current.value = address.countryCode;
- // Clear validation errors for all populated fields
clearError(
fieldName,
addressLine2Name,
@@ -159,10 +149,37 @@ const AddressAutocomplete = ({
postalCodeName,
countryCodeName
);
+ },
+ [
+ clearSuggestions,
+ selectPlace,
+ setValue,
+ clearError,
+ fieldName,
+ addressLine2Name,
+ cityName,
+ stateProvinceName,
+ postalCodeName,
+ countryCodeName,
+ ]
+ );
+
+ const handleInputFocus = useCallback(() => {
+ setUserInteracted(true);
+ if ((value || "").length >= 3 && !justSelected) {
+ setOpen(true);
}
- };
+ }, [value, justSelected]);
+
+ const handleChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ setUserInteracted(true);
+ setJustSelected(false);
+ setValue(e.target.value);
+ },
+ [setValue]
+ );
- // Build field objects
const fields: AddressFields = {
autocomplete: (
<div className="relative w-full" ref={containerRef}>
@@ -170,20 +187,12 @@ const AddressAutocomplete = ({
name={fieldName}
label={label}
value={value || ""}
- onChange={(e) => {
- setUserInteracted(true); // Mark that user has interacted
- setJustSelected(false); // Allow new searches when user types
- setValue(e.target.value);
- }}
- onFocus={() => {
- setUserInteracted(true); // Mark that user has interacted
- if ((value || "").length >= 3 && !justSelected) {
- setOpen(true);
- }
- }}
+ onChange={handleChange}
+ onFocus={handleInputFocus}
+ autoComplete="off"
/>
{open && suggestions.length > 0 && (
- <div className="absolute w-full mt-1" style={{ zIndex: 9999 }}>
+ <div className="absolute w-full mt-1 z-[9999]">
<div className="rounded-md border bg-popover text-popover-foreground shadow-md p-0">
<Command shouldFilter={false}>
<CommandList>
diff --git a/apps/erp/app/hooks/useGooglePlaces.tsx b/apps/erp/app/hooks/useGooglePlaces.tsx
index c679cce06c..08ea893d45 100644
--- a/apps/erp/app/hooks/useGooglePlaces.tsx
+++ b/apps/erp/app/hooks/useGooglePlaces.tsx
@@ -1,4 +1,4 @@
-import { useState, useCallback, useRef } from "react";
+import { useCallback, useRef, useState } from "react";
import { nanoid } from "nanoid";
import { GOOGLE_PLACES_API_KEY } from "@carbon/auth";
@@ -40,7 +40,7 @@ export const useGooglePlaces = () => {
const [suggestions, setSuggestions] = useState<PlaceSuggestion[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
- const sessionTokenRef = useRef<string>(nanoid());
+ const sessionTokenRef = useRef<string>("");
const getSuggestions = useCallback(async (input: string) => {
if (!GOOGLE_PLACES_API_KEY) {
@@ -54,6 +54,11 @@ export const useGooglePlaces = () => {
return;
}
+ // Generate session token on first autocomplete request
+ if (!sessionTokenRef.current) {
+ sessionTokenRef.current = nanoid();
+ }
+
setLoading(true);
setError(null);
@@ -107,56 +112,13 @@ export const useGooglePlaces = () => {
}
}, []);
- const getPlaceDetails = useCallback(
- async (placeId: string): Promise<AddressComponents | null> => {
- if (!GOOGLE_PLACES_API_KEY) {
- setError("Google Places API key not configured");
- return null;
- }
-
- setLoading(true);
- setError(null);
-
- try {
- const response = await fetch(
- `https://places.googleapis.com/v1/places/${placeId}?sessionToken=${sessionTokenRef.current}`,
- {
- headers: {
- "X-Goog-Api-Key": GOOGLE_PLACES_API_KEY,
- "X-Goog-FieldMask": "addressComponents",
- },
- }
- );
-
- if (!response.ok) {
- throw new Error(`Google Places API error: ${response.status}`);
- }
-
- const data: PlaceDetailsResponse = await response.json();
-
- if (!data.addressComponents) {
- throw new Error("No address components found");
- }
-
- return parseAddressComponents(data.addressComponents);
- } catch (err) {
- console.error("Google Places API error:", err);
- setError(
- err instanceof Error ? err.message : "Failed to fetch place details"
- );
- return null;
- } finally {
- setLoading(false);
- }
- },
- []
- );
-
const parseAddressComponents = (
- components: Array<{ longText: string; shortText: string; types: string[] }>
+ components: Array<{
+ longText: string;
+ shortText: string;
+ types: string[];
+ }>
): AddressComponents => {
- // console.debug("components");
- // console.debug(components);
if (!components) {
return {
addressLine1: "",
@@ -211,17 +173,62 @@ export const useGooglePlaces = () => {
};
};
+ const getPlaceDetails = async (
+ placeId: string
+ ): Promise<AddressComponents | null> => {
+ if (!GOOGLE_PLACES_API_KEY) {
+ setError("Google Places API key not configured");
+ return null;
+ }
+
+ setLoading(true);
+ setError(null);
+
+ try {
+ const response = await fetch(
+ `https://places.googleapis.com/v1/places/${placeId}?sessionToken=${sessionTokenRef.current}`,
+ {
+ headers: {
+ "X-Goog-Api-Key": GOOGLE_PLACES_API_KEY,
+ "X-Goog-FieldMask": "addressComponents",
+ },
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error(`Google Places API error: ${response.status}`);
+ }
+
+ const data: PlaceDetailsResponse = await response.json();
+
+ if (!data.addressComponents) {
+ throw new Error("No address components found");
+ }
+
+ return parseAddressComponents(data.addressComponents);
+ } catch (err) {
+ console.error("Google Places API error:", err);
+ setError(
+ err instanceof Error ? err.message : "Failed to fetch place details"
+ );
+ return null;
+ } finally {
+ setLoading(false);
+ }
+ };
+
const selectPlace = useCallback(
async (placeId: string): Promise<AddressComponents | null> => {
const addressComponents = await getPlaceDetails(placeId);
- setSuggestions([]); // Clear suggestions after selection
+ setSuggestions([]);
// Generate a new session token for the next autocomplete session
sessionTokenRef.current = nanoid();
return addressComponents;
},
- [getPlaceDetails]
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ []
);
const clearSuggestions = useCallback(() => {
diff --git a/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx b/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx
index 91c9720185..57478b1c9d 100644
--- a/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx
+++ b/apps/erp/app/modules/resources/ui/Locations/LocationForm.tsx
@@ -23,7 +23,7 @@ import {
Submit,
Timezone,
} from "~/components/Form";
-import Country from "~/components/Form/Country";
+import AddressAutocomplete from "~/components/Form/AddressAutocomplete";
import { usePermissions } from "~/hooks";
import { locationValidator } from "~/modules/resources";
import { path } from "~/utils/path";
@@ -91,12 +91,7 @@ const LocationForm = ({
<Hidden name="type" value={type} />
<VStack spacing={4}>
<Input name="name" label="Location Name" />
- <Input name="addressLine1" label="Address Line 1" />
- <Input name="addressLine2" label="Address Line 2" />
- <Input name="city" label="City" />
- <Input name="stateProvince" label="State / Province" />
- <Input name="postalCode" label="Postal Code" />
- <Country name="countryCode" />
+ <AddressAutocomplete />
<Timezone name="timezone" label="Timezone" />
{/* <Number name="latitude" label="Latitude" minValue={-90} maxValue={90} />
<Number name="longitude" label="Longitude" minVale={-180} maxValue={180} /> */}