@garagem-ai/site-sdk 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ import { callJson, type FetchLike } from "./fetchers";
2
+ import { coerceSiteId, normalizeBaseUrl } from "./internal/url";
3
+ import type { RequestNextOptions } from "./types";
4
+ import type {
5
+ PhotoSearchItem,
6
+ PhotoSearchParams,
7
+ PhotoSearchResult,
8
+ } from "./types-photo-search";
9
+
10
+ export interface SearchListingPhotosOptions {
11
+ /** Garagem API base URL. Defaults to `https://app.garagem.ai`. */
12
+ baseUrl?: string;
13
+ /** Override the fetch implementation (testing, edge runtimes, retries). */
14
+ fetch?: FetchLike;
15
+ /** Next.js App Router caching hints. Ignored on other runtimes. */
16
+ next?: RequestNextOptions;
17
+ }
18
+
19
+ /** Shortest query the API will embed; shorter text returns the empty result locally. */
20
+ export const PHOTO_SEARCH_MIN_QUERY_LENGTH = 3;
21
+
22
+ const EMPTY_RESULT: PhotoSearchResult = {
23
+ available: true,
24
+ items: [],
25
+ total: 0,
26
+ page: 1,
27
+ limit: 12,
28
+ };
29
+
30
+ function positiveInt(value: number | undefined): number | null {
31
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1) {
32
+ return null;
33
+ }
34
+ return Math.floor(value);
35
+ }
36
+
37
+ /** Build the request URL (exported for tests and custom transports). */
38
+ export function photoSearchUrl(
39
+ siteId: string,
40
+ params: PhotoSearchParams,
41
+ baseUrl?: string
42
+ ): string {
43
+ const search = new URLSearchParams();
44
+ search.set("q", params.q.trim());
45
+ const limit = positiveInt(params.limit);
46
+ if (limit != null) search.set("limit", String(limit));
47
+ const page = positiveInt(params.page);
48
+ if (page != null) search.set("page", String(page));
49
+ return `${normalizeBaseUrl(baseUrl)}/api/sites/${encodeURIComponent(
50
+ siteId
51
+ )}/search/photos?${search.toString()}`;
52
+ }
53
+
54
+ /**
55
+ * Search a site's listings by what their public photos show.
56
+ *
57
+ * Returns `{ available: false, items: [] }` (not an error) when the tenant
58
+ * has not enabled photo search, so a site can hide the control. Queries
59
+ * shorter than {@link PHOTO_SEARCH_MIN_QUERY_LENGTH} resolve locally to an
60
+ * empty result without a request.
61
+ *
62
+ * @example
63
+ * const result = await searchListingPhotos("abc", { q: "varanda gourmet" });
64
+ * const cards = applyMatchedPhotoCover(
65
+ * result.items.map((item) => item.listing),
66
+ * result
67
+ * );
68
+ */
69
+ export async function searchListingPhotos(
70
+ siteId: string,
71
+ params: PhotoSearchParams,
72
+ options: SearchListingPhotosOptions = {}
73
+ ): Promise<PhotoSearchResult> {
74
+ const q = (params?.q ?? "").trim();
75
+ const limit = positiveInt(params?.limit) ?? EMPTY_RESULT.limit;
76
+ if (q.length < PHOTO_SEARCH_MIN_QUERY_LENGTH) {
77
+ return { ...EMPTY_RESULT, limit, page: positiveInt(params?.page) ?? 1 };
78
+ }
79
+ const resolvedSiteId = await coerceSiteId(siteId);
80
+ const url = photoSearchUrl(resolvedSiteId, { ...params, q }, options.baseUrl);
81
+ const data = await callJson<Partial<PhotoSearchResult>>(
82
+ url,
83
+ {
84
+ method: "GET",
85
+ headers: { Accept: "application/json" },
86
+ next: options.next,
87
+ },
88
+ options.fetch ?? fetch
89
+ );
90
+ const items: PhotoSearchItem[] = Array.isArray(data.items) ? data.items : [];
91
+ return {
92
+ available: data.available !== false,
93
+ items,
94
+ total: typeof data.total === "number" ? data.total : items.length,
95
+ page:
96
+ typeof data.page === "number"
97
+ ? data.page
98
+ : (positiveInt(params.page) ?? 1),
99
+ limit: typeof data.limit === "number" ? data.limit : limit,
100
+ };
101
+ }
package/src/index.ts CHANGED
@@ -259,6 +259,8 @@ export {
259
259
  studioListingDetailInstruction,
260
260
  studioSearchInstruction,
261
261
  studioSearchLandmarkInstruction,
262
+ studioPhotoSearchInstruction,
263
+ isPhotoSearchOnPin,
262
264
  studioSdkPinInstruction,
263
265
  studioSiteWidthCss,
264
266
  hasShowcaseLeadsPostUrl,
@@ -271,3 +273,62 @@ export {
271
273
  type CreateGaragemClientOptions,
272
274
  type GaragemClient,
273
275
  } from "./client";
276
+
277
+ // ---------------------------------------------------------------------------
278
+ // Market data (requires the IPTU module — `iptu_itbi_integration`).
279
+ // Self-contained block: fetchers, headless pt-BR labels and types. Every
280
+ // helper answers `available: false` for tenants without the module.
281
+ // ---------------------------------------------------------------------------
282
+ export {
283
+ getListingMarketPosition,
284
+ getNeighborhoodSummary,
285
+ requestPriceEstimate,
286
+ type GetListingMarketPositionOptions,
287
+ type GetNeighborhoodSummaryOptions,
288
+ type RequestPriceEstimateOptions,
289
+ } from "./fetchers-market";
290
+
291
+ export { marketPositionLabel, priceBandLabel } from "./market-labels";
292
+
293
+ export type {
294
+ ListingMarketPosition,
295
+ MarketListingType,
296
+ MarketPriceBand,
297
+ MarketPropertyType,
298
+ MarketUnavailableReason,
299
+ NeighborhoodSummary,
300
+ NeighborhoodSummaryQuery,
301
+ PriceEstimate,
302
+ PriceEstimateConfidence,
303
+ PriceEstimateInput,
304
+ } from "./types-market";
305
+
306
+ export {
307
+ marketExportsAvailableAt,
308
+ studioMarketInstruction,
309
+ } from "./studio-contract";
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // Photo search ("busca pelo que as fotos mostram"): search a site's catalog by
313
+ // what the public photos show and use the matched photo as the card cover.
314
+ // Self-contained block — the React hook lives on `@garagem-ai/site-sdk/react`.
315
+ // ---------------------------------------------------------------------------
316
+ export {
317
+ PHOTO_SEARCH_MIN_QUERY_LENGTH,
318
+ photoSearchUrl,
319
+ searchListingPhotos,
320
+ type SearchListingPhotosOptions,
321
+ } from "./fetchers-photo-search";
322
+ export {
323
+ MATCHED_PHOTO_COVER_MAX_DISTANCE,
324
+ applyMatchedPhotoCover,
325
+ resolveMatchedCoverPhoto,
326
+ type ApplyMatchedPhotoCoverOptions,
327
+ } from "./photo-search-cover";
328
+ export type {
329
+ ListingWithMatchedPhoto,
330
+ MatchedListingPhoto,
331
+ PhotoSearchItem,
332
+ PhotoSearchParams,
333
+ PhotoSearchResult,
334
+ } from "./types-photo-search";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Headless pt-BR labels for the market-data blocks. Every helper returns
3
+ * `null` when there is nothing to say (unavailable, missing numbers), so a
4
+ * component can `label && <p>{label}</p>` without re-checking `available`.
5
+ */
6
+ import type { ListingMarketPosition, MarketPriceBand } from "./types-market";
7
+
8
+ /**
9
+ * "8% abaixo da mediana do bairro" / "12% acima da mediana do bairro" /
10
+ * "Na mediana do bairro". `null` when the position is unavailable.
11
+ */
12
+ export function marketPositionLabel(
13
+ position:
14
+ | Pick<ListingMarketPosition, "available" | "percentVsMedian">
15
+ | null
16
+ | undefined
17
+ ): string | null {
18
+ if (!position?.available) return null;
19
+ const percent = position.percentVsMedian;
20
+ if (percent == null || !Number.isFinite(percent)) return null;
21
+ const rounded = Math.round(percent);
22
+ if (rounded === 0) return "Na mediana do bairro";
23
+ const magnitude = Math.abs(rounded);
24
+ return rounded < 0
25
+ ? `${magnitude}% abaixo da mediana do bairro`
26
+ : `${magnitude}% acima da mediana do bairro`;
27
+ }
28
+
29
+ const BAND_LABELS: Record<MarketPriceBand, string> = {
30
+ below_range: "Abaixo da faixa do bairro",
31
+ lower_range: "Na faixa do bairro, abaixo da mediana",
32
+ upper_range: "Na faixa do bairro, acima da mediana",
33
+ above_range: "Acima da faixa do bairro",
34
+ };
35
+
36
+ /**
37
+ * Quartile band copy. Accepts the band itself or a position; `null` when
38
+ * the band is missing or the position is unavailable.
39
+ */
40
+ export function priceBandLabel(
41
+ input:
42
+ | MarketPriceBand
43
+ | Pick<ListingMarketPosition, "available" | "band">
44
+ | null
45
+ | undefined
46
+ ): string | null {
47
+ if (!input) return null;
48
+ if (typeof input === "string") return BAND_LABELS[input] ?? null;
49
+ if (!input.available || !input.band) return null;
50
+ return BAND_LABELS[input.band] ?? null;
51
+ }
@@ -0,0 +1,90 @@
1
+ import type { Listing } from "./types";
2
+ import type {
3
+ ListingWithMatchedPhoto,
4
+ MatchedListingPhoto,
5
+ PhotoSearchItem,
6
+ PhotoSearchResult,
7
+ } from "./types-photo-search";
8
+
9
+ /**
10
+ * Largest vector distance a photo may have and still replace the cover.
11
+ * Mirrors the CRM "Foto que combina com a busca" threshold
12
+ * (`MATCHED_PHOTO_COVER_MAX_DISTANCE` in apps/foundation); keyword matches
13
+ * (`distance: null`) are exact caption / room-type matches and always win.
14
+ */
15
+ export const MATCHED_PHOTO_COVER_MAX_DISTANCE = 0.4;
16
+
17
+ export interface ApplyMatchedPhotoCoverOptions {
18
+ /** Override {@link MATCHED_PHOTO_COVER_MAX_DISTANCE}. `Infinity` accepts every match. */
19
+ maxDistance?: number;
20
+ }
21
+
22
+ /**
23
+ * The photo that replaces a card cover, or `null` to keep the card's own
24
+ * cover: keyword matches as-is, vector matches only within `maxDistance`.
25
+ */
26
+ export function resolveMatchedCoverPhoto(
27
+ photo: MatchedListingPhoto | null | undefined,
28
+ maxDistance: number = MATCHED_PHOTO_COVER_MAX_DISTANCE
29
+ ): MatchedListingPhoto | null {
30
+ if (!photo || !photo.src) return null;
31
+ if (photo.distance == null) return photo;
32
+ if (!Number.isFinite(photo.distance)) return null;
33
+ return photo.distance <= maxDistance ? photo : null;
34
+ }
35
+
36
+ function itemsOf(
37
+ photoResults:
38
+ | PhotoSearchResult
39
+ | ReadonlyArray<PhotoSearchItem>
40
+ | null
41
+ | undefined
42
+ ): ReadonlyArray<PhotoSearchItem> {
43
+ if (!photoResults) return [];
44
+ return Array.isArray(photoResults)
45
+ ? photoResults
46
+ : ((photoResults as PhotoSearchResult).items ?? []);
47
+ }
48
+
49
+ /**
50
+ * Headless mirror of the CRM cover switch: for every card whose listing has
51
+ * a photo-search match, swap `coverImage` for the matched photo and attach
52
+ * it as `matchedPhoto`. Cards without a match (or whose match is too far)
53
+ * keep their cover with `matchedPhoto: null`. Order is preserved — pass
54
+ * `result.items.map((item) => item.listing)` to render the photo-search
55
+ * page nearest-first, or the regular search page to only swap covers.
56
+ *
57
+ * @example
58
+ * const cards = applyMatchedPhotoCover(search.listings, photos.items);
59
+ * cards.map((card) => <Card model={toListingCardModel(card)} badge={card.matchedPhoto} />)
60
+ */
61
+ export function applyMatchedPhotoCover<T extends Listing>(
62
+ cards: ReadonlyArray<T>,
63
+ photoResults:
64
+ | PhotoSearchResult
65
+ | ReadonlyArray<PhotoSearchItem>
66
+ | null
67
+ | undefined,
68
+ options: ApplyMatchedPhotoCoverOptions = {}
69
+ ): Array<T & ListingWithMatchedPhoto> {
70
+ const maxDistance = options.maxDistance ?? MATCHED_PHOTO_COVER_MAX_DISTANCE;
71
+ const photoByListingId = new Map<string, MatchedListingPhoto>();
72
+ for (const item of itemsOf(photoResults)) {
73
+ const id = item?.listing?.id;
74
+ if (!id || photoByListingId.has(id)) continue;
75
+ const photo = resolveMatchedCoverPhoto(item.matchedPhoto, maxDistance);
76
+ if (photo) photoByListingId.set(id, photo);
77
+ }
78
+ return cards.map((card) => {
79
+ const photo = photoByListingId.get(card.id) ?? null;
80
+ if (!photo) return { ...card, matchedPhoto: null };
81
+ return {
82
+ ...card,
83
+ coverImage: {
84
+ src: photo.src,
85
+ alt: photo.alt || card.coverImage?.alt || card.title,
86
+ },
87
+ matchedPhoto: photo,
88
+ };
89
+ });
90
+ }
@@ -7,3 +7,11 @@ export type {
7
7
  SiteIdInput,
8
8
  UsePublicSearchOptions,
9
9
  } from "./types";
10
+
11
+ // --- Photo search ("busca pelo que as fotos mostram") ----------------------
12
+ export {
13
+ PHOTO_SEARCH_DEBOUNCE_MS,
14
+ usePublicPhotoSearch,
15
+ type PublicPhotoSearchState,
16
+ type UsePublicPhotoSearchOptions,
17
+ } from "./use-public-photo-search";
@@ -0,0 +1,165 @@
1
+ "use client";
2
+
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+
5
+ import type { FetchLike } from "../fetchers";
6
+ import {
7
+ PHOTO_SEARCH_MIN_QUERY_LENGTH,
8
+ searchListingPhotos,
9
+ } from "../fetchers-photo-search";
10
+ import { coerceSiteId } from "../internal/url";
11
+ import { applyMatchedPhotoCover } from "../photo-search-cover";
12
+ import type {
13
+ ListingWithMatchedPhoto,
14
+ PhotoSearchItem,
15
+ PhotoSearchResult,
16
+ } from "../types-photo-search";
17
+ import type { SiteIdInput } from "./types";
18
+
19
+ /** Same debounce as the CRM "Foto que combina com a busca" evidence lane. */
20
+ export const PHOTO_SEARCH_DEBOUNCE_MS = 400;
21
+
22
+ export type UsePublicPhotoSearchOptions = {
23
+ siteId: SiteIdInput;
24
+ baseUrl?: string;
25
+ /**
26
+ * The text to search by (usually the main search box). The hook trims it,
27
+ * debounces requests and ignores responses that arrive out of order.
28
+ */
29
+ query: string;
30
+ /** Listings per page (API default 12, cap 24). */
31
+ limit?: number;
32
+ /** 1-based page. */
33
+ page?: number;
34
+ /** `false` pauses the hook and clears its results (e.g. a hidden panel). */
35
+ enabled?: boolean;
36
+ /** Milliseconds to wait after the last `query` change. Default 400. */
37
+ debounceMs?: number;
38
+ /** Override the fetch implementation (testing, retries). */
39
+ fetch?: FetchLike;
40
+ };
41
+
42
+ export type PublicPhotoSearchState = {
43
+ /** `false` once the API says the tenant has no photo search: hide the UI. */
44
+ available: boolean;
45
+ /** Nearest-first matches, each with its card and matched photo. */
46
+ items: PhotoSearchItem[];
47
+ /** `items` as cards with the matched photo already applied as cover. */
48
+ listings: ListingWithMatchedPhoto[];
49
+ total: number;
50
+ page: number;
51
+ limit: number;
52
+ /** A request is in flight (or scheduled by the debounce). */
53
+ loading: boolean;
54
+ error: Error | null;
55
+ /** The trimmed query the current `items` answer (`""` before the first result). */
56
+ query: string;
57
+ };
58
+
59
+ const EMPTY: PhotoSearchResult = {
60
+ available: true,
61
+ items: [],
62
+ total: 0,
63
+ page: 1,
64
+ limit: 12,
65
+ };
66
+
67
+ async function resolveSiteIdInput(siteId: SiteIdInput): Promise<string> {
68
+ const value = typeof siteId === "function" ? siteId() : siteId;
69
+ return coerceSiteId(value);
70
+ }
71
+
72
+ export function usePublicPhotoSearch(
73
+ options: UsePublicPhotoSearchOptions
74
+ ): PublicPhotoSearchState {
75
+ const {
76
+ siteId,
77
+ baseUrl,
78
+ limit,
79
+ page,
80
+ enabled = true,
81
+ debounceMs = PHOTO_SEARCH_DEBOUNCE_MS,
82
+ fetch: fetchImpl,
83
+ } = options;
84
+ const query = (options.query ?? "").trim();
85
+ const searchable = enabled && query.length >= PHOTO_SEARCH_MIN_QUERY_LENGTH;
86
+
87
+ const siteIdRef = useRef(siteId);
88
+ siteIdRef.current = siteId;
89
+ const siteIdToken = typeof siteId === "string" ? siteId : null;
90
+ const fetchRef = useRef(fetchImpl);
91
+ fetchRef.current = fetchImpl;
92
+ const requestRef = useRef(0);
93
+
94
+ const [result, setResult] = useState<PhotoSearchResult>(EMPTY);
95
+ const [answered, setAnswered] = useState("");
96
+ const [loading, setLoading] = useState(searchable);
97
+ const [error, setError] = useState<Error | null>(null);
98
+
99
+ useEffect(() => {
100
+ const requestId = ++requestRef.current;
101
+ if (!searchable) {
102
+ setResult(EMPTY);
103
+ setAnswered("");
104
+ setLoading(false);
105
+ setError(null);
106
+ return;
107
+ }
108
+ setLoading(true);
109
+ let active = true;
110
+ let timer: ReturnType<typeof setTimeout> | null = null;
111
+ const run = () => {
112
+ void (async () => {
113
+ try {
114
+ const id = await resolveSiteIdInput(siteIdRef.current);
115
+ const next = await searchListingPhotos(
116
+ id,
117
+ { q: query, limit, page },
118
+ { baseUrl, fetch: fetchRef.current }
119
+ );
120
+ if (!active || requestId !== requestRef.current) return;
121
+ setResult(next);
122
+ setAnswered(query);
123
+ setError(null);
124
+ } catch (caught) {
125
+ if (!active || requestId !== requestRef.current) return;
126
+ setResult(EMPTY);
127
+ setAnswered(query);
128
+ setError(
129
+ caught instanceof Error ? caught : new Error(String(caught))
130
+ );
131
+ } finally {
132
+ if (active && requestId === requestRef.current) setLoading(false);
133
+ }
134
+ })();
135
+ };
136
+ // `0` means no wait. A zero-delay timer still yields a macrotask.
137
+ if (debounceMs <= 0) run();
138
+ else timer = setTimeout(run, debounceMs);
139
+ return () => {
140
+ active = false;
141
+ if (timer != null) clearTimeout(timer);
142
+ };
143
+ }, [searchable, query, limit, page, baseUrl, siteIdToken, debounceMs]);
144
+
145
+ const listings = useMemo(
146
+ () =>
147
+ applyMatchedPhotoCover(
148
+ result.items.map((item) => item.listing),
149
+ result.items
150
+ ),
151
+ [result.items]
152
+ );
153
+
154
+ return {
155
+ available: result.available,
156
+ items: result.items,
157
+ listings,
158
+ total: result.total,
159
+ page: result.page,
160
+ limit: result.limit,
161
+ loading,
162
+ error,
163
+ query: answered,
164
+ };
165
+ }