feat: Headless router - queue recording booking response (#21805)

* Add queued booking response table

* Create `RoutingFormResponseRepository`

* Pass `queueFormResponse` param

* Queue up form response if param is passed

* Forward queued form response parma to booker

* Pass `queuedFormResponse` from booker to `handleNewBooking`

* Write queued routing form response

* Type fixes

* Clean up

* Allow dry run to work which wont have any QueuedFormResponse or FormResponse

* Support passing the time when the modal was actually shown to the user and consider that time as the time of form submission

* fix ts error

* Queue -> Response through separate endpoint that would be triggered by
embed

* Make queueResponseId a non-guessable uid

* Change queueFormResponse query param

* fix ts error

* Support useQueuedResponse to record new response data

* revert handleNewBooking

* Remove dead code formResponse

* Refactor use repository

* Unify migration files

* refactor: moved api endpoint to app dir

Signed-off-by: Omar López <[email protected]>

* Update formResponse.ts

* Refactor use-queued-response for test

* Add tests

* Fix ts error and unit test. recordFormResponse cant return nullish response

* fix schema

* feat: Support full reuse of preloaded iframe (#21803)

* feat: support updating cal video settings in API v2 (#21784)

* feat: support updating cal video settings in API v2

* chore: update descriptio

* feat: support create event type

* test: add test for updating event type

* test: add test for create event type

* chore: undo openapi

* chore: bump libraries

* Revert "chore: bump libraries"

This reverts commit bdf36d09b021fc531497a7b7ea66ab9c52b7d136.

* chore: bump libraries

---------

Co-authored-by: Lauris Skraucis <[email protected]>
Co-authored-by: supalarry <[email protected]>

* fix tests and ts

* Fix tests

* wip-useQueuedResponseEndpoint

* Add one more test

* Change queueFormResponse query param

* wip

* Support useQueuedResponse to record new response data

* Use the update useQueuedResponse endpoint

* self-review addressed

* Use queuedResponse if available in slots/utils

* Add documentation

* Remove use-queued-response from critical-path

---------

Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Lauris Skraucis <[email protected]>
Co-authored-by: supalarry <[email protected]>

* Update schema.prisma

* refactor: renamed to avoid react hooks confusion

Signed-off-by: Omar López <[email protected]>

---------

Signed-off-by: Omar López <[email protected]>
Co-authored-by: Hariom Balhara <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Lauris Skraucis <[email protected]>
Co-authored-by: supalarry <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2025-06-17 12:11:49 -03:00
1 parent 9a40e54159
commit 22f136d19b
28 files changed
+1408 -424

No files matched your search

@@ -0,0 +1,118 @@
import type {
EmbedThemeConfig,
UiConfig,
EmbedNonStylesConfig,
EmbedStyles,
SetStyles,
setNonStylesConfig,
} from "../../types";
import { isParamValuePresentInUrlSearchParams } from "../../utils";
import { runAsap } from "./utils";
export const enum EMBED_IFRAME_STATE {
NOT_INITIALIZED,
INITIALIZED,
}
/**
* This is in-memory persistence needed so that when user browses through the embed, the configurations from the instructions aren't lost.
*/
export const embedStore = {
connectVersion: 0 as number,
/**
* Tracks whether the iframe is fully rendered or in progress of rendering.
* In case of prerendering as well as non-prerendering, it would be "completed" after the iframe is fully rendered.
*/
renderState: null as null | "inProgress" | "completed",
// Handles the commands of routing received from parent even when React hasn't initialized and nextRouter isn't available
router: {
/**
* When we do the history push, it is possible that
* - React might revert that change depending on in what state React is in while initializing
* - So, we use a declarative approach to ensure that our requirement is continuously met
*/
ensureQueryParamsInUrl({
toBeThereParams,
toRemoveParams,
}: {
toBeThereParams: Record<string, string | string[]>;
toRemoveParams: string[];
}) {
let stopUpdating = false;
function updateIfNeeded() {
if (stopUpdating) {
return { hasChanged: false };
}
const currentUrl = new URL(document.URL);
let hasChanged = false;
// Ensuring toBeThereSearchParams
for (const [key, newValue] of Object.entries(toBeThereParams)) {
// It checks that the value must be present and if an array no other item should be there except those in newValue
hasChanged = !isParamValuePresentInUrlSearchParams({
param: key,
value: newValue,
container: currentUrl.searchParams,
});
if (hasChanged) {
setParamInUrl({ key, value: newValue, url: currentUrl });
}
}
removeParamsFromUrl({ keys: toRemoveParams, url: currentUrl });
hasChanged = hasChanged || toRemoveParams.length > 0;
if (hasChanged) {
// Avoid unnecessary history push
window.history.replaceState({}, "", currentUrl.toString());
}
runAsap(updateIfNeeded);
return {
hasChanged,
};
}
const { hasChanged } = updateIfNeeded();
return {
stopEnsuringQueryParamsInUrl: () => {
stopUpdating = true;
},
hasChanged,
};
function removeParamsFromUrl({ keys, url }: { keys: string[]; url: URL }) {
for (const key of keys) {
url.searchParams.delete(key);
}
}
function setParamInUrl({ key, value, url }: { key: string; value: string | string[]; url: URL }) {
// Reset and then set the new value, to ensure nothing else remains in value
url.searchParams.delete(key);
const newValueArray = Array.isArray(value) ? value : [value];
newValueArray.forEach((val) => {
url.searchParams.append(key, val);
});
}
},
},
state: EMBED_IFRAME_STATE.NOT_INITIALIZED,
// Store all embed styles here so that as and when new elements are mounted, styles can be applied to it.
styles: {} as EmbedStyles | undefined,
nonStyles: {} as EmbedNonStylesConfig | undefined,
namespace: null as string | null,
embedType: undefined as undefined | null | string,
// Store all React State setters here.
reactStylesStateSetters: {} as Record<keyof EmbedStyles, SetStyles>,
reactNonStylesStateSetters: {} as Record<keyof EmbedNonStylesConfig, setNonStylesConfig>,
// Embed can show itself only after this is set to true
parentInformedAboutContentHeight: false,
windowLoadEventFired: false,
setTheme: undefined as ((arg0: EmbedThemeConfig) => void) | undefined,
theme: undefined as UiConfig["theme"],
uiConfig: undefined as Omit<UiConfig, "styles" | "theme"> | undefined,
/**
* We maintain a list of all setUiConfig setters that are in use at the moment so that we can update all those components.
*/
setUiConfig: [] as ((arg0: UiConfig) => void)[],
};
@@ -0,0 +1,58 @@
export function runAsap(fn: (...arg: unknown[]) => void) {
// We don't use rAF because it runs slower in Safari plus doesn't run if the iframe is hidden sometimes
return setTimeout(fn, 50);
}
export function isBookerPage() {
return !!window._embedBookerState;
}
export function isBookerReady() {
return window._embedBookerState === "slotsDone";
}
/**
* It is important to be able to check realtime(instead of storing isLinkReady as a variable) if the link is ready, because there is a possibility that booker might have moved to non-ready state from ready state
*/
export function isLinkReady({ embedStore }: { embedStore: typeof import("./embedStore").embedStore }) {
if (!embedStore.parentInformedAboutContentHeight) {
return false;
}
if (isBookerPage()) {
// Let's wait for Booker to be ready before showing the embed
// It means that booker has loaded all its data and is ready to show
// TODO: We could try to mark the embed as ready earlier in this case not relying on document.readyState
return isBookerReady();
}
return true;
}
/**
* Moves the queuedFormResponse to the routingFormResponse record to mark it as an actual response now.
*/
export const recordResponseIfQueued = async (params: Record<string, string | string[]>) => {
const url = new URL(document.URL);
let routingFormResponseId: number | null = null;
const queuedFormResponseIdParam = url.searchParams.get("cal.queuedFormResponseId");
const queuedFormResponseId = queuedFormResponseIdParam;
if (!queuedFormResponseId) {
return null;
}
// form is formId and isn't acutal Form data
const { form: _1, ...actualFormData } = params;
const res = await fetch(`/api/routing-forms/queued-response`, {
method: "POST",
body: JSON.stringify({ queuedFormResponseId, params: actualFormData }),
});
if (!res.ok) {
return null;
}
const response = await res.json();
const formResponseId = response.data.formResponseId;
if (formResponseId) {
// Now we have the actual routingFormResponseId.
routingFormResponseId = formResponseId;
}
return routingFormResponseId;
};