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.

feat: init google places

edsammy5be23e92e5b5
diff --git a/.env.example b/.env.example
index d4b7dd7cb3..495655a89d 100644
--- a/.env.example
+++ b/.env.example
@@ -40,4 +40,6 @@ VERCEL_URL="http://localhost:3000"
ANTHROPIC_API_KEY="sk-ant-***************"
-OPENAI_API_KEY="sk-proj-*****************"
\ No newline at end of file
+OPENAI_API_KEY="sk-proj-*****************"
+
+GOOGLE_PLACES_API_KEY="*******************"
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index e6c6cbe05b..bcd5887ba5 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -17,6 +17,7 @@ import { usePermissions } from "./usePermissions";
import { useRealtime } from "./useRealtime";
import { useScrollPosition } from "./useScrollPosition";
import { useUser } from "./useUser";
+import { useGooglePlaces } from "./useGooglePlaces";
export {
useCurrencyFormatter,
@@ -34,4 +35,5 @@ export {
useScrollPosition,
useUrlParams,
useUser,
+ useGooglePlaces,
};
diff --git a/apps/erp/app/hooks/useGooglePlaces.tsx b/apps/erp/app/hooks/useGooglePlaces.tsx
new file mode 100644
index 0000000000..f3eeec2236
--- /dev/null
+++ b/apps/erp/app/hooks/useGooglePlaces.tsx
@@ -0,0 +1,228 @@
+import { useState, useCallback } from "react";
+import { GOOGLE_PLACES_API_KEY } from "@carbon/auth";
+
+interface PlaceSuggestion {
+ placeId: string;
+ text: string;
+}
+
+interface AddressComponents {
+ addressLine1: string;
+ addressLine2: string;
+ city: string;
+ stateProvince: string;
+ postalCode: string;
+ countryCode: string;
+}
+
+interface GooglePlacesApiResponse {
+ suggestions?: Array<{
+ placePrediction?: {
+ place: string;
+ placeId: string;
+ text: {
+ text: string;
+ };
+ };
+ }>;
+}
+
+interface PlaceDetailsResponse {
+ addressComponents?: Array<{
+ longText: string;
+ shortText: string;
+ types: string[];
+ }>;
+}
+
+export const useGooglePlaces = () => {
+ const [suggestions, setSuggestions] = useState<PlaceSuggestion[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const getSuggestions = useCallback(async (input: string) => {
+ if (!GOOGLE_PLACES_API_KEY) {
+ setError("Google Places API key not configured");
+ return;
+ }
+
+ if (!input || input.length < 3) {
+ setSuggestions([]);
+ setError(null);
+ return;
+ }
+
+ setLoading(true);
+ setError(null);
+
+ try {
+ const response = await fetch(
+ "https://places.googleapis.com/v1/places:autocomplete",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-Goog-Api-Key": GOOGLE_PLACES_API_KEY,
+ },
+ body: JSON.stringify({
+ input,
+ includedPrimaryTypes: ["street_address"],
+ languageCode: "en",
+ }),
+ }
+ );
+
+ if (!response.ok) {
+ throw new Error(`Google Places API error: ${response.status}`);
+ }
+
+ const data: GooglePlacesApiResponse = await response.json();
+
+ const placeSuggestions: PlaceSuggestion[] = (data.suggestions || [])
+ .map((suggestion) => {
+ const prediction = suggestion.placePrediction;
+ if (!prediction) return null;
+
+ return {
+ placeId: prediction.placeId,
+ text: prediction.text.text,
+ };
+ })
+ .filter(
+ (suggestion): suggestion is PlaceSuggestion => suggestion !== null
+ );
+
+ setSuggestions(placeSuggestions);
+ } catch (err) {
+ console.error("Google Places API error:", err);
+ setError(
+ err instanceof Error ? err.message : "Failed to fetch suggestions"
+ );
+ setSuggestions([]);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ 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}`,
+ {
+ 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[] }>
+ ): AddressComponents => {
+ if (!components) {
+ return {
+ addressLine1: "",
+ addressLine2: "",
+ city: "",
+ stateProvince: "",
+ postalCode: "",
+ countryCode: "",
+ };
+ }
+
+ const addressMap: Record<string, string> = {};
+
+ components.forEach((component) => {
+ const types = component.types;
+
+ if (types.includes("street_number")) {
+ addressMap.streetNumber = component.longText;
+ }
+ if (types.includes("route")) {
+ addressMap.route = component.longText;
+ }
+ if (types.includes("subpremise")) {
+ addressMap.subpremise = component.longText;
+ }
+ if (types.includes("locality")) {
+ addressMap.city = component.longText;
+ }
+ if (types.includes("administrative_area_level_1")) {
+ addressMap.stateProvince = component.shortText;
+ }
+ if (types.includes("postal_code")) {
+ addressMap.postalCode = component.longText;
+ }
+ if (types.includes("country")) {
+ addressMap.countryCode = component.shortText;
+ }
+ });
+
+ return {
+ addressLine1: `${addressMap.streetNumber || ""} ${
+ addressMap.route || ""
+ }`.trim(),
+ addressLine2: addressMap.subpremise || "",
+ city: addressMap.city || "",
+ stateProvince: addressMap.stateProvince || "",
+ postalCode: addressMap.postalCode || "",
+ countryCode: addressMap.countryCode || "",
+ };
+ };
+
+ const selectPlace = useCallback(
+ async (placeId: string): Promise<AddressComponents | null> => {
+ const addressComponents = await getPlaceDetails(placeId);
+ setSuggestions([]); // Clear suggestions after selection
+ return addressComponents;
+ },
+ [getPlaceDetails]
+ );
+
+ const clearSuggestions = useCallback(() => {
+ setSuggestions([]);
+ setError(null);
+ }, []);
+
+ return {
+ suggestions,
+ loading,
+ error,
+ getSuggestions,
+ selectPlace,
+ clearSuggestions,
+ };
+};
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index ba7dbc84d1..8aa1a09e25 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -61,6 +61,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
NOVU_APPLICATION_ID,
VERCEL_ENV,
VERCEL_URL,
+ GOOGLE_PLACES_API_KEY,
} = getBrowserEnv();
const sessionFlash = await getSessionFlash(request);
@@ -78,6 +79,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
NOVU_APPLICATION_ID,
VERCEL_ENV,
VERCEL_URL,
+ GOOGLE_PLACES_API_KEY,
},
mode: getMode(request),
theme: getTheme(request),
diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.ts
index 97c71e7666..d99c4ecb8d 100644
--- a/packages/auth/src/config/env.ts
+++ b/packages/auth/src/config/env.ts
@@ -97,6 +97,10 @@ export const EXCHANGE_RATES_API_KEY = getEnv("EXCHANGE_RATES_API_KEY", {
isSecret: true,
});
+export const GOOGLE_PLACES_API_KEY = getEnv("GOOGLE_PLACES_API_KEY", {
+ isRequired: false,
+});
+
const itarEnvironment = getEnv("CONTROLLED_ENVIRONMENT", {
isRequired: false,
isSecret: false,
@@ -230,6 +234,7 @@ export function getBrowserEnv() {
VERCEL_URL,
NODE_ENV,
CLOUDFLARE_TURNSTILE_SITE_KEY,
+ GOOGLE_PLACES_API_KEY,
};
}