feat(jobs/new): location autocomplete using /api/v1/locations/search

- Replace free-text location input with debounced autocomplete
- On country select, fetch its numeric ID from /api/v1/locations/countries
  and use it to scope the search results to that country
- Typing ≥2 chars in location field triggers GET /api/v1/locations/search
  with 350ms debounce; results show city (blue) and state (green) badges
- On result selection, stores cityId + regionId and sets the display label
  to "Name, Region" format; IDs are included in the job creation payload
- Spinner shown while searching; dropdown closes on outside click / select
- CEP search button preserved alongside the autocomplete

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Tiago Yamamoto 2026-02-22 12:39:46 -06:00
parent 2686b69506
commit fd085ec193

View file

@ -1,7 +1,7 @@
"use client";
import Image from "next/image";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Search } from "lucide-react";
import { toast } from "sonner";
@ -22,6 +22,21 @@ type SalaryMode = "range" | "fixed";
type ApplicationChannel = "email" | "url" | "phone";
type LocationResult = {
id: number;
name: string;
type: "city" | "state";
country_id: number;
state_id?: number;
region_name?: string;
};
type ApiCountry = {
id: number;
name: string;
iso2: string;
};
const cleanDigits = (value: string) => value.replace(/\D/g, "");
const isValidCNPJ = (value: string) => {
@ -626,11 +641,70 @@ export default function PostJobPage() {
const [paymentMethod, setPaymentMethod] = useState("");
const [descriptionLanguageTouched, setDescriptionLanguageTouched] = useState(false);
// Location autocomplete
const [apiCountries, setApiCountries] = useState<ApiCountry[]>([]);
const [locationIds, setLocationIds] = useState<{ cityId: number | null; regionId: number | null }>({ cityId: null, regionId: null });
const [locationResults, setLocationResults] = useState<LocationResult[]>([]);
const [locationSearching, setLocationSearching] = useState(false);
const [showLocationDropdown, setShowLocationDropdown] = useState(false);
const locationRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (descriptionLanguageTouched) return;
setJob((prev) => ({ ...prev, descriptionLanguage: locale }));
}, [descriptionLanguageTouched, locale]);
// Fetch countries from API for location search (numeric IDs needed)
useEffect(() => {
const apiBase = process.env.NEXT_PUBLIC_API_URL || "";
fetch(`${apiBase}/api/v1/locations/countries`)
.then((r) => r.json())
.then((data: ApiCountry[]) => setApiCountries(data))
.catch(() => {});
}, []);
// Derive numeric country ID from selected ISO2 code
const selectedCountryId = useMemo(
() => apiCountries.find((c) => c.iso2 === job.country)?.id ?? null,
[apiCountries, job.country]
);
// Debounced location search
const searchLocation = useCallback((query: string, countryId: number) => {
const apiBase = process.env.NEXT_PUBLIC_API_URL || "";
setLocationSearching(true);
fetch(`${apiBase}/api/v1/locations/search?q=${encodeURIComponent(query)}&country_id=${countryId}`)
.then((r) => r.json())
.then((data) => {
setLocationResults(Array.isArray(data) ? data : []);
setShowLocationDropdown(true);
})
.catch(() => setLocationResults([]))
.finally(() => setLocationSearching(false));
}, []);
useEffect(() => {
const query = job.location.trim();
if (query.length < 2 || !selectedCountryId) {
setLocationResults([]);
setShowLocationDropdown(false);
return;
}
const timer = setTimeout(() => searchLocation(query, selectedCountryId), 350);
return () => clearTimeout(timer);
}, [job.location, selectedCountryId, searchLocation]);
// Close dropdown on outside click
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (locationRef.current && !locationRef.current.contains(e.target as Node)) {
setShowLocationDropdown(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const currentPrice = useMemo(() => {
const country = billing.billingCountry || job.country;
return pricingByCountry[country] || { amount: "Consulte comercial", duration: "30 dias" };
@ -763,6 +837,8 @@ export default function PostJobPage() {
title: job.title,
description: job.description,
location: `${job.location}, ${job.country}`,
...(locationIds.cityId && { cityId: locationIds.cityId }),
...(locationIds.regionId && { regionId: locationIds.regionId }),
salaryMin: salaryMin || null,
salaryMax: salaryMax || null,
salaryType: job.salaryPeriod,
@ -878,11 +954,58 @@ export default function PostJobPage() {
<div className="grid md:grid-cols-[1fr_auto] gap-4 items-end">
<div>
<Label>{c.labels.location}</Label>
<div ref={locationRef} className="relative">
<Input
placeholder={c.labels.locationPlaceholder}
value={job.location}
onChange={(e) => setJob({ ...job, location: e.target.value })}
autoComplete="off"
onChange={(e) => {
setJob({ ...job, location: e.target.value });
setLocationIds({ cityId: null, regionId: null });
}}
onFocus={() => {
if (locationResults.length > 0) setShowLocationDropdown(true);
}}
/>
{locationSearching && (
<div className="absolute right-3 top-2.5">
<div className="h-4 w-4 animate-spin rounded-full border-2 border-[#ef9225] border-t-transparent" />
</div>
)}
{showLocationDropdown && locationResults.length > 0 && (
<div className="absolute z-50 mt-1 w-full rounded-md border bg-white shadow-md max-h-60 overflow-y-auto">
{locationResults.map((result) => (
<button
key={`${result.type}-${result.id}`}
type="button"
className="flex w-full items-center justify-between px-3 py-2 text-left hover:bg-gray-50"
onMouseDown={(e) => {
e.preventDefault();
const label = result.region_name
? `${result.name}, ${result.region_name}`
: result.name;
setJob({ ...job, location: label });
setLocationIds({
cityId: result.type === "city" ? result.id : null,
regionId: result.type === "state" ? result.id : (result.state_id ?? null),
});
setShowLocationDropdown(false);
}}
>
<span>
<span className="text-sm font-medium">{result.name}</span>
{result.region_name && (
<span className="ml-1 text-xs text-muted-foreground"> {result.region_name}</span>
)}
</span>
<span className={`rounded px-1.5 py-0.5 text-xs ${result.type === "city" ? "bg-blue-50 text-blue-600" : "bg-emerald-50 text-emerald-600"}`}>
{result.type}
</span>
</button>
))}
</div>
)}
</div>
<p className="text-xs text-muted-foreground mt-1">{c.labels.locationHint}</p>
</div>
<Button type="button" variant="outline" className="h-10 w-10 p-0" onClick={() => setJob({ ...job, useCepSearch: !job.useCepSearch })}>