@meetelise/chat 1.67.0 → 1.69.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.
@@ -11,6 +11,8 @@ import {
11
11
  import { StyleInfo, styleMap } from "lit/directives/style-map.js";
12
12
  import { installCallUsWindow } from "../actions/call-us-window";
13
13
  import { TourScheduler } from "../Scheduler/tour-scheduler";
14
+ import "../SchedulerV2/tour-scheduler-v2";
15
+ import type { TourSchedulerV2 } from "../SchedulerV2/tour-scheduler-v2";
14
16
  import { FeeCalculator } from "../FeeCalculator/fee-calculator";
15
17
  import { installFeeCalculator } from "../FeeCalculator";
16
18
  import { LabeledOption } from "../../fetchBuildingInfo";
@@ -159,6 +161,11 @@ export class Launcher extends LitElement {
159
161
  bedroomPreferenceRequired = false;
160
162
  @property({ attribute: false })
161
163
  brokerIntakeEnabled = false;
164
+ /** The building is on the `webchat_tour_scheduler_v2` rollout. */
165
+ @property({ attribute: false })
166
+ tourSchedulerV2 = false;
167
+ @property({ attribute: false })
168
+ getSessionToken: () => string | null = () => null;
162
169
  @property({ attribute: true })
163
170
  hasDynamicSchedulingEnabled = false;
164
171
 
@@ -288,6 +295,12 @@ export class Launcher extends LitElement {
288
295
 
289
296
  emailUsWindowRef: Ref<EmailUsWindow> = createRef();
290
297
  tourSchedulerRef: Ref<TourScheduler> = createRef();
298
+ tourSchedulerV2Ref: Ref<TourSchedulerV2> = createRef();
299
+ /**
300
+ * Which scheduler the open window shows, fixed when it opens so that the
301
+ * rollout answer arriving later can't swap it mid-booking.
302
+ */
303
+ private sstWindowIsV2 = false;
291
304
  calculatorWindowRef: Ref<FeeCalculator> = createRef();
292
305
 
293
306
  willUpdate(changedProperties: PropertyValues<this>): void {
@@ -297,6 +310,9 @@ export class Launcher extends LitElement {
297
310
  ) {
298
311
  this.isSSTWindowOpen = true;
299
312
  }
313
+ if (changedProperties.has("isSSTWindowOpen") && this.isSSTWindowOpen) {
314
+ this.sstWindowIsV2 = this.tourSchedulerV2;
315
+ }
300
316
  }
301
317
 
302
318
  updated = async (): Promise<void> => {
@@ -322,6 +338,10 @@ export class Launcher extends LitElement {
322
338
  };
323
339
 
324
340
  attachOnClickToSSTWindow = (): void => {
341
+ const sstWindowV2 = this.tourSchedulerV2Ref.value;
342
+ if (sstWindowV2) {
343
+ sstWindowV2.onCloseClicked = this.onCloseSSTWindow;
344
+ }
325
345
  const sstWindowRef = this.tourSchedulerRef.value;
326
346
  if (!sstWindowRef) {
327
347
  return;
@@ -389,8 +409,11 @@ export class Launcher extends LitElement {
389
409
  e.stopPropagation();
390
410
  closeRengrataWidget();
391
411
  pushGtmEvent("bookTourClicked", { buildingId: this.buildingId });
392
- resetAvailabilitiesCache();
393
- getRawAvailabilities(this.buildingId);
412
+ // Warms today's scheduler's availabilities; the v2 scheduler asks /plan instead.
413
+ if (!this.tourSchedulerV2) {
414
+ resetAvailabilitiesCache();
415
+ getRawAvailabilities(this.buildingId);
416
+ }
394
417
 
395
418
  this.isSSTWindowOpen = true;
396
419
  };
@@ -1350,7 +1373,44 @@ export class Launcher extends LitElement {
1350
1373
  </email-us-window>
1351
1374
  </div>`
1352
1375
  : ""}
1353
- ${this.isSSTWindowOpen
1376
+ ${this.isSSTWindowOpen && this.sstWindowIsV2
1377
+ ? html`<div
1378
+ class="launcher__window-wrapper"
1379
+ style=${styleMap(overrideStyleWindows)}
1380
+ >
1381
+ <tour-scheduler-v2
1382
+ id="tour-scheduler-window"
1383
+ orgSlug=${this.orgSlug}
1384
+ buildingSlug=${this.buildingSlug}
1385
+ buildingId=${this.buildingId}
1386
+ orgId=${this.orgId}
1387
+ .buildingName=${this.buildingName}
1388
+ sgtUrl=${this.sgtUrl}
1389
+ selfGuidedToursTypeOffered=${this.selfGuidedToursTypeOffered}
1390
+ escortedToursLink=${this.escortedToursLink}
1391
+ .escortedToursTypeOffered=${this.escortedToursTypeOffered}
1392
+ virtualToursLink=${this.virtualToursLink}
1393
+ virtualToursTypeOffered=${this.virtualToursTypeOffered}
1394
+ .tourTypeOptions=${this.tourTypeOptions}
1395
+ .layoutOptions=${this.layoutOptions}
1396
+ currentLeadSource=${this.currentLeadSource}
1397
+ .leadSources=${this.leadSources}
1398
+ featureFlagShowDropdown=${this.featureFlagShowDropdown}
1399
+ .bedroomPreferenceRequired=${this.bedroomPreferenceRequired}
1400
+ .orgLegalName=${this.orgLegalName}
1401
+ .country=${this.country}
1402
+ .buildingState=${this.buildingState}
1403
+ .primaryColor=${this.primaryColor}
1404
+ .foregroundColorOnPrimaryBackgroundColor=${this
1405
+ .foregroundColorOnPrimaryBackgroundColor}
1406
+ .compactDesign=${this.showTourNextToChat}
1407
+ .leadSourceClient=${this.leadSourceClient}
1408
+ .leadSourceMultitouchClient=${this.leadSourceMultitouchClient}
1409
+ .getSessionToken=${this.getSessionToken}
1410
+ ${ref(this.tourSchedulerV2Ref)}
1411
+ ></tour-scheduler-v2>
1412
+ </div>`
1413
+ : this.isSSTWindowOpen
1354
1414
  ? html`<div
1355
1415
  class="launcher__window-wrapper"
1356
1416
  style=${styleMap(overrideStyleWindows)}
@@ -17,6 +17,7 @@ import {
17
17
  fetchFeatureFlagUseOverrideContactUsForm,
18
18
  fetchTrackedRolloutBedroomPreferenceRequired,
19
19
  fetchTrackedRolloutBrokerIntake,
20
+ fetchTrackedRolloutTourSchedulerV2,
20
21
  } from "../fetchFeatureFlag";
21
22
  import { HIDE_DATA_LAYER_PII_ORG_IDS, setGtmPiiRedaction } from "../gtm";
22
23
  import fetchPhoneNumberFromSource, {
@@ -197,6 +198,9 @@ export class MEChat extends LitElement {
197
198
  FeatureFlagsShowDropdown.always;
198
199
  @state()
199
200
  private bedroomPreferenceRequired = false;
201
+ /** The building is on the `webchat_tour_scheduler_v2` rollout. */
202
+ @state()
203
+ private tourSchedulerV2 = false;
200
204
  @state()
201
205
  private brokerIntakeEnabled = false;
202
206
  @state()
@@ -225,6 +229,10 @@ export class MEChat extends LitElement {
225
229
  @state()
226
230
  private myPubnub: MyPubnub | null = null;
227
231
 
232
+ /** For the v2 tour scheduler, which calls the session-authenticated endpoints. */
233
+ private getSessionToken = (): string | null =>
234
+ this.myPubnub?.getSessionToken() ?? null;
235
+
228
236
  @state()
229
237
  private LeadSourceClient: LeadSourceClient | null = null; // DEPRECATED IN FAVOR OF LeadSourceMultitouchClient
230
238
 
@@ -421,6 +429,7 @@ export class MEChat extends LitElement {
421
429
  isAip,
422
430
  bedroomPreferenceRequired,
423
431
  brokerIntakeEnabled,
432
+ tourSchedulerV2,
424
433
  ] = await Promise.all([
425
434
  // Per-building endpoint; org mode has no building to ask about.
426
435
  this.isOrgMode()
@@ -430,6 +439,7 @@ export class MEChat extends LitElement {
430
439
  fetchBuildingAip(this.buildingSlug),
431
440
  fetchTrackedRolloutBedroomPreferenceRequired(this.buildingSlug),
432
441
  fetchTrackedRolloutBrokerIntake(this.buildingSlug),
442
+ fetchTrackedRolloutTourSchedulerV2(this.buildingSlug),
433
443
  ]);
434
444
 
435
445
  if (this.buildingWebchatView) {
@@ -443,6 +453,7 @@ export class MEChat extends LitElement {
443
453
  featureFlagShowDropdown as FeatureFlagsShowDropdown;
444
454
  this.bedroomPreferenceRequired = bedroomPreferenceRequired;
445
455
  this.brokerIntakeEnabled = brokerIntakeEnabled;
456
+ this.tourSchedulerV2 = tourSchedulerV2;
446
457
 
447
458
  // The backend is cached for ~4 hours, so falling back to the existing api request until the cache propagates all the changes
448
459
  // Org-level webchat never offers Text Us, so it needs no number for it.
@@ -1164,6 +1175,8 @@ export class MEChat extends LitElement {
1164
1175
  []}
1165
1176
  .bedroomPreferenceRequired=${this.bedroomPreferenceRequired}
1166
1177
  .brokerIntakeEnabled=${this.brokerIntakeEnabled}
1178
+ .tourSchedulerV2=${this.tourSchedulerV2}
1179
+ .getSessionToken=${this.getSessionToken}
1167
1180
  .launcherStyles=${this.launcherStyles}
1168
1181
  .primaryColor=${this.primaryColor}
1169
1182
  .backgroundColor=${this.backgroundColor}
@@ -155,6 +155,26 @@ export async function fetchTrackedRolloutCoastalCustomTourTypes(
155
155
  }
156
156
  }
157
157
 
158
+ /** Whether the building shows the rebuilt tour scheduler (<tour-scheduler-v2>) instead of today's. */
159
+ export async function fetchTrackedRolloutTourSchedulerV2(
160
+ buildingSlug: string
161
+ ): Promise<boolean> {
162
+ if (!buildingSlug) return false;
163
+ try {
164
+ const response = await axios.get(trackedRolloutEndpoint(buildingSlug), {
165
+ params: {
166
+ rollout_name: "webchat_tour_scheduler_v2",
167
+ default_value: false,
168
+ },
169
+ // Read with the other startup flags; a slow answer means today's scheduler.
170
+ timeout: 3000,
171
+ });
172
+ return response.data === true;
173
+ } catch (_) {
174
+ return false;
175
+ }
176
+ }
177
+
158
178
  /** Whether brokers are on for the building (the broker_rollout rollout), so the email form offers the broker referral fields. */
159
179
  export async function fetchTrackedRolloutBrokerIntake(
160
180
  buildingSlug: string
@@ -0,0 +1,478 @@
1
+ import { expect } from "@esm-bundle/chai";
2
+ import { restore, useFakeXMLHttpRequest } from "sinon/pkg/sinon-esm";
3
+ import "../public/dist/index";
4
+ import type { TourSchedulerV2 } from "./WebComponent/SchedulerV2/tour-scheduler-v2";
5
+ import type { ContactForm } from "./WebComponent/SchedulerV2/contact-form";
6
+ import type { CommunityPicker } from "./WebComponent/SchedulerV2/community-picker";
7
+ import type {
8
+ BookingRequest,
9
+ BookingResponse,
10
+ Community,
11
+ CommunitiesResponse,
12
+ PlanRequest,
13
+ PlanResponse,
14
+ PlanStop,
15
+ TourTypeId,
16
+ } from "./WebComponent/SchedulerV2/tourItineraryApi";
17
+
18
+ declare const afterEach: (callback: () => void) => void;
19
+ declare const it: (name: string, callback: () => Promise<void>) => void;
20
+
21
+ // The v2 scheduler driven through its own UI, with its real API client, against
22
+ // a fake of the three endpoints: checks what it sends to the booking endpoint
23
+ // and what it pushes to the dataLayer. Every request is answered by the fake.
24
+
25
+ type FakeRequest = XMLHttpRequest & {
26
+ url: string;
27
+ requestBody?: string;
28
+ requestHeaders: Record<string, string>;
29
+ respond: (
30
+ status: number,
31
+ headers?: Record<string, string>,
32
+ body?: string
33
+ ) => void;
34
+ error: () => void;
35
+ onSend?: () => void;
36
+ };
37
+
38
+ const header = (request: FakeRequest, name: string): string | undefined =>
39
+ Object.entries(request.requestHeaders).find(
40
+ ([key]) => key.toLowerCase() === name.toLowerCase()
41
+ )?.[1];
42
+
43
+ const DATE = "2026-10-30";
44
+ const ANCHOR = 12;
45
+ const LINDEN = 40;
46
+
47
+ const community = (building_id: number, name: string): Community => ({
48
+ building_id,
49
+ name,
50
+ address: { line1: "1 Main St", city: "Chicago", state: "IL" },
51
+ timezone: "America/Chicago",
52
+ distance_mi: building_id === ANCHOR ? 0 : 1.8,
53
+ price_from: null,
54
+ next_available: { date: DATE, time: "10:00" },
55
+ best_match: false,
56
+ image_url: null,
57
+ tourable: true,
58
+ unavailable_reason: null,
59
+ });
60
+
61
+ const isoMinutes = (iso: string) =>
62
+ parseInt(iso.slice(11, 13), 10) * 60 + parseInt(iso.slice(14, 16), 10);
63
+
64
+ const at = (minutes: number) =>
65
+ `${DATE}T${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(
66
+ minutes % 60
67
+ ).padStart(2, "0")}:00-05:00`;
68
+
69
+ /**
70
+ * A central group of two, chaining 30-minute tours from 10:00, served on the
71
+ * widget's tour endpoints. Records what the scheduler sent.
72
+ */
73
+ const fakeBackend = ({
74
+ tourTypes = ["escorted-tour"],
75
+ dropFirstBooking = false,
76
+ }: {
77
+ /** The tour types the building offers. */
78
+ tourTypes?: TourTypeId[];
79
+ /** Drops the first booking's connection, as a timeout would. */
80
+ dropFirstBooking?: boolean;
81
+ } = {}): {
82
+ bookings: BookingRequest[];
83
+ keys: string[];
84
+ sessionTokens: string[];
85
+ communityQueries: URLSearchParams[];
86
+ plannedTourTypes: TourTypeId[];
87
+ } => {
88
+ const bookings: BookingRequest[] = [];
89
+ const keys: string[] = [];
90
+ const sessionTokens: string[] = [];
91
+ const communityQueries: URLSearchParams[] = [];
92
+ const plannedTourTypes: TourTypeId[] = [];
93
+ let nextEventId = 990;
94
+ let dropped = false;
95
+ const group = (extend: boolean): CommunitiesResponse => ({
96
+ anchor: {
97
+ building_id: ANCHOR,
98
+ name: "Parkside Commons",
99
+ is_general_building: false,
100
+ },
101
+ communities: extend
102
+ ? [community(LINDEN, "The Linden")]
103
+ : [
104
+ community(ANCHOR, "Parkside Commons"),
105
+ community(LINDEN, "The Linden"),
106
+ ],
107
+ });
108
+ const plan = (request: PlanRequest): PlanResponse => {
109
+ const stops: PlanStop[] = [];
110
+ let start = 10 * 60;
111
+ if (request.fixed_first) {
112
+ stops.push({
113
+ building_id: ANCHOR,
114
+ start: at(start),
115
+ end: at(start + 30),
116
+ timezone: "America/Chicago",
117
+ distance_from_prev_mi: null,
118
+ alternatives: [],
119
+ fixed: true,
120
+ });
121
+ start += 30;
122
+ }
123
+ request.building_ids.forEach((building_id) => {
124
+ stops.push({
125
+ building_id,
126
+ start: at(start),
127
+ end: at(start + 30),
128
+ timezone: "America/Chicago",
129
+ distance_from_prev_mi: stops.length > 0 ? 1.8 : null,
130
+ alternatives: [at(start + 15)],
131
+ fixed: false,
132
+ });
133
+ start += 30;
134
+ });
135
+ // As /plan does: dates and times only for a tour type the building offers.
136
+ const offered = tourTypes.includes(request.tour_type);
137
+ return {
138
+ bookable_dates: offered ? [DATE] : [],
139
+ tour_types: tourTypes,
140
+ stops: offered ? stops : [],
141
+ changed: [],
142
+ unchainable: [],
143
+ };
144
+ };
145
+ const book = (request: BookingRequest): BookingResponse => {
146
+ return {
147
+ itinerary_id: request.stops.length > 1 ? "itinerary" : null,
148
+ stops: request.stops.map((stop) =>
149
+ "existing_calendar_event_id" in stop
150
+ ? {
151
+ building_id: ANCHOR,
152
+ calendar_event_id: stop.existing_calendar_event_id,
153
+ start: at(600),
154
+ end: at(630),
155
+ status: "existing" as const,
156
+ error: null,
157
+ }
158
+ : {
159
+ building_id: stop.building_id,
160
+ calendar_event_id: nextEventId++,
161
+ start: stop.start,
162
+ end: at(isoMinutes(stop.start) + 30),
163
+ status: "booked" as const,
164
+ error: null,
165
+ }
166
+ ),
167
+ };
168
+ };
169
+
170
+ const fakeXhr = useFakeXMLHttpRequest();
171
+ fakeXhr.onCreate = (request: FakeRequest) => {
172
+ request.onSend = () =>
173
+ setTimeout(() => {
174
+ const json = (status: number, data: unknown) =>
175
+ request.respond(
176
+ status,
177
+ { "Content-Type": "application/json" },
178
+ JSON.stringify(data)
179
+ );
180
+ const { pathname, searchParams } = new URL(request.url);
181
+ const body = request.requestBody
182
+ ? JSON.parse(request.requestBody)
183
+ : null;
184
+ if (!pathname.startsWith("/platformApi/webchat/tour-")) {
185
+ return json(200, null);
186
+ }
187
+ sessionTokens.push(header(request, "X-Session-Token") ?? "");
188
+ if (pathname === "/platformApi/webchat/tour-communities") {
189
+ communityQueries.push(searchParams);
190
+ return json(200, group(searchParams.has("available_after")));
191
+ }
192
+ if (pathname === "/platformApi/webchat/tour-itineraries/plan") {
193
+ plannedTourTypes.push(body.tour_type);
194
+ return json(200, plan(body));
195
+ }
196
+ if (pathname === "/platformApi/webchat/tour-itineraries") {
197
+ keys.push(header(request, "Idempotency-Key") ?? "");
198
+ if (dropFirstBooking && !dropped) {
199
+ dropped = true;
200
+ return request.error();
201
+ }
202
+ bookings.push(body);
203
+ return json(200, book(body));
204
+ }
205
+ return json(404, null);
206
+ }, 0);
207
+ };
208
+ return { bookings, keys, sessionTokens, communityQueries, plannedTourTypes };
209
+ };
210
+
211
+ const waitFor = async <T>(
212
+ find: () => T | null | undefined | false
213
+ ): Promise<T> => {
214
+ for (let i = 0; i < 300; i++) {
215
+ const found = find();
216
+ if (found) return found;
217
+ await new Promise((resolve) => setTimeout(resolve, 10));
218
+ }
219
+ throw new Error("Timed out waiting for the scheduler");
220
+ };
221
+
222
+ const mount = (): TourSchedulerV2 => {
223
+ const scheduler = document.createElement(
224
+ "tour-scheduler-v2"
225
+ ) as TourSchedulerV2;
226
+ Object.assign(scheduler, {
227
+ getSessionToken: () => "session-from-init",
228
+ orgSlug: "test-org",
229
+ buildingSlug: "parkside-commons",
230
+ buildingId: ANCHOR,
231
+ buildingName: "Parkside Commons",
232
+ currentLeadSource: "google",
233
+ leadSourceClient: {
234
+ chatId: "webchat_lead_test",
235
+ checkAndHandleForLogLeadSource: () => Promise.resolve(),
236
+ resetLeadSource: () => true,
237
+ },
238
+ leadSourceMultitouchClient: {
239
+ getSafeLeadSourceTouchpointsWithDefault: () => [
240
+ {
241
+ timestampInitiallyLogged: "2026-10-29T10:00:00Z",
242
+ leadSourceValue: "google",
243
+ type: "touchpoint",
244
+ },
245
+ ],
246
+ resetLeadSourceTouchpoints: () => undefined,
247
+ },
248
+ });
249
+ document.body.appendChild(scheduler);
250
+ return scheduler;
251
+ };
252
+
253
+ const inScheduler = <T extends Element>(
254
+ scheduler: TourSchedulerV2,
255
+ selector: string
256
+ ): T | null => scheduler.shadowRoot?.querySelector<T>(selector) ?? null;
257
+
258
+ const clickButton = (button: Element | null | undefined) =>
259
+ button?.shadowRoot?.querySelector<HTMLButtonElement>("button")?.click();
260
+
261
+ const fillContactAndSubmit = async (scheduler: TourSchedulerV2) => {
262
+ const form = await waitFor(() =>
263
+ inScheduler<ContactForm>(scheduler, "contact-form")
264
+ );
265
+ form.dispatchEvent(
266
+ new CustomEvent("contact-change", {
267
+ detail: {
268
+ values: {
269
+ ...form.values,
270
+ firstName: "Jane",
271
+ lastName: "Doe",
272
+ email: "jane@example.com",
273
+ phone: "(312) 555-0142",
274
+ phoneE164: "+13125550142",
275
+ layout: 10,
276
+ },
277
+ },
278
+ bubbles: true,
279
+ composed: true,
280
+ })
281
+ );
282
+ const submit = await waitFor(() => {
283
+ const button = inScheduler<HTMLElement & { disabled: boolean }>(
284
+ scheduler,
285
+ "#schedule-bttn"
286
+ );
287
+ return button && !button.disabled ? button : null;
288
+ });
289
+ clickButton(submit);
290
+ };
291
+
292
+ afterEach(() => {
293
+ restore();
294
+ document.querySelectorAll("tour-scheduler-v2").forEach((el) => el.remove());
295
+ window.dataLayer = [];
296
+ });
297
+
298
+ it("books a tour with the prospect's details, attribution and conversation, and keeps them out of the dataLayer", async () => {
299
+ window.dataLayer = [];
300
+ const { bookings, keys, sessionTokens } = fakeBackend();
301
+ const scheduler = mount();
302
+
303
+ await fillContactAndSubmit(scheduler);
304
+ await waitFor(() => inScheduler(scheduler, "booking-confirmation"));
305
+
306
+ expect(bookings).to.have.length(1);
307
+ const [booking] = bookings;
308
+ expect(booking.stops).to.deep.equal([
309
+ { building_id: ANCHOR, start: at(600) },
310
+ ]);
311
+ expect(booking.contact).to.deep.equal({
312
+ first_name: "Jane",
313
+ last_name: "Doe",
314
+ email: "jane@example.com",
315
+ phone_e164: "+13125550142",
316
+ bedrooms: [1],
317
+ move_in: null,
318
+ notes: "",
319
+ });
320
+ expect(booking.conversation_tracking_id).to.equal("webchat_lead_test");
321
+ expect(booking.cancel_existing_tours).to.equal(false);
322
+ expect(booking.lead_sources.lead_sources).to.deep.equal([
323
+ "google",
324
+ "property-website",
325
+ ]);
326
+ expect(booking.lead_sources.lead_sources_with_timestamps).to.deep.equal([
327
+ {
328
+ timestamp_initially_logged: "2026-10-29T10:00:00Z",
329
+ lead_source_value: "google",
330
+ type: "touchpoint",
331
+ },
332
+ ]);
333
+ expect(keys[0]).to.match(/^[0-9a-f-]{36}$/);
334
+ expect(sessionTokens).to.not.be.empty;
335
+ expect(new Set(sessionTokens)).to.deep.equal(new Set(["session-from-init"]));
336
+
337
+ const pushed = JSON.stringify(window.dataLayer);
338
+ expect(pushed).to.contain("scheduleTourSubmitted");
339
+ for (const pii of [
340
+ "Jane",
341
+ "Doe",
342
+ "jane@example.com",
343
+ "3125550142",
344
+ "webchat_lead_test",
345
+ ]) {
346
+ expect(pushed, `dataLayer leaks ${pii}`).not.to.contain(pii);
347
+ }
348
+ });
349
+
350
+ it("extends a booking by sending the booked tour as an existing stop and only the new community as a new one", async () => {
351
+ const { bookings, communityQueries } = fakeBackend();
352
+ const scheduler = mount();
353
+
354
+ await fillContactAndSubmit(scheduler);
355
+ const picker = await waitFor(() =>
356
+ inScheduler<CommunityPicker>(
357
+ scheduler,
358
+ "booking-confirmation community-picker"
359
+ )
360
+ );
361
+ await picker.updateComplete;
362
+ picker.shadowRoot
363
+ ?.querySelector<HTMLButtonElement>("button.floorplan-image-card")
364
+ ?.click();
365
+ clickButton(await waitFor(() => inScheduler(scheduler, "#continue-bttn")));
366
+
367
+ await waitFor(
368
+ () => bookings.length === 1 && inScheduler(scheduler, "itinerary-editor")
369
+ );
370
+ await fillContactAndSubmit(scheduler);
371
+ await waitFor(() => bookings.length === 2);
372
+
373
+ expect(bookings[1].stops).to.deep.equal([
374
+ { existing_calendar_event_id: 990 },
375
+ { building_id: LINDEN, start: at(630) },
376
+ ]);
377
+ expect(bookings[1].tour_type).to.equal(bookings[0].tour_type);
378
+ // The extension was offered from what the first booking returned.
379
+ const extend = communityQueries.find((q) => q.has("available_after"));
380
+ expect({
381
+ available_after: extend?.get("available_after"),
382
+ tour_type: extend?.get("tour_type"),
383
+ near_building_id: extend?.get("near_building_id"),
384
+ exclude_building_ids: extend?.getAll("exclude_building_ids"),
385
+ }).to.deep.equal({
386
+ available_after: at(630),
387
+ tour_type: "escorted-tour",
388
+ near_building_id: String(ANCHOR),
389
+ exclude_building_ids: [String(ANCHOR)],
390
+ });
391
+ });
392
+
393
+ it("keeps the prospect's picks when they filter after picking", async () => {
394
+ fakeBackend();
395
+ const scheduler = mount();
396
+
397
+ const editor = await waitFor(() =>
398
+ inScheduler<HTMLElement>(scheduler, "itinerary-editor")
399
+ );
400
+ editor.dispatchEvent(
401
+ new CustomEvent("edit-communities", { bubbles: true, composed: true })
402
+ );
403
+ const picker = await waitFor(() =>
404
+ inScheduler<CommunityPicker>(scheduler, "community-picker")
405
+ );
406
+ await picker.updateComplete;
407
+ const cards = () =>
408
+ Array.from(
409
+ picker.shadowRoot?.querySelectorAll<HTMLButtonElement>(
410
+ "button.floorplan-image-card"
411
+ ) ?? []
412
+ );
413
+ cards()
414
+ .find((card) => card.textContent?.includes("The Linden"))
415
+ ?.click();
416
+ await picker.updateComplete;
417
+
418
+ Array.from(
419
+ picker.shadowRoot?.querySelectorAll<HTMLButtonElement>(
420
+ "#picker-filters .floor-plan-badge"
421
+ ) ?? []
422
+ )
423
+ .find((badge) => badge.textContent?.trim() === "1 bd")
424
+ ?.click();
425
+ // The filter reloads the list, and the scheduler renders again.
426
+ await new Promise((resolve) => setTimeout(resolve, 100));
427
+ await picker.updateComplete;
428
+
429
+ await scheduler.updateComplete;
430
+ const picked = Array.from(
431
+ scheduler.shadowRoot?.querySelectorAll(".tray .floor-plan-badge") ?? []
432
+ ).map((chip) => chip.textContent?.trim());
433
+ expect(picked).to.deep.equal(["Parkside Commons", "The Linden"]);
434
+ });
435
+
436
+ it("retries a failed booking with the same idempotency key, though attribution is stamped anew", async () => {
437
+ const { bookings, keys } = fakeBackend({ dropFirstBooking: true });
438
+ const scheduler = mount();
439
+ // As LeadSourceMultitouchClient does for a picked lead source: each call stamps now.
440
+ let calls = 0;
441
+ scheduler.leadSourceMultitouchClient = {
442
+ getSafeLeadSourceTouchpointsWithDefault: () => [
443
+ {
444
+ timestampInitiallyLogged: `2026-10-29T10:00:0${calls++}Z`,
445
+ leadSourceValue: "google",
446
+ type: "user-selected",
447
+ },
448
+ ],
449
+ resetLeadSourceTouchpoints: () => true,
450
+ } as unknown as TourSchedulerV2["leadSourceMultitouchClient"];
451
+
452
+ await fillContactAndSubmit(scheduler);
453
+ await waitFor(() => keys.length === 1 && !bookings.length);
454
+ await fillContactAndSubmit(scheduler);
455
+ await waitFor(() => inScheduler(scheduler, "booking-confirmation"));
456
+
457
+ expect(bookings).to.have.length(1);
458
+ expect(keys).to.have.length(2);
459
+ expect(keys[1]).to.equal(keys[0]);
460
+ expect(calls).to.equal(2);
461
+ });
462
+
463
+ it("moves to the server's first tour type when escorted tours aren't offered", async () => {
464
+ // A building that only offers self-guided tours.
465
+ const { bookings, plannedTourTypes } = fakeBackend({
466
+ tourTypes: ["self-guided-tour"],
467
+ });
468
+ const scheduler = mount();
469
+
470
+ await fillContactAndSubmit(scheduler);
471
+ await waitFor(() => bookings.length === 1);
472
+
473
+ expect(plannedTourTypes.slice(0, 2)).to.deep.equal([
474
+ "escorted-tour",
475
+ "self-guided-tour",
476
+ ]);
477
+ expect(bookings[0].tour_type).to.equal("self-guided-tour");
478
+ });