@garagem-ai/site-sdk 0.9.0 → 0.10.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.
- package/dist/index.d.mts +135 -13
- package/dist/index.d.ts +135 -13
- package/dist/index.js +436 -69
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +423 -69
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +4 -4
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +4 -4
- package/dist/react.mjs.map +1 -1
- package/dist/{types-photo-search-D88oevZv.d.mts → types-photo-search-DIoV75SN.d.mts} +1 -1
- package/dist/{types-photo-search-D88oevZv.d.ts → types-photo-search-DIoV75SN.d.ts} +1 -1
- package/package.json +2 -2
- package/src/index.ts +24 -0
- package/src/leads.ts +47 -3
- package/src/map-search.ts +9 -5
- package/src/seller-lead.ts +428 -0
- package/src/studio-contract.ts +71 -11
|
@@ -1018,7 +1018,7 @@ declare function searchListingsInPolygon(siteId: string, options: MapPolygonSear
|
|
|
1018
1018
|
declare function mapClusterCellDegrees(zoom: number): number;
|
|
1019
1019
|
/**
|
|
1020
1020
|
* Headless grid cluster. A cell with one pin keeps that pin's coordinates.
|
|
1021
|
-
* A group centroid is rounded
|
|
1021
|
+
* A group centroid is rounded to the members' own precision so clustering
|
|
1022
1022
|
* cannot invent extra decimals.
|
|
1023
1023
|
*/
|
|
1024
1024
|
declare function clusterPins(pins: readonly MapPin[], zoom: number): MapPinCluster[];
|
|
@@ -1018,7 +1018,7 @@ declare function searchListingsInPolygon(siteId: string, options: MapPolygonSear
|
|
|
1018
1018
|
declare function mapClusterCellDegrees(zoom: number): number;
|
|
1019
1019
|
/**
|
|
1020
1020
|
* Headless grid cluster. A cell with one pin keeps that pin's coordinates.
|
|
1021
|
-
* A group centroid is rounded
|
|
1021
|
+
* A group centroid is rounded to the members' own precision so clustering
|
|
1022
1022
|
* cannot invent extra decimals.
|
|
1023
1023
|
*/
|
|
1024
1024
|
declare function clusterPins(pins: readonly MapPin[], zoom: number): MapPinCluster[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@garagem-ai/site-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Typed, runtime-agnostic SDK for building custom real estate sites against the Garagem platform. Drop into any Next.js (or other JS) project to fetch listings, sites and CMS data.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"@types/react": "19.1.4",
|
|
59
59
|
"eslint": "^9.0.0",
|
|
60
60
|
"jsdom": "^26.1.0",
|
|
61
|
-
"next": "16.4.0
|
|
61
|
+
"next": "16.4.0",
|
|
62
62
|
"react": "19.2.1",
|
|
63
63
|
"react-dom": "19.2.1",
|
|
64
64
|
"tsup": "^8.0.1",
|
package/src/index.ts
CHANGED
|
@@ -100,6 +100,8 @@ export {
|
|
|
100
100
|
export {
|
|
101
101
|
LeadSubmitError,
|
|
102
102
|
getLeadUi,
|
|
103
|
+
isValidEmail,
|
|
104
|
+
isValidName,
|
|
103
105
|
studioDefaultLeadUi,
|
|
104
106
|
submitContactLead,
|
|
105
107
|
submitVisitLead,
|
|
@@ -114,6 +116,25 @@ export {
|
|
|
114
116
|
type VisitLeadInput,
|
|
115
117
|
} from "./leads";
|
|
116
118
|
|
|
119
|
+
export {
|
|
120
|
+
SELLER_LEAD_PHOTO_MAX_BYTES,
|
|
121
|
+
SELLER_LEAD_PHOTO_MAX_COUNT,
|
|
122
|
+
SELLER_LEAD_PHOTO_TYPES,
|
|
123
|
+
STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG,
|
|
124
|
+
sellerAddressErrors,
|
|
125
|
+
sellerPhotoSchedule,
|
|
126
|
+
submitSellerLead,
|
|
127
|
+
uploadSellerLeadPhoto,
|
|
128
|
+
type SellerAddressErrors,
|
|
129
|
+
type SellerAddressField,
|
|
130
|
+
type SellerBusinessType,
|
|
131
|
+
type SellerLeadAddress,
|
|
132
|
+
type SellerLeadInput,
|
|
133
|
+
type SellerLeadProperty,
|
|
134
|
+
type SellerPhotoScheduleConfig,
|
|
135
|
+
type UploadSellerLeadPhotoInput,
|
|
136
|
+
} from "./seller-lead";
|
|
137
|
+
|
|
117
138
|
export {
|
|
118
139
|
AMENITY_FALLBACK_LABELS,
|
|
119
140
|
LISTING_AMENITY_TITLES,
|
|
@@ -264,11 +285,14 @@ export {
|
|
|
264
285
|
studioPublishableKeyInstruction,
|
|
265
286
|
studioPhotoSearchInstruction,
|
|
266
287
|
isPhotoSearchOnPin,
|
|
288
|
+
isSellerLeadOnPin,
|
|
289
|
+
studioSellerLeadSdkInstruction,
|
|
267
290
|
studioSdkPinInstruction,
|
|
268
291
|
studioSiteWidthCss,
|
|
269
292
|
hasShowcaseLeadsPostUrl,
|
|
270
293
|
mapsExportsPublished,
|
|
271
294
|
studioMapsInstruction,
|
|
295
|
+
studioMapSearchInstruction,
|
|
272
296
|
unavailableReactImports,
|
|
273
297
|
type StudioSdkContract,
|
|
274
298
|
} from "./studio-contract";
|
package/src/leads.ts
CHANGED
|
@@ -66,7 +66,7 @@ function browserHost(): string {
|
|
|
66
66
|
* Generated dialogs often omit `siteId` or pass `process.env.GARAGEM_SITE_ID`
|
|
67
67
|
* (undefined in the published browser bundle). Recover from the host.
|
|
68
68
|
*/
|
|
69
|
-
async function resolveLeadSiteId(input: {
|
|
69
|
+
export async function resolveLeadSiteId(input: {
|
|
70
70
|
siteId?: unknown;
|
|
71
71
|
baseUrl?: string;
|
|
72
72
|
fetch?: FetchLike;
|
|
@@ -126,6 +126,10 @@ export type LeadSubmitErrorCode =
|
|
|
126
126
|
| "invalid_listing_id"
|
|
127
127
|
| "invalid_contact"
|
|
128
128
|
| "invalid_slot"
|
|
129
|
+
| "invalid_address"
|
|
130
|
+
| "invalid_property"
|
|
131
|
+
| "invalid_photo"
|
|
132
|
+
| "duplicate_property"
|
|
129
133
|
| "unauthorized"
|
|
130
134
|
| "rate_limited"
|
|
131
135
|
| "not_found"
|
|
@@ -161,8 +165,20 @@ export class LeadSubmitError extends Error {
|
|
|
161
165
|
const UUID_RE =
|
|
162
166
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
163
167
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
168
|
+
const NAME_RE = /^[^\d\s]{2,}.*$/;
|
|
164
169
|
const MESSAGE_MAX = 2000;
|
|
165
170
|
|
|
171
|
+
/** Same email rule the webhook applies. */
|
|
172
|
+
export function isValidEmail(value: string): boolean {
|
|
173
|
+
return EMAIL_RE.test(value.trim());
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** At least two leading non-digit characters, as the editor form requires. */
|
|
177
|
+
export function isValidName(value: string): boolean {
|
|
178
|
+
const name = value.trim();
|
|
179
|
+
return name.length <= 200 && NAME_RE.test(name);
|
|
180
|
+
}
|
|
181
|
+
|
|
166
182
|
const CONTACT_FIELDS: LeadField[] = [
|
|
167
183
|
{ id: "name", required: true },
|
|
168
184
|
{ id: "email", required: false },
|
|
@@ -298,12 +314,38 @@ function normalizeSdkBusinessType(
|
|
|
298
314
|
return undefined;
|
|
299
315
|
}
|
|
300
316
|
|
|
301
|
-
|
|
317
|
+
const ADDRESS_REJECTIONS = new Set([
|
|
318
|
+
"missing_postal_code",
|
|
319
|
+
"ungeocoded_address",
|
|
320
|
+
]);
|
|
321
|
+
|
|
322
|
+
async function rejectedLeadError(
|
|
323
|
+
response: Response
|
|
324
|
+
): Promise<LeadSubmitError | null> {
|
|
325
|
+
if (response.status !== 400 && response.status !== 409) return null;
|
|
326
|
+
const parsed = parseSdkErrorBody(await response.text().catch(() => ""));
|
|
327
|
+
if (response.status === 409 || parsed.reason === "duplicate_property") {
|
|
328
|
+
return new LeadSubmitError(
|
|
329
|
+
parsed.summary || "Garagem SDK: property already registered.",
|
|
330
|
+
{ code: "duplicate_property", status: response.status }
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
if (parsed.reason && ADDRESS_REJECTIONS.has(parsed.reason)) {
|
|
334
|
+
return new LeadSubmitError(`Garagem SDK: ${parsed.reason}.`, {
|
|
335
|
+
code: "invalid_address",
|
|
336
|
+
status: 400,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** @internal Shared by visit/contact and seller submissions. */
|
|
343
|
+
export async function postSiteLead(input: {
|
|
302
344
|
siteId?: string | Promise<string>;
|
|
303
345
|
baseUrl?: string;
|
|
304
346
|
fetch?: FetchLike;
|
|
305
347
|
publishableKey?: string;
|
|
306
|
-
body: SiteSdkLeadBody
|
|
348
|
+
body: SiteSdkLeadBody | Record<string, unknown>;
|
|
307
349
|
}): Promise<LeadSubmitResult> {
|
|
308
350
|
const siteId = await resolveLeadSiteId(input);
|
|
309
351
|
const base = normalizeBaseUrl(input.baseUrl);
|
|
@@ -360,6 +402,8 @@ async function postSiteLead(input: {
|
|
|
360
402
|
status: 404,
|
|
361
403
|
});
|
|
362
404
|
}
|
|
405
|
+
const rejected = await rejectedLeadError(response);
|
|
406
|
+
if (rejected) throw rejected;
|
|
363
407
|
throw new LeadSubmitError(
|
|
364
408
|
`Garagem SDK: lead submit failed (${response.status}).`,
|
|
365
409
|
{ code: "http", status: response.status }
|
package/src/map-search.ts
CHANGED
|
@@ -283,16 +283,20 @@ function usablePin(pin: MapPin): boolean {
|
|
|
283
283
|
);
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
+
/**
|
|
287
|
+
* The finest precision any member shows. A masked `-23.600` prints as
|
|
288
|
+
* `-23.6`, so the coarsest member would round the centroid kilometres away.
|
|
289
|
+
*/
|
|
286
290
|
function groupPrecision(group: readonly MapPin[]): number {
|
|
287
|
-
let
|
|
291
|
+
let max = 0;
|
|
288
292
|
for (const pin of group) {
|
|
289
|
-
|
|
290
|
-
|
|
293
|
+
max = Math.max(
|
|
294
|
+
max,
|
|
291
295
|
coordinateDecimals(pin.lat),
|
|
292
296
|
coordinateDecimals(pin.lng)
|
|
293
297
|
);
|
|
294
298
|
}
|
|
295
|
-
return
|
|
299
|
+
return max;
|
|
296
300
|
}
|
|
297
301
|
|
|
298
302
|
function multiCluster(key: string, group: MapPin[]): MapPinCluster {
|
|
@@ -322,7 +326,7 @@ function singleCluster(pin: MapPin): MapPinCluster {
|
|
|
322
326
|
|
|
323
327
|
/**
|
|
324
328
|
* Headless grid cluster. A cell with one pin keeps that pin's coordinates.
|
|
325
|
-
* A group centroid is rounded
|
|
329
|
+
* A group centroid is rounded to the members' own precision so clustering
|
|
326
330
|
* cannot invent extra decimals.
|
|
327
331
|
*/
|
|
328
332
|
export function clusterPins(
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Headless seller lead (property registration). The site draws the form;
|
|
3
|
+
* the SDK owns validation, photo upload and the webhook contract.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { FetchLike } from "./fetchers";
|
|
7
|
+
import { normalizeBaseUrl } from "./internal/url";
|
|
8
|
+
import {
|
|
9
|
+
LeadSubmitError,
|
|
10
|
+
isValidEmail,
|
|
11
|
+
isValidName,
|
|
12
|
+
postSiteLead,
|
|
13
|
+
resolveLeadSiteId,
|
|
14
|
+
type LeadSubmitResult,
|
|
15
|
+
} from "./leads";
|
|
16
|
+
import { isValidPhone, toE164 } from "./phone";
|
|
17
|
+
import {
|
|
18
|
+
VISIT_TIME_ZONE,
|
|
19
|
+
isVisitSlotAllowed,
|
|
20
|
+
normalizeVisitDate,
|
|
21
|
+
normalizeVisitTime,
|
|
22
|
+
type HHmm,
|
|
23
|
+
type VisitSchedule,
|
|
24
|
+
} from "./schedule";
|
|
25
|
+
|
|
26
|
+
/** Shape of the address search value (Google Places + complement flags). */
|
|
27
|
+
export type SellerLeadAddress = {
|
|
28
|
+
fullAddress: string;
|
|
29
|
+
street: string;
|
|
30
|
+
number?: string;
|
|
31
|
+
neighborhood: string;
|
|
32
|
+
city: string;
|
|
33
|
+
state: string;
|
|
34
|
+
postalCode: string;
|
|
35
|
+
country?: string;
|
|
36
|
+
latitude?: number | null;
|
|
37
|
+
longitude?: number | null;
|
|
38
|
+
blocoTorre?: string;
|
|
39
|
+
unidade?: string;
|
|
40
|
+
noNumber?: boolean;
|
|
41
|
+
noBlocoTorre?: boolean;
|
|
42
|
+
noUnidade?: boolean;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type SellerAddressField =
|
|
46
|
+
| "fullAddress"
|
|
47
|
+
| "number"
|
|
48
|
+
| "blocoTorre"
|
|
49
|
+
| "unidade"
|
|
50
|
+
| "postalCode";
|
|
51
|
+
|
|
52
|
+
export type SellerAddressErrors = Partial<Record<SellerAddressField, string>>;
|
|
53
|
+
|
|
54
|
+
function text(value: string | undefined | null): string {
|
|
55
|
+
return typeof value === "string" ? value.trim() : "";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function inRange(value: unknown, min: number, max: number): boolean {
|
|
59
|
+
return (
|
|
60
|
+
typeof value === "number" &&
|
|
61
|
+
Number.isFinite(value) &&
|
|
62
|
+
value >= min &&
|
|
63
|
+
value <= max
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* pt-BR messages keyed by field; `{}` when the address can be submitted.
|
|
69
|
+
* A missing geocode reports on `fullAddress`: pick a suggestion again.
|
|
70
|
+
*/
|
|
71
|
+
export function sellerAddressErrors(
|
|
72
|
+
address: Partial<SellerLeadAddress> | null | undefined
|
|
73
|
+
): SellerAddressErrors {
|
|
74
|
+
const errors: SellerAddressErrors = {};
|
|
75
|
+
if (!address || !text(address.fullAddress)) {
|
|
76
|
+
errors.fullAddress = "Informe o endereço do imóvel.";
|
|
77
|
+
} else if (
|
|
78
|
+
!inRange(address.latitude, -90, 90) ||
|
|
79
|
+
!inRange(address.longitude, -180, 180) ||
|
|
80
|
+
!text(address.street) ||
|
|
81
|
+
!text(address.city) ||
|
|
82
|
+
!text(address.neighborhood) ||
|
|
83
|
+
!/^[A-Za-z]{2}$/.test(text(address.state))
|
|
84
|
+
) {
|
|
85
|
+
errors.fullAddress = "Selecione o endereço em uma das sugestões.";
|
|
86
|
+
}
|
|
87
|
+
if (!address?.noNumber && !text(address?.number)) {
|
|
88
|
+
errors.number = "Informe o número ou marque sem número.";
|
|
89
|
+
}
|
|
90
|
+
if (!address?.noBlocoTorre && !text(address?.blocoTorre)) {
|
|
91
|
+
errors.blocoTorre = "Informe o bloco/torre ou marque que não tem.";
|
|
92
|
+
}
|
|
93
|
+
if (!address?.noUnidade && !text(address?.unidade)) {
|
|
94
|
+
errors.unidade = "Informe a unidade ou marque que não tem.";
|
|
95
|
+
}
|
|
96
|
+
if (text(address?.postalCode).replace(/\D/g, "").length !== 8) {
|
|
97
|
+
errors.postalCode = "Informe um CEP com 8 dígitos.";
|
|
98
|
+
}
|
|
99
|
+
return errors;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const SELLER_LEAD_PHOTO_MAX_BYTES = 10 * 1024 * 1024;
|
|
103
|
+
export const SELLER_LEAD_PHOTO_MAX_COUNT = 30;
|
|
104
|
+
export const SELLER_LEAD_PHOTO_TYPES = [
|
|
105
|
+
"image/jpeg",
|
|
106
|
+
"image/png",
|
|
107
|
+
"image/webp",
|
|
108
|
+
] as const;
|
|
109
|
+
|
|
110
|
+
type SellerLeadTransport = {
|
|
111
|
+
siteId?: string | Promise<string>;
|
|
112
|
+
baseUrl?: string;
|
|
113
|
+
fetch?: FetchLike;
|
|
114
|
+
/** Site publishable key (`pk_live_…`). Not a secret. */
|
|
115
|
+
publishableKey?: string;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
export type UploadSellerLeadPhotoInput = SellerLeadTransport & {
|
|
119
|
+
file: Blob & { name?: string; type: string; size: number };
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** Uploads one photo and returns its public URL for `submitSellerLead`. */
|
|
123
|
+
export async function uploadSellerLeadPhoto(
|
|
124
|
+
input: UploadSellerLeadPhotoInput
|
|
125
|
+
): Promise<string> {
|
|
126
|
+
const { file } = input;
|
|
127
|
+
if (!(SELLER_LEAD_PHOTO_TYPES as readonly string[]).includes(file.type)) {
|
|
128
|
+
throw new LeadSubmitError("Garagem SDK: photo must be JPG, PNG or WEBP.", {
|
|
129
|
+
code: "invalid_photo",
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
if (file.size <= 0) {
|
|
133
|
+
throw new LeadSubmitError("Garagem SDK: photo is empty.", {
|
|
134
|
+
code: "invalid_photo",
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (file.size > SELLER_LEAD_PHOTO_MAX_BYTES) {
|
|
138
|
+
throw new LeadSubmitError("Garagem SDK: photo is larger than 10MB.", {
|
|
139
|
+
code: "invalid_photo",
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const siteId = await resolveLeadSiteId(input);
|
|
143
|
+
const url = `${normalizeBaseUrl(input.baseUrl)}/api/webhooks/sites/${encodeURIComponent(siteId)}/photos`;
|
|
144
|
+
const form = new FormData();
|
|
145
|
+
form.append("file", file);
|
|
146
|
+
if (file.name) form.append("fileName", file.name);
|
|
147
|
+
|
|
148
|
+
let response: Response;
|
|
149
|
+
try {
|
|
150
|
+
response = await (input.fetch ?? fetch)(url, {
|
|
151
|
+
method: "POST",
|
|
152
|
+
body: form,
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new LeadSubmitError(
|
|
156
|
+
error instanceof Error ? error.message : "Garagem SDK: network error.",
|
|
157
|
+
{ code: "network" }
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
if (response.status === 404) {
|
|
161
|
+
throw new LeadSubmitError("Garagem SDK: site not found.", {
|
|
162
|
+
code: "not_found",
|
|
163
|
+
status: 404,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
const data = (await response.json().catch(() => ({}))) as { url?: unknown };
|
|
167
|
+
if (!response.ok || typeof data.url !== "string" || !data.url) {
|
|
168
|
+
throw new LeadSubmitError(
|
|
169
|
+
`Garagem SDK: photo upload failed (${response.status}).`,
|
|
170
|
+
{
|
|
171
|
+
code: response.status === 400 ? "invalid_photo" : "http",
|
|
172
|
+
status: response.status,
|
|
173
|
+
}
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return data.url;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Studio "Cadastro de imóvel" photo-session grid. */
|
|
180
|
+
export type SellerPhotoScheduleConfig = {
|
|
181
|
+
disabledDays: number[];
|
|
182
|
+
weekdayTimeSlots: HHmm[];
|
|
183
|
+
weekendTimeSlots: HHmm[];
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export const STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG: SellerPhotoScheduleConfig = {
|
|
187
|
+
disabledDays: [0, 6],
|
|
188
|
+
weekdayTimeSlots: [
|
|
189
|
+
"09:00",
|
|
190
|
+
"10:00",
|
|
191
|
+
"11:00",
|
|
192
|
+
"14:00",
|
|
193
|
+
"15:00",
|
|
194
|
+
"16:00",
|
|
195
|
+
"17:00",
|
|
196
|
+
],
|
|
197
|
+
weekendTimeSlots: ["10:00", "11:00", "14:00", "15:00", "16:00"],
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** Feed the result to `slotsForDate` / `isVisitSlotAllowed`. */
|
|
201
|
+
export function sellerPhotoSchedule(
|
|
202
|
+
config: SellerPhotoScheduleConfig = STUDIO_DEFAULT_PHOTO_SCHEDULE_CONFIG
|
|
203
|
+
): VisitSchedule {
|
|
204
|
+
const weekdayTimeSlots = [...config.weekdayTimeSlots].sort();
|
|
205
|
+
const weekendTimeSlots = [...config.weekendTimeSlots].sort();
|
|
206
|
+
const hours = (slots: HHmm[]) =>
|
|
207
|
+
slots.length > 0
|
|
208
|
+
? { start: slots[0]!, end: slots[slots.length - 1]! }
|
|
209
|
+
: null;
|
|
210
|
+
return {
|
|
211
|
+
timeZone: VISIT_TIME_ZONE,
|
|
212
|
+
saturday: !config.disabledDays.includes(6),
|
|
213
|
+
sunday: !config.disabledDays.includes(0),
|
|
214
|
+
weekday: hours(weekdayTimeSlots) ?? { start: "09:00", end: "09:00" },
|
|
215
|
+
weekend: hours(weekendTimeSlots),
|
|
216
|
+
minHoursAhead: 2,
|
|
217
|
+
disabledDays: [...config.disabledDays],
|
|
218
|
+
weekdayTimeSlots,
|
|
219
|
+
weekendTimeSlots,
|
|
220
|
+
timeSlots: Array.from(
|
|
221
|
+
new Set([...weekdayTimeSlots, ...weekendTimeSlots])
|
|
222
|
+
).sort(),
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export type SellerBusinessType = "sale" | "rent" | "both";
|
|
227
|
+
|
|
228
|
+
export type SellerLeadProperty = {
|
|
229
|
+
businessType: SellerBusinessType;
|
|
230
|
+
saleValue?: number;
|
|
231
|
+
rentValue?: number;
|
|
232
|
+
condoFee?: number;
|
|
233
|
+
totalArea?: number;
|
|
234
|
+
bedrooms?: number;
|
|
235
|
+
bathrooms?: number;
|
|
236
|
+
suites?: number;
|
|
237
|
+
parkingSpaces?: number;
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
export type SellerLeadInput = SellerLeadTransport & {
|
|
241
|
+
owner: { name: string; email: string; phone: string };
|
|
242
|
+
address: SellerLeadAddress;
|
|
243
|
+
property: SellerLeadProperty;
|
|
244
|
+
/** URLs returned by `uploadSellerLeadPhoto`. */
|
|
245
|
+
photos?: string[];
|
|
246
|
+
/** Photo session slot when the owner chose "Agendar". */
|
|
247
|
+
photoSession?: { date: Date | string; time: HHmm };
|
|
248
|
+
photoSchedule?: VisitSchedule;
|
|
249
|
+
visitorId?: string;
|
|
250
|
+
brokerRef?: string;
|
|
251
|
+
referrer?: string;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
function contactError(message: string): LeadSubmitError {
|
|
255
|
+
return new LeadSubmitError(`Garagem SDK: ${message}`, {
|
|
256
|
+
code: "invalid_contact",
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function normalizeOwner(owner: SellerLeadInput["owner"]) {
|
|
261
|
+
const name = text(owner?.name);
|
|
262
|
+
const email = text(owner?.email);
|
|
263
|
+
if (!isValidName(name)) throw contactError("owner name is invalid.");
|
|
264
|
+
if (!isValidEmail(email)) throw contactError("owner email is invalid.");
|
|
265
|
+
const phone = toE164(text(owner?.phone));
|
|
266
|
+
if (!phone || !isValidPhone(phone) || phone.length > 40) {
|
|
267
|
+
throw contactError("owner phone is invalid.");
|
|
268
|
+
}
|
|
269
|
+
return { name, email, phone };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function normalizeAddress(address: SellerLeadAddress) {
|
|
273
|
+
const errors = sellerAddressErrors(address);
|
|
274
|
+
const first = Object.values(errors)[0];
|
|
275
|
+
if (first) {
|
|
276
|
+
throw new LeadSubmitError(`Garagem SDK: ${first}`, {
|
|
277
|
+
code: "invalid_address",
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
const optional = (value: string | undefined) =>
|
|
281
|
+
text(value) ? { value: text(value) } : null;
|
|
282
|
+
const number = address.noNumber ? null : optional(address.number);
|
|
283
|
+
const bloco = address.noBlocoTorre ? null : optional(address.blocoTorre);
|
|
284
|
+
const unidade = address.noUnidade ? null : optional(address.unidade);
|
|
285
|
+
return {
|
|
286
|
+
fullAddress: text(address.fullAddress),
|
|
287
|
+
street: text(address.street),
|
|
288
|
+
...(number ? { number: number.value } : {}),
|
|
289
|
+
neighborhood: text(address.neighborhood),
|
|
290
|
+
city: text(address.city),
|
|
291
|
+
state: text(address.state),
|
|
292
|
+
postalCode: text(address.postalCode).replace(/\D/g, ""),
|
|
293
|
+
country: text(address.country) || "BR",
|
|
294
|
+
latitude: address.latitude as number,
|
|
295
|
+
longitude: address.longitude as number,
|
|
296
|
+
...(bloco ? { blocoTorre: bloco.value } : {}),
|
|
297
|
+
...(unidade ? { unidade: unidade.value } : {}),
|
|
298
|
+
noNumber: address.noNumber === true,
|
|
299
|
+
noBlocoTorre: address.noBlocoTorre === true,
|
|
300
|
+
noUnidade: address.noUnidade === true,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const COUNT_FIELDS = [
|
|
305
|
+
"bedrooms",
|
|
306
|
+
"bathrooms",
|
|
307
|
+
"suites",
|
|
308
|
+
"parkingSpaces",
|
|
309
|
+
] as const;
|
|
310
|
+
const AMOUNT_FIELDS = [
|
|
311
|
+
"saleValue",
|
|
312
|
+
"rentValue",
|
|
313
|
+
"condoFee",
|
|
314
|
+
"totalArea",
|
|
315
|
+
] as const;
|
|
316
|
+
|
|
317
|
+
function propertyError(message: string): LeadSubmitError {
|
|
318
|
+
return new LeadSubmitError(`Garagem SDK: ${message}`, {
|
|
319
|
+
code: "invalid_property",
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function normalizeProperty(property: SellerLeadProperty) {
|
|
324
|
+
if (!["sale", "rent", "both"].includes(property?.businessType)) {
|
|
325
|
+
throw propertyError("businessType must be sale, rent or both.");
|
|
326
|
+
}
|
|
327
|
+
for (const field of COUNT_FIELDS) {
|
|
328
|
+
const value = property[field];
|
|
329
|
+
if (
|
|
330
|
+
value != null &&
|
|
331
|
+
(!Number.isInteger(value) || value < 0 || value > 999)
|
|
332
|
+
) {
|
|
333
|
+
throw propertyError(`${field} must be a whole number.`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
for (const field of AMOUNT_FIELDS) {
|
|
337
|
+
const value = property[field];
|
|
338
|
+
if (
|
|
339
|
+
value != null &&
|
|
340
|
+
(!Number.isFinite(value) || value < 0 || value > 1e12)
|
|
341
|
+
) {
|
|
342
|
+
throw propertyError(`${field} must be a non-negative number.`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const sale =
|
|
346
|
+
property.businessType === "rent" ? undefined : property.saleValue;
|
|
347
|
+
const rent =
|
|
348
|
+
property.businessType === "sale" ? undefined : property.rentValue;
|
|
349
|
+
// Rent-only uses `price` as its single amount. Sale and both keep `price`
|
|
350
|
+
// as the sale amount, never filled from rent.
|
|
351
|
+
const price = property.businessType === "rent" ? rent : sale;
|
|
352
|
+
const counts = Object.fromEntries(
|
|
353
|
+
COUNT_FIELDS.filter((field) => property[field] != null).map((field) => [
|
|
354
|
+
field,
|
|
355
|
+
property[field],
|
|
356
|
+
])
|
|
357
|
+
);
|
|
358
|
+
return {
|
|
359
|
+
businessType: property.businessType,
|
|
360
|
+
...(price != null ? { price } : {}),
|
|
361
|
+
...(property.businessType === "both" && rent != null
|
|
362
|
+
? { rentPrice: rent }
|
|
363
|
+
: {}),
|
|
364
|
+
...(property.condoFee != null ? { condominiumFee: property.condoFee } : {}),
|
|
365
|
+
...(property.totalArea != null ? { totalArea: property.totalArea } : {}),
|
|
366
|
+
...counts,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function normalizePhotos(photos: string[] | undefined): string[] | undefined {
|
|
371
|
+
if (!photos?.length) return undefined;
|
|
372
|
+
if (photos.length > SELLER_LEAD_PHOTO_MAX_COUNT) {
|
|
373
|
+
throw new LeadSubmitError("Garagem SDK: too many photos (max 30).", {
|
|
374
|
+
code: "invalid_photo",
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
return photos.map((url) => {
|
|
378
|
+
const trimmed = url.trim();
|
|
379
|
+
if (!trimmed.startsWith("https://")) {
|
|
380
|
+
throw new LeadSubmitError("Garagem SDK: photo URL must be https.", {
|
|
381
|
+
code: "invalid_photo",
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
return trimmed;
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function normalizePhotoSession(input: SellerLeadInput) {
|
|
389
|
+
if (!input.photoSession) return undefined;
|
|
390
|
+
const schedule = input.photoSchedule ?? sellerPhotoSchedule();
|
|
391
|
+
const date = normalizeVisitDate(input.photoSession.date, schedule.timeZone);
|
|
392
|
+
const time = normalizeVisitTime(input.photoSession.time);
|
|
393
|
+
if (!date || !time || !isVisitSlotAllowed(schedule, date, time)) {
|
|
394
|
+
throw new LeadSubmitError(
|
|
395
|
+
"Garagem SDK: photo session slot is outside the schedule.",
|
|
396
|
+
{ code: "invalid_slot" }
|
|
397
|
+
);
|
|
398
|
+
}
|
|
399
|
+
return { date, time };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export async function submitSellerLead(
|
|
403
|
+
input: SellerLeadInput
|
|
404
|
+
): Promise<LeadSubmitResult> {
|
|
405
|
+
const owner = normalizeOwner(input.owner);
|
|
406
|
+
const address = normalizeAddress(input.address);
|
|
407
|
+
const property = normalizeProperty(input.property);
|
|
408
|
+
const photos = normalizePhotos(input.photos);
|
|
409
|
+
const photoScheduling = normalizePhotoSession(input);
|
|
410
|
+
return postSiteLead({
|
|
411
|
+
siteId: input.siteId,
|
|
412
|
+
baseUrl: input.baseUrl,
|
|
413
|
+
fetch: input.fetch,
|
|
414
|
+
publishableKey: input.publishableKey,
|
|
415
|
+
body: {
|
|
416
|
+
source: "site-sdk",
|
|
417
|
+
leadType: "seller_lead",
|
|
418
|
+
...owner,
|
|
419
|
+
address,
|
|
420
|
+
...property,
|
|
421
|
+
...(photos ? { photos } : {}),
|
|
422
|
+
...(photoScheduling ? { photoScheduling } : {}),
|
|
423
|
+
...(input.visitorId ? { visitorId: input.visitorId } : {}),
|
|
424
|
+
...(input.brokerRef ? { brokerRef: input.brokerRef } : {}),
|
|
425
|
+
...(input.referrer ? { referrer: input.referrer } : {}),
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
}
|