@meetelise/chat 1.66.0 → 1.68.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,1202 @@
1
+ import { css, html, LitElement, PropertyValues, TemplateResult } from "lit";
2
+ import { customElement, property, state } from "lit/decorators.js";
3
+ import { classMap } from "lit/directives/class-map.js";
4
+ import { v4 as uuid } from "uuid";
5
+ import "./community-picker";
6
+ import "./itinerary-editor";
7
+ import "./contact-form";
8
+ import "./booking-confirmation";
9
+ import "../actions/action-confirm-button";
10
+ import "../loaders/mega-loader";
11
+ import { tourSchedulerStyles } from "../Scheduler/tourSchedulerStyles";
12
+ import { InputStyles } from "../actions/InputStyles";
13
+ import { ChevronLeftIcon } from "../icons/ChevronLeftIcon";
14
+ import { XOutlineIcon } from "../icons/XOutlineIcon";
15
+ import { CalendarCheckIcon } from "../icons/CalendarCheckIcon";
16
+ import formDisclaimer from "../../disclaimers";
17
+ import {
18
+ BookingResponse,
19
+ CommunitiesResponse,
20
+ CommunityFilters,
21
+ createTourItineraryApi,
22
+ ExtendQuery,
23
+ MAX_ITINERARY_STOPS,
24
+ PlanResponse,
25
+ TourApiError,
26
+ TourItineraryApi,
27
+ CommunitySummary,
28
+ toCommunitySummary,
29
+ TourTypeId,
30
+ } from "./tourItineraryApi";
31
+ import { renderSelectionTray, selectionTrayStyles } from "./community-picker";
32
+ import type { TourTypeChoice, StopProblem } from "./itinerary-editor";
33
+ import { contactIsValid, ContactValues, EMPTY_CONTACT } from "./contact-form";
34
+ import type { ConfirmedStop } from "./booking-confirmation";
35
+ import {
36
+ buildAttribution,
37
+ buildBookingRequest,
38
+ buildPlanRequest,
39
+ ItineraryChoice,
40
+ } from "./schedulerRequests";
41
+ import {
42
+ isoDate,
43
+ isoHourMinute,
44
+ toIsoDate,
45
+ TOUR_TYPE_ORDER,
46
+ } from "./tourTimes";
47
+ import { LabeledOption } from "../../fetchBuildingInfo";
48
+ import { FeatureFlagsShowDropdown } from "../../fetchFeatureFlag";
49
+ import { shouldOpenTourLink } from "../../fetchBuildingWebchatView";
50
+ import {
51
+ appendParamsToUrl,
52
+ getUrlQueryParameters,
53
+ } from "../../postLeadSources";
54
+ import { pushGtmEvent } from "../../gtm";
55
+ import { LogType, sendLoggingEvent } from "../../analytics";
56
+ import { defaultPrimaryColor } from "../../themes";
57
+ import type { LayoutOption } from "../../fetchBuildingWebchatView";
58
+ import { isMobile, onMobileChange } from "../../utils";
59
+ import { readGoogleReserveReferral } from "../../googleReserve";
60
+ import { layoutToBedrooms } from "../../services/fees/utils";
61
+ import { focusFirstTabStop, trapTabInside } from "../pubnub-chat";
62
+ import type LeadSourceClient from "../LeadSourceClient";
63
+ import type { LeadSourceMultitouchClient } from "../LeadSourceMultitouchClient";
64
+
65
+ type Step = "loading" | "error" | "pick" | "schedule" | "booked";
66
+
67
+ /**
68
+ * /plan answers for one tour type and date and lists the ones it offers. When
69
+ * the type asked for isn't offered, one more request moves to the server's first
70
+ * type; when that type's dates don't include the date asked for, another moves
71
+ * to its first date.
72
+ */
73
+ const PLAN_RETRIES = 2;
74
+
75
+ const EMPTY_FILTERS: CommunityFilters = {
76
+ bedrooms: [],
77
+ moveIn: null,
78
+ maxBudget: null,
79
+ };
80
+
81
+ /** The building config value each tour type is offered under. */
82
+ const TOUR_TYPE_OPTION_VALUE: Record<TourTypeId, string> = {
83
+ "escorted-tour": "WITH_AGENT",
84
+ "self-guided-tour": "SELF_GUIDED",
85
+ "live-virtual-tour": "VIRTUAL_SHOWING",
86
+ };
87
+
88
+ /**
89
+ * The rebuilt tour scheduler, behind the `webchat_tour_scheduler_v2` rollout.
90
+ * It books one community, or up to the server's cap of communities in a
91
+ * central group as one same-day itinerary, and offers more communities after a
92
+ * booking. The server decides which communities can tour, their order, the
93
+ * chained times and the cap; this element keeps only the step, the prospect's
94
+ * choices and the form.
95
+ */
96
+ @customElement("tour-scheduler-v2")
97
+ export class TourSchedulerV2 extends LitElement {
98
+ @property({ attribute: true }) orgSlug = "";
99
+ @property({ attribute: true }) buildingSlug = "";
100
+ @property({ type: Number }) buildingId = 0;
101
+ @property({ type: Number }) orgId = 0;
102
+ @property({ attribute: false }) buildingName = "";
103
+ @property({ attribute: true }) sgtUrl = "";
104
+ @property({ attribute: true }) selfGuidedToursTypeOffered = "";
105
+ @property({ attribute: true }) escortedToursLink = "";
106
+ @property({ attribute: false }) escortedToursTypeOffered = "";
107
+ @property({ attribute: true }) virtualToursLink = "";
108
+ @property({ attribute: true }) virtualToursTypeOffered = "";
109
+ @property({ attribute: false }) tourTypeOptions: LabeledOption[] = [];
110
+ @property({ attribute: false }) layoutOptions: LayoutOption[] = [];
111
+ @property({ attribute: true }) currentLeadSource = "";
112
+ @property({ attribute: false }) leadSources: string[] = [];
113
+ @property({ attribute: true }) featureFlagShowDropdown = "";
114
+ @property({ attribute: false }) bedroomPreferenceRequired = false;
115
+ @property({ attribute: false }) orgLegalName = "";
116
+ @property({ attribute: false }) country: string | null = null;
117
+ @property({ attribute: false }) buildingState: string | null = null;
118
+ @property({ attribute: false }) primaryColor = defaultPrimaryColor;
119
+ @property({ attribute: false }) foregroundColorOnPrimaryBackgroundColor =
120
+ "white";
121
+ @property({ attribute: false }) compactDesign: boolean | string = false;
122
+ @property({ attribute: false }) leadSourceClient: LeadSourceClient | null =
123
+ null;
124
+ @property({ attribute: false })
125
+ leadSourceMultitouchClient: LeadSourceMultitouchClient | null = null;
126
+ /** The /webchat/init session token, read when each request is sent. */
127
+ @property({ attribute: false }) getSessionToken: () => string | null = () =>
128
+ null;
129
+ private api: TourItineraryApi | null = null;
130
+
131
+ onCloseClicked?: (e: MouseEvent) => void;
132
+
133
+ @state() private step: Step = "loading";
134
+ @state() private loadError: string | null = null;
135
+ @state() private mobile = isMobile();
136
+ /** Null outside a central group, where only this building can be toured. */
137
+ @state() private group: CommunitiesResponse | null = null;
138
+ @state() private communities = new Map<number, CommunitySummary>();
139
+ @state() private selectedIds: number[] = [];
140
+ /** The open picker's picks, shown in the footer until Continue. */
141
+ @state() private picks: CommunitySummary[] = [];
142
+ @state() private existingEventIds: number[] = [];
143
+ @state() private tourType: TourTypeId = "escorted-tour";
144
+ /** A tour type this building books on its own page, once picked. */
145
+ @state() private linkTourType: TourTypeId | null = null;
146
+ @state() private date: string | null = null;
147
+ @state() private firstStart: string | null = null;
148
+ @state() private laterStarts: Record<number, string> = {};
149
+ @state() private plan: PlanResponse | null = null;
150
+ @state() private planLoading = false;
151
+ @state() private planError: string | null = null;
152
+ @state() private notice: string | null = null;
153
+ @state() private contact: ContactValues = EMPTY_CONTACT;
154
+ @state() private submitting = false;
155
+ @state() private bookingError: string | null = null;
156
+ @state() private reschedulePrompt: string | null = null;
157
+ @state() private confirmed: ConfirmedStop[] = [];
158
+ @state() private bookedTourType: TourTypeId | null = null;
159
+ @state() private bookedEventIds: number[] = [];
160
+ @state() private extendInitial: CommunitiesResponse | null = null;
161
+ /** The booking the extend picker adds stops after. */
162
+ @state() private extendFrom: ExtendQuery | null = null;
163
+ /** The schedule step is adding stops to a booking. */
164
+ @state() private extending = false;
165
+ /** The prospect agreed to move a tour they already had. */
166
+ @state() private rescheduled = false;
167
+ /** The prospect kept the tour they already had. */
168
+ @state() private rescheduleCanceled = false;
169
+
170
+ private planRequestId = 0;
171
+ private idempotency: { booking: string; key: string } | null = null;
172
+ private cleanupMobileListener?: () => void;
173
+
174
+ connectedCallback(): void {
175
+ super.connectedCallback();
176
+ if (!this.hasAttribute("role")) this.setAttribute("role", "dialog");
177
+ if (!this.hasAttribute("aria-modal"))
178
+ this.setAttribute("aria-modal", "true");
179
+ if (!this.hasAttribute("aria-label")) {
180
+ this.setAttribute("aria-label", "Schedule a Tour");
181
+ }
182
+ this.cleanupMobileListener = onMobileChange((m) => (this.mobile = m));
183
+ this.addEventListener("keydown", this.onKeydown);
184
+ }
185
+
186
+ disconnectedCallback(): void {
187
+ this.cleanupMobileListener?.();
188
+ this.removeEventListener("keydown", this.onKeydown);
189
+ super.disconnectedCallback();
190
+ }
191
+
192
+ private onKeydown = (e: KeyboardEvent): void => {
193
+ // Tab stays inside the dialog, as in today's scheduler.
194
+ trapTabInside(e, this);
195
+ // Escape while composing (IME) cancels the conversion, as in the chat.
196
+ if (e.key === "Escape" && !e.defaultPrevented && !e.isComposing) {
197
+ e.stopPropagation();
198
+ this.close();
199
+ }
200
+ };
201
+
202
+ private close(): void {
203
+ this.onCloseClicked?.(new MouseEvent("click"));
204
+ }
205
+
206
+ private get client(): TourItineraryApi {
207
+ if (!this.api) {
208
+ this.api = createTourItineraryApi({
209
+ orgSlug: this.orgSlug,
210
+ buildingSlug: this.buildingSlug,
211
+ getSessionToken: () => this.getSessionToken(),
212
+ });
213
+ }
214
+ return this.api;
215
+ }
216
+
217
+ willUpdate(changed: PropertyValues<this>): void {
218
+ if (
219
+ changed.has("primaryColor") ||
220
+ changed.has("foregroundColorOnPrimaryBackgroundColor")
221
+ ) {
222
+ // The building's brand color, as the fee calculator sets it.
223
+ const primary = this.primaryColor || defaultPrimaryColor;
224
+ this.style.setProperty("--primary-color", primary);
225
+ // Continue and Schedule Tours in the brand color, as in the Central Agent design.
226
+ this.style.setProperty("--action-confirm-button-background", primary);
227
+ this.style.setProperty(
228
+ "--action-confirm-button-color",
229
+ this.foregroundColorOnPrimaryBackgroundColor
230
+ );
231
+ // The calendar's chosen day.
232
+ this.style.setProperty(
233
+ "--on-primary-color",
234
+ this.foregroundColorOnPrimaryBackgroundColor
235
+ );
236
+ }
237
+ }
238
+
239
+ firstUpdated(): void {
240
+ void this.start();
241
+ }
242
+
243
+ updated(changed: PropertyValues): void {
244
+ // As today's windows: open on the first control, the header's.
245
+ if (changed.has("step") && changed.get("step") === undefined) {
246
+ focusFirstTabStop(this);
247
+ return;
248
+ }
249
+ // A later step, or the reschedule prompt and its outcome, replaces the
250
+ // controls: hold focus on the dialog, where the Tab trap wraps it, instead
251
+ // of letting it fall back to the page.
252
+ if (
253
+ changed.has("step") ||
254
+ changed.has("reschedulePrompt") ||
255
+ changed.has("rescheduleCanceled")
256
+ ) {
257
+ if (!this.hasAttribute("tabindex")) this.setAttribute("tabindex", "-1");
258
+ this.focus({ preventScroll: true });
259
+ }
260
+ }
261
+
262
+ private async start(): Promise<void> {
263
+ this.step = "loading";
264
+ this.loadError = null;
265
+ try {
266
+ const group = await this.client.getCommunities(EMPTY_FILTERS);
267
+ this.group = group;
268
+ this.remember(group.communities);
269
+ if (group.anchor.is_general_building) {
270
+ this.goTo("pick");
271
+ return;
272
+ }
273
+ this.rememberOne({
274
+ building_id: group.anchor.building_id,
275
+ name: group.anchor.name,
276
+ address: null,
277
+ timezone: null,
278
+ });
279
+ this.startSchedule([group.anchor.building_id]);
280
+ } catch (e) {
281
+ if (e instanceof TourApiError && e.code === "NOT_IN_GROUP") {
282
+ // Not in a central group: book this building on its own.
283
+ this.group = null;
284
+ this.rememberOne({
285
+ building_id: this.buildingId,
286
+ name: this.buildingName,
287
+ address: null,
288
+ timezone: null,
289
+ });
290
+ this.startSchedule([this.buildingId]);
291
+ return;
292
+ }
293
+ this.loadError = (e as Error).message;
294
+ this.step = "error";
295
+ this.log("TOUR_SCHEDULER_V2_LOAD_ERROR", e);
296
+ }
297
+ }
298
+
299
+ private goTo(step: Step): void {
300
+ this.step = step;
301
+ // Each picker opens on the stops already chosen, or on none after a booking.
302
+ if (step === "pick") {
303
+ this.picks = this.selectedIds
304
+ .map((id) => this.communities.get(id))
305
+ .filter((c): c is CommunitySummary => !!c);
306
+ } else if (step === "booked") {
307
+ this.picks = [];
308
+ }
309
+ pushGtmEvent("tourSchedulerStepViewed", {
310
+ step: step === "schedule" && this.extending ? "extend-schedule" : step,
311
+ buildingId: this.buildingId,
312
+ });
313
+ }
314
+
315
+ private remember(communities: CommunitiesResponse["communities"]): void {
316
+ const next = new Map(this.communities);
317
+ communities.forEach((c) => next.set(c.building_id, toCommunitySummary(c)));
318
+ this.communities = next;
319
+ }
320
+
321
+ private rememberOne(community: CommunitySummary): void {
322
+ const known = this.communities.get(community.building_id);
323
+ if (known?.address) return;
324
+ this.communities = new Map(this.communities).set(
325
+ community.building_id,
326
+ community
327
+ );
328
+ }
329
+
330
+ private startSchedule(buildingIds: number[]): void {
331
+ this.selectedIds = buildingIds;
332
+ // The last plan was for other stops; show none until /plan answers for these.
333
+ this.plan = null;
334
+ this.firstStart = null;
335
+ this.laterStarts = {};
336
+ this.linkTourType = null;
337
+ this.notice = null;
338
+ this.bookingError = null;
339
+ this.reschedulePrompt = null;
340
+ this.goTo("schedule");
341
+ void this.runPlan();
342
+ }
343
+
344
+ private choice(): ItineraryChoice {
345
+ return {
346
+ buildingIds: this.selectedIds,
347
+ tourType: this.tourType,
348
+ // Until the server has listed its dates; runPlan moves to the first one
349
+ // it offers when this isn't among them.
350
+ date: this.date ?? toIsoDate(new Date()),
351
+ firstStart: this.firstStart,
352
+ laterStarts: this.laterStarts,
353
+ existingEventIds: this.existingEventIds,
354
+ };
355
+ }
356
+
357
+ /**
358
+ * Asks /plan for the chained times. When the server reports that the tour
359
+ * type or date isn't offered, moves to the first one it offers and asks again.
360
+ */
361
+ private async runPlan(keepNotice = false): Promise<void> {
362
+ if (this.selectedIds.length === 0) return;
363
+ const requestId = ++this.planRequestId;
364
+ this.planLoading = true;
365
+ this.planError = null;
366
+ // A notice explains the plan it came with; the prospect's next change replaces it.
367
+ if (!keepNotice) this.notice = null;
368
+ try {
369
+ let choice = this.choice();
370
+ let plan = await this.client.plan(buildPlanRequest(choice));
371
+ for (
372
+ let retry = 0;
373
+ retry < PLAN_RETRIES && requestId === this.planRequestId;
374
+ retry++
375
+ ) {
376
+ // The dates offered are the asked-for type's (none when it isn't
377
+ // offered), so move to the server's first type before reading them.
378
+ if (!plan.tour_types.includes(choice.tourType)) {
379
+ if (plan.tour_types.length === 0) break;
380
+ this.tourType = plan.tour_types[0];
381
+ } else if (
382
+ plan.bookable_dates.length > 0 &&
383
+ !plan.bookable_dates.includes(choice.date)
384
+ ) {
385
+ this.date = plan.bookable_dates[0];
386
+ } else {
387
+ break;
388
+ }
389
+ this.firstStart = null;
390
+ this.laterStarts = {};
391
+ choice = this.choice();
392
+ plan = await this.client.plan(buildPlanRequest(choice));
393
+ }
394
+ if (requestId !== this.planRequestId) return;
395
+ this.plan = plan;
396
+ if (plan.bookable_dates.includes(choice.date)) this.date = choice.date;
397
+ if (plan.changed.length > 0) {
398
+ this.notice = plan.changed.map((c) => c.text).join(" ");
399
+ }
400
+ } catch (e) {
401
+ if (requestId !== this.planRequestId) return;
402
+ this.planError = (e as Error).message;
403
+ this.log("TOUR_SCHEDULER_V2_PLAN_ERROR", e);
404
+ } finally {
405
+ if (requestId === this.planRequestId) this.planLoading = false;
406
+ }
407
+ }
408
+
409
+ // --- Tour types that open the building's own booking page ---
410
+
411
+ private tourLink(type: TourTypeId): string | null {
412
+ const offered = this.tourTypeOptions
413
+ .map((o) => o.value)
414
+ .includes(TOUR_TYPE_OPTION_VALUE[type]);
415
+ if (!offered) return null;
416
+ const [link, typeOffered] = {
417
+ "self-guided-tour": [this.sgtUrl, this.selfGuidedToursTypeOffered],
418
+ "escorted-tour": [this.escortedToursLink, this.escortedToursTypeOffered],
419
+ "live-virtual-tour": [
420
+ this.virtualToursLink,
421
+ this.virtualToursTypeOffered,
422
+ ],
423
+ }[type];
424
+ return link && shouldOpenTourLink(type, typeOffered) ? link : null;
425
+ }
426
+
427
+ /**
428
+ * Only a lone tour of this widget's own building can use its links: the widget
429
+ * has its own building's tour settings and no other's. An itinerary with
430
+ * other buildings offers only the tour types /plan serves for all of them.
431
+ */
432
+ private get bookingOwnBuildingAlone(): boolean {
433
+ return (
434
+ this.existingEventIds.length === 0 &&
435
+ this.selectedIds.length === 1 &&
436
+ this.selectedIds[0] === this.buildingId
437
+ );
438
+ }
439
+
440
+ private openTourLink(type: TourTypeId): void {
441
+ const link = this.tourLink(type);
442
+ if (!link) return;
443
+ // As today's scheduler: AMLI (org 52) forwards the page's query string.
444
+ const url =
445
+ type === "self-guided-tour" && this.orgId === 52
446
+ ? appendParamsToUrl(link, getUrlQueryParameters())
447
+ : link;
448
+ window.open(url, "_blank");
449
+ }
450
+
451
+ private tourTypeChoices(): TourTypeChoice[] {
452
+ const served = this.plan?.tour_types ?? [];
453
+ return TOUR_TYPE_ORDER.filter(
454
+ (t) =>
455
+ served.includes(t) ||
456
+ (this.bookingOwnBuildingAlone && !!this.tourLink(t))
457
+ ).map((id) => ({
458
+ id,
459
+ opensLink: this.bookingOwnBuildingAlone && !!this.tourLink(id),
460
+ }));
461
+ }
462
+
463
+ /** The tour type shown as chosen: a link type the prospect picked, or the plan's. */
464
+ private get shownTourType(): TourTypeId | null {
465
+ if (this.linkTourType) return this.linkTourType;
466
+ return this.plan?.tour_types.includes(this.tourType) ? this.tourType : null;
467
+ }
468
+
469
+ /**
470
+ * The shown tour type when this building books it on its own page, whether the
471
+ * prospect picked it or the plan did. It replaces the times and blocks booking.
472
+ */
473
+ private get activeLinkType(): TourTypeId | null {
474
+ const type = this.shownTourType;
475
+ return type && this.bookingOwnBuildingAlone && this.tourLink(type)
476
+ ? type
477
+ : null;
478
+ }
479
+
480
+ // --- Editor events ---
481
+
482
+ private onTourType(tourType: TourTypeId): void {
483
+ pushGtmEvent("tourTypeSelected", { tourType, buildingId: this.buildingId });
484
+ if (this.bookingOwnBuildingAlone && this.tourLink(tourType)) {
485
+ this.linkTourType = tourType;
486
+ this.openTourLink(tourType);
487
+ return;
488
+ }
489
+ this.linkTourType = null;
490
+ if (tourType === this.tourType) return;
491
+ this.tourType = tourType;
492
+ this.firstStart = null;
493
+ this.laterStarts = {};
494
+ void this.runPlan();
495
+ }
496
+
497
+ private onDate(date: string): void {
498
+ if (date === this.date) return;
499
+ pushGtmEvent("tourDateSelected", {
500
+ tourType: this.tourType,
501
+ buildingId: this.buildingId,
502
+ });
503
+ this.date = date;
504
+ this.firstStart = null;
505
+ this.laterStarts = {};
506
+ void this.runPlan();
507
+ }
508
+
509
+ private onStopTime(buildingId: number, start: string): void {
510
+ const index = this.selectedIds.indexOf(buildingId);
511
+ if (index < 0) return;
512
+ pushGtmEvent("tourTimeSelected", {
513
+ tourType: this.tourType,
514
+ buildingId: this.buildingId,
515
+ stopNumber: index + 1,
516
+ });
517
+ // A new time can move every stop after it, so their own picks are dropped.
518
+ const earlier = this.selectedIds.slice(1, index);
519
+ if (index === 0) {
520
+ this.firstStart = isoHourMinute(start);
521
+ this.laterStarts = {};
522
+ } else {
523
+ this.laterStarts = {
524
+ ...Object.fromEntries(
525
+ earlier
526
+ .filter((id) => this.laterStarts[id])
527
+ .map((id) => [id, this.laterStarts[id]])
528
+ ),
529
+ [buildingId]: start,
530
+ };
531
+ }
532
+ void this.runPlan();
533
+ }
534
+
535
+ private onReorder(buildingIds: number[]): void {
536
+ pushGtmEvent("tourStopsReordered", {
537
+ buildingId: this.buildingId,
538
+ stopCount: buildingIds.length,
539
+ });
540
+ // The editor orders the chained stops; any /plan couldn't chain stay, after them.
541
+ const unchained = this.selectedIds.filter(
542
+ (id) => !buildingIds.includes(id)
543
+ );
544
+ this.selectedIds = [...buildingIds, ...unchained];
545
+ this.firstStart = null;
546
+ this.laterStarts = {};
547
+ void this.runPlan();
548
+ }
549
+
550
+ private onRemove(buildingId: number): void {
551
+ const remaining = this.selectedIds.filter((id) => id !== buildingId);
552
+ pushGtmEvent("tourStopRemoved", {
553
+ buildingId: this.buildingId,
554
+ stopCount: remaining.length,
555
+ });
556
+ if (remaining.length === 0) {
557
+ this.selectedIds = [];
558
+ this.plan = null;
559
+ this.goTo(this.extending ? "booked" : "pick");
560
+ return;
561
+ }
562
+ // The first stop's time belongs to that stop, not to whichever moves up.
563
+ if (this.selectedIds[0] === buildingId) this.firstStart = null;
564
+ this.selectedIds = remaining;
565
+ this.laterStarts = {};
566
+ void this.runPlan();
567
+ }
568
+
569
+ private onEditCommunities(): void {
570
+ this.goTo("pick");
571
+ }
572
+
573
+ // --- Picker ---
574
+
575
+ private loadSelectCommunities = (
576
+ filters: CommunityFilters
577
+ ): Promise<CommunitiesResponse> =>
578
+ this.client.getCommunities(filters).then(this.rememberPage);
579
+
580
+ private loadExtendCommunities = (
581
+ filters: CommunityFilters
582
+ ): Promise<CommunitiesResponse> => {
583
+ const extend = this.extendFrom;
584
+ // The extend picker only shows once a booking has given these.
585
+ if (!extend) return Promise.reject(new Error("No booking to extend"));
586
+ return this.client
587
+ .getCommunities({ ...filters, extend })
588
+ .then(this.rememberPage);
589
+ };
590
+
591
+ private rememberPage = (
592
+ response: CommunitiesResponse
593
+ ): CommunitiesResponse => {
594
+ this.remember(response.communities);
595
+ return response;
596
+ };
597
+
598
+ private onCommunitiesSelected(
599
+ picked: CommunitySummary[],
600
+ mode: "select" | "extend"
601
+ ): void {
602
+ picked.forEach((c) => this.rememberOne(c));
603
+ pushGtmEvent("tourCommunitiesSelected", {
604
+ buildingId: this.buildingId,
605
+ count: picked.length,
606
+ mode,
607
+ });
608
+ this.extending = mode === "extend";
609
+ if (this.extending) {
610
+ this.existingEventIds = this.bookedEventIds;
611
+ this.tourType = this.bookedTourType ?? this.tourType;
612
+ const last = this.confirmed.filter((s) => s.start).slice(-1)[0];
613
+ this.date = last?.start ? isoDate(last.start) : this.date;
614
+ } else {
615
+ this.existingEventIds = [];
616
+ }
617
+ this.startSchedule(picked.map((c) => c.building_id));
618
+ }
619
+
620
+ // --- Booking ---
621
+
622
+ private async submit(
623
+ values: ContactValues,
624
+ cancelExistingTours = false
625
+ ): Promise<void> {
626
+ // What's booked, kept apart from the screen, which stays editable while the request runs.
627
+ const plan = this.plan;
628
+ if (!plan || this.submitting) return;
629
+ const choice = this.choice();
630
+ const showDropdown = this.showLeadSourceDropdown();
631
+ const selectedLeadSource = showDropdown ? values.leadSource : null;
632
+ const request = buildBookingRequest({
633
+ choice,
634
+ plan,
635
+ contact: {
636
+ first_name: values.firstName.trim(),
637
+ last_name: values.lastName.trim(),
638
+ email: values.email.trim(),
639
+ phone_e164: values.phoneE164 ?? "",
640
+ bedrooms:
641
+ values.layout === null ? [] : [layoutToBedrooms(values.layout)],
642
+ move_in: values.moveIn || null,
643
+ notes: values.notes.trim(),
644
+ },
645
+ attribution: buildAttribution({
646
+ orgSlug: this.orgSlug,
647
+ selectedLeadSource,
648
+ currentLeadSource: this.currentLeadSource,
649
+ touchpoints:
650
+ this.leadSourceMultitouchClient?.getSafeLeadSourceTouchpointsWithDefault(
651
+ { includedUserSelectedLeadSource: selectedLeadSource || null }
652
+ ) ?? [],
653
+ search: window.location.search,
654
+ referrer: document.referrer,
655
+ googleReferral: readGoogleReserveReferral(),
656
+ }),
657
+ conversationTrackingId: this.leadSourceClient?.chatId ?? null,
658
+ cancelExistingTours,
659
+ });
660
+ // Retrying the same booking reuses its key, so it can't book twice. The key
661
+ // follows what is booked, not the whole request: attribution is stamped with
662
+ // the time of each submit.
663
+ const booking = JSON.stringify({
664
+ tour_type: request.tour_type,
665
+ stops: request.stops,
666
+ contact: request.contact,
667
+ cancel_existing_tours: request.cancel_existing_tours,
668
+ });
669
+ if (this.idempotency?.booking !== booking) {
670
+ this.idempotency = { booking, key: uuid() };
671
+ }
672
+ pushGtmEvent("scheduleTourSubmitted", {
673
+ tourType: choice.tourType,
674
+ stopCount: request.stops.length,
675
+ buildingId: this.buildingId,
676
+ });
677
+ this.submitting = true;
678
+ this.bookingError = null;
679
+ try {
680
+ const response = await this.client.book(request, this.idempotency.key);
681
+ this.idempotency = null;
682
+ this.rescheduled = cancelExistingTours;
683
+ this.onBooked(response, choice.tourType, plan);
684
+ } catch (e) {
685
+ this.onBookingError(e, values);
686
+ } finally {
687
+ this.submitting = false;
688
+ }
689
+ }
690
+
691
+ private onBooked(
692
+ response: BookingResponse,
693
+ tourType: TourTypeId,
694
+ plan: PlanResponse
695
+ ): void {
696
+ this.reschedulePrompt = null;
697
+ // Nothing booked: stay on the form with fresh times, as a taken slot does.
698
+ if (response.stops.every((s) => s.status === "failed")) {
699
+ this.notice =
700
+ response.stops.find((s) => s.error)?.error?.message ??
701
+ "We couldn't book your tour. Please pick another time.";
702
+ this.log("TOUR_SCHEDULER_V2_BOOKING_ERROR", response.stops);
703
+ void this.runPlan(true);
704
+ return;
705
+ }
706
+ const plannedStops = new Map(plan.stops.map((s) => [s.building_id, s]));
707
+ this.confirmed = response.stops.map((stop) => {
708
+ const community = this.communities.get(stop.building_id) ?? {
709
+ building_id: stop.building_id,
710
+ name: "",
711
+ address: null,
712
+ timezone: null,
713
+ };
714
+ // A community card's time zone can be missing; its /plan stop always has one.
715
+ const timezone =
716
+ community.timezone ??
717
+ plannedStops.get(stop.building_id)?.timezone ??
718
+ null;
719
+ return {
720
+ community: { ...community, timezone },
721
+ start: stop.start,
722
+ end: stop.end,
723
+ status: stop.status,
724
+ error: stop.error?.message ?? null,
725
+ distanceFromPrevMi:
726
+ plannedStops.get(stop.building_id)?.distance_from_prev_mi ?? null,
727
+ };
728
+ });
729
+ const bookedStops = response.stops.filter(
730
+ (s) => s.status !== "failed" && s.calendar_event_id !== null
731
+ );
732
+ this.bookedEventIds = bookedStops.map((s) => s.calendar_event_id as number);
733
+ this.bookedTourType = tourType;
734
+ this.extending = false;
735
+ this.extendInitial = null;
736
+ pushGtmEvent("tourItineraryBooked", {
737
+ buildingId: this.buildingId,
738
+ stopCount: bookedStops.length,
739
+ failedCount: response.stops.length - bookedStops.length,
740
+ });
741
+ if (bookedStops.length > 0) {
742
+ // As today's scheduler does after a booking.
743
+ this.leadSourceClient?.checkAndHandleForLogLeadSource({
744
+ webchatAction: "tour-scheduler",
745
+ stateId: null,
746
+ });
747
+ this.leadSourceClient?.resetLeadSource();
748
+ this.leadSourceMultitouchClient?.resetLeadSourceTouchpoints();
749
+ }
750
+ this.goTo("booked");
751
+ void this.loadExtension();
752
+ }
753
+
754
+ /**
755
+ * What the server needs to offer stops after this booking: when its last stop
756
+ * ends, its tour type, where that stop is, and every building already in it.
757
+ */
758
+ private extendQueryFromBooking(): ExtendQuery | null {
759
+ const booked = this.confirmed.filter((s) => s.status !== "failed");
760
+ const last = booked[booked.length - 1];
761
+ if (!last?.end || !this.bookedTourType) return null;
762
+ return {
763
+ availableAfter: last.end,
764
+ tourType: this.bookedTourType,
765
+ nearBuildingId: last.community.building_id,
766
+ excludeBuildingIds: booked.map((s) => s.community.building_id),
767
+ };
768
+ }
769
+
770
+ private stopsRemaining(): number {
771
+ return MAX_ITINERARY_STOPS - this.bookedEventIds.length;
772
+ }
773
+
774
+ /** Offers more communities while the itinerary has stops left. */
775
+ private async loadExtension(): Promise<void> {
776
+ const extend = this.extendQueryFromBooking();
777
+ this.extendFrom = extend;
778
+ const stopsRemaining = this.stopsRemaining();
779
+ if (!this.group || !extend || stopsRemaining <= 0) return;
780
+ try {
781
+ const response = await this.client.getCommunities({
782
+ ...EMPTY_FILTERS,
783
+ extend,
784
+ });
785
+ this.remember(response.communities);
786
+ if (response.communities.some((c) => c.tourable)) {
787
+ this.extendInitial = response;
788
+ pushGtmEvent("tourExtensionOffered", {
789
+ buildingId: this.buildingId,
790
+ stopsRemaining,
791
+ });
792
+ }
793
+ } catch (e) {
794
+ this.log("TOUR_SCHEDULER_V2_EXTEND_LOAD_ERROR", e);
795
+ }
796
+ }
797
+
798
+ private onBookingError(e: unknown, values: ContactValues): void {
799
+ const error =
800
+ e instanceof TourApiError
801
+ ? e
802
+ : new TourApiError(0, null, "Something went wrong. Please try again.");
803
+ if (error.code === "EXISTING_TOUR") {
804
+ this.reschedulePrompt = error.message;
805
+ this.contact = values;
806
+ return;
807
+ }
808
+ this.reschedulePrompt = null;
809
+ if (error.code === "SLOT_TAKEN") {
810
+ this.notice = error.message;
811
+ void this.runPlan(true);
812
+ return;
813
+ }
814
+ this.bookingError = error.message;
815
+ this.log("TOUR_SCHEDULER_V2_BOOKING_ERROR", e);
816
+ }
817
+
818
+ private showLeadSourceDropdown(): boolean {
819
+ return (
820
+ this.featureFlagShowDropdown === FeatureFlagsShowDropdown.always ||
821
+ (this.featureFlagShowDropdown ===
822
+ FeatureFlagsShowDropdown.onAttributionFailure &&
823
+ this.currentLeadSource.length === 0)
824
+ );
825
+ }
826
+
827
+ private log(title: string, error: unknown): void {
828
+ sendLoggingEvent({
829
+ logTitle: title,
830
+ logData: { error },
831
+ logType: LogType.error,
832
+ buildingSlug: this.buildingSlug,
833
+ orgSlug: this.orgSlug,
834
+ error,
835
+ });
836
+ }
837
+
838
+ // --- Rendering ---
839
+
840
+ /** Where the back button goes from the current step, if anywhere. */
841
+ private backStep(): Step | null {
842
+ // The prospect kept their existing tour: nothing to go back to.
843
+ if (this.rescheduleCanceled) return null;
844
+ if (this.step === "schedule") {
845
+ if (this.extending) return "booked";
846
+ return this.group ? "pick" : null;
847
+ }
848
+ // A member building opens on its schedule step, so the picker can go back to it.
849
+ if (
850
+ this.step === "pick" &&
851
+ this.group &&
852
+ !this.group.anchor.is_general_building &&
853
+ this.plan &&
854
+ this.selectedIds.length > 0
855
+ ) {
856
+ return "schedule";
857
+ }
858
+ return null;
859
+ }
860
+
861
+ private problems(): StopProblem[] {
862
+ return this.plan?.unchainable ?? [];
863
+ }
864
+
865
+ private isMultiStop(): boolean {
866
+ return this.selectedIds.length > 1 || this.existingEventIds.length > 0;
867
+ }
868
+
869
+ private canSubmit(): boolean {
870
+ const plan = this.plan;
871
+ return (
872
+ !!plan &&
873
+ !this.planLoading &&
874
+ // After a failed refresh the plan on hand is for the previous choices.
875
+ !this.planError &&
876
+ plan.stops.some((s) => !s.fixed) &&
877
+ plan.unchainable.length === 0 &&
878
+ this.activeLinkType === null &&
879
+ contactIsValid(this.contact, this.bedroomPreferenceRequired)
880
+ );
881
+ }
882
+
883
+ private disclaimer(): TemplateResult {
884
+ return formDisclaimer({
885
+ buildingName: this.buildingName,
886
+ phoneNumberInput: this.contact.phone,
887
+ emailInput: this.contact.email,
888
+ orgLegalName: this.orgLegalName,
889
+ orgSlug: this.orgSlug,
890
+ country: this.country,
891
+ buildingState: this.buildingState,
892
+ clickingButtonText: "schedule tour",
893
+ });
894
+ }
895
+
896
+ /** Today's scheduler's body area, which scrolls the whole sheet on phones. */
897
+ private container(content: TemplateResult): TemplateResult {
898
+ return html`<div
899
+ id=${this.mobile ? "mobile-body-container" : "scheduler-container"}
900
+ >
901
+ ${content}
902
+ </div>`;
903
+ }
904
+
905
+ private renderPicker(): TemplateResult {
906
+ return html`${this.container(html`<community-picker
907
+ variant="select"
908
+ .load=${this.loadSelectCommunities}
909
+ .initial=${this.group}
910
+ .maxSelectable=${MAX_ITINERARY_STOPS}
911
+ .selected=${this.picks}
912
+ @selection-change=${this.onPicksChange}
913
+ ></community-picker>`)}
914
+ ${this.renderTray("select")}`;
915
+ }
916
+
917
+ private onPicksChange = (
918
+ e: CustomEvent<{ communities: CommunitySummary[] }>
919
+ ): void => {
920
+ this.picks = e.detail.communities;
921
+ };
922
+
923
+ private renderTray(mode: "select" | "extend"): TemplateResult | string {
924
+ return renderSelectionTray({
925
+ selected: this.picks,
926
+ mobile: this.mobile,
927
+ onRemove: (buildingId) =>
928
+ (this.picks = this.picks.filter((c) => c.building_id !== buildingId)),
929
+ onContinue: () => this.onCommunitiesSelected(this.picks, mode),
930
+ });
931
+ }
932
+
933
+ private renderSchedule(): TemplateResult {
934
+ if (this.reschedulePrompt !== null) return this.renderReschedulePrompt();
935
+ const plan = this.plan;
936
+ const totalStops =
937
+ (plan?.stops.length ?? 0) + (plan?.unchainable.length ?? 0);
938
+ return html`${this.container(html`
939
+ ${this.planError
940
+ ? html`<p class="error-message" role="alert">
941
+ ${this.planError}
942
+ <button class="link-button" @click=${() => this.runPlan()}>
943
+ Try again
944
+ </button>
945
+ </p>`
946
+ : ""}
947
+ ${this.notice
948
+ ? html`<p class="explanation notice" role="status">${this.notice}</p>`
949
+ : ""}
950
+ <div id="book-tour-journey-items">
951
+ <itinerary-editor
952
+ .stops=${plan?.stops ?? []}
953
+ .communities=${this.communities}
954
+ .problems=${this.problems()}
955
+ .tourTypes=${this.tourTypeChoices()}
956
+ .tourType=${this.shownTourType}
957
+ .bookableDates=${plan?.bookable_dates ?? []}
958
+ .date=${this.date}
959
+ ?single=${!this.isMultiStop()}
960
+ ?canEditCommunities=${this.group !== null && !this.extending}
961
+ ?canAddStop=${this.group !== null &&
962
+ totalStops < MAX_ITINERARY_STOPS}
963
+ ?loading=${this.planLoading}
964
+ .primaryColor=${this.primaryColor}
965
+ .foregroundColorOnPrimaryBackgroundColor=${this
966
+ .foregroundColorOnPrimaryBackgroundColor}
967
+ @tour-type-change=${(e: CustomEvent<{ tourType: TourTypeId }>) =>
968
+ this.onTourType(e.detail.tourType)}
969
+ @date-change=${(e: CustomEvent<{ date: string }>) =>
970
+ this.onDate(e.detail.date)}
971
+ @stop-time-change=${(
972
+ e: CustomEvent<{ buildingId: number; start: string }>
973
+ ) => this.onStopTime(e.detail.buildingId, e.detail.start)}
974
+ @stops-reorder=${(e: CustomEvent<{ buildingIds: number[] }>) =>
975
+ this.onReorder(e.detail.buildingIds)}
976
+ @stop-remove=${(e: CustomEvent<{ buildingId: number }>) =>
977
+ this.onRemove(e.detail.buildingId)}
978
+ @edit-communities=${() => this.onEditCommunities()}
979
+ @open-tour-link=${() =>
980
+ this.activeLinkType && this.openTourLink(this.activeLinkType)}
981
+ ></itinerary-editor>
982
+ <contact-form
983
+ .values=${this.contact}
984
+ .layoutOptions=${this.layoutOptions}
985
+ ?bedroomsRequired=${this.bedroomPreferenceRequired}
986
+ .leadSources=${this.leadSources}
987
+ ?showLeadSourceDropdown=${this.showLeadSourceDropdown()}
988
+ currentLeadSource=${this.currentLeadSource}
989
+ .country=${this.country}
990
+ ?mobile=${this.mobile}
991
+ @contact-change=${(e: CustomEvent<{ values: ContactValues }>) =>
992
+ (this.contact = e.detail.values)}
993
+ @lead-source-selected=${(e: CustomEvent<{ leadSource: string }>) =>
994
+ pushGtmEvent("tourLeadSourceSelected", {
995
+ leadSource: e.detail.leadSource,
996
+ buildingId: this.buildingId,
997
+ })}
998
+ ></contact-form>
999
+ </div>
1000
+ `)}
1001
+ <div
1002
+ id="tour-scheduler-footer"
1003
+ class=${classMap({ stacked: this.mobile })}
1004
+ >
1005
+ <div class="explanation">
1006
+ We'll send a confirmation and any follow-ups to your email address,
1007
+ please reply to the email to make any appointment changes.
1008
+ ${this.disclaimer()}
1009
+ ${this.bookingError
1010
+ ? html`<p class="error-message" role="alert">
1011
+ ${this.bookingError}
1012
+ </p>`
1013
+ : ""}
1014
+ </div>
1015
+ <action-confirm-button
1016
+ id="schedule-bttn"
1017
+ .onClick=${() => this.submit(this.contact)}
1018
+ .isLoading=${this.submitting}
1019
+ height="50px"
1020
+ width=${this.mobile ? "100%" : "145px"}
1021
+ text=${this.isMultiStop() ? "Schedule tours" : "Schedule tour"}
1022
+ ?disabled=${!this.canSubmit()}
1023
+ ></action-confirm-button>
1024
+ </div>`;
1025
+ }
1026
+
1027
+ /** Today's reschedule prompt, with the server's reason. */
1028
+ private renderReschedulePrompt(): TemplateResult {
1029
+ return html`${this.container(html`<div>
1030
+ <h2 class="journey-header">Reschedule Tour</h2>
1031
+ <div class="explanation">
1032
+ ${this.reschedulePrompt} Would you like to reschedule?
1033
+ </div>
1034
+ </div>`)}
1035
+ <div id="tour-scheduler-footer">
1036
+ <div class="explanation">${this.disclaimer()}</div>
1037
+ <div class="reschedule-buttons-wrapper">
1038
+ <action-confirm-button
1039
+ id="cancel-reschedule-bttn"
1040
+ .onClick=${() => {
1041
+ this.reschedulePrompt = null;
1042
+ // Adding stops: the first booking stands, so show it again.
1043
+ if (this.extending) this.goTo("booked");
1044
+ else this.rescheduleCanceled = true;
1045
+ }}
1046
+ .isLoading=${this.submitting}
1047
+ height="50px"
1048
+ width="145px"
1049
+ text="Cancel"
1050
+ ></action-confirm-button>
1051
+ <action-confirm-button
1052
+ id="reschedule-button"
1053
+ .onClick=${() => this.submit(this.contact, true)}
1054
+ .isLoading=${this.submitting}
1055
+ height="50px"
1056
+ width="145px"
1057
+ text="Reschedule"
1058
+ ></action-confirm-button>
1059
+ </div>
1060
+ </div>`;
1061
+ }
1062
+
1063
+ private renderRescheduleCanceled(): TemplateResult {
1064
+ return html`<div id="confirmationMessage">
1065
+ ${CalendarCheckIcon()}
1066
+ <p>Thank you!</p>
1067
+ <p>We'll see you at your originally scheduled tour time.</p>
1068
+ </div>`;
1069
+ }
1070
+
1071
+ private renderBooked(): TemplateResult {
1072
+ return html`${this.container(html`<booking-confirmation
1073
+ .stops=${this.confirmed}
1074
+ .tourType=${this.bookedTourType}
1075
+ ?rescheduled=${this.rescheduled}
1076
+ >
1077
+ ${this.extendInitial
1078
+ ? html`<community-picker
1079
+ variant="extend"
1080
+ .load=${this.loadExtendCommunities}
1081
+ .initial=${this.extendInitial}
1082
+ .maxSelectable=${this.stopsRemaining()}
1083
+ .selected=${this.picks}
1084
+ @selection-change=${this.onPicksChange}
1085
+ ></community-picker>`
1086
+ : ""}
1087
+ </booking-confirmation>`)}
1088
+ ${this.extendInitial ? this.renderTray("extend") : ""}`;
1089
+ }
1090
+
1091
+ private renderBody(): TemplateResult {
1092
+ if (this.rescheduleCanceled) return this.renderRescheduleCanceled();
1093
+ switch (this.step) {
1094
+ case "loading":
1095
+ return html`<div class="center-tour-not-avail" role="status">
1096
+ <h1>Searching for availabilities...</h1>
1097
+ <div class="loading-entire-tour-icon">
1098
+ <mega-loader size="48"></mega-loader>
1099
+ </div>
1100
+ </div>`;
1101
+ case "error":
1102
+ return html`<div class="center-tour-not-avail">
1103
+ <p class="error-message" role="alert">${this.loadError}</p>
1104
+ <action-confirm-button
1105
+ text="Try again"
1106
+ height="40px"
1107
+ .onClick=${() => this.start()}
1108
+ ></action-confirm-button>
1109
+ </div>`;
1110
+ case "pick":
1111
+ return this.renderPicker();
1112
+ case "schedule":
1113
+ return this.renderSchedule();
1114
+ case "booked":
1115
+ return this.renderBooked();
1116
+ }
1117
+ }
1118
+
1119
+ render(): TemplateResult {
1120
+ const back = this.backStep();
1121
+ return html`<div
1122
+ class=${classMap({
1123
+ "tour-scheduler-full": !this.compactDesign && !this.mobile,
1124
+ "tour-scheduler-compact": !!this.compactDesign && !this.mobile,
1125
+ "tour-scheduler-mobile": this.mobile,
1126
+ })}
1127
+ >
1128
+ <div id="top-header">
1129
+ <div class="title">
1130
+ ${back
1131
+ ? html`<button
1132
+ id="back-button"
1133
+ aria-label="Back"
1134
+ @click=${() => this.goTo(back)}
1135
+ >
1136
+ ${ChevronLeftIcon("#202020")}
1137
+ </button>`
1138
+ : ""}
1139
+ <h1 id="tour-header-title">Schedule a Tour</h1>
1140
+ </div>
1141
+ <button
1142
+ id="close-button"
1143
+ aria-label="Close scheduler"
1144
+ @click=${(e: MouseEvent) => this.onCloseClicked?.(e)}
1145
+ >
1146
+ ${XOutlineIcon("#202020")}
1147
+ </button>
1148
+ </div>
1149
+ ${this.renderBody()}
1150
+ </div>`;
1151
+ }
1152
+
1153
+ static styles = [
1154
+ tourSchedulerStyles,
1155
+ InputStyles,
1156
+ selectionTrayStyles,
1157
+ css`
1158
+ /* New layout only: the back button beside the title. */
1159
+ .title {
1160
+ align-items: center;
1161
+ display: flex;
1162
+ gap: 12px;
1163
+ }
1164
+
1165
+ #back-button {
1166
+ align-items: center;
1167
+ background: none;
1168
+ border: none;
1169
+ cursor: pointer;
1170
+ display: inline-flex;
1171
+ height: 24px;
1172
+ justify-content: center;
1173
+ padding: 0;
1174
+ width: 24px;
1175
+ }
1176
+
1177
+ #back-button svg {
1178
+ height: 12px;
1179
+ width: 8px;
1180
+ }
1181
+
1182
+ .notice {
1183
+ margin: 0 0 16px;
1184
+ }
1185
+
1186
+ .link-button {
1187
+ background: none;
1188
+ border: none;
1189
+ color: inherit;
1190
+ cursor: pointer;
1191
+ font: inherit;
1192
+ text-decoration: underline;
1193
+ }
1194
+ `,
1195
+ ];
1196
+ }
1197
+
1198
+ declare global {
1199
+ interface HTMLElementTagNameMap {
1200
+ "tour-scheduler-v2": TourSchedulerV2;
1201
+ }
1202
+ }