-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathNewPlacesService.ts
More file actions
489 lines (433 loc) · 15 KB
/
Copy pathNewPlacesService.ts
File metadata and controls
489 lines (433 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { PlacesClient } from "@googlemaps/places";
import { Logger } from "../index.js";
export class NewPlacesService {
private client: PlacesClient;
private readonly defaultLanguage: string = "en";
private readonly placeFieldMask: string = [
"displayName",
"name",
"id",
"formattedAddress",
"location",
"utcOffsetMinutes",
"primaryType",
"types",
"regularOpeningHours.periods",
"regularOpeningHours.weekdayDescriptions",
"currentOpeningHours.openNow",
"nationalPhoneNumber",
"websiteUri",
"priceLevel",
"rating",
"userRatingCount",
"editorialSummary",
"reviews.rating",
"reviews.text",
"reviews.publishTime",
"reviews.authorAttribution.displayName",
"photos.heightPx",
"photos.widthPx",
"photos.name",
// Parking & Accessibility
"parkingOptions",
"accessibilityOptions",
// Food & Drink
"servesVegetarianFood",
"servesBeer",
"servesWine",
"servesCocktails",
"servesBreakfast",
"servesLunch",
"servesDinner",
"servesBrunch",
"servesCoffee",
"servesDessert",
// Dining options
"dineIn",
"delivery",
"takeout",
"curbsidePickup",
"reservable",
// Atmosphere
"goodForGroups",
"goodForChildren",
"goodForWatchingSports",
"liveMusic",
"outdoorSeating",
"allowsDogs",
"menuForChildren",
"restroom",
// Payment
"paymentOptions",
// AI Summaries (region-limited)
"reviewSummary",
"generativeSummary",
].join(",");
private readonly searchNearbyFieldMask: string = [
"places.displayName",
"places.name",
"places.id",
"places.formattedAddress",
"places.location",
"places.rating",
"places.userRatingCount",
"places.currentOpeningHours.openNow",
"places.primaryType",
"places.priceLevel",
].join(",");
constructor(apiKey?: string) {
this.client = new PlacesClient({
apiKey: apiKey || process.env.GOOGLE_MAPS_API_KEY || "",
});
if (!apiKey && !process.env.GOOGLE_MAPS_API_KEY) {
throw new Error("Google Maps API Key is required");
}
}
async searchNearby(params: {
location: { lat: number; lng: number };
keyword?: string;
radius?: number;
maxResultCount?: number;
}): Promise<any[]> {
try {
const request: any = {
locationRestriction: {
circle: {
center: {
latitude: params.location.lat,
longitude: params.location.lng,
},
radius: params.radius || 1000,
},
},
maxResultCount: Math.min(params.maxResultCount || 20, 20),
languageCode: this.defaultLanguage,
};
if (params.keyword) {
request.includedTypes = [params.keyword];
}
const [response] = await this.client.searchNearby(request, {
otherArgs: {
headers: {
"X-Goog-FieldMask": this.searchNearbyFieldMask,
},
},
});
return (response.places || []).map((place: any) => this.transformSearchResult(place));
} catch (error: any) {
Logger.error("Error in searchNearby (New API):", error);
throw new Error(`Failed to search nearby places: ${this.extractErrorMessage(error)}`);
}
}
async searchText(params: {
textQuery: string;
locationBias?: { lat: number; lng: number; radius?: number };
openNow?: boolean;
minRating?: number;
includedType?: string;
maxResultCount?: number;
}): Promise<any[]> {
try {
const request: any = {
textQuery: params.textQuery,
languageCode: this.defaultLanguage,
maxResultCount: Math.min(params.maxResultCount || 10, 20),
};
if (params.locationBias) {
request.locationBias = {
circle: {
center: {
latitude: params.locationBias.lat,
longitude: params.locationBias.lng,
},
radius: params.locationBias.radius || 5000,
},
};
}
if (params.openNow) {
request.openNow = true;
}
if (params.minRating) {
request.minRating = params.minRating;
}
if (params.includedType) {
request.includedType = params.includedType;
}
const [response] = await this.client.searchText(request, {
otherArgs: {
headers: {
"X-Goog-FieldMask": this.searchNearbyFieldMask,
},
},
});
return (response.places || []).map((place: any) => this.transformSearchResult(place));
} catch (error: any) {
Logger.error("Error in searchText (New API):", error);
throw new Error(`Failed to search places: ${this.extractErrorMessage(error)}`);
}
}
async getPhotoUri(photoName: string, maxWidthPx: number = 800): Promise<string> {
try {
const [response] = await this.client.getPhotoMedia({
name: `${photoName}/media`,
maxWidthPx,
skipHttpRedirect: true,
});
return response.photoUri || "";
} catch (error: any) {
Logger.error("Error in getPhotoUri:", error);
throw new Error(`Failed to get photo URI: ${this.extractErrorMessage(error)}`);
}
}
async getPlaceDetails(placeId: string) {
try {
const placeName = `places/${placeId}`;
const [place] = await this.client.getPlace(
{
name: placeName,
languageCode: this.defaultLanguage,
},
{
otherArgs: {
headers: {
"X-Goog-FieldMask": this.placeFieldMask,
},
},
}
);
return this.transformPlaceResponse(place);
} catch (error: any) {
Logger.error("Error in getPlaceDetails (New API):", error);
throw new Error(`Failed to get place details for ${placeId}: ${this.extractErrorMessage(error)}`);
}
}
private transformSearchResult(place: any) {
return {
name: place.displayName?.text || "",
place_id: this.extractLegacyPlaceId(place),
formatted_address: place.formattedAddress || "",
geometry: {
location: {
lat: place.location?.latitude || 0,
lng: place.location?.longitude || 0,
},
},
primary_type: place.primaryType || null,
price_level: place.priceLevel || null,
rating: place.rating || 0,
user_ratings_total: place.userRatingCount || 0,
opening_hours: {
open_now: place.currentOpeningHours?.openNow ?? null,
},
};
}
private transformPlaceResponse(place: any) {
// Build parking info (only include truthy values)
const parking = place.parkingOptions
? Object.fromEntries(Object.entries(place.parkingOptions).filter(([, v]) => v === true))
: undefined;
// Build accessibility info (only include truthy values)
const accessibility = place.accessibilityOptions
? Object.fromEntries(Object.entries(place.accessibilityOptions).filter(([, v]) => v === true))
: undefined;
// Build dining_options (only include truthy values)
const diningOptions: Record<string, boolean> = {};
if (place.dineIn) diningOptions.dine_in = true;
if (place.delivery) diningOptions.delivery = true;
if (place.takeout) diningOptions.takeout = true;
if (place.curbsidePickup) diningOptions.curbside_pickup = true;
if (place.reservable) diningOptions.reservable = true;
// Build serves (only include truthy values)
const serves: Record<string, boolean> = {};
if (place.servesVegetarianFood) serves.vegetarian_food = true;
if (place.servesBeer) serves.beer = true;
if (place.servesWine) serves.wine = true;
if (place.servesCocktails) serves.cocktails = true;
if (place.servesBreakfast) serves.breakfast = true;
if (place.servesLunch) serves.lunch = true;
if (place.servesDinner) serves.dinner = true;
if (place.servesBrunch) serves.brunch = true;
if (place.servesCoffee) serves.coffee = true;
if (place.servesDessert) serves.dessert = true;
// Build atmosphere (only include truthy values)
const atmosphere: Record<string, boolean> = {};
if (place.goodForGroups) atmosphere.good_for_groups = true;
if (place.goodForChildren) atmosphere.good_for_children = true;
if (place.goodForWatchingSports) atmosphere.good_for_watching_sports = true;
if (place.liveMusic) atmosphere.live_music = true;
if (place.outdoorSeating) atmosphere.outdoor_seating = true;
if (place.allowsDogs) atmosphere.allows_dogs = true;
if (place.menuForChildren) atmosphere.menu_for_children = true;
if (place.restroom) atmosphere.restroom = true;
return {
name: place.displayName?.text || place.name || "",
place_id: this.extractLegacyPlaceId(place),
formatted_address: place.formattedAddress || "",
geometry: {
location: {
lat: place.location?.latitude || 0,
lng: place.location?.longitude || 0,
},
},
primary_type: place.primaryType || null,
types: place.types || [],
rating: place.rating || 0,
user_ratings_total: place.userRatingCount || 0,
opening_hours: place.regularOpeningHours
? {
open_now: this.isCurrentlyOpen(
place.regularOpeningHours,
place.utcOffsetMinutes,
place.currentOpeningHours
),
weekday_text: this.formatOpeningHours(place.regularOpeningHours),
}
: undefined,
formatted_phone_number: place.nationalPhoneNumber || "",
website: place.websiteUri || "",
price_level: place.priceLevel || 0,
editorial_summary: place.editorialSummary?.text || null,
...(Object.keys(parking || {}).length > 0 ? { parking } : {}),
...(Object.keys(accessibility || {}).length > 0 ? { accessibility } : {}),
...(Object.keys(diningOptions).length > 0 ? { dining_options: diningOptions } : {}),
...(Object.keys(serves).length > 0 ? { serves } : {}),
...(Object.keys(atmosphere).length > 0 ? { atmosphere } : {}),
...(place.paymentOptions
? {
payment_options: Object.fromEntries(
Object.entries(place.paymentOptions).filter(([k]) => !k.startsWith("_"))
),
}
: {}),
...(place.reviewSummary?.text?.text ? { review_summary: place.reviewSummary.text.text } : {}),
...(place.generativeSummary?.overview?.text ? { generative_summary: place.generativeSummary.overview.text } : {}),
reviews:
place.reviews?.map((review: any) => ({
rating: review.rating || 0,
text: review.text?.text || "",
language: review.text?.languageCode || null,
time: review.publishTime?.seconds || 0,
author_name: review.authorAttribution?.displayName || "",
})) || [],
photos:
place.photos?.map((photo: any) => ({
photo_reference: photo.name || "",
height: photo.heightPx || 0,
width: photo.widthPx || 0,
})) || [],
};
}
private extractLegacyPlaceId(place: any): string {
const resourceName = place?.name;
if (typeof resourceName === "string" && resourceName.startsWith("places/")) {
const legacyId = resourceName.substring("places/".length);
if (legacyId) {
return legacyId;
}
}
return place?.id || "";
}
private isCurrentlyOpen(openingHours: any, utcOffsetMinutes?: number, currentOpeningHours?: any): boolean {
if (typeof currentOpeningHours?.openNow === "boolean") {
return currentOpeningHours.openNow;
}
if (typeof openingHours?.openNow === "boolean") {
return openingHours.openNow;
}
const periods = openingHours?.periods;
if (!Array.isArray(periods) || periods.length === 0) {
return false;
}
const minutesInDay = 24 * 60;
const minutesInWeek = minutesInDay * 7;
const { day: localDay, minutes: localMinutes } = this.getLocalTimeComponents(utcOffsetMinutes);
const localTimeValue = localDay * minutesInDay + localMinutes;
const dayMapping = {
SUNDAY: 0,
MONDAY: 1,
TUESDAY: 2,
WEDNESDAY: 3,
THURSDAY: 4,
FRIDAY: 5,
SATURDAY: 6,
};
const toDayNumber = (value: any): number | undefined => {
if (typeof value === "number" && value >= 0 && value <= 6) {
return value;
}
if (typeof value === "string") {
const normalized = value.toUpperCase();
if (normalized in dayMapping) {
return dayMapping[normalized as keyof typeof dayMapping];
}
}
return undefined;
};
const toMinutes = (time: any): number | undefined => {
if (!time) {
return undefined;
}
const hours = typeof time.hours === "number" ? time.hours : Number(time.hours ?? NaN);
const minutes = typeof time.minutes === "number" ? time.minutes : Number(time.minutes ?? NaN);
if (!Number.isFinite(hours) || !Number.isFinite(minutes)) {
return undefined;
}
return hours * 60 + minutes;
};
for (const period of periods) {
const openDay = toDayNumber(period?.openDay);
const closeDay = toDayNumber(period?.closeDay ?? period?.openDay);
const openMinutes = toMinutes(period?.openTime);
const closeMinutes = toMinutes(period?.closeTime);
if (openDay === undefined || openMinutes === undefined) {
continue;
}
const start = openDay * minutesInDay + openMinutes;
let end: number;
if (closeDay === undefined || closeMinutes === undefined) {
end = start + minutesInDay;
} else {
end = closeDay * minutesInDay + closeMinutes;
}
if (end <= start) {
end += minutesInWeek;
}
let comparableLocalTime = localTimeValue;
while (comparableLocalTime < start) {
comparableLocalTime += minutesInWeek;
}
if (comparableLocalTime >= start && comparableLocalTime < end) {
return true;
}
}
return false;
}
private getLocalTimeComponents(utcOffsetMinutes?: number): { day: number; minutes: number } {
const now = new Date();
if (typeof utcOffsetMinutes === "number" && Number.isFinite(utcOffsetMinutes)) {
const localTime = new Date(now.getTime() + utcOffsetMinutes * 60000);
return {
day: localTime.getUTCDay(),
minutes: localTime.getUTCHours() * 60 + localTime.getUTCMinutes(),
};
}
return {
day: now.getDay(),
minutes: now.getHours() * 60 + now.getMinutes(),
};
}
private formatOpeningHours(openingHours: any): string[] {
return openingHours?.weekdayDescriptions || [];
}
private extractErrorMessage(error: any): string {
const statusCode = error?.code;
const message = error?.message || error?.details;
if (statusCode === 7 || statusCode === 403) {
return "API key invalid or Places API (New) not enabled. Check: console.cloud.google.com → APIs & Services → Enable 'Places API (New)'";
}
if (statusCode === 8 || statusCode === 429) {
return "API quota exceeded. Wait and retry, or check quota at console.cloud.google.com → Quotas";
}
return message || (error instanceof Error ? error.message : String(error));
}
}