fix: Preview queue position and contact owner in preview (#17552)
* wip * Add preview mode in router * only fetch bookings of this month for weighted rr * test set up * only get bookings of current month * reverts test setup * first changes for weight adjustments * reset booking count + adjust calibration * depreciate weightAdjustment * get only bookings created this month * fix typo * make sure createdAt for hosts is correct * use earliest possibel date as fallback * add missing createdAt date to tests * fix typo * clean up changes in tests * fix typo * change end date to current date * fix: Fall back to empty host array when no hosts are found * fix: Restructure code a little * fixed test, incorrectly used now outdated var * perf: remove Dayjs from getLuckyUser * Refactor getHostsWithCalibration for optimised performance, intentionally break test as findMany is always an array * Better mock for host.findMany * Remove team-event-types.test.ts, move to appropriate package * TypeScript cannot auto-infer that an array is non-empty when assigning to a var * fix: Type Fixes and DistributionMethod enum add * Optimise tests * Added test to show that bookings made before a newHost was added affect the lucky user result * Throw error when the usersWithHighestPriority is empty, which should never happen * WIP * remove comment * update migrations * get attributes weights and virtual queue data * use attribute weights and use bookings of virtual queue only * clean up migrations * Add shortfall column and add tests * code clean up from feedback * wrapper function for getLuckyUser * code clean up * fetch routingFormResponse in handleNewBooking * fix type errors * fix type errors in tests * fix getAttributesQueryValue import for tests * fix totalWeight * add test for attributes weights and virtual queues * clean up code * add test for prepareQueuesAndAttributesData * remove console.log * use lazy import * Add more tests and more columns to matching members queue * fix issue from merge * always send usersAndTheirBookingShortfalls --------- Co-authored-by: CarinaWolli <[email protected]> Co-authored-by: Alex van Andel <[email protected]>
This commit is contained in:
28 files changed
+2109
-871
No files matched your search
@@ -2,6 +2,7 @@ import type { Prisma } from "@prisma/client";
|
||||
import type { z } from "zod";
|
||||
|
||||
import CrmManager from "@calcom/core/crmManager/crmManager";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { EventTypeAppMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
@@ -11,14 +12,15 @@ export async function getCRMContactOwnerForRRLeadSkip(
|
||||
eventTypeMetadata: Prisma.JsonValue
|
||||
): Promise<string | undefined> {
|
||||
const parsedEventTypeMetadata = EventTypeMetaDataSchema.safeParse(eventTypeMetadata);
|
||||
|
||||
if (!parsedEventTypeMetadata.success || !parsedEventTypeMetadata.data?.apps) return;
|
||||
|
||||
const crm = await getCRMManagerWithRRLeadSkip(parsedEventTypeMetadata.data.apps);
|
||||
|
||||
if (!crm) return;
|
||||
|
||||
const startTime = performance.now();
|
||||
const contact = await crm.getContacts({ emails: bookerEmail, forRoundRobinSkip: true });
|
||||
const endTime = performance.now();
|
||||
logger.info(`Fetching from CRM took ${endTime - startTime}ms`);
|
||||
if (!contact?.length) return;
|
||||
return contact[0].ownerEmail;
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ vi.mock("@calcom/lib/hooks/useLocale", () => ({
|
||||
}));
|
||||
|
||||
let findTeamMembersMatchingAttributeLogicResponse: {
|
||||
result: { email: string }[] | null;
|
||||
result: { users: { email: string }[] } | null;
|
||||
checkedFallback: boolean;
|
||||
mainWarnings?: string[] | null;
|
||||
fallbackWarnings?: string[] | null;
|
||||
@@ -97,7 +97,7 @@ function mockFindTeamMembersMatchingAttributeLogicResponse(
|
||||
vi.mock("@calcom/trpc/react", () => ({
|
||||
trpc: {
|
||||
viewer: {
|
||||
appRoutingForms: {
|
||||
routingForms: {
|
||||
findTeamMembersMatchingAttributeLogic: {
|
||||
useMutation: vi.fn(({ onSuccess }) => {
|
||||
return {
|
||||
@@ -210,7 +210,9 @@ describe("TestFormDialog", () => {
|
||||
it("suggests to add fallback when matching members is empty and fallback is not checked", async () => {
|
||||
mockEventTypeRedirectUrlMatchingRoute();
|
||||
mockFindTeamMembersMatchingAttributeLogicResponse({
|
||||
result: [],
|
||||
result: {
|
||||
users: [],
|
||||
},
|
||||
checkedFallback: false,
|
||||
});
|
||||
render(<TestFormDialog form={mockTeamForm} isTestPreviewOpen={true} setIsTestPreviewOpen={() => {}} />);
|
||||
@@ -264,7 +266,9 @@ describe("TestFormDialog", () => {
|
||||
it("should show No in main and fallback matched", async () => {
|
||||
mockEventTypeRedirectUrlMatchingRoute();
|
||||
mockFindTeamMembersMatchingAttributeLogicResponse({
|
||||
result: [],
|
||||
result: {
|
||||
users: [],
|
||||
},
|
||||
checkedFallback: true,
|
||||
mainWarnings: null,
|
||||
fallbackWarnings: null,
|
||||
|
||||
@@ -237,7 +237,16 @@ type SingleFormComponentProps = {
|
||||
};
|
||||
|
||||
type MembersMatchResultType = {
|
||||
isUsingAttributeWeights: boolean;
|
||||
eventTypeRedirectUrl: string | null;
|
||||
contactOwnerEmail: string | null;
|
||||
teamMembersMatchingAttributeLogic: { id: number; name: string | null; email: string }[] | null;
|
||||
perUserData: {
|
||||
bookingsCount: Record<number, number>;
|
||||
bookingShortfalls: Record<number, number> | null;
|
||||
calibrations: Record<number, number> | null;
|
||||
weights: Record<number, number> | null;
|
||||
} | null;
|
||||
checkedFallback: boolean;
|
||||
mainWarnings: string[] | null;
|
||||
fallbackWarnings: string[] | null;
|
||||
@@ -273,7 +282,7 @@ const TeamMembersMatchResult = ({
|
||||
return !membersMatchResult.checkedFallback ? t("yes") : t("no");
|
||||
};
|
||||
|
||||
const renderMatchingMembers = () => {
|
||||
const renderQueue = () => {
|
||||
if (isNoLogicFound(membersMatchResult.teamMembersMatchingAttributeLogic)) {
|
||||
if (membersMatchResult.checkedFallback) {
|
||||
return (
|
||||
@@ -291,12 +300,48 @@ const TeamMembersMatchResult = ({
|
||||
);
|
||||
}
|
||||
|
||||
const matchingMembers = membersMatchResult.teamMembersMatchingAttributeLogic.map(
|
||||
(member) => member.email
|
||||
);
|
||||
const matchingMembers = membersMatchResult.teamMembersMatchingAttributeLogic;
|
||||
|
||||
if (matchingMembers.length) {
|
||||
return <span className="font-semibold">{matchingMembers.join(", ")}</span>;
|
||||
if (matchingMembers.length && membersMatchResult.perUserData) {
|
||||
const perUserData = membersMatchResult.perUserData;
|
||||
return (
|
||||
<span className="font-semibold">
|
||||
<div className="mt-2 overflow-x-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr className="border-b text-left">
|
||||
<th className="py-2 pr-4">#</th>
|
||||
<th className="py-2 pr-4">Email</th>
|
||||
<th className="py-2 pr-4">Bookings</th>
|
||||
{membersMatchResult.perUserData.weights ? <th className="py-2">Weight</th> : null}
|
||||
{membersMatchResult.perUserData.calibrations ? <th className="py-2">Calibration</th> : null}
|
||||
{membersMatchResult.perUserData.bookingShortfalls ? (
|
||||
<th className="border-l py-2 pl-2">Shortfall</th>
|
||||
) : null}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{matchingMembers.map((member, index) => (
|
||||
<tr key={member.id} className="border-b">
|
||||
<td className="py-2 pr-4">{index + 1}</td>
|
||||
<td className="py-2 pr-4">{member.email}</td>
|
||||
<td className="py-2">{perUserData.bookingsCount[member.id] ?? 0}</td>
|
||||
{perUserData.weights ? (
|
||||
<td className="py-2">{perUserData.weights[member.id] ?? 0}</td>
|
||||
) : null}
|
||||
{perUserData.calibrations ? (
|
||||
<td className="py-2">{perUserData.calibrations[member.id] ?? 0}</td>
|
||||
) : null}
|
||||
{perUserData.bookingShortfalls ? (
|
||||
<td className="border-l py-2 pl-2">{perUserData.bookingShortfalls[member.id] ?? 0}</td>
|
||||
) : null}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -328,8 +373,23 @@ const TeamMembersMatchResult = ({
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div data-testid="matching-members">
|
||||
{t("matching_members")}: {renderMatchingMembers()}
|
||||
<div className="mt-4">
|
||||
{membersMatchResult.contactOwnerEmail ? (
|
||||
<div data-testid="contact-owner-email">
|
||||
{t("contact_owner")}:{" "}
|
||||
<span className="font-semibold">{membersMatchResult.contactOwnerEmail}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div data-testid="contact-owner-email">
|
||||
{t("contact_owner")}: <span className="font-semibold">Not found</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2" data-testid="matching-members">
|
||||
{membersMatchResult.isUsingAttributeWeights
|
||||
? t("matching_members_queue_using_attribute_weights")
|
||||
: t("matching_members_queue_using_event_assignee_weights")}
|
||||
{renderQueue()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -362,7 +422,7 @@ export const TestFormDialog = ({
|
||||
const { t } = useLocale();
|
||||
const [response, setResponse] = useState<FormResponse>({});
|
||||
const [chosenRoute, setChosenRoute] = useState<NonRouterRoute | null>(null);
|
||||
const [eventTypeUrl, setEventTypeUrl] = useState("");
|
||||
const [eventTypeUrlWithoutParams, setEventTypeUrlWithoutParams] = useState("");
|
||||
const searchParams = useCompatSearchParams();
|
||||
const isTeamForm = !!form.teamId;
|
||||
const [membersMatchResult, setMembersMatchResult] = useState<MembersMatchResultType | null>(null);
|
||||
@@ -371,10 +431,14 @@ export const TestFormDialog = ({
|
||||
setMembersMatchResult(null);
|
||||
};
|
||||
const findTeamMembersMatchingAttributeLogicMutation =
|
||||
trpc.viewer.appRoutingForms.findTeamMembersMatchingAttributeLogic.useMutation({
|
||||
trpc.viewer.routingForms.findTeamMembersMatchingAttributeLogic.useMutation({
|
||||
onSuccess(data) {
|
||||
setMembersMatchResult({
|
||||
teamMembersMatchingAttributeLogic: data.result,
|
||||
isUsingAttributeWeights: data.isUsingAttributeWeights,
|
||||
eventTypeRedirectUrl: data.eventTypeRedirectUrl,
|
||||
contactOwnerEmail: data.contactOwnerEmail,
|
||||
teamMembersMatchingAttributeLogic: data.result ? data.result.users : data.result,
|
||||
perUserData: data.result ? data.result.perUserData : null,
|
||||
checkedFallback: data.checkedFallback,
|
||||
mainWarnings: data.mainWarnings,
|
||||
fallbackWarnings: data.fallbackWarnings,
|
||||
@@ -391,27 +455,30 @@ export const TestFormDialog = ({
|
||||
|
||||
function testRouting() {
|
||||
const route = findMatchingRoute({ form, response });
|
||||
let eventTypeRedirectUrl: string | null = null;
|
||||
|
||||
if (route?.action?.type === "eventTypeRedirectUrl") {
|
||||
setEventTypeUrl(
|
||||
getAbsoluteEventTypeRedirectUrl({
|
||||
eventTypeRedirectUrl: route.action.value,
|
||||
form,
|
||||
allURLSearchParams: new URLSearchParams(),
|
||||
})
|
||||
);
|
||||
eventTypeRedirectUrl = getAbsoluteEventTypeRedirectUrl({
|
||||
eventTypeRedirectUrl: route.action.value,
|
||||
form,
|
||||
allURLSearchParams: new URLSearchParams(),
|
||||
});
|
||||
setEventTypeUrlWithoutParams(eventTypeRedirectUrl);
|
||||
}
|
||||
|
||||
setChosenRoute(route || null);
|
||||
|
||||
if (!route) return;
|
||||
|
||||
findTeamMembersMatchingAttributeLogicMutation.mutate({
|
||||
formId: form.id,
|
||||
response,
|
||||
route,
|
||||
isPreview: true,
|
||||
_enablePerf: searchParams.get("enablePerf") === "true",
|
||||
});
|
||||
if (isTeamForm) {
|
||||
findTeamMembersMatchingAttributeLogicMutation.mutate({
|
||||
formId: form.id,
|
||||
response,
|
||||
route,
|
||||
isPreview: true,
|
||||
_enablePerf: searchParams.get("enablePerf") === "true",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const renderTestResult = () => {
|
||||
@@ -461,7 +528,14 @@ export const TestFormDialog = ({
|
||||
) : (
|
||||
<div className="flex flex-col space-y-2">
|
||||
<span className="text-default underline">
|
||||
<a target="_blank" href={eventTypeUrl} rel="noreferrer" data-testid="test-routing-result">
|
||||
<a
|
||||
target="_blank"
|
||||
className={cn(
|
||||
findTeamMembersMatchingAttributeLogicMutation.isPending && "pointer-events-none"
|
||||
)}
|
||||
href={membersMatchResult?.eventTypeRedirectUrl ?? eventTypeUrlWithoutParams}
|
||||
rel="noreferrer"
|
||||
data-testid="test-routing-result">
|
||||
{chosenRoute.action.value}
|
||||
</a>
|
||||
</span>
|
||||
@@ -486,7 +560,7 @@ export const TestFormDialog = ({
|
||||
|
||||
return (
|
||||
<Dialog open={isTestPreviewOpen} onOpenChange={setIsTestPreviewOpen}>
|
||||
<DialogContent enableOverflow>
|
||||
<DialogContent size="md" enableOverflow>
|
||||
<DialogHeader title={t("test_routing_form")} subtitle={t("test_preview_description")} />
|
||||
<div>
|
||||
<form
|
||||
@@ -554,7 +628,6 @@ function SingleForm({ form, appUrl, Page, enrichedWithUserProfileForm }: SingleF
|
||||
|
||||
const sendUpdatesTo = hookForm.watch("settings.sendUpdatesTo", []) as number[];
|
||||
const sendToAll = hookForm.watch("settings.sendToAll", false) as boolean;
|
||||
|
||||
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
|
||||
onSuccess() {
|
||||
showToast(t("form_updated_successfully"), "success");
|
||||
|
||||
@@ -20,7 +20,7 @@ type GetUrlSearchParamsToForwardOptions = {
|
||||
"id" | "type" | "options" | "identifier" | "label"
|
||||
>[];
|
||||
searchParams: URLSearchParams;
|
||||
formResponseId: number;
|
||||
formResponseId: number | null;
|
||||
teamMembersMatchingAttributeLogic: number[] | null;
|
||||
attributeRoutingConfig: AttributeRoutingConfig | null;
|
||||
reroutingFormResponses?: FormResponseValueOnly;
|
||||
@@ -152,3 +152,26 @@ export function getUrlSearchParamsToForwardForReroute({
|
||||
reroutingFormResponses,
|
||||
});
|
||||
}
|
||||
|
||||
export function getUrlSearchParamsToForwardForTestPreview({
|
||||
formResponse,
|
||||
fields,
|
||||
attributeRoutingConfig,
|
||||
teamMembersMatchingAttributeLogic,
|
||||
}: Pick<
|
||||
GetUrlSearchParamsToForwardOptions,
|
||||
"formResponse" | "fields" | "attributeRoutingConfig" | "teamMembersMatchingAttributeLogic"
|
||||
>) {
|
||||
// There are no existing query params to forward in test preview. These are available only when doing the actual form submission
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set("cal.isTestPreviewLink", "true");
|
||||
return getUrlSearchParamsToForward({
|
||||
formResponse,
|
||||
fields,
|
||||
attributeRoutingConfig,
|
||||
teamMembersMatchingAttributeLogic,
|
||||
// There is no form response being stored in test preview
|
||||
formResponseId: null,
|
||||
searchParams,
|
||||
});
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import publicProcedure from "@calcom/trpc/server/procedures/publicProcedure";
|
||||
import { router } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { ZDeleteFormInputSchema } from "./deleteForm.schema";
|
||||
import { ZFindTeamMembersMatchingAttributeLogicInputSchema } from "./findTeamMembersMatchingAttributeLogic.schema";
|
||||
import { ZFormMutationInputSchema } from "./formMutation.schema";
|
||||
import { ZFormQueryInputSchema } from "./formQuery.schema";
|
||||
import { ZGetAttributesForTeamInputSchema } from "./getAttributesForTeam.schema";
|
||||
@@ -97,16 +96,6 @@ const appRoutingForms = router({
|
||||
);
|
||||
return handler({ ctx, input });
|
||||
}),
|
||||
|
||||
findTeamMembersMatchingAttributeLogic: authedProcedure
|
||||
.input(ZFindTeamMembersMatchingAttributeLogicInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const handler = await getHandler(
|
||||
"findTeamMembersMatchingAttributeLogic",
|
||||
() => import("./findTeamMembersMatchingAttributeLogic.handler")
|
||||
);
|
||||
return handler({ ctx, input });
|
||||
}),
|
||||
});
|
||||
|
||||
export default appRoutingForms;
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
import type { ServerResponse } from "http";
|
||||
import type { NextApiResponse } from "next";
|
||||
|
||||
import { entityPrismaWhereClause } from "@calcom/lib/entityPermissionUtils";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import { findTeamMembersMatchingAttributeLogicOfRoute } from "../lib/findTeamMembersMatchingAttributeLogicOfRoute";
|
||||
import { getSerializableForm } from "../lib/getSerializableForm";
|
||||
import type { TFindTeamMembersMatchingAttributeLogicInputSchema } from "./findTeamMembersMatchingAttributeLogic.schema";
|
||||
|
||||
interface FindTeamMembersMatchingAttributeLogicHandlerOptions {
|
||||
ctx: {
|
||||
prisma: PrismaClient;
|
||||
user: NonNullable<TrpcSessionUser>;
|
||||
res: ServerResponse | NextApiResponse | undefined;
|
||||
};
|
||||
input: TFindTeamMembersMatchingAttributeLogicInputSchema;
|
||||
}
|
||||
|
||||
export const findTeamMembersMatchingAttributeLogicHandler = async ({
|
||||
ctx,
|
||||
input,
|
||||
}: FindTeamMembersMatchingAttributeLogicHandlerOptions) => {
|
||||
const { prisma, user } = ctx;
|
||||
const { formId, response, route, isPreview, _enablePerf, _concurrency } = input;
|
||||
|
||||
const form = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
id: formId,
|
||||
...entityPrismaWhereClause({ userId: user.id }),
|
||||
},
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Form not found",
|
||||
});
|
||||
}
|
||||
|
||||
if (!form.teamId) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "This form is not associated with a team",
|
||||
});
|
||||
}
|
||||
|
||||
const serializableForm = await getSerializableForm({ form });
|
||||
|
||||
const {
|
||||
teamMembersMatchingAttributeLogic: matchingTeamMembersWithResult,
|
||||
timeTaken: teamMembersMatchingAttributeLogicTimeTaken,
|
||||
troubleshooter,
|
||||
checkedFallback,
|
||||
mainAttributeLogicBuildingWarnings: mainWarnings,
|
||||
fallbackAttributeLogicBuildingWarnings: fallbackWarnings,
|
||||
} = await findTeamMembersMatchingAttributeLogicOfRoute(
|
||||
{
|
||||
response,
|
||||
route,
|
||||
form: serializableForm,
|
||||
teamId: form.teamId,
|
||||
isPreview: !!isPreview,
|
||||
},
|
||||
{
|
||||
enablePerf: _enablePerf,
|
||||
// Reuse same flag for enabling troubleshooter. We would normall use them together
|
||||
enableTroubleshooter: _enablePerf,
|
||||
concurrency: _concurrency,
|
||||
}
|
||||
);
|
||||
|
||||
if (!matchingTeamMembersWithResult) {
|
||||
return {
|
||||
troubleshooter,
|
||||
checkedFallback,
|
||||
mainWarnings,
|
||||
fallbackWarnings,
|
||||
result: null,
|
||||
};
|
||||
}
|
||||
const matchingTeamMembersIds = matchingTeamMembersWithResult.map((member) => member.userId);
|
||||
const matchingTeamMembers = await UserRepository.findByIds({ ids: matchingTeamMembersIds });
|
||||
|
||||
console.log("_enablePerf, _concurrency", _enablePerf, _concurrency);
|
||||
if (_enablePerf) {
|
||||
const serverTimingHeader = getServerTimingHeader(teamMembersMatchingAttributeLogicTimeTaken);
|
||||
ctx.res?.setHeader("Server-Timing", serverTimingHeader);
|
||||
console.log("Server-Timing", serverTimingHeader);
|
||||
}
|
||||
|
||||
return {
|
||||
troubleshooter,
|
||||
checkedFallback,
|
||||
mainWarnings,
|
||||
fallbackWarnings,
|
||||
result: matchingTeamMembers.map((user) => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
function getServerTimingHeader(timeTaken: Record<string, number | null | undefined>) {
|
||||
const headerParts = Object.entries(timeTaken)
|
||||
.map(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
return `${key};dur=${value}`;
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return headerParts.join(", ");
|
||||
}
|
||||
|
||||
export default findTeamMembersMatchingAttributeLogicHandler;
|
||||
@@ -1,16 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { zodNonRouterRoute } from "../zod";
|
||||
|
||||
export const ZFindTeamMembersMatchingAttributeLogicInputSchema = z.object({
|
||||
formId: z.string(),
|
||||
response: z.record(z.string(), z.any()),
|
||||
route: zodNonRouterRoute,
|
||||
isPreview: z.boolean().optional(),
|
||||
_enablePerf: z.boolean().optional(),
|
||||
_concurrency: z.number().optional(),
|
||||
});
|
||||
|
||||
export type TFindTeamMembersMatchingAttributeLogicInputSchema = z.infer<
|
||||
typeof ZFindTeamMembersMatchingAttributeLogicInputSchema
|
||||
>;
|
||||
@@ -8,6 +8,7 @@ import type { PrismaClient } from "@calcom/prisma";
|
||||
import { RoutingFormSettings } from "@calcom/prisma/zod-utils";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
|
||||
// import { RoutingFormFieldType } from "../lib/FieldTypes";
|
||||
import { findTeamMembersMatchingAttributeLogicOfRoute } from "../lib/findTeamMembersMatchingAttributeLogicOfRoute";
|
||||
import { getSerializableForm } from "../lib/getSerializableForm";
|
||||
import type { FormResponse } from "../types/types";
|
||||
@@ -96,14 +97,6 @@ export const responseHandler = async ({ ctx, input }: ResponseHandlerOptions) =>
|
||||
});
|
||||
}
|
||||
|
||||
const dbFormResponse = await prisma.app_RoutingForms_FormResponse.create({
|
||||
data: {
|
||||
formId,
|
||||
response: response,
|
||||
chosenRouteId,
|
||||
},
|
||||
});
|
||||
|
||||
const settings = RoutingFormSettings.parse(form.settings);
|
||||
let userWithEmails: string[] = [];
|
||||
if (form.teamId && settings?.sendUpdatesTo?.length) {
|
||||
@@ -155,13 +148,81 @@ export const responseHandler = async ({ ctx, input }: ResponseHandlerOptions) =>
|
||||
)
|
||||
: null;
|
||||
|
||||
// const chosenRouteName = `Route ${chosenRouteIndex + 1}`;
|
||||
|
||||
// if (input.isPreview) {
|
||||
// // Detect if response has value for a field that isn't in the field list
|
||||
// const formFields = serializableFormWithFields.fields.map((field) => field.id);
|
||||
// const extraFields = Object.keys(response).filter((fieldId) => !formFields.includes(fieldId));
|
||||
// const attributeRoutingConfig =
|
||||
// "attributeRoutingConfig" in chosenRoute ? chosenRoute.attributeRoutingConfig ?? null : null;
|
||||
|
||||
// let previewData = {
|
||||
// teamMemberIdsMatchingAttributeLogic,
|
||||
// chosenRoute: {
|
||||
// name: chosenRouteName,
|
||||
// action: "action" in chosenRoute ? chosenRoute.action : null,
|
||||
// },
|
||||
// skipContactOwner: attributeRoutingConfig?.skipContactOwner ?? false,
|
||||
// warnings: [] as string[],
|
||||
// errors: [] as string[],
|
||||
// };
|
||||
|
||||
// if (extraFields.length > 0) {
|
||||
// // If response submitted directly through the /response.handler, it is useful to know which fields were non-existent
|
||||
// // If we reach here through router, all extra fields are already removed from here
|
||||
// previewData.warnings.push(
|
||||
// `Response contains values for non-existent fields: ${extraFields.join(", ")}`
|
||||
// );
|
||||
// }
|
||||
|
||||
// // Check for values not present in options for SINGLE_SELECT and MULTISELECT fields
|
||||
// serializableFormWithFields.fields.forEach((field) => {
|
||||
// if (
|
||||
// field.type !== RoutingFormFieldType.SINGLE_SELECT &&
|
||||
// field.type !== RoutingFormFieldType.MULTI_SELECT
|
||||
// ) {
|
||||
// return;
|
||||
// }
|
||||
|
||||
// const fieldResponse = response[field.id];
|
||||
|
||||
// if (fieldResponse && fieldResponse.value) {
|
||||
// const values = Array.isArray(fieldResponse.value) ? fieldResponse.value : [fieldResponse.value];
|
||||
// const invalidValues = values.filter(
|
||||
// (value) => !field.options?.some((option) => option.id === value || option.label === value)
|
||||
// );
|
||||
// if (invalidValues.length > 0) {
|
||||
// previewData.errors.push(`Invalid value(s) for ${field.label}: ${invalidValues.join(", ")}`);
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
// return {
|
||||
// isPreview: true,
|
||||
// previewData,
|
||||
// formResponse: null,
|
||||
// teamMembersMatchingAttributeLogic: teamMemberIdsMatchingAttributeLogic,
|
||||
// };
|
||||
// }
|
||||
|
||||
const dbFormResponse = await prisma.app_RoutingForms_FormResponse.create({
|
||||
data: {
|
||||
formId,
|
||||
response: response,
|
||||
chosenRouteId,
|
||||
},
|
||||
});
|
||||
|
||||
await onFormSubmission(
|
||||
{ ...serializableFormWithFields, userWithEmails },
|
||||
dbFormResponse.response as FormResponse,
|
||||
dbFormResponse.id,
|
||||
"action" in chosenRoute ? chosenRoute.action : undefined
|
||||
);
|
||||
|
||||
return {
|
||||
isPreview: false,
|
||||
formResponse: dbFormResponse,
|
||||
teamMembersMatchingAttributeLogic: teamMemberIdsMatchingAttributeLogic,
|
||||
attributeRoutingConfig:
|
||||
|
||||
@@ -11,6 +11,7 @@ export const ZResponseInputSchema = z.object({
|
||||
),
|
||||
// TODO: There could be existing forms loaded that will not send chosenRouteId. Make it required later.
|
||||
chosenRouteId: z.string().optional(),
|
||||
isPreview: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type TResponseInputSchema = z.infer<typeof ZResponseInputSchema>;
|
||||
@@ -112,6 +112,7 @@ export async function onFormSubmission(
|
||||
throw new Error(`Field with id ${fieldId} not found`);
|
||||
}
|
||||
// Use the label lowercased as the key to identify a field.
|
||||
// TODO: We seem to be using label from the response, Can we not use the field.label
|
||||
const key =
|
||||
form.fields.find((f) => f.id === fieldId)?.identifier ||
|
||||
(fieldResponse.label as keyof typeof fieldResponsesByIdentifier);
|
||||
|
||||
@@ -200,6 +200,7 @@ export const appDataSchema = z.any();
|
||||
export const appKeysSchema = z.object({});
|
||||
|
||||
// This is different from FormResponse in types.d.ts in that it has label optional. We don't seem to be using label at this point, so we might want to use this only while saving the response when Routing Form is submitted
|
||||
// Record key is formFieldId
|
||||
export const routingFormResponseInDbSchema = z.record(
|
||||
z.object({
|
||||
label: z.string().optional(),
|
||||
|
||||
Reference in new issue
Block a user