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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(autocomplete): wip, move to sessions to save usage, fill form and print debug
edsammydbe9ea1af158
diff --git a/apps/erp/app/components/Form/AddressAutocomplete.tsx b/apps/erp/app/components/Form/AddressAutocomplete.tsxnew file mode 100644index 0000000000..13af5836f6--- /dev/null+++ b/apps/erp/app/components/Form/AddressAutocomplete.tsx@@ -0,0 +1,220 @@+import { useControlField, useFormContext } from "@carbon/form";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandItem,+ CommandList,+ useDebounce,+ VStack,+} from "@carbon/react";+import { useEffect, useState, useCallback, useRef } from "react";+import { useGooglePlaces } from "~/hooks/useGooglePlaces";+import { Input } from ".";+import Country from "./Country";++type AddressAutocompleteProps = {+ name?: string;+ label?: string;+ // Optional field name overrides+ addressLine1Name?: string;+ addressLine2Name?: string;+ cityName?: string;+ stateProvinceName?: string;+ postalCodeName?: string;+ countryCodeName?: string;+ // Control which fields to show+ showAddressLine2?: boolean;+ showCity?: boolean;+ showStateProvince?: boolean;+ showPostalCode?: boolean;+ showCountryCode?: boolean;+};++const AddressAutocomplete = ({+ name,+ label = "Address Line 1",+ addressLine1Name = "addressLine1",+ addressLine2Name = "addressLine2",+ cityName = "city",+ stateProvinceName = "stateProvince",+ postalCodeName = "postalCode",+ countryCodeName = "countryCode",+ showAddressLine2 = true,+ showCity = true,+ showStateProvince = true,+ showPostalCode = true,+ showCountryCode = true,+}: AddressAutocompleteProps) => {+ // Use provided name or default to addressLine1Name+ const fieldName = name ?? addressLine1Name;++ const [value, setValue] = useControlField<string>(fieldName);+ const { clearError } = useFormContext();+ const [open, setOpen] = useState(false);+ const [justSelected, setJustSelected] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);++ // Refs to access the input elements directly+ const addressLine2Ref = useRef<HTMLInputElement>(null);+ const cityRef = useRef<HTMLInputElement>(null);+ const stateProvinceRef = useRef<HTMLInputElement>(null);+ const postalCodeRef = useRef<HTMLInputElement>(null);+ const countryRef = useRef<HTMLInputElement>(null);++ const {+ suggestions,+ loading,+ getSuggestions,+ selectPlace,+ clearSuggestions,+ } = useGooglePlaces();++ // Memoize the callback to prevent recreating the debounced function+ const handleInputChange = useCallback(+ (input: string) => {+ if (input && !justSelected) {+ getSuggestions(input);+ setOpen(true);+ } else {+ clearSuggestions();+ setOpen(false);+ }+ },+ [getSuggestions, clearSuggestions, justSelected]+ );++ // Debounce the API calls to avoid excessive requests+ const debouncedGetSuggestions = useDebounce(handleInputChange, 300);++ // Watch for changes to trigger API calls+ useEffect(() => {+ debouncedGetSuggestions(value || "");+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [value]);++ // Handle clicks outside the component+ useEffect(() => {+ const handleClickOutside = (event: MouseEvent) => {+ if (+ containerRef.current &&+ !containerRef.current.contains(event.target as Node)+ ) {+ setOpen(false);+ }+ };++ if (open) {+ 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 address = await selectPlace(placeId);++ if (address) {+ // Populate all address fields+ setValue(address.addressLine1);++ // Set values directly on the input elements+ if (addressLine2Ref.current)+ addressLine2Ref.current.value = address.addressLine2;+ if (cityRef.current) cityRef.current.value = address.city;+ if (stateProvinceRef.current)+ stateProvinceRef.current.value = address.stateProvince;+ if (postalCodeRef.current)+ postalCodeRef.current.value = address.postalCode;+ if (countryRef.current) countryRef.current.value = address.countryCode;++ // Clear validation errors for all populated fields+ clearError(+ fieldName,+ addressLine2Name,+ cityName,+ stateProvinceName,+ postalCodeName,+ countryCodeName+ );+ }+ };++ return (+ <VStack spacing={4}>+ <div className="relative w-full" ref={containerRef}>+ <Input+ name={fieldName}+ label={label}+ value={value || ""}+ onChange={(e) => {+ setJustSelected(false); // Allow new searches when user types+ setValue(e.target.value);+ }}+ onFocus={() => {+ if ((value || "").length >= 3 && !justSelected) {+ setOpen(true);+ }+ }}+ autoComplete="off"+ />+ {open && suggestions.length > 0 && (+ <div className="absolute w-full mt-1" style={{ zIndex: 9999 }}>+ <div className="rounded-md border bg-popover text-popover-foreground shadow-md p-0">+ <Command shouldFilter={false}>+ <CommandList>+ <CommandEmpty>+ {loading ? "Loading..." : "No addresses found"}+ </CommandEmpty>+ <CommandGroup>+ {suggestions.map((suggestion) => (+ <CommandItem+ key={suggestion.placeId}+ value={suggestion.placeId}+ onMouseDown={(e) => {+ e.preventDefault();+ handleSelect(suggestion.placeId);+ }}+ >+ {suggestion.text}+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ </div>+ </div>+ )}+ </div>++ {showAddressLine2 && (+ <Input+ ref={addressLine2Ref}+ name={addressLine2Name}+ label="Address Line 2"+ />+ )}+ {showCity && <Input ref={cityRef} name={cityName} label="City" />}+ {showStateProvince && (+ <Input+ ref={stateProvinceRef}+ name={stateProvinceName}+ label="State / Province"+ />+ )}+ {showPostalCode && (+ <Input ref={postalCodeRef} name={postalCodeName} label="Postal Code" />+ )}+ {showCountryCode && <Country name={countryCodeName} />}+ </VStack>+ );+};++export default AddressAutocomplete;diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.tsindex 7233bc595a..ed1653dccf 100644--- a/apps/erp/app/components/Form/index.ts+++ b/apps/erp/app/components/Form/index.ts@@ -28,6 +28,7 @@ import {import Abilities from "./Abilities";import Ability from "./Ability";import Account from "./Account";+import AddressAutocomplete from "./AddressAutocomplete";import AccountCategory from "./AccountCategory";import AccountSubcategory from "./AccountSubcategory";import Color from "./Color";@@ -80,6 +81,7 @@ export {Account,AccountCategory,AccountSubcategory,+ AddressAutocomplete,Array,ArrayNumeric,Boolean,diff --git a/apps/erp/app/hooks/useGooglePlaces.tsx b/apps/erp/app/hooks/useGooglePlaces.tsxindex f3eeec2236..47328aeff5 100644--- a/apps/erp/app/hooks/useGooglePlaces.tsx+++ b/apps/erp/app/hooks/useGooglePlaces.tsx@@ -1,4 +1,5 @@-import { useState, useCallback } from "react";+import { useState, useCallback, useRef } from "react";+import { nanoid } from "nanoid";import { GOOGLE_PLACES_API_KEY } from "@carbon/auth";interface PlaceSuggestion {@@ -39,6 +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 getSuggestions = useCallback(async (input: string) => {if (!GOOGLE_PLACES_API_KEY) {@@ -46,7 +48,7 @@ export const useGooglePlaces = () => {return;}- if (!input || input.length < 3) {+ if (!input) {setSuggestions([]);setError(null);return;@@ -68,6 +70,7 @@ export const useGooglePlaces = () => {input,includedPrimaryTypes: ["street_address"],languageCode: "en",+ sessionToken: sessionTokenRef.current,}),});@@ -116,7 +119,7 @@ export const useGooglePlaces = () => {try {const response = await fetch(- `https://places.googleapis.com/v1/places/${placeId}`,+ `https://places.googleapis.com/v1/places/${placeId}?sessionToken=${sessionTokenRef.current}`,{headers: {"X-Goog-Api-Key": GOOGLE_PLACES_API_KEY,@@ -207,6 +210,10 @@ export const useGooglePlaces = () => {async (placeId: string): Promise<AddressComponents | null> => {const addressComponents = await getPlaceDetails(placeId);setSuggestions([]); // Clear suggestions after selection++ // Generate a new session token for the next autocomplete session+ sessionTokenRef.current = nanoid();+return addressComponents;},[getPlaceDetails]diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerLocationForm.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerLocationForm.tsxindex eb0e383551..0fc35b6192 100644--- a/apps/erp/app/modules/sales/ui/Customer/CustomerLocationForm.tsx+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerLocationForm.tsx@@ -14,7 +14,14 @@ import {import { ValidatedForm } from "@carbon/form";import { useFetcher } from "@remix-run/react";import type { z } from "zod";-import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";+import {+ AddressAutocomplete,+ CustomFormFields,+ Hidden,+ Input,+ InputControlled,+ Submit,+} from "~/components/Form";import Country from "~/components/Form/Country";import { usePermissions } from "~/hooks";import { path } from "~/utils/path";@@ -80,11 +87,17 @@ const CustomerLocationForm = ({<Hidden name="addressId" /><VStack spacing={4}><Input name="name" label="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" />+ <AddressAutocomplete+ name="addressLine1"+ label="Address Line 1"+ />+ <InputControlled name="addressLine2" label="Address Line 2" />+ <InputControlled name="city" label="City" />+ <InputControlled+ name="stateProvince"+ label="State / Province"+ />+ <InputControlled name="postalCode" label="Postal Code" /><Country name="countryCode" /><CustomFormFields table="customerLocation" /></VStack>diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsxindex df415b7df3..ec6d0c2566 100644--- a/apps/erp/app/routes/onboarding+/company.tsx+++ b/apps/erp/app/routes/onboarding+/company.tsx@@ -22,8 +22,14 @@ import { getLocalTimeZone } from "@internationalized/date";import { Link, useLoaderData } from "@remix-run/react";import { tasks } from "@trigger.dev/sdk/v3";import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";-import { Currency, Hidden, Input, Submit } from "~/components/Form";-import Country from "~/components/Form/Country";+import { useEffect } from "react";+import {+ AddressAutocomplete,+ Currency,+ Hidden,+ Input,+ Submit,+} from "~/components/Form";import { useOnboarding } from "~/hooks";import { insertEmployeeJob } from "~/modules/people";import { getLocationsList, upsertLocation } from "~/modules/resources";@@ -195,6 +201,23 @@ export default function OnboardingCompany() {baseCurrencyCode: company?.baseCurrencyCode ?? "USD",};+ // Debug: watch form values+ useEffect(() => {+ const interval = setInterval(() => {+ const form = document.querySelector("form");+ if (form) {+ const formData = new FormData(form);+ const entries: Record<string, any> = {};+ formData.forEach((value, key) => {+ entries[key] = value;+ });+ console.log("📋 Current form values:", entries);+ }+ }, 2000); // Log every 2 seconds++ return () => clearInterval(interval);+ }, []);+return (<Card className="max-w-lg"><ValidatedForm@@ -209,11 +232,7 @@ export default function OnboardingCompany() {<Hidden name="next" value={next} /><VStack spacing={4}><Input autoFocus name="name" label="Company Name" />- <Input name="addressLine1" label="Address" />- <Input name="city" label="City" />- <Input name="stateProvince" label="State / Province" />- <Input name="postalCode" label="Postal Code" />- <Country name="countryCode" />+ <AddressAutocomplete /><Input name="website" label="Website" /><Currency name="baseCurrencyCode" label="Base Currency" /></VStack>