@garagem-ai/site-sdk 0.9.1 → 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 +114 -2
- package/dist/index.d.ts +114 -2
- package/dist/index.js +410 -53
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +398 -53
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +23 -0
- package/src/leads.ts +47 -3
- package/src/seller-lead.ts +428 -0
- package/src/studio-contract.ts +42 -0
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",
|
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,6 +285,8 @@ export {
|
|
|
264
285
|
studioPublishableKeyInstruction,
|
|
265
286
|
studioPhotoSearchInstruction,
|
|
266
287
|
isPhotoSearchOnPin,
|
|
288
|
+
isSellerLeadOnPin,
|
|
289
|
+
studioSellerLeadSdkInstruction,
|
|
267
290
|
studioSdkPinInstruction,
|
|
268
291
|
studioSiteWidthCss,
|
|
269
292
|
hasShowcaseLeadsPostUrl,
|
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 }
|
|
@@ -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
|
+
}
|
package/src/studio-contract.ts
CHANGED
|
@@ -203,10 +203,45 @@ export const STUDIO_SDK_CONTRACT = {
|
|
|
203
203
|
"applyMatchedPhotoCover",
|
|
204
204
|
] as const,
|
|
205
205
|
photoSearchSince: "0.7.0",
|
|
206
|
+
/**
|
|
207
|
+
* Seller lead (property registration on `/anunciar-imovel`). Prompt-safe
|
|
208
|
+
* only once `minNpmVersion` reaches `sellerLeadSince`; below it
|
|
209
|
+
* `studioSellerLeadSdkInstruction` prints nothing and
|
|
210
|
+
* `studioCodegenContractViolations` flags the names.
|
|
211
|
+
*/
|
|
212
|
+
sellerLeadExports: [
|
|
213
|
+
"submitSellerLead",
|
|
214
|
+
"uploadSellerLeadPhoto",
|
|
215
|
+
"sellerAddressErrors",
|
|
216
|
+
"sellerPhotoSchedule",
|
|
217
|
+
"isValidEmail",
|
|
218
|
+
"isValidName",
|
|
219
|
+
] as const,
|
|
220
|
+
sellerLeadSince: "0.10.0",
|
|
206
221
|
} as const;
|
|
207
222
|
|
|
208
223
|
export type StudioSdkContract = typeof STUDIO_SDK_CONTRACT;
|
|
209
224
|
|
|
225
|
+
/** Whether the pinned tarball carries the seller-lead surface. */
|
|
226
|
+
export function isSellerLeadOnPin(
|
|
227
|
+
pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
|
|
228
|
+
): boolean {
|
|
229
|
+
return compareSemver(pin, STUDIO_SDK_CONTRACT.sellerLeadSince) >= 0;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Fixed SDK half of the property-registration page. The configured fields
|
|
234
|
+
* and photo options come from the Studio onboarding block. Empty below
|
|
235
|
+
* `sellerLeadSince`, so no prompt names an identifier v0 cannot import.
|
|
236
|
+
*/
|
|
237
|
+
export function studioSellerLeadSdkInstruction(
|
|
238
|
+
pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
|
|
239
|
+
): string {
|
|
240
|
+
if (!isSellerLeadOnPin(pin)) return "";
|
|
241
|
+
const names = STUDIO_SDK_CONTRACT.sellerLeadExports.join(", ");
|
|
242
|
+
return `Property registration (\`/anunciar-imovel\`, client component): import ${names}, isValidPhone, toE164 from \`${STUDIO_SDK_PACKAGE}\`. Address: load Maps JS only through \`<script src="https://maps.fndn.ai/sdk.js?callback=initPlaces" async defer />\` (Places is included; never a Google key, never \`maps.googleapis.com\`), then \`google.maps.places.Autocomplete\` with \`componentRestrictions: { country: "br" }\` and pt-BR. Picking a suggestion fills fullAddress, street, number, neighborhood, city, state (the 2-letter code), postalCode, latitude and longitude from the place; a typed address without a suggestion is not enough. The visitor confirms number or "Sem número", bloco/torre or "Não tem", unidade or "Não tem" (noNumber, noBlocoTorre, noUnidade). Block the next group while \`sellerAddressErrors(address)\` has keys and show each message on its field. Owner: name, email and phone are all required — \`isValidName\`, \`isValidEmail\`, the phone mask with \`isValidPhone(toE164(phone))\`. Photos: \`await uploadSellerLeadPhoto({ siteId, baseUrl: GARAGEM_API_BASE, file, publishableKey })\` per file (JPG/PNG/WEBP, 10MB, up to 30), keep the returned URLs. Photo session: \`const schedule = sellerPhotoSchedule(config)\` and \`slotsForDate(schedule, day)\` for the hours. Submit once with \`await submitSellerLead({ siteId, baseUrl: GARAGEM_API_BASE, publishableKey, owner: { name, email, phone }, address, property: { businessType, saleValue, rentValue, condoFee, totalArea, bedrooms, bathrooms, suites, parkingSpaces }, photos, photoSession: { date, time }, photoSchedule: schedule })\` (omit what the visitor did not fill). Errors are \`LeadSubmitError\`: \`duplicate_property\` → "Este imóvel já está cadastrado. Nossa equipe entrará em contato."; \`invalid_address\` → ask to pick the address again; anything else → a retry message. Disable the submit while pending and show a success state after it resolves. Never POST the leads webhook by hand.`;
|
|
243
|
+
}
|
|
244
|
+
|
|
210
245
|
/** Whether the pinned tarball carries the photo-search surface. */
|
|
211
246
|
export function isPhotoSearchOnPin(
|
|
212
247
|
pin: string = STUDIO_SDK_CONTRACT.minNpmVersion
|
|
@@ -525,6 +560,13 @@ export function studioCodegenContractViolations(text: string): string[] {
|
|
|
525
560
|
}
|
|
526
561
|
}
|
|
527
562
|
}
|
|
563
|
+
if (!isSellerLeadOnPin()) {
|
|
564
|
+
for (const name of STUDIO_SDK_CONTRACT.sellerLeadExports) {
|
|
565
|
+
if (mentionsExportName(text, name) && !violations.includes(name)) {
|
|
566
|
+
violations.push(name);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
528
570
|
const pin = STUDIO_SDK_CONTRACT.minNpmVersion;
|
|
529
571
|
if (!marketExportsAvailableAt(pin)) {
|
|
530
572
|
for (const name of STUDIO_SDK_CONTRACT.marketExports) {
|