feat: trpc v10 migration (#5332)
* migrate router * createTRPCReact * frontend 1 * random format change * frontend 2 * withQuery * form router * TS-ERROR: proxy on utils-client * inferance * ssg * reuse * trpc rc4 * Apply suggestions from code review * skip test * move skip one level up * whops * rc 6 with new setData func Co-authored-by: zomars <[email protected]>
This commit is contained in:
1 parent
6d67808627
commit
db7c3fb52f
157 files changed
+3062
-3144
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import Link from "next/link";
|
||||
|
||||
import { inferQueryOutput } from "@calcom/trpc/react";
|
||||
import { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Switch } from "@calcom/ui/v2";
|
||||
import OmniInstallAppButton from "@calcom/web/components/apps/OmniInstallAppButton";
|
||||
|
||||
@@ -16,7 +16,7 @@ export default function AppCard({
|
||||
children,
|
||||
setAppData,
|
||||
}: {
|
||||
app: inferQueryOutput<"viewer.apps">[number];
|
||||
app: RouterOutputs["viewer"]["apps"][number];
|
||||
description?: React.ReactNode;
|
||||
switchChecked?: boolean;
|
||||
switchOnClick?: (e: boolean) => void;
|
||||
|
||||
@@ -28,7 +28,7 @@ export const InstallAppButton = (
|
||||
wrapperClassName?: string;
|
||||
} & InstallAppButtonProps
|
||||
) => {
|
||||
const { isLoading, data: user } = trpc.useQuery(["viewer.me"]);
|
||||
const { isLoading, data: user } = trpc.viewer.me.useQuery();
|
||||
const router = useRouter();
|
||||
const proProtectionElementRef = useRef<HTMLDivElement | null>(null);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -57,7 +57,7 @@ function NewFormDialog({ appUrl }: { appUrl: string }) {
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const mutation = trpc.useMutation("viewer.app_routing_forms.formMutation", {
|
||||
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
|
||||
onSuccess: (_data, variables) => {
|
||||
router.push(`${appUrl}/form-edit/${variables.id}`);
|
||||
},
|
||||
@@ -65,7 +65,7 @@ function NewFormDialog({ appUrl }: { appUrl: string }) {
|
||||
showToast(`Something went wrong`, "error");
|
||||
},
|
||||
onSettled: () => {
|
||||
utils.invalidateQueries("viewer.app_routing_forms.forms");
|
||||
utils.viewer.appRoutingForms.forms.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -161,13 +161,13 @@ function Dialogs({
|
||||
}) {
|
||||
const utils = trpc.useContext();
|
||||
const router = useRouter();
|
||||
const deleteMutation = trpc.useMutation("viewer.app_routing_forms.deleteForm", {
|
||||
const deleteMutation = trpc.viewer.appRoutingForms.deleteForm.useMutation({
|
||||
onMutate: async ({ id: formId }) => {
|
||||
await utils.cancelQuery(["viewer.app_routing_forms.forms"]);
|
||||
const previousValue = utils.getQueryData(["viewer.app_routing_forms.forms"]);
|
||||
await utils.viewer.appRoutingForms.forms.cancel();
|
||||
const previousValue = utils.viewer.appRoutingForms.forms.getData();
|
||||
if (previousValue) {
|
||||
const filtered = previousValue.filter(({ id }) => id !== formId);
|
||||
utils.setQueryData(["viewer.app_routing_forms.forms"], filtered);
|
||||
utils.viewer.appRoutingForms.forms.setData(undefined, filtered);
|
||||
}
|
||||
return { previousValue };
|
||||
},
|
||||
@@ -177,12 +177,12 @@ function Dialogs({
|
||||
router.replace(`${appUrl}/forms`);
|
||||
},
|
||||
onSettled: () => {
|
||||
utils.invalidateQueries(["viewer.app_routing_forms.forms"]);
|
||||
utils.viewer.appRoutingForms.forms.invalidate();
|
||||
setDeleteDialogOpen(false);
|
||||
},
|
||||
onError: (err, newTodo, context) => {
|
||||
if (context?.previousValue) {
|
||||
utils.setQueryData(["viewer.app_routing_forms.forms"], context.previousValue);
|
||||
utils.viewer.appRoutingForms.forms.setData(undefined, context.previousValue);
|
||||
}
|
||||
showToast("Something went wrong", "error");
|
||||
},
|
||||
@@ -234,7 +234,7 @@ export function FormActionsProvider({ appUrl, children }: { appUrl: string; chil
|
||||
const [deleteDialogFormId, setDeleteDialogFormId] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
|
||||
const toggleMutation = trpc.useMutation("viewer.app_routing_forms.formMutation", {
|
||||
const toggleMutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
|
||||
onError: () => {
|
||||
showToast(`Something went wrong`, "error");
|
||||
},
|
||||
|
||||
@@ -212,7 +212,7 @@ function SingleForm({ form, appUrl, Page }: SingleFormComponentProps) {
|
||||
hookForm.reset(form);
|
||||
}, [form, hookForm]);
|
||||
|
||||
const mutation = trpc.useMutation("viewer.app_routing_forms.formMutation", {
|
||||
const mutation = trpc.viewer.appRoutingForms.formMutation.useMutation({
|
||||
onSuccess() {
|
||||
showToast("Form updated successfully.", "success");
|
||||
},
|
||||
@@ -220,7 +220,7 @@ function SingleForm({ form, appUrl, Page }: SingleFormComponentProps) {
|
||||
showToast(`Something went wrong`, "error");
|
||||
},
|
||||
onSettled() {
|
||||
utils.invalidateQueries(["viewer.app_routing_forms.formQuery", { id: form.id }]);
|
||||
utils.viewer.appRoutingForms.formQuery.invalidate({ id: form.id });
|
||||
},
|
||||
});
|
||||
return (
|
||||
@@ -373,9 +373,13 @@ function SingleForm({ form, appUrl, Page }: SingleFormComponentProps) {
|
||||
}
|
||||
|
||||
export default function SingleFormWrapper({ form: _form, ...props }: SingleFormComponentProps) {
|
||||
const { data: form, isLoading } = trpc.useQuery(["viewer.app_routing_forms.formQuery", { id: _form.id }], {
|
||||
initialData: _form,
|
||||
});
|
||||
const { data: form, isLoading } = trpc.viewer.appRoutingForms.formQuery.useQuery(
|
||||
{ id: _form.id },
|
||||
{
|
||||
initialData: _form,
|
||||
trpc: {},
|
||||
}
|
||||
);
|
||||
const { t } = useLocale();
|
||||
|
||||
if (isLoading) {
|
||||
|
||||
@@ -22,7 +22,9 @@ export default function RoutingForms({
|
||||
appUrl,
|
||||
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
|
||||
const { t } = useLocale();
|
||||
const { data: forms } = trpc.useQuery(["viewer.app_routing_forms.forms"], { initialData: forms_ });
|
||||
const { data: forms } = trpc.viewer.appRoutingForms.forms.useQuery(undefined, {
|
||||
initialData: forms_,
|
||||
});
|
||||
|
||||
const { data: typeformApp } = useApp("typeform");
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ const Route = ({
|
||||
}) => {
|
||||
const index = routes.indexOf(route);
|
||||
|
||||
const { data: eventTypesByGroup } = trpc.useQuery(["viewer.eventTypes"]);
|
||||
const { data: eventTypesByGroup } = trpc.viewer.eventTypes.getByViewer.useQuery();
|
||||
|
||||
const eventOptions: { label: string; value: string }[] = [];
|
||||
eventTypesByGroup?.eventTypeGroups.forEach((group) => {
|
||||
|
||||
@@ -59,7 +59,7 @@ function RoutingForm({ form, profile, ...restProps }: inferSSRProps<typeof getSe
|
||||
sdkActionManager?.fire("__routeChanged", {});
|
||||
}, [customPageMessage]);
|
||||
|
||||
const responseMutation = trpc.useMutation("viewer.app_routing_forms.public.response", {
|
||||
const responseMutation = trpc.viewer.appRoutingForms.public.response.useMutation({
|
||||
onSuccess: () => {
|
||||
const decidedAction = decidedActionRef.current;
|
||||
if (!decidedAction) {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { sendGenericWebhookPayload } from "@calcom/features/webhooks/lib/sendPay
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { RoutingFormSettings } from "@calcom/prisma/zod-utils";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
import { createProtectedRouter, createRouter } from "@calcom/trpc/server/createRouter";
|
||||
import { authedProcedure, publicProcedure, router } from "@calcom/trpc/server/trpc";
|
||||
import { Ensure } from "@calcom/types/utils";
|
||||
|
||||
import ResponseEmail from "./emails/templates/response-email";
|
||||
@@ -72,21 +72,23 @@ const sendResponseEmail = async (
|
||||
}
|
||||
};
|
||||
|
||||
const app_RoutingForms = createRouter()
|
||||
.merge(
|
||||
"public.",
|
||||
createRouter().mutation("response", {
|
||||
input: z.object({
|
||||
formId: z.string(),
|
||||
formFillerId: z.string(),
|
||||
response: z.record(
|
||||
z.object({
|
||||
label: z.string(),
|
||||
value: z.union([z.string(), z.array(z.string())]),
|
||||
})
|
||||
),
|
||||
}),
|
||||
async resolve({ ctx: { prisma }, input }) {
|
||||
const appRoutingForms = router({
|
||||
public: router({
|
||||
response: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
formId: z.string(),
|
||||
formFillerId: z.string(),
|
||||
response: z.record(
|
||||
z.object({
|
||||
label: z.string(),
|
||||
value: z.union([z.string(), z.array(z.string())]),
|
||||
})
|
||||
),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { prisma } = ctx;
|
||||
try {
|
||||
const { response, formId } = input;
|
||||
const form = await prisma.app_RoutingForms_Form.findFirst({
|
||||
@@ -168,213 +170,213 @@ const app_RoutingForms = createRouter()
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}),
|
||||
}),
|
||||
forms: authedProcedure.query(async ({ ctx }) => {
|
||||
const { prisma, user } = ctx;
|
||||
const forms = await prisma.app_RoutingForms_Form.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
)
|
||||
.merge(
|
||||
"",
|
||||
createProtectedRouter()
|
||||
.query("forms", {
|
||||
async resolve({ ctx: { user, prisma } }) {
|
||||
const forms = await prisma.app_RoutingForms_Form.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
responses: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const serializableForms = forms.map((form) => getSerializableForm(form));
|
||||
return serializableForms;
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
responses: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const serializableForms = forms.map((form) => getSerializableForm(form));
|
||||
return serializableForms;
|
||||
}),
|
||||
formQuery: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
})
|
||||
.query("formQuery", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx: { prisma, user }, input }) {
|
||||
const form = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
id: input.id,
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
responses: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!form) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return getSerializableForm(form);
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { prisma, user } = ctx;
|
||||
const form = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
id: input.id,
|
||||
},
|
||||
})
|
||||
.mutation("formMutation", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
fields: zodFields,
|
||||
routes: zodRoutes,
|
||||
addFallback: z.boolean().optional(),
|
||||
duplicateFrom: z.string().nullable().optional(),
|
||||
settings: RoutingFormSettings.optional(),
|
||||
}),
|
||||
async resolve({ ctx: { user, prisma }, input }) {
|
||||
const { name, id, description, settings, disabled, addFallback, duplicateFrom } = input;
|
||||
if (!(await isAllowed({ userId: user.id, formId: id }))) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
let { routes } = input;
|
||||
let { fields } = input;
|
||||
|
||||
if (duplicateFrom) {
|
||||
const sourceForm = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
id: duplicateFrom,
|
||||
},
|
||||
select: {
|
||||
fields: true,
|
||||
routes: true,
|
||||
},
|
||||
});
|
||||
if (!sourceForm) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Form to duplicate: ${duplicateFrom} not found`,
|
||||
});
|
||||
}
|
||||
const fieldParsed = zodFields.safeParse(sourceForm.fields);
|
||||
const routesParsed = zodRoutes.safeParse(sourceForm.routes);
|
||||
if (!fieldParsed.success || !routesParsed.success) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Could not parse source form's fields or routes",
|
||||
});
|
||||
}
|
||||
// Duplicate just routes and fields
|
||||
// We don't want name, description and responses to be copied
|
||||
routes = routesParsed.data;
|
||||
fields = fieldParsed.data;
|
||||
}
|
||||
|
||||
fields = fields || [];
|
||||
|
||||
const form = await prisma.app_RoutingForms_Form.findUnique({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
id: true,
|
||||
user: true,
|
||||
name: true,
|
||||
description: true,
|
||||
userId: true,
|
||||
disabled: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
routes: true,
|
||||
fields: true,
|
||||
settings: true,
|
||||
responses: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Add back deleted fields in the end. Fields can't be deleted, to make sure columns never decrease which hugely simplifies CSV generation
|
||||
if (form) {
|
||||
const serializedForm = getSerializableForm(form, true);
|
||||
// Find all fields that are in DB(including deleted) but not in the mutation
|
||||
const deletedFields =
|
||||
serializedForm.fields?.filter((f) => !fields!.find((field) => field.id === f.id)) || [];
|
||||
|
||||
fields = fields.concat(
|
||||
deletedFields.map((f) => {
|
||||
f.deleted = true;
|
||||
return f;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (addFallback) {
|
||||
const uuid = uuidv4();
|
||||
routes = routes || [];
|
||||
// Add a fallback route if there is none
|
||||
if (!routes.find((route) => route.isFallback)) {
|
||||
routes.push({
|
||||
id: uuid,
|
||||
isFallback: true,
|
||||
action: {
|
||||
type: "customPageMessage",
|
||||
value: "Thank you for your interest! We will be in touch soon.",
|
||||
},
|
||||
queryValue: { id: uuid, type: "group" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return await prisma.app_RoutingForms_Form.upsert({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
create: {
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
fields: fields,
|
||||
name: name,
|
||||
description,
|
||||
// Prisma doesn't allow setting null value directly for JSON. It recommends using JsonNull for that case.
|
||||
routes: routes === null ? Prisma.JsonNull : routes,
|
||||
id: id,
|
||||
},
|
||||
update: {
|
||||
disabled: disabled,
|
||||
fields: fields,
|
||||
name: name,
|
||||
description,
|
||||
settings: settings === null ? Prisma.JsonNull : settings,
|
||||
routes: routes === null ? Prisma.JsonNull : routes,
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
})
|
||||
// TODO: Can't we use DELETE method on form?
|
||||
.mutation("deleteForm", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ ctx: { user, prisma }, input }) {
|
||||
if (!(await isAllowed({ userId: user.id, formId: input.id }))) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
return await prisma.app_RoutingForms_Form.deleteMany({
|
||||
where: {
|
||||
id: input.id,
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
export default app_RoutingForms;
|
||||
if (!form) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return getSerializableForm(form);
|
||||
}),
|
||||
formMutation: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
fields: zodFields,
|
||||
routes: zodRoutes,
|
||||
addFallback: z.boolean().optional(),
|
||||
duplicateFrom: z.string().nullable().optional(),
|
||||
settings: RoutingFormSettings.optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { user, prisma } = ctx;
|
||||
const { name, id, description, settings, disabled, addFallback, duplicateFrom } = input;
|
||||
if (!(await isAllowed({ userId: user.id, formId: id }))) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
let { routes } = input;
|
||||
let { fields } = input;
|
||||
|
||||
if (duplicateFrom) {
|
||||
const sourceForm = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
id: duplicateFrom,
|
||||
},
|
||||
select: {
|
||||
fields: true,
|
||||
routes: true,
|
||||
},
|
||||
});
|
||||
if (!sourceForm) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Form to duplicate: ${duplicateFrom} not found`,
|
||||
});
|
||||
}
|
||||
const fieldParsed = zodFields.safeParse(sourceForm.fields);
|
||||
const routesParsed = zodRoutes.safeParse(sourceForm.routes);
|
||||
if (!fieldParsed.success || !routesParsed.success) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Could not parse source form's fields or routes",
|
||||
});
|
||||
}
|
||||
// Duplicate just routes and fields
|
||||
// We don't want name, description and responses to be copied
|
||||
routes = routesParsed.data;
|
||||
fields = fieldParsed.data;
|
||||
}
|
||||
|
||||
fields = fields || [];
|
||||
|
||||
const form = await prisma.app_RoutingForms_Form.findUnique({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
user: true,
|
||||
name: true,
|
||||
description: true,
|
||||
userId: true,
|
||||
disabled: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
routes: true,
|
||||
fields: true,
|
||||
settings: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Add back deleted fields in the end. Fields can't be deleted, to make sure columns never decrease which hugely simplifies CSV generation
|
||||
if (form) {
|
||||
const serializedForm = getSerializableForm(form, true);
|
||||
// Find all fields that are in DB(including deleted) but not in the mutation
|
||||
const deletedFields =
|
||||
serializedForm.fields?.filter((f) => !fields!.find((field) => field.id === f.id)) || [];
|
||||
|
||||
fields = fields.concat(
|
||||
deletedFields.map((f) => {
|
||||
f.deleted = true;
|
||||
return f;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (addFallback) {
|
||||
const uuid = uuidv4();
|
||||
routes = routes || [];
|
||||
// Add a fallback route if there is none
|
||||
if (!routes.find((route) => route.isFallback)) {
|
||||
routes.push({
|
||||
id: uuid,
|
||||
isFallback: true,
|
||||
action: {
|
||||
type: "customPageMessage",
|
||||
value: "Thank you for your interest! We will be in touch soon.",
|
||||
},
|
||||
queryValue: { id: uuid, type: "group" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return await prisma.app_RoutingForms_Form.upsert({
|
||||
where: {
|
||||
id: id,
|
||||
},
|
||||
create: {
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
fields: fields,
|
||||
name: name,
|
||||
description,
|
||||
// Prisma doesn't allow setting null value directly for JSON. It recommends using JsonNull for that case.
|
||||
routes: routes === null ? Prisma.JsonNull : routes,
|
||||
id: id,
|
||||
},
|
||||
update: {
|
||||
disabled: disabled,
|
||||
fields: fields,
|
||||
name: name,
|
||||
description,
|
||||
settings: settings === null ? Prisma.JsonNull : settings,
|
||||
routes: routes === null ? Prisma.JsonNull : routes,
|
||||
},
|
||||
});
|
||||
}),
|
||||
deleteForm: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { user, prisma } = ctx;
|
||||
if (!(await isAllowed({ userId: user.id, formId: input.id }))) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
});
|
||||
}
|
||||
return await prisma.app_RoutingForms_Form.deleteMany({
|
||||
where: {
|
||||
id: input.id,
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export default appRoutingForms;
|
||||
@@ -71,12 +71,12 @@ const BalanceCheck: React.FC<RainbowGateProps> = ({ chainId, setToken, tokenAddr
|
||||
} = useSignMessage({
|
||||
message: ETH_MESSAGE,
|
||||
});
|
||||
const { data: contractData, isLoading: isContractLoading } = trpc.useQuery([
|
||||
"viewer.eth.contract",
|
||||
{ address: tokenAddress, chainId },
|
||||
]);
|
||||
const { data: balanceData, isLoading: isBalanceLoading } = trpc.useQuery(
|
||||
["viewer.eth.balance", { address: address || "", tokenAddress, chainId }],
|
||||
const { data: contractData, isLoading: isContractLoading } = trpc.viewer.eth.contract.useQuery({
|
||||
address: tokenAddress,
|
||||
chainId,
|
||||
});
|
||||
const { data: balanceData, isLoading: isBalanceLoading } = trpc.viewer.eth.balance.useQuery(
|
||||
{ address: address || "", tokenAddress, chainId },
|
||||
{
|
||||
enabled: !!address,
|
||||
}
|
||||
|
||||
@@ -2,28 +2,33 @@ import { ethers } from "ethers";
|
||||
import { configureChains, createClient } from "wagmi";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createRouter } from "@calcom/trpc/server/createRouter";
|
||||
import { router, publicProcedure } from "@calcom/trpc/server/trpc";
|
||||
|
||||
import abi from "../utils/abi.json";
|
||||
import { checkBalance, getProviders, SUPPORTED_CHAINS } from "../utils/ethereum";
|
||||
|
||||
const ethRouter = createRouter()
|
||||
const ethRouter = router({
|
||||
// Fetch contract `name` and `symbol` or error
|
||||
.query("contract", {
|
||||
input: z.object({
|
||||
address: z.string(),
|
||||
chainId: z.number(),
|
||||
}),
|
||||
output: z.object({
|
||||
data: z
|
||||
.object({
|
||||
name: z.string(),
|
||||
symbol: z.string(),
|
||||
})
|
||||
.nullish(),
|
||||
error: z.string().nullish(),
|
||||
}),
|
||||
async resolve({ input: { address, chainId } }) {
|
||||
contract: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
address: z.string(),
|
||||
chainId: z.number(),
|
||||
})
|
||||
)
|
||||
.output(
|
||||
z.object({
|
||||
data: z
|
||||
.object({
|
||||
name: z.string(),
|
||||
symbol: z.string(),
|
||||
})
|
||||
.nullish(),
|
||||
error: z.string().nullish(),
|
||||
})
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
const { address, chainId } = input;
|
||||
const { provider } = configureChains(
|
||||
SUPPORTED_CHAINS.filter((chain) => chain.id === chainId),
|
||||
getProviders()
|
||||
@@ -53,24 +58,28 @@ const ethRouter = createRouter()
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
})
|
||||
}),
|
||||
// Fetch user's `balance` of either ERC-20 or ERC-721 compliant token or error
|
||||
.query("balance", {
|
||||
input: z.object({
|
||||
address: z.string(),
|
||||
tokenAddress: z.string(),
|
||||
chainId: z.number(),
|
||||
}),
|
||||
output: z.object({
|
||||
data: z
|
||||
.object({
|
||||
hasBalance: z.boolean(),
|
||||
})
|
||||
.nullish(),
|
||||
error: z.string().nullish(),
|
||||
}),
|
||||
async resolve({ input: { address, tokenAddress, chainId } }) {
|
||||
balance: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
address: z.string(),
|
||||
tokenAddress: z.string(),
|
||||
chainId: z.number(),
|
||||
})
|
||||
)
|
||||
.output(
|
||||
z.object({
|
||||
data: z
|
||||
.object({
|
||||
hasBalance: z.boolean(),
|
||||
})
|
||||
.nullish(),
|
||||
error: z.string().nullish(),
|
||||
})
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
const { address, tokenAddress, chainId } = input;
|
||||
try {
|
||||
const hasBalance = await checkBalance(address, tokenAddress, chainId);
|
||||
|
||||
@@ -86,7 +95,7 @@ const ethRouter = createRouter()
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
export default ethRouter;
|
||||
Vendored
+2
-2
@@ -2,7 +2,7 @@ import React from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
import { _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import { inferQueryOutput } from "@calcom/trpc/react";
|
||||
import { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { ButtonBaseProps } from "@calcom/ui/Button";
|
||||
import { ButtonBaseProps as v2ButtonBaseProps } from "@calcom/ui/components/button";
|
||||
|
||||
@@ -30,6 +30,6 @@ export type EventTypeAppCardComponentProps = {
|
||||
> & {
|
||||
URL: string;
|
||||
};
|
||||
app: inferQueryOutput<"viewer.apps">[number];
|
||||
app: RouterOutputs["viewer"]["apps"][number];
|
||||
};
|
||||
export type EventTypeAppCardComponent = React.FC<EventTypeAppCardComponentProps>;
|
||||
@@ -73,7 +73,7 @@ export const ConfirmDialog = (props: IConfirmDialogWipe) => {
|
||||
},
|
||||
{
|
||||
async onSettled() {
|
||||
await utils.invalidateQueries(["viewer.bookings"]);
|
||||
await utils.viewer.bookings.invalidate();
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
@@ -13,10 +13,10 @@ interface IWipeMyCalActionButtonProps {
|
||||
const WipeMyCalActionButton = (props: IWipeMyCalActionButtonProps) => {
|
||||
const { bookingsEmpty, bookingStatus } = props;
|
||||
const [openDialog, setOpenDialog] = useState(false);
|
||||
const { isSuccess, isLoading, data } = trpc.useQuery([
|
||||
"viewer.integrations",
|
||||
{ variant: "other", onlyInstalled: undefined },
|
||||
]);
|
||||
const { isSuccess, isLoading, data } = trpc.viewer.integrations.useQuery({
|
||||
variant: "other",
|
||||
onlyInstalled: undefined,
|
||||
});
|
||||
|
||||
if (bookingStatus !== "upcoming" || bookingsEmpty) {
|
||||
return <></>;
|
||||
|
||||
@@ -19,10 +19,10 @@ export default function ZapierSetup(props: IZapierSetupProps) {
|
||||
const [newApiKey, setNewApiKey] = useState("");
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const integrations = trpc.useQuery(["viewer.integrations", { variant: "automation" }]);
|
||||
const oldApiKey = trpc.useQuery(["viewer.apiKeys.findKeyOfType", { appId: ZAPIER }]);
|
||||
const integrations = trpc.viewer.integrations.useQuery({ variant: "automation" });
|
||||
const oldApiKey = trpc.viewer.apiKeys.findKeyOfType.useQuery({ appId: ZAPIER });
|
||||
|
||||
const deleteApiKey = trpc.useMutation("viewer.apiKeys.delete");
|
||||
const deleteApiKey = trpc.viewer.apiKeys.delete.useMutation();
|
||||
const zapierCredentials: { credentialIds: number[] } | undefined = integrations.data?.items.find(
|
||||
(item: { type: string }) => item.type === "zapier_automation"
|
||||
);
|
||||
@@ -32,7 +32,7 @@ export default function ZapierSetup(props: IZapierSetupProps) {
|
||||
|
||||
async function createApiKey() {
|
||||
const event = { note: "Zapier", expiresAt: null, appId: ZAPIER };
|
||||
const apiKey = await utils.client.mutation("viewer.apiKeys.create", event);
|
||||
const apiKey = await utils.client.viewer.apiKeys.create.mutate(event);
|
||||
if (oldApiKey.data) {
|
||||
deleteApiKey.mutate({
|
||||
id: oldApiKey.data.id,
|
||||
|
||||
@@ -14,7 +14,7 @@ If you are working with embed on website, don't forget to do `yarn build` after
|
||||
## Running Tests
|
||||
|
||||
Runs tests and updates the snapshots. Right now we don't care about snapshots
|
||||
`yarn embed-tests-quick --update-snapshots`
|
||||
`yarn embed-tests-quick --update-snapshots`
|
||||
TODO
|
||||
|
||||
- Playwright tests.
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Badge } from "@calcom/ui/components/badge/Badge";
|
||||
|
||||
export default function UnconfirmedBookingBadge() {
|
||||
const { t } = useLocale();
|
||||
const { data: unconfirmedBookingCount } = trpc.useQuery(["viewer.bookingUnconfirmedCount"]);
|
||||
const { data: unconfirmedBookingCount } = trpc.viewer.bookingUnconfirmedCount.useQuery();
|
||||
if (!unconfirmedBookingCount) return null;
|
||||
else
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import classNames from "classnames";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { components } from "react-select";
|
||||
import { SingleValueProps, OptionProps, SingleValue, ActionMeta } from "react-select";
|
||||
import { SingleValueProps, OptionProps } from "react-select";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { DestinationCalendar } from "@calcom/prisma/client";
|
||||
@@ -51,7 +51,7 @@ const DestinationCalendarSelector = ({
|
||||
destinationCalendar,
|
||||
}: Props): JSX.Element | null => {
|
||||
const { t } = useLocale();
|
||||
const query = trpc.useQuery(["viewer.connectedCalendars"]);
|
||||
const query = trpc.viewer.connectedCalendars.useQuery();
|
||||
const [selectedOption, setSelectedOption] = useState<{
|
||||
value: string;
|
||||
label: string;
|
||||
|
||||
@@ -94,10 +94,10 @@ export default function ApiKeyDialogForm(props: {
|
||||
<Form<Omit<TApiKeys, "userId" | "createdAt" | "lastUsedAt"> & { neverExpires?: boolean }>
|
||||
form={form}
|
||||
handleSubmit={async (event) => {
|
||||
const apiKey = await utils.client.mutation("viewer.apiKeys.create", event);
|
||||
const apiKey = await utils.client.viewer.apiKeys.create.mutate(event);
|
||||
setApiKey(apiKey);
|
||||
setApiKeyDetails({ ...event, neverExpires: !!event.neverExpires });
|
||||
await utils.invalidateQueries(["viewer.apiKeys.list"]);
|
||||
await utils.viewer.apiKeys.list.invalidate();
|
||||
setSuccessfulNewApiKeyModal(true);
|
||||
}}
|
||||
className="space-y-4">
|
||||
|
||||
@@ -15,7 +15,7 @@ import ApiKeyListItem, { TApiKeys } from "./ApiKeyListItem";
|
||||
|
||||
function ApiKeyListContainer() {
|
||||
const { t } = useLocale();
|
||||
const query = trpc.useQuery(["viewer.apiKeys.list"]);
|
||||
const query = trpc.viewer.apiKeys.list.useQuery();
|
||||
const data = query.data;
|
||||
|
||||
const [newApiKeyModal, setNewApiKeyModal] = useState(false);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import Button from "@calcom/ui/Button";
|
||||
import ConfirmationDialogContent from "@calcom/ui/ConfirmationDialogContent";
|
||||
import { Dialog, DialogTrigger } from "@calcom/ui/Dialog";
|
||||
@@ -10,16 +10,16 @@ import { ListItem } from "@calcom/ui/List";
|
||||
import { Tooltip } from "@calcom/ui/Tooltip";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
|
||||
export type TApiKeys = inferQueryOutput<"viewer.apiKeys.list">[number];
|
||||
export type TApiKeys = RouterOutputs["viewer"]["apiKeys"]["list"][number];
|
||||
|
||||
export default function ApiKeyListItem(props: { apiKey: TApiKeys; onEditApiKey: () => void }) {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const isExpired = props?.apiKey?.expiresAt ? props.apiKey.expiresAt < new Date() : null;
|
||||
const neverExpires = props?.apiKey?.expiresAt === null;
|
||||
const deleteApiKey = trpc.useMutation("viewer.apiKeys.delete", {
|
||||
const deleteApiKey = trpc.viewer.apiKeys.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.apiKeys.list"]);
|
||||
await utils.viewer.apiKeys.list.invalidate();
|
||||
},
|
||||
});
|
||||
return (
|
||||
|
||||
@@ -25,9 +25,9 @@ export default function ApiKeyDialogForm({
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const updateApiKeyMutation = trpc.useMutation("viewer.apiKeys.edit", {
|
||||
const updateApiKeyMutation = trpc.viewer.apiKeys.edit.useMutation({
|
||||
onSuccess() {
|
||||
utils.invalidateQueries("viewer.apiKeys.list");
|
||||
utils.viewer.apiKeys.list.invalidate();
|
||||
showToast(t("api_key_updated"), "success");
|
||||
handleClose();
|
||||
},
|
||||
@@ -104,10 +104,10 @@ export default function ApiKeyDialogForm({
|
||||
console.log("Name changed");
|
||||
await updateApiKeyMutation.mutate({ id: defaultValues.id, note: event.note });
|
||||
} else {
|
||||
const apiKey = await utils.client.mutation("viewer.apiKeys.create", event);
|
||||
const apiKey = await utils.client.viewer.apiKeys.create.mutate(event);
|
||||
setApiKey(apiKey);
|
||||
setApiKeyDetails({ ...event });
|
||||
await utils.invalidateQueries(["viewer.apiKeys.list"]);
|
||||
await utils.viewer.apiKeys.list.invalidate();
|
||||
setSuccessfulNewApiKeyModal(true);
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -28,9 +28,9 @@ const ApiKeyListItem = ({
|
||||
const isExpired = apiKey?.expiresAt ? apiKey.expiresAt < new Date() : null;
|
||||
const neverExpires = apiKey?.expiresAt === null;
|
||||
|
||||
const deleteApiKey = trpc.useMutation("viewer.apiKeys.delete", {
|
||||
const deleteApiKey = trpc.viewer.apiKeys.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.apiKeys.list"]);
|
||||
await utils.viewer.apiKeys.list.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -27,10 +27,10 @@ export default function ConfigDialogForm({
|
||||
|
||||
const form = useForm<TeamSSOValues>();
|
||||
|
||||
const mutation = trpc.useMutation("viewer.saml.update", {
|
||||
const mutation = trpc.viewer.saml.update.useMutation({
|
||||
async onSuccess() {
|
||||
telemetry.event(telemetryEventTypes.samlConfig, collectPageParameters());
|
||||
await utils.invalidateQueries(["viewer.saml.get"]);
|
||||
await utils.viewer.saml.get.invalidate();
|
||||
showToast(t("saml_config_updated_successfully"), "success");
|
||||
handleClose();
|
||||
},
|
||||
|
||||
@@ -22,20 +22,23 @@ export default function SAMLConfiguration({ teamId }: { teamId: number | null })
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [configModal, setConfigModal] = useState(false);
|
||||
|
||||
const { data: connection, isLoading } = trpc.useQuery(["viewer.saml.get", { teamId }], {
|
||||
onError: (err) => {
|
||||
setHasError(true);
|
||||
setErrorMessage(err.message);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setHasError(false);
|
||||
setErrorMessage("");
|
||||
},
|
||||
});
|
||||
const { data: connection, isLoading } = trpc.viewer.saml.get.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
onError: (err) => {
|
||||
setHasError(true);
|
||||
setErrorMessage(err.message);
|
||||
},
|
||||
onSuccess: () => {
|
||||
setHasError(false);
|
||||
setErrorMessage("");
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const mutation = trpc.useMutation("viewer.saml.delete", {
|
||||
const mutation = trpc.viewer.saml.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.saml.get"]);
|
||||
await utils.viewer.saml.get.invalidate();
|
||||
showToast(t("saml_config_deleted_successfully"), "success");
|
||||
},
|
||||
onError: (err) => {
|
||||
|
||||
@@ -16,11 +16,14 @@ const SAMLSSO = () => {
|
||||
|
||||
const teamId = Number(router.query.id);
|
||||
|
||||
const { data: team, isLoading } = trpc.useQuery(["viewer.teams.get", { teamId }], {
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
});
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return <SkeletonLoader />;
|
||||
|
||||
@@ -22,7 +22,7 @@ export default function HelpMenuItem({ onHelpItemSelect }: HelpMenuItemProps) {
|
||||
const [, loadChat] = useChat();
|
||||
const { t } = useLocale();
|
||||
|
||||
const mutation = trpc.useMutation("viewer.submitFeedback", {
|
||||
const mutation = trpc.viewer.submitFeedback.useMutation({
|
||||
onSuccess: () => {
|
||||
setDisableSubmit(true);
|
||||
showToast("Thank you, feedback submitted", "success");
|
||||
|
||||
@@ -7,7 +7,7 @@ import MemberInvitationModal from "@calcom/features/ee/teams/components/MemberIn
|
||||
import { classNames } from "@calcom/lib";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Icon } from "@calcom/ui";
|
||||
import { Avatar, Badge, Button } from "@calcom/ui/components";
|
||||
import { showToast } from "@calcom/ui/v2/core";
|
||||
@@ -17,7 +17,7 @@ const querySchema = z.object({
|
||||
id: z.string().transform((val) => parseInt(val)),
|
||||
});
|
||||
|
||||
type TeamMember = inferQueryOutput<"viewer.teams.get">["members"][number];
|
||||
type TeamMember = RouterOutputs["viewer"]["teams"]["get"]["members"][number];
|
||||
|
||||
type FormValues = {
|
||||
members: TeamMember[];
|
||||
@@ -27,7 +27,7 @@ const AddNewTeamMembers = () => {
|
||||
const session = useSession();
|
||||
const router = useRouter();
|
||||
const { id: teamId } = router.isReady ? querySchema.parse(router.query) : { id: -1 };
|
||||
const teamQuery = trpc.useQuery(["viewer.teams.get", { teamId }], { enabled: router.isReady });
|
||||
const teamQuery = trpc.viewer.teams.get.useQuery({ teamId }, { enabled: router.isReady });
|
||||
if (session.status === "loading" || !teamQuery.data) return <AddNewTeamMemberSkeleton />;
|
||||
|
||||
return <AddNewTeamMembersForm defaultValues={{ members: teamQuery.data.members }} teamId={teamId} />;
|
||||
@@ -38,16 +38,16 @@ const AddNewTeamMembersForm = ({ defaultValues, teamId }: { defaultValues: FormV
|
||||
const [memberInviteModal, setMemberInviteModal] = useState(false);
|
||||
const utils = trpc.useContext();
|
||||
const router = useRouter();
|
||||
const inviteMemberMutation = trpc.useMutation("viewer.teams.inviteMember", {
|
||||
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
setMemberInviteModal(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
showToast(error.message, "error");
|
||||
},
|
||||
});
|
||||
const publishTeamMutation = trpc.useMutation("viewer.teams.publish", {
|
||||
const publishTeamMutation = trpc.viewer.teams.publish.useMutation({
|
||||
onSuccess(data) {
|
||||
router.push(data.url);
|
||||
},
|
||||
@@ -125,9 +125,9 @@ const PendingMemberItem = (props: { member: TeamMember; index: number; teamId: n
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const removeMemberMutation = trpc.useMutation("viewer.teams.removeMember", {
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
showToast("Member removed", "success");
|
||||
},
|
||||
async onError(err) {
|
||||
|
||||
@@ -17,14 +17,14 @@ export const CreateANewTeamForm = () => {
|
||||
const router = useRouter();
|
||||
const newTeamFormMethods = useForm<NewTeamFormValues>();
|
||||
|
||||
const createTeamMutation = trpc.useMutation(["viewer.teams.create"], {
|
||||
const createTeamMutation = trpc.viewer.teams.create.useMutation({
|
||||
onSuccess: (data) => {
|
||||
router.push(`/settings/teams/${data.id}/onboard-members`);
|
||||
},
|
||||
});
|
||||
|
||||
const validateTeamSlugQuery = trpc.useQuery(
|
||||
["viewer.teams.validateTeamSlug", { slug: newTeamFormMethods.watch("slug") }],
|
||||
const validateTeamSlugQuery = trpc.viewer.teams.validateTeamSlug.useQuery(
|
||||
{ slug: newTeamFormMethods.watch("slug") },
|
||||
{
|
||||
enabled: false,
|
||||
refetchOnWindowFocus: false,
|
||||
|
||||
@@ -16,15 +16,15 @@ const DisableTeamImpersonation = ({
|
||||
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const query = trpc.useQuery(["viewer.teams.getMembershipbyUser", { teamId, memberId }]);
|
||||
const query = trpc.viewer.teams.getMembershipbyUser.useQuery({ teamId, memberId });
|
||||
|
||||
const mutation = trpc.useMutation("viewer.teams.updateMembership", {
|
||||
const mutation = trpc.viewer.teams.updateMembership.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("your_user_profile_updated_successfully"), "success");
|
||||
await utils.invalidateQueries(["viewer.teams.getMembershipbyUser"]);
|
||||
await utils.viewer.teams.getMembershipbyUser.invalidate();
|
||||
},
|
||||
async onSettled() {
|
||||
await utils.invalidateQueries(["viewer.public.i18n"]);
|
||||
await utils.viewer.public.i18n.invalidate();
|
||||
},
|
||||
});
|
||||
if (query.isLoading) return <></>;
|
||||
|
||||
@@ -47,9 +47,9 @@ export default function MemberChangeRoleModal(props: {
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const changeRoleMutation = trpc.useMutation("viewer.teams.changeMemberRole", {
|
||||
const changeRoleMutation = trpc.viewer.teams.changeMemberRole.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
props.onExit();
|
||||
},
|
||||
async onError(err) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState } from "react";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
import { Icon } from "@calcom/ui/Icon";
|
||||
import { Button, ButtonGroup, Avatar } from "@calcom/ui/components";
|
||||
@@ -28,8 +28,8 @@ import TeamPill, { TeamRole } from "./TeamPill";
|
||||
import TeamAvailabilityModal from "./v2/TeamAvailabilityModal";
|
||||
|
||||
interface Props {
|
||||
team: inferQueryOutput<"viewer.teams.get">;
|
||||
member: inferQueryOutput<"viewer.teams.get">["members"][number];
|
||||
team: RouterOutputs["viewer"]["teams"]["get"];
|
||||
member: RouterOutputs["viewer"]["teams"]["get"]["members"][number];
|
||||
}
|
||||
|
||||
/** TODO: Migrate the one in apps/web to tRPC package */
|
||||
@@ -45,11 +45,10 @@ export default function MemberListItem(props: Props) {
|
||||
const utils = trpc.useContext();
|
||||
const [showChangeMemberRoleModal, setShowChangeMemberRoleModal] = useState(false);
|
||||
const [showTeamAvailabilityModal, setShowTeamAvailabilityModal] = useState(false);
|
||||
const [showImpersonateModal, setShowImpersonateModal] = useState(false);
|
||||
|
||||
const removeMemberMutation = trpc.useMutation("viewer.teams.removeMember", {
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
showToast(t("success"), "success");
|
||||
},
|
||||
async onError(err) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import Select from "@calcom/ui/form/Select";
|
||||
import TimezoneSelect, { ITimezone } from "@calcom/ui/form/TimezoneSelect";
|
||||
@@ -12,8 +12,8 @@ import LicenseRequired from "../../common/components/LicenseRequired";
|
||||
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
|
||||
|
||||
interface Props {
|
||||
team?: inferQueryOutput<"viewer.teams.get">;
|
||||
member?: inferQueryOutput<"viewer.teams.get">["members"][number];
|
||||
team?: RouterOutputs["viewer"]["teams"]["get"];
|
||||
member?: RouterOutputs["viewer"]["teams"]["get"]["members"][number];
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityModal(props: Props) {
|
||||
@@ -25,7 +25,7 @@ export default function TeamAvailabilityModal(props: Props) {
|
||||
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
|
||||
|
||||
useEffect(() => {
|
||||
utils.invalidateQueries(["viewer.teams.getMemberAvailability"]);
|
||||
utils.viewer.teams.getMemberAvailability.invalidate();
|
||||
}, [utils, selectedTimeZone, selectedDate]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -4,7 +4,7 @@ import { FixedSizeList as List } from "react-window";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import Select from "@calcom/ui/form/Select";
|
||||
import TimezoneSelect, { ITimezone } from "@calcom/ui/form/TimezoneSelect";
|
||||
@@ -13,7 +13,7 @@ import DatePicker from "@calcom/ui/v2/core/form/DatePicker";
|
||||
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
|
||||
|
||||
interface Props {
|
||||
team?: inferQueryOutput<"viewer.teams.get">;
|
||||
team?: RouterOutputs["viewer"]["teams"]["get"];
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityScreen(props: Props) {
|
||||
@@ -25,7 +25,7 @@ export default function TeamAvailabilityScreen(props: Props) {
|
||||
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
|
||||
|
||||
useEffect(() => {
|
||||
utils.invalidateQueries(["viewer.teams.getMemberAvailability"]);
|
||||
utils.viewer.teams.getMemberAvailability.invalidate();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedTimeZone, selectedDate]);
|
||||
|
||||
|
||||
@@ -18,17 +18,14 @@ interface Props {
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityTimes(props: Props) {
|
||||
const { data, isLoading } = trpc.useQuery(
|
||||
[
|
||||
"viewer.teams.getMemberAvailability",
|
||||
{
|
||||
teamId: props.teamId,
|
||||
memberId: props.memberId,
|
||||
dateFrom: props.selectedDate.toString(),
|
||||
dateTo: props.selectedDate.add(1, "day").toString(),
|
||||
timezone: `${props.selectedTimeZone.toString()}`,
|
||||
},
|
||||
],
|
||||
const { data, isLoading } = trpc.viewer.teams.getMemberAvailability.useQuery(
|
||||
{
|
||||
teamId: props.teamId,
|
||||
memberId: props.memberId,
|
||||
dateFrom: props.selectedDate.toString(),
|
||||
dateTo: props.selectedDate.add(1, "day").toString(),
|
||||
timezone: `${props.selectedTimeZone.toString()}`,
|
||||
},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
|
||||
@@ -32,9 +32,9 @@ export default function TeamInviteList(props: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
const deleteTeamMutation = trpc.useMutation("viewer.teams.delete", {
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.list"]);
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
|
||||
@@ -31,10 +31,10 @@ export default function TeamInviteListItem(props: Props) {
|
||||
const utils = trpc.useContext();
|
||||
const team = props.team;
|
||||
|
||||
const acceptOrLeaveMutation = trpc.useMutation("viewer.teams.acceptOrLeave", {
|
||||
const acceptOrLeaveMutation = trpc.viewer.teams.acceptOrLeave.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.invalidateQueries(["viewer.teams.list"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -48,10 +48,7 @@ export default function TeamInviteListItem(props: Props) {
|
||||
const acceptInvite = () => acceptOrLeave(true);
|
||||
const declineInvite = () => acceptOrLeave(false);
|
||||
|
||||
const isOwner = props.team.role === MembershipRole.OWNER;
|
||||
const isInvitee = !props.team.accepted;
|
||||
const isAdmin = props.team.role === MembershipRole.OWNER || props.team.role === MembershipRole.ADMIN;
|
||||
const { hideDropdown, setHideDropdown } = props;
|
||||
|
||||
if (!team) return <></>;
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import showToast from "@calcom/ui/v2/core/notifications";
|
||||
|
||||
import TeamListItem from "./TeamListItem";
|
||||
|
||||
interface Props {
|
||||
teams: inferQueryOutput<"viewer.teams.list">;
|
||||
teams: RouterOutputs["viewer"]["teams"]["list"];
|
||||
}
|
||||
|
||||
export default function TeamList(props: Props) {
|
||||
@@ -22,9 +22,9 @@ export default function TeamList(props: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
const deleteTeamMutation = trpc.useMutation("viewer.teams.delete", {
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.list"]);
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
},
|
||||
async onError(err) {
|
||||
showToast(err.message, "error");
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useRouter } from "next/router";
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/getPlaceholderAvatar";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Icon } from "@calcom/ui/Icon";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
@@ -26,7 +26,7 @@ import Avatar from "@components/ui/Avatar";
|
||||
import { TeamRole } from "./TeamPill";
|
||||
|
||||
interface Props {
|
||||
team: inferQueryOutput<"viewer.teams.list">[number];
|
||||
team: RouterOutputs["viewer"]["teams"]["list"][number];
|
||||
key: number;
|
||||
onActionSelect: (text: string) => void;
|
||||
isLoading?: boolean;
|
||||
@@ -39,9 +39,9 @@ export default function TeamListItem(props: Props) {
|
||||
const utils = trpc.useContext();
|
||||
const team = props.team;
|
||||
|
||||
const acceptOrLeaveMutation = trpc.useMutation("viewer.teams.acceptOrLeave", {
|
||||
const acceptOrLeaveMutation = trpc.viewer.teams.acceptOrLeave.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.invalidateQueries(["viewer.teams.list"]);
|
||||
utils.viewer.teams.list.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -250,7 +250,7 @@ export default function TeamListItem(props: Props) {
|
||||
const TeamPublishButton = ({ teamId }: { teamId: number }) => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
const publishTeamMutation = trpc.useMutation("viewer.teams.publish", {
|
||||
const publishTeamMutation = trpc.viewer.teams.publish.useMutation({
|
||||
onSuccess(data) {
|
||||
router.push(data.url);
|
||||
},
|
||||
|
||||
@@ -15,7 +15,7 @@ export function TeamsListing() {
|
||||
const { t } = useLocale();
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
|
||||
const { data, isLoading } = trpc.useQuery(["viewer.teams.list"], {
|
||||
const { data, isLoading } = trpc.viewer.teams.list.useQuery(undefined, {
|
||||
onError: (e) => {
|
||||
setErrorMessage(e.message);
|
||||
},
|
||||
|
||||
@@ -3,7 +3,7 @@ import React, { useState, useEffect } from "react";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Avatar, Label } from "@calcom/ui/components";
|
||||
import TimezoneSelect, { ITimezone } from "@calcom/ui/form/TimezoneSelect";
|
||||
import { Select, DatePicker } from "@calcom/ui/v2";
|
||||
@@ -12,8 +12,8 @@ import LicenseRequired from "../../../common/components/LicenseRequired";
|
||||
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
|
||||
|
||||
interface Props {
|
||||
team?: inferQueryOutput<"viewer.teams.get">;
|
||||
member?: inferQueryOutput<"viewer.teams.get">["members"][number];
|
||||
team?: RouterOutputs["viewer"]["teams"]["get"];
|
||||
member?: RouterOutputs["viewer"]["teams"]["get"]["members"][number];
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityModal(props: Props) {
|
||||
@@ -28,7 +28,7 @@ export default function TeamAvailabilityModal(props: Props) {
|
||||
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
|
||||
|
||||
useEffect(() => {
|
||||
utils.invalidateQueries(["viewer.teams.getMemberAvailability"]);
|
||||
utils.viewer.teams.getMemberAvailability.invalidate();
|
||||
}, [utils, selectedTimeZone, selectedDate]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -4,7 +4,7 @@ import { FixedSizeList as List } from "react-window";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import Select from "@calcom/ui/form/Select";
|
||||
import TimezoneSelect, { ITimezone } from "@calcom/ui/form/TimezoneSelect";
|
||||
@@ -13,7 +13,7 @@ import DatePicker from "@calcom/ui/v2/core/form/DatePicker";
|
||||
import TeamAvailabilityTimes from "./TeamAvailabilityTimes";
|
||||
|
||||
interface Props {
|
||||
team?: inferQueryOutput<"viewer.teams.get">;
|
||||
team?: RouterOutputs["viewer"]["teams"]["get"];
|
||||
}
|
||||
|
||||
export default function TeamAvailabilityScreen(props: Props) {
|
||||
@@ -25,7 +25,7 @@ export default function TeamAvailabilityScreen(props: Props) {
|
||||
const [frequency, setFrequency] = useState<15 | 30 | 60>(30);
|
||||
|
||||
useEffect(() => {
|
||||
utils.invalidateQueries(["viewer.teams.getMemberAvailability"]);
|
||||
utils.viewer.teams.getMemberAvailability.invalidate();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedTimeZone, selectedDate]);
|
||||
|
||||
|
||||
@@ -22,17 +22,14 @@ interface Props {
|
||||
export default function TeamAvailabilityTimes(props: Props) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const { data, isLoading } = trpc.useQuery(
|
||||
[
|
||||
"viewer.teams.getMemberAvailability",
|
||||
{
|
||||
teamId: props.teamId,
|
||||
memberId: props.memberId,
|
||||
dateFrom: props.selectedDate.toString(),
|
||||
dateTo: props.selectedDate.add(1, "day").toString(),
|
||||
timezone: `${props.selectedTimeZone.toString()}`,
|
||||
},
|
||||
],
|
||||
const { data, isLoading } = trpc.viewer.teams.getMemberAvailability.useQuery(
|
||||
{
|
||||
teamId: props.teamId,
|
||||
memberId: props.memberId,
|
||||
dateFrom: props.selectedDate.toString(),
|
||||
dateTo: props.selectedDate.add(1, "day").toString(),
|
||||
timezone: `${props.selectedTimeZone.toString()}`,
|
||||
},
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
|
||||
@@ -22,12 +22,15 @@ export function TeamAvailabilityPage() {
|
||||
const me = useMeQuery();
|
||||
const isFreeUser = me.data?.plan === "FREE";
|
||||
|
||||
const { data: team, isLoading } = trpc.useQuery(["viewer.teams.get", { teamId: Number(router.query.id) }], {
|
||||
refetchOnWindowFocus: false,
|
||||
onError: (e) => {
|
||||
setErrorMessage(e.message);
|
||||
},
|
||||
});
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(router.query.id) },
|
||||
{
|
||||
refetchOnWindowFocus: false,
|
||||
onError: (e) => {
|
||||
setErrorMessage(e.message);
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// prevent unnecessary re-renders due to shell queries
|
||||
const TeamAvailability = useMemo(() => {
|
||||
|
||||
@@ -18,28 +18,31 @@ const ProfileView = () => {
|
||||
const router = useRouter();
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const mutation = trpc.useMutation("viewer.teams.update", {
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm<TeamAppearanceValues>();
|
||||
|
||||
const { data: team, isLoading } = trpc.useQuery(["viewer.teams.get", { teamId: Number(router.query.id) }], {
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
onSuccess: (team) => {
|
||||
if (team) {
|
||||
form.setValue("hideBranding", team.hideBranding);
|
||||
}
|
||||
},
|
||||
});
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(router.query.id) },
|
||||
{
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
onSuccess: (team) => {
|
||||
if (team) {
|
||||
form.setValue("hideBranding", team.hideBranding);
|
||||
}
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const isAdmin =
|
||||
team && (team.membership.role === MembershipRole.OWNER || team.membership.role === MembershipRole.ADMIN);
|
||||
|
||||
@@ -24,15 +24,18 @@ const MembersView = () => {
|
||||
const [showMemberInvitationModal, setShowMemberInvitationModal] = useState(false);
|
||||
const teamId = Number(router.query.id);
|
||||
|
||||
const { data: team, isLoading } = trpc.useQuery(["viewer.teams.get", { teamId }], {
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
});
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId },
|
||||
{
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const inviteMemberMutation = trpc.useMutation("viewer.teams.inviteMember", {
|
||||
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
setShowMemberInvitationModal(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
|
||||
@@ -32,50 +32,53 @@ const ProfileView = () => {
|
||||
const utils = trpc.useContext();
|
||||
const session = useSession();
|
||||
|
||||
const mutation = trpc.useMutation("viewer.teams.update", {
|
||||
const mutation = trpc.viewer.teams.update.useMutation({
|
||||
onError: (err) => {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
|
||||
const form = useForm<TeamProfileValues>();
|
||||
|
||||
const { data: team, isLoading } = trpc.useQuery(["viewer.teams.get", { teamId: Number(router.query.id) }], {
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
onSuccess: (team) => {
|
||||
if (team) {
|
||||
form.setValue("name", team.name || "");
|
||||
form.setValue("url", team.slug || "");
|
||||
form.setValue("logo", team.logo || "");
|
||||
form.setValue("bio", team.bio || "");
|
||||
}
|
||||
},
|
||||
});
|
||||
const { data: team, isLoading } = trpc.viewer.teams.get.useQuery(
|
||||
{ teamId: Number(router.query.id) },
|
||||
{
|
||||
onError: () => {
|
||||
router.push("/settings");
|
||||
},
|
||||
onSuccess: (team) => {
|
||||
if (team) {
|
||||
form.setValue("name", team.name || "");
|
||||
form.setValue("url", team.slug || "");
|
||||
form.setValue("logo", team.logo || "");
|
||||
form.setValue("bio", team.bio || "");
|
||||
}
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const isAdmin =
|
||||
team && (team.membership.role === MembershipRole.OWNER || team.membership.role === MembershipRole.ADMIN);
|
||||
|
||||
const permalink = `${process.env.NEXT_PUBLIC_WEBSITE_URL}/team/${team?.slug}`;
|
||||
|
||||
const deleteTeamMutation = trpc.useMutation("viewer.teams.delete", {
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.invalidateQueries(["viewer.teams.list"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
showToast(t("your_team_disbanded_successfully"), "success");
|
||||
router.push(`${WEBAPP_URL}/teams`);
|
||||
},
|
||||
});
|
||||
|
||||
const removeMemberMutation = trpc.useMutation("viewer.teams.removeMember", {
|
||||
const removeMemberMutation = trpc.viewer.teams.removeMember.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.invalidateQueries(["viewer.teams.list"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
await utils.viewer.teams.list.invalidate();
|
||||
showToast(t("success"), "success");
|
||||
},
|
||||
async onError(err) {
|
||||
|
||||
@@ -62,7 +62,7 @@ export function NewWorkflowButton() {
|
||||
resolver: zodResolver(formSchema),
|
||||
});
|
||||
|
||||
const createMutation = trpc.useMutation("viewer.workflows.create", {
|
||||
const createMutation = trpc.viewer.workflows.create.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
await router.replace("/workflows/" + workflow.id);
|
||||
setIsPhoneNumberNeeded(false);
|
||||
|
||||
@@ -33,7 +33,7 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
const [reload, setReload] = useState(false);
|
||||
const [editCounter, setEditCounter] = useState(0);
|
||||
|
||||
const { data, isLoading } = trpc.useQuery(["viewer.eventTypes"]);
|
||||
const { data, isLoading } = trpc.viewer.eventTypes.getByViewer.useQuery();
|
||||
|
||||
const eventTypeOptions = useMemo(
|
||||
() =>
|
||||
@@ -50,10 +50,10 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
[data]
|
||||
);
|
||||
|
||||
const updateMutation = trpc.useMutation("viewer.workflows.update", {
|
||||
const updateMutation = trpc.viewer.workflows.update.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
if (workflow) {
|
||||
utils.setQueryData(["viewer.workflows.get", { id: +workflow.id }], workflow);
|
||||
utils.viewer.workflows.get.setData({ id: +workflow.id }, workflow);
|
||||
|
||||
showToast(
|
||||
t("workflow_updated_successfully", {
|
||||
@@ -95,6 +95,7 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
reminderBody: null,
|
||||
emailSubject: null,
|
||||
template: WorkflowTemplates.REMINDER,
|
||||
numberRequired: null,
|
||||
};
|
||||
steps?.push(step);
|
||||
form.setValue("steps", steps);
|
||||
|
||||
@@ -35,11 +35,11 @@ export default function WorkflowListPage({ workflows }: Props) {
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [deleteDialogTypeId, setDeleteDialogTypeId] = useState(0);
|
||||
|
||||
const query = trpc.useQuery(["viewer.workflows.list"]);
|
||||
const query = trpc.viewer.workflows.list.useQuery();
|
||||
|
||||
const deleteMutation = trpc.useMutation("viewer.workflows.delete", {
|
||||
const deleteMutation = trpc.viewer.workflows.delete.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.invalidateQueries(["viewer.workflows.list"]);
|
||||
await utils.viewer.workflows.list.invalidate();
|
||||
showToast(t("workflow_deleted_successfully"), "success");
|
||||
setDeleteDialogOpen(false);
|
||||
},
|
||||
|
||||
@@ -122,7 +122,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const testActionMutation = trpc.useMutation("viewer.workflows.testAction", {
|
||||
const testActionMutation = trpc.viewer.workflows.testAction.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("notification_sent"), "success");
|
||||
},
|
||||
|
||||
@@ -19,9 +19,9 @@ export const DeleteDialog = (props: IDeleteDialog) => {
|
||||
const { isOpenDialog, setIsOpenDialog, workflowId, additionalFunction } = props;
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const deleteMutation = trpc.useMutation("viewer.workflows.delete", {
|
||||
const deleteMutation = trpc.viewer.workflows.delete.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.invalidateQueries(["viewer.workflows.list"]);
|
||||
await utils.viewer.workflows.list.invalidate();
|
||||
additionalFunction();
|
||||
showToast(t("workflow_deleted_successfully"), "success");
|
||||
setIsOpenDialog(false);
|
||||
|
||||
@@ -38,7 +38,7 @@ const WorkflowListItem = (props: ItemProps) => {
|
||||
|
||||
const isActive = activeEventTypeIds.includes(eventType.id);
|
||||
|
||||
const activateEventTypeMutation = trpc.useMutation("viewer.workflows.activateEventType", {
|
||||
const activateEventTypeMutation = trpc.viewer.workflows.activateEventType.useMutation({
|
||||
onSuccess: async () => {
|
||||
let offOn = "";
|
||||
if (activeEventTypeIds.includes(eventType.id)) {
|
||||
@@ -158,7 +158,7 @@ type Props = {
|
||||
function EventWorkflowsTab(props: Props) {
|
||||
const { workflows } = props;
|
||||
const { t } = useLocale();
|
||||
const { data, isLoading } = trpc.useQuery(["viewer.workflows.list"]);
|
||||
const { data, isLoading } = trpc.viewer.workflows.list.useQuery();
|
||||
const router = useRouter();
|
||||
const [sortedWorkflows, setSortedWorkflows] = useState<Array<WorkflowType>>([]);
|
||||
|
||||
@@ -179,7 +179,7 @@ function EventWorkflowsTab(props: Props) {
|
||||
}
|
||||
}, [isLoading]);
|
||||
|
||||
const createMutation = trpc.useMutation("viewer.workflows.createV2", {
|
||||
const createMutation = trpc.viewer.workflows.createV2.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
await router.replace("/workflows/" + workflow.id);
|
||||
},
|
||||
|
||||
@@ -34,7 +34,7 @@ export default function WorkflowDetailsPage(props: Props) {
|
||||
const [reload, setReload] = useState(false);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
|
||||
const { data, isLoading } = trpc.useQuery(["viewer.eventTypes"]);
|
||||
const { data, isLoading } = trpc.viewer.eventTypes.getByViewer.useQuery();
|
||||
|
||||
const eventTypeOptions = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -26,7 +26,7 @@ const CreateEmptyWorkflowView = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const createMutation = trpc.useMutation("viewer.workflows.createV2", {
|
||||
const createMutation = trpc.viewer.workflows.createV2.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
await router.replace("/workflows/" + workflow.id);
|
||||
},
|
||||
@@ -208,7 +208,7 @@ export default function WorkflowListPage({ workflows }: Props) {
|
||||
setIsOpenDialog={setDeleteDialogOpen}
|
||||
workflowId={workflowToDeleteId}
|
||||
additionalFunction={async () => {
|
||||
await utils.invalidateQueries(["viewer.workflows.list"]);
|
||||
await utils.viewer.workflows.list.invalidate();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -113,7 +113,7 @@ export default function WorkflowStepContainer(props: WorkflowStepProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const testActionMutation = trpc.useMutation("viewer.workflows.testAction", {
|
||||
const testActionMutation = trpc.viewer.workflows.testAction.useMutation({
|
||||
onSuccess: async () => {
|
||||
showToast(t("notification_sent"), "success");
|
||||
},
|
||||
|
||||
@@ -19,7 +19,7 @@ function WorkflowsPage() {
|
||||
const me = useMeQuery();
|
||||
const isFreeUser = me.data?.plan === "FREE";
|
||||
|
||||
const { data, isLoading } = trpc.useQuery(["viewer.workflows.list"]);
|
||||
const { data, isLoading } = trpc.viewer.workflows.list.useQuery();
|
||||
|
||||
return (
|
||||
<Shell
|
||||
|
||||
@@ -19,9 +19,9 @@ function WorkflowsPage() {
|
||||
const session = useSession();
|
||||
const router = useRouter();
|
||||
|
||||
const { data, isLoading } = trpc.useQuery(["viewer.workflows.list"]);
|
||||
const { data, isLoading } = trpc.viewer.workflows.list.useQuery();
|
||||
|
||||
const createMutation = trpc.useMutation("viewer.workflows.createV2", {
|
||||
const createMutation = trpc.viewer.workflows.createV2.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
await router.replace("/workflows/" + workflow.id);
|
||||
},
|
||||
|
||||
@@ -86,9 +86,12 @@ function WorkflowPage() {
|
||||
data: workflow,
|
||||
isError,
|
||||
error,
|
||||
} = trpc.useQuery(["viewer.workflows.get", { id: +workflowId }], {
|
||||
enabled: router.isReady && !!workflowId,
|
||||
});
|
||||
} = trpc.viewer.workflows.get.useQuery(
|
||||
{ id: +workflowId },
|
||||
{
|
||||
enabled: router.isReady && !!workflowId,
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (workflow) {
|
||||
@@ -133,10 +136,10 @@ function WorkflowPage() {
|
||||
}
|
||||
}, [workflow]);
|
||||
|
||||
const updateMutation = trpc.useMutation("viewer.workflows.update", {
|
||||
const updateMutation = trpc.viewer.workflows.update.useMutation({
|
||||
onSuccess: async ({ workflow }) => {
|
||||
if (workflow) {
|
||||
utils.setQueryData(["viewer.workflows.get", { id: +workflow.id }], workflow);
|
||||
utils.viewer.workflows.get.setData({ id: +workflow.id }, workflow);
|
||||
|
||||
showToast(
|
||||
t("workflow_updated_successfully", {
|
||||
|
||||
@@ -83,9 +83,12 @@ function WorkflowPage() {
|
||||
isError,
|
||||
error,
|
||||
dataUpdatedAt,
|
||||
} = trpc.useQuery(["viewer.workflows.get", { id: +workflowId }], {
|
||||
enabled: router.isReady && !!workflowId,
|
||||
});
|
||||
} = trpc.viewer.workflows.get.useQuery(
|
||||
{ id: +workflowId },
|
||||
{
|
||||
enabled: router.isReady && !!workflowId,
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (workflow && !form.getValues("name")) {
|
||||
|
||||
@@ -20,11 +20,11 @@ export function NewScheduleButton({ name = "new-schedule" }: { name?: string })
|
||||
const { register } = form;
|
||||
const utils = trpc.useContext();
|
||||
|
||||
const createMutation = trpc.useMutation("viewer.availability.schedule.create", {
|
||||
const createMutation = trpc.viewer.availability.schedule.create.useMutation({
|
||||
onSuccess: async ({ schedule }) => {
|
||||
await router.push("/availability/" + schedule.id);
|
||||
showToast(t("schedule_created_successfully", { scheduleName: schedule.name }), "success");
|
||||
utils.setQueryData(["viewer.availability.list"], (data) => {
|
||||
utils.viewer.availability.list.setData(undefined, (data) => {
|
||||
const newSchedule = { ...schedule, isDefault: false, availability: [] };
|
||||
if (!data)
|
||||
return {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Fragment } from "react";
|
||||
import { availabilityAsString } from "@calcom/lib/availability";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Availability } from "@calcom/prisma/client";
|
||||
import { inferQueryOutput } from "@calcom/trpc/react";
|
||||
import { RouterOutputs } from "@calcom/trpc/react";
|
||||
import Dropdown, { DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@calcom/ui/Dropdown";
|
||||
import { Icon } from "@calcom/ui/Icon";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
@@ -15,7 +15,7 @@ export function ScheduleListItem({
|
||||
deleteFunction,
|
||||
displayOptions,
|
||||
}: {
|
||||
schedule: inferQueryOutput<"viewer.availability.list">["schedules"][number];
|
||||
schedule: RouterOutputs["viewer"]["availability"]["list"]["schedules"][number];
|
||||
deleteFunction: ({ scheduleId }: { scheduleId: number }) => void;
|
||||
displayOptions?: {
|
||||
timeZone?: string;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Controller, useForm } from "react-hook-form";
|
||||
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput } from "@calcom/trpc/react";
|
||||
import { RouterOutputs } from "@calcom/trpc/react";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Form, Label, TextArea, TextField } from "@calcom/ui/components/form";
|
||||
import Switch from "@calcom/ui/v2/core/Switch";
|
||||
@@ -14,7 +14,7 @@ import Select from "@calcom/ui/v2/core/form/select";
|
||||
import customTemplate, { hasTemplateIntegration } from "../lib/integrationTemplate";
|
||||
import WebhookTestDisclosure from "./WebhookTestDisclosure";
|
||||
|
||||
export type TWebhook = inferQueryOutput<"viewer.webhook.list">[number];
|
||||
export type TWebhook = RouterOutputs["viewer"]["webhook"]["list"][number];
|
||||
|
||||
export type WebhookFormData = {
|
||||
id?: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { inferQueryOutput, trpc } from "@calcom/trpc/react";
|
||||
import { RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import { Icon } from "@calcom/ui/Icon";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
@@ -8,7 +8,7 @@ import Switch from "@calcom/ui/v2/core/Switch";
|
||||
import { Tooltip } from "@calcom/ui/v2/core/Tooltip";
|
||||
import showToast from "@calcom/ui/v2/core/notifications";
|
||||
|
||||
export type TWebhook = inferQueryOutput<"viewer.webhook.list">[number];
|
||||
export type TWebhook = RouterOutputs["viewer"]["webhook"]["list"][number];
|
||||
|
||||
export default function WebhookListItem(props: {
|
||||
webhook: TWebhook;
|
||||
@@ -18,16 +18,16 @@ export default function WebhookListItem(props: {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const { webhook } = props;
|
||||
const deleteWebhook = trpc.useMutation("viewer.webhook.delete", {
|
||||
const deleteWebhook = trpc.viewer.webhook.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.webhook.list"]);
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
showToast(t("webhook_removed_successfully"), "success");
|
||||
},
|
||||
});
|
||||
const toggleWebhook = trpc.useMutation("viewer.webhook.edit", {
|
||||
const toggleWebhook = trpc.viewer.webhook.edit.useMutation({
|
||||
async onSuccess(data) {
|
||||
console.log("data", data);
|
||||
await utils.invalidateQueries(["viewer.webhook.list"]);
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
// TODO: Better success message
|
||||
showToast(t(data?.active ? "enabled" : "disabled"), "success");
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ export default function WebhookTestDisclosure() {
|
||||
const subscriberUrl: string = useWatch({ name: "subscriberUrl" });
|
||||
const payloadTemplate = useWatch({ name: "payloadTemplate" }) || null;
|
||||
const { t } = useLocale();
|
||||
const mutation = trpc.useMutation("viewer.webhook.testTrigger", {
|
||||
const mutation = trpc.viewer.webhook.testTrigger.useMutation({
|
||||
onError(err) {
|
||||
showToast(err.message, "error");
|
||||
},
|
||||
|
||||
@@ -18,24 +18,27 @@ const EditWebhook = () => {
|
||||
const router = useRouter();
|
||||
|
||||
function Component({ webhookId }: { webhookId: string }) {
|
||||
const { data: installedApps, isLoading } = trpc.useQuery(
|
||||
["viewer.integrations", { variant: "other", onlyInstalled: true }],
|
||||
const { data: installedApps, isLoading } = trpc.viewer.integrations.useQuery(
|
||||
{ variant: "other", onlyInstalled: true },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
}
|
||||
);
|
||||
const { data: webhook } = trpc.useQuery(["viewer.webhook.get", { webhookId }], {
|
||||
const { data: webhook } = trpc.viewer.webhook.get.useQuery(
|
||||
{ webhookId },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
}
|
||||
);
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery(undefined, {
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
});
|
||||
const { data: webhooks } = trpc.useQuery(["viewer.webhook.list"], {
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
});
|
||||
const editWebhookMutation = trpc.useMutation("viewer.webhook.edit", {
|
||||
const editWebhookMutation = trpc.viewer.webhook.edit.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.webhook.list"]);
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
showToast(t("webhook_updated_successfully"), "success");
|
||||
router.back();
|
||||
},
|
||||
|
||||
@@ -13,22 +13,22 @@ const NewWebhookView = () => {
|
||||
const { t } = useLocale();
|
||||
const utils = trpc.useContext();
|
||||
const router = useRouter();
|
||||
const { data: installedApps, isLoading } = trpc.useQuery(
|
||||
["viewer.integrations", { variant: "other", onlyInstalled: true }],
|
||||
const { data: installedApps, isLoading } = trpc.viewer.integrations.useQuery(
|
||||
{ variant: "other", onlyInstalled: true },
|
||||
{
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
}
|
||||
);
|
||||
const { data: webhooks } = trpc.useQuery(["viewer.webhook.list"], {
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery(undefined, {
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
});
|
||||
|
||||
const createWebhookMutation = trpc.useMutation("viewer.webhook.create", {
|
||||
const createWebhookMutation = trpc.viewer.webhook.create.useMutation({
|
||||
async onSuccess() {
|
||||
showToast(t("webhook_created_successfully"), "success");
|
||||
await utils.invalidateQueries(["viewer.webhook.list"]);
|
||||
await utils.viewer.webhook.list.invalidate();
|
||||
router.back();
|
||||
},
|
||||
onError(error) {
|
||||
|
||||
@@ -45,7 +45,7 @@ const WebhooksList = () => {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const { data: webhooks } = trpc.useQuery(["viewer.webhook.list"], {
|
||||
const { data: webhooks } = trpc.viewer.webhook.list.useQuery(undefined, {
|
||||
suspense: true,
|
||||
enabled: router.isReady,
|
||||
});
|
||||
|
||||
@@ -5,7 +5,10 @@ import { trpc } from "@calcom/trpc/react";
|
||||
export default function useApp(appId: string) {
|
||||
const { status } = useSession();
|
||||
|
||||
return trpc.useQuery(["viewer.appById", { appId }], {
|
||||
enabled: status === "authenticated",
|
||||
});
|
||||
return trpc.viewer.appById.useQuery(
|
||||
{ appId },
|
||||
{
|
||||
enabled: status === "authenticated",
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -7,10 +7,10 @@
|
||||
"main": "index.ts",
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^4.3.9",
|
||||
"@trpc/client": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/next": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/react": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/server": "^10.0.0-proxy-beta.5",
|
||||
"@trpc/client": "^10.0.0-rc.6",
|
||||
"@trpc/next": "^10.0.0-rc.6",
|
||||
"@trpc/react-query": "^10.0.0-rc.6",
|
||||
"@trpc/server": "^10.0.0-rc.6",
|
||||
"superjson": "1.9.1",
|
||||
"zod": "^3.19.1"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { trpc } from "../trpc";
|
||||
|
||||
export function useMeQuery() {
|
||||
const meQuery = trpc.useQuery(["viewer.me"], {
|
||||
const meQuery = trpc.viewer.me.useQuery(undefined, {
|
||||
retry(failureCount) {
|
||||
return failureCount > 3;
|
||||
},
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export * from "@trpc/react";
|
||||
export * from "@trpc/react-query";
|
||||
export * from "./trpc";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@trpc/react-query/shared";
|
||||
@@ -1 +1 @@
|
||||
export * from "@trpc/react/ssg";
|
||||
export * from "@trpc/react-query/ssg";
|
||||
@@ -1,36 +1,19 @@
|
||||
import superjson from "superjson";
|
||||
|
||||
import { createReactQueryHooks } from "@trpc/react";
|
||||
import { createTRPCReact } from "@trpc/react-query";
|
||||
|
||||
// ℹ️ Type-only import:
|
||||
// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export
|
||||
import type { inferProcedureInput, inferProcedureOutput } from "../server";
|
||||
import type { inferRouterInputs, inferRouterOutputs } from "../server";
|
||||
import type { AppRouter } from "../server/routers/_app";
|
||||
|
||||
/**
|
||||
* A set of strongly-typed React hooks from your `AppRouter` type signature with `createReactQueryHooks`.
|
||||
* @link https://trpc.io/docs/react#3-create-trpc-hooks
|
||||
* A set of strongly-typed React hooks from your `AppRouter` type signature with `createTRPCReact`.
|
||||
* @link https://trpc.io/docs/v10/react#2-create-trpc-hooks
|
||||
*/
|
||||
export const trpc = createReactQueryHooks<AppRouter>();
|
||||
|
||||
export const proxy = trpc.proxy;
|
||||
export const trpc = createTRPCReact<AppRouter>();
|
||||
|
||||
export const transformer = superjson;
|
||||
/**
|
||||
* This is a helper method to infer the output of a query resolver
|
||||
* @example type HelloOutput = inferQueryOutput<'hello'>
|
||||
*/
|
||||
export type inferQueryOutput<TRouteKey extends keyof AppRouter["_def"]["queries"]> = inferProcedureOutput<
|
||||
AppRouter["_def"]["queries"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferQueryInput<TRouteKey extends keyof AppRouter["_def"]["queries"]> = inferProcedureInput<
|
||||
AppRouter["_def"]["queries"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferMutationInput<TRouteKey extends keyof AppRouter["_def"]["mutations"]> = inferProcedureInput<
|
||||
AppRouter["_def"]["mutations"][TRouteKey]
|
||||
>;
|
||||
|
||||
export type inferMutationOutput<TRouteKey extends keyof AppRouter["_def"]["mutations"]> =
|
||||
inferProcedureOutput<AppRouter["_def"]["mutations"][TRouteKey]>;
|
||||
export type RouterInputs = inferRouterInputs<AppRouter>;
|
||||
export type RouterOutputs = inferRouterOutputs<AppRouter>;
|
||||
@@ -1,38 +0,0 @@
|
||||
import { performance } from "@calcom/lib/server/perfObserver";
|
||||
|
||||
import * as trpc from "@trpc/server";
|
||||
|
||||
import { Context } from "./createContext";
|
||||
|
||||
/**
|
||||
* Helper function to create a router with context
|
||||
* @deprecated
|
||||
*/
|
||||
export function createRouter() {
|
||||
return trpc.router<Context>().middleware(async ({ path, type, next }) => {
|
||||
performance.mark("Start");
|
||||
const result = await next();
|
||||
performance.mark("End");
|
||||
performance.measure(`[${result.ok ? "OK" : "ERROR"}][$1] ${type} '${path}'`, "Start", "End");
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
export function createProtectedRouter() {
|
||||
return createRouter().middleware(({ ctx, next }) => {
|
||||
if (!ctx.user || !ctx.session) {
|
||||
throw new trpc.TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return next({
|
||||
ctx: {
|
||||
...ctx,
|
||||
// infers that `user` and `session` are non-nullable to downstream procedures
|
||||
session: ctx.session,
|
||||
user: ctx.user,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
/**
|
||||
* This file contains the root router of your tRPC-backend
|
||||
*/
|
||||
import { createRouter } from "../createRouter";
|
||||
import { publicProcedure, t } from "../trpc";
|
||||
import { publicRouter } from "./public";
|
||||
import { router } from "../trpc";
|
||||
import { viewerRouter } from "./viewer";
|
||||
|
||||
/**
|
||||
@@ -11,22 +9,9 @@ import { viewerRouter } from "./viewer";
|
||||
* If you want to use SSG, you need export this
|
||||
* @link https://trpc.io/docs/ssg
|
||||
* @link https://trpc.io/docs/router
|
||||
* @deprecated
|
||||
*/
|
||||
export const legacyRouter = createRouter()
|
||||
/**
|
||||
* Optionally do custom error (type safe!) formatting
|
||||
* @link https://trpc.io/docs/error-formatting
|
||||
*/
|
||||
// .formatError(({ shape, error }) => { })
|
||||
.merge("viewer.", viewerRouter)
|
||||
.interop();
|
||||
|
||||
const v10Router = t.router({
|
||||
hello: publicProcedure.query(() => "hello"),
|
||||
public: publicRouter,
|
||||
export const appRouter = router({
|
||||
viewer: viewerRouter,
|
||||
});
|
||||
|
||||
export const appRouter = t.mergeRouters(legacyRouter, v10Router);
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
@@ -1,5 +0,0 @@
|
||||
import { t, publicProcedure } from "../trpc";
|
||||
|
||||
export const publicRouter = t.router({
|
||||
session: publicProcedure.query(({ ctx }) => ctx.session),
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,34 +3,34 @@ import { z } from "zod";
|
||||
|
||||
import { generateUniqueAPIKey } from "@calcom/features/ee/api-keys/lib/apiKeys";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const apiKeysRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
OR: [
|
||||
{
|
||||
NOT: {
|
||||
appId: "zapier",
|
||||
},
|
||||
export const apiKeysRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.prisma.apiKey.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
OR: [
|
||||
{
|
||||
NOT: {
|
||||
appId: "zapier",
|
||||
},
|
||||
{
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("findKeyOfType", {
|
||||
input: z.object({
|
||||
appId: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
},
|
||||
{
|
||||
appId: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}),
|
||||
findKeyOfType: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
appId: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return await ctx.prisma.apiKey.findFirst({
|
||||
where: {
|
||||
AND: [
|
||||
@@ -43,16 +43,17 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional().nullable(),
|
||||
neverExpires: z.boolean().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional().nullable(),
|
||||
neverExpires: z.boolean().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const [hashedApiKey, apiKey] = generateUniqueAPIKey();
|
||||
// Here we snap never expires before deleting it so it's not passed to prisma create call.
|
||||
const neverExpires = input.neverExpires;
|
||||
@@ -69,15 +70,16 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
});
|
||||
const prefixedApiKey = `${process.env.API_KEY_PREFIX ?? "cal_"}${apiKey}`;
|
||||
return prefixedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("edit", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
edit: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
note: z.string().optional().nullish(),
|
||||
expiresAt: z.date().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...data } = input;
|
||||
const {
|
||||
apiKeys: [updatedApiKey],
|
||||
@@ -104,14 +106,15 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
},
|
||||
});
|
||||
return updatedApiKey;
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
|
||||
const apiKeyToDelete = await ctx.prisma.apiKey.findFirst({
|
||||
@@ -145,5 +148,5 @@ export const apiKeysRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -6,15 +6,17 @@ import prisma from "@calcom/prisma";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const authRouter = createProtectedRouter()
|
||||
.mutation("changePassword", {
|
||||
input: z.object({
|
||||
oldPassword: z.string(),
|
||||
newPassword: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
export const authRouter = router({
|
||||
changePassword: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
oldPassword: z.string(),
|
||||
newPassword: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { oldPassword, newPassword } = input;
|
||||
|
||||
const { user } = ctx;
|
||||
@@ -60,13 +62,14 @@ export const authRouter = createProtectedRouter()
|
||||
password: hashedPassword,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("verifyPassword", {
|
||||
input: z.object({
|
||||
passwordInput: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
verifyPassword: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
passwordInput: z.string(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
@@ -84,5 +87,5 @@ export const authRouter = createProtectedRouter()
|
||||
}
|
||||
|
||||
return;
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -9,284 +9,290 @@ import { Schedule } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const availabilityRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const { prisma, user } = ctx;
|
||||
export const availabilityRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
const { prisma, user } = ctx;
|
||||
|
||||
const schedules = await prisma.schedule.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
const schedules = await prisma.schedule.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
|
||||
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
|
||||
const defaultScheduleId = await getDefaultScheduleId(user.id, prisma);
|
||||
|
||||
return {
|
||||
schedules: schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
isDefault: schedule.id === defaultScheduleId,
|
||||
})),
|
||||
};
|
||||
},
|
||||
})
|
||||
.query("schedule", {
|
||||
input: z.object({
|
||||
scheduleId: z.optional(z.number()),
|
||||
return {
|
||||
schedules: schedules.map((schedule) => ({
|
||||
...schedule,
|
||||
isDefault: schedule.id === defaultScheduleId,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
user: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
username: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
eventTypeId: stringOrNumber.optional(),
|
||||
withSource: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.query(({ input }) => {
|
||||
return getUserAvailability(input);
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId || (await getDefaultScheduleId(user.id, prisma)),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
schedule: router({
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
scheduleId: z.optional(z.number()),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { prisma, user } = ctx;
|
||||
const schedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId || (await getDefaultScheduleId(user.id, prisma)),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = convertScheduleToAvailability(schedule);
|
||||
return {
|
||||
schedule,
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.query("user", {
|
||||
input: z.object({
|
||||
username: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
eventTypeId: stringOrNumber.optional(),
|
||||
withSource: z.boolean().optional(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
return getUserAvailability(input);
|
||||
},
|
||||
})
|
||||
.mutation("schedule.create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
copyScheduleId: z.number().optional(),
|
||||
schedule: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
)
|
||||
.optional(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const data: Prisma.ScheduleCreateInput = {
|
||||
name: input.name,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
if (!schedule || schedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
const availability = convertScheduleToAvailability(schedule);
|
||||
return {
|
||||
schedule,
|
||||
availability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: !input.scheduleId || user.defaultScheduleId === schedule.id,
|
||||
};
|
||||
}),
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
copyScheduleId: z.number().optional(),
|
||||
schedule: z
|
||||
.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
)
|
||||
.optional(),
|
||||
eventTypeId: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
const data: Prisma.ScheduleCreateInput = {
|
||||
name: input.name,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
// If an eventTypeId is provided then connect the new schedule to that event type
|
||||
...(input.eventTypeId && { eventType: { connect: { id: input.eventTypeId } } }),
|
||||
};
|
||||
// If an eventTypeId is provided then connect the new schedule to that event type
|
||||
...(input.eventTypeId && { eventType: { connect: { id: input.eventTypeId } } }),
|
||||
};
|
||||
|
||||
const availability = getAvailabilityFromSchedule(input.schedule || DEFAULT_SCHEDULE);
|
||||
data.availability = {
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
const availability = getAvailabilityFromSchedule(input.schedule || DEFAULT_SCHEDULE);
|
||||
data.availability = {
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
const schedule = await prisma.schedule.create({
|
||||
data,
|
||||
});
|
||||
const hasDefaultScheduleId = await hasDefaultSchedule(user, prisma);
|
||||
if (!hasDefaultScheduleId) {
|
||||
await setupDefaultSchedule(user.id, schedule.id, prisma);
|
||||
}
|
||||
const schedule = await prisma.schedule.create({
|
||||
data,
|
||||
});
|
||||
const hasDefaultScheduleId = await hasDefaultSchedule(user, prisma);
|
||||
if (!hasDefaultScheduleId) {
|
||||
await setupDefaultSchedule(user.id, schedule.id, prisma);
|
||||
}
|
||||
|
||||
return { schedule };
|
||||
},
|
||||
})
|
||||
.mutation("schedule.delete", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
return { schedule };
|
||||
}),
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
scheduleId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
|
||||
const scheduleToDelete = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (scheduleToDelete?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (user.defaultScheduleId === input.scheduleId) {
|
||||
// set a new default or unset default if no other schedule
|
||||
const scheduleToSetAsDefault = await prisma.schedule.findFirst({
|
||||
const scheduleToDelete = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
NOT: {
|
||||
id: input.scheduleId,
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (scheduleToDelete?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (user.defaultScheduleId === input.scheduleId) {
|
||||
// set a new default or unset default if no other schedule
|
||||
const scheduleToSetAsDefault = await prisma.schedule.findFirst({
|
||||
where: {
|
||||
userId: user.id,
|
||||
NOT: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: scheduleToSetAsDefault?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.schedule.delete({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
});
|
||||
}),
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
scheduleId: z.number(),
|
||||
timeZone: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
schedule: z.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const { user, prisma } = ctx;
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
|
||||
let updatedUser;
|
||||
if (input.isDefault) {
|
||||
const setupDefault = await setupDefaultSchedule(user.id, input.scheduleId, prisma);
|
||||
updatedUser = setupDefault;
|
||||
}
|
||||
|
||||
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
|
||||
// Bug: https://github.com/prisma/prisma/issues/7290
|
||||
const userSchedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (userSchedule?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (!userSchedule || userSchedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
|
||||
const schedule = await prisma.schedule.update({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
data: {
|
||||
timeZone: input.timeZone,
|
||||
name: input.name,
|
||||
availability: {
|
||||
deleteMany: {
|
||||
scheduleId: {
|
||||
equals: input.scheduleId,
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
defaultScheduleId: scheduleToSetAsDefault?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
await prisma.schedule.delete({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("schedule.update", {
|
||||
input: z.object({
|
||||
scheduleId: z.number(),
|
||||
timeZone: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
schedule: z.array(
|
||||
z.array(
|
||||
z.object({
|
||||
start: z.date(),
|
||||
end: z.date(),
|
||||
})
|
||||
)
|
||||
),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { user, prisma } = ctx;
|
||||
const availability = getAvailabilityFromSchedule(input.schedule);
|
||||
|
||||
let updatedUser;
|
||||
if (input.isDefault) {
|
||||
const setupDefault = await setupDefaultSchedule(user.id, input.scheduleId, prisma);
|
||||
updatedUser = setupDefault;
|
||||
}
|
||||
|
||||
// Not able to update the schedule with userId where clause, so fetch schedule separately and then validate
|
||||
// Bug: https://github.com/prisma/prisma/issues/7290
|
||||
const userSchedule = await prisma.schedule.findUnique({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (userSchedule?.userId !== user.id) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (!userSchedule || userSchedule.userId !== user.id) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
|
||||
const schedule = await prisma.schedule.update({
|
||||
where: {
|
||||
id: input.scheduleId,
|
||||
},
|
||||
data: {
|
||||
timeZone: input.timeZone,
|
||||
name: input.name,
|
||||
availability: {
|
||||
deleteMany: {
|
||||
scheduleId: {
|
||||
equals: input.scheduleId,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
createMany: {
|
||||
data: availability.map((schedule) => ({
|
||||
days: schedule.days,
|
||||
startTime: schedule.startTime,
|
||||
endTime: schedule.endTime,
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
name: true,
|
||||
availability: true,
|
||||
timeZone: true,
|
||||
eventType: {
|
||||
select: {
|
||||
_count: true,
|
||||
id: true,
|
||||
eventName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const userAvailability = convertScheduleToAvailability(schedule);
|
||||
const userAvailability = convertScheduleToAvailability(schedule);
|
||||
|
||||
return {
|
||||
schedule,
|
||||
availability: userAvailability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: updatedUser
|
||||
? updatedUser.defaultScheduleId === schedule.id
|
||||
: user.defaultScheduleId === schedule.id,
|
||||
prevDefaultId: user.defaultScheduleId,
|
||||
currentDefaultId: updatedUser ? updatedUser.defaultScheduleId : user.defaultScheduleId,
|
||||
};
|
||||
},
|
||||
});
|
||||
return {
|
||||
schedule,
|
||||
availability: userAvailability,
|
||||
timeZone: schedule.timeZone || user.timeZone,
|
||||
isDefault: updatedUser
|
||||
? updatedUser.defaultScheduleId === schedule.id
|
||||
: user.defaultScheduleId === schedule.id,
|
||||
prevDefaultId: user.defaultScheduleId,
|
||||
currentDefaultId: updatedUser ? updatedUser.defaultScheduleId : user.defaultScheduleId,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
export const convertScheduleToAvailability = (
|
||||
schedule: Partial<ScheduleModel> & { availability: AvailabilityModel[] }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,18 +1,22 @@
|
||||
import { EventTypeCustomInput, MembershipRole, PeriodType, Prisma } from "@prisma/client";
|
||||
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
|
||||
// REVIEW: From lint error
|
||||
import _ from "lodash";
|
||||
import { z } from "zod";
|
||||
|
||||
import getAppKeysFromSlug from "@calcom/app-store/_utils/getAppKeysFromSlug";
|
||||
import { DailyLocationType } from "@calcom/app-store/locations";
|
||||
import { stripeDataSchema } from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { validateBookingLimitOrder } from "@calcom/lib";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import { baseEventTypeSelect, baseUserSelect } from "@calcom/prisma";
|
||||
import { _DestinationCalendarModel, _EventTypeCustomInputModel, _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import { EventTypeMetaDataSchema, stringOrNumber } from "@calcom/prisma/zod-utils";
|
||||
import { createEventTypeInput } from "@calcom/prisma/zod/custom/eventtype";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { authedProcedure, router } from "../../trpc";
|
||||
import { viewerRouter } from "../viewer";
|
||||
|
||||
function isPeriodType(keyInput: string): keyInput is PeriodType {
|
||||
@@ -88,143 +92,318 @@ const EventTypeUpdateInput = _EventTypeModel
|
||||
})
|
||||
);
|
||||
|
||||
export const eventTypesRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
return await ctx.prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
team: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
description: true,
|
||||
length: true,
|
||||
schedulingType: true,
|
||||
slug: true,
|
||||
hidden: true,
|
||||
metadata: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: createEventTypeInput,
|
||||
async resolve({ ctx, input }) {
|
||||
const { schedulingType, teamId, ...rest } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const data: Prisma.EventTypeCreateInput = {
|
||||
...rest,
|
||||
owner: teamId ? undefined : { connect: { id: userId } },
|
||||
users: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const appKeys = await getAppKeysFromSlug("daily-video");
|
||||
if (typeof appKeys.api_key === "string") {
|
||||
data.locations = [{ type: DailyLocationType }];
|
||||
}
|
||||
|
||||
if (teamId && schedulingType) {
|
||||
const hasMembership = await ctx.prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasMembership?.role || !["ADMIN", "OWNER"].includes(hasMembership.role)) {
|
||||
console.warn(`User ${userId} does not have permission to create this new event type`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
data.team = {
|
||||
connect: {
|
||||
id: teamId,
|
||||
},
|
||||
};
|
||||
data.schedulingType = schedulingType;
|
||||
}
|
||||
|
||||
try {
|
||||
const eventType = await ctx.prisma.eventType.create({ data });
|
||||
return { eventType };
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002" && Array.isArray(e.meta?.target) && e.meta?.target.includes("slug")) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "URL Slug already exists for given user." });
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
const eventOwnerProcedure = authedProcedure.use(async ({ ctx, rawInput, next }) => {
|
||||
// Prevent non-owners to update/delete a team event
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
const event = await ctx.prisma.eventType.findUnique({
|
||||
where: { id: (rawInput as Record<"id", number>)?.id },
|
||||
include: {
|
||||
users: true,
|
||||
team: {
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
const event = await ctx.prisma.eventType.findUnique({
|
||||
where: { id: (rawInput as Record<"id", number>)?.id },
|
||||
include: {
|
||||
users: true,
|
||||
team: {
|
||||
select: {
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
}
|
||||
|
||||
const isAuthorized = (function () {
|
||||
if (event.team) {
|
||||
return event.team.members
|
||||
.filter((member) => member.role === MembershipRole.OWNER || member.role === MembershipRole.ADMIN)
|
||||
.map((member) => member.userId)
|
||||
.includes(ctx.user.id);
|
||||
}
|
||||
return event.userId === ctx.user.id || event.users.find((user) => user.id === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAuthorized) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an access an event ${event.id} they do not own.`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
|
||||
const inputUsers = (rawInput as any).users || [];
|
||||
|
||||
const isAllowed = (function () {
|
||||
if (event.team) {
|
||||
const allTeamMembers = event.team.members.map((member) => member.userId);
|
||||
return inputUsers.every((userId: string) => allTeamMembers.includes(Number.parseInt(userId)));
|
||||
}
|
||||
return inputUsers.every((userId: string) => Number.parseInt(userId) === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAllowed) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an create an event for users ${inputUsers.join(", ")}.`);
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
|
||||
export const eventTypesRouter = router({
|
||||
// REVIEW: What should we name this procedure?
|
||||
getByViewer: authedProcedure.query(async ({ ctx }) => {
|
||||
const { prisma } = ctx;
|
||||
const eventTypeSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
// Position is required by lodash to sort on it. Don't remove it, TS won't complain but it would silently break reordering
|
||||
position: true,
|
||||
hashedLink: true,
|
||||
destinationCalendar: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
// logo: true, // Skipping to avoid 4mb limit
|
||||
bio: true,
|
||||
hideBranding: true,
|
||||
},
|
||||
},
|
||||
metadata: true,
|
||||
users: {
|
||||
select: baseUserSelect,
|
||||
},
|
||||
...baseEventTypeSelect,
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
bufferTime: true,
|
||||
plan: true,
|
||||
teams: {
|
||||
where: {
|
||||
accepted: true,
|
||||
},
|
||||
select: {
|
||||
role: true,
|
||||
team: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
members: {
|
||||
select: {
|
||||
userId: true,
|
||||
},
|
||||
},
|
||||
eventTypes: {
|
||||
select: eventTypeSelect,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
eventTypes: {
|
||||
where: {
|
||||
team: null,
|
||||
},
|
||||
select: eventTypeSelect,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
|
||||
}
|
||||
|
||||
const isAuthorized = (function () {
|
||||
if (event.team) {
|
||||
return event.team.members
|
||||
.filter((member) => member.role === MembershipRole.OWNER || member.role === MembershipRole.ADMIN)
|
||||
.map((member) => member.userId)
|
||||
.includes(ctx.user.id);
|
||||
const mapEventType = (eventType: typeof user.eventTypes[number]) => ({
|
||||
...eventType,
|
||||
// @FIXME: cc @hariombalhara This is failing with production data
|
||||
// metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
||||
});
|
||||
|
||||
const userEventTypes = user.eventTypes.map(mapEventType);
|
||||
// backwards compatibility, TMP:
|
||||
const typesRaw = (
|
||||
await prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
select: eventTypeSelect,
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
})
|
||||
).map(mapEventType);
|
||||
|
||||
type EventTypeGroup = {
|
||||
teamId?: number | null;
|
||||
profile: {
|
||||
slug: typeof user["username"];
|
||||
name: typeof user["name"];
|
||||
};
|
||||
metadata: {
|
||||
membershipCount: number;
|
||||
readOnly: boolean;
|
||||
};
|
||||
eventTypes: typeof userEventTypes;
|
||||
};
|
||||
|
||||
let eventTypeGroups: EventTypeGroup[] = [];
|
||||
const eventTypesHashMap = userEventTypes.concat(typesRaw).reduce((hashMap, newItem) => {
|
||||
const oldItem = hashMap[newItem.id];
|
||||
hashMap[newItem.id] = { ...oldItem, ...newItem };
|
||||
return hashMap;
|
||||
}, {} as Record<number, EventTypeGroup["eventTypes"][number]>);
|
||||
const mergedEventTypes = Object.values(eventTypesHashMap).map((eventType) => eventType);
|
||||
eventTypeGroups.push({
|
||||
teamId: null,
|
||||
profile: {
|
||||
slug: user.username,
|
||||
name: user.name,
|
||||
},
|
||||
eventTypes: _.orderBy(mergedEventTypes, ["position", "id"], ["desc", "asc"]),
|
||||
metadata: {
|
||||
membershipCount: 1,
|
||||
readOnly: false,
|
||||
},
|
||||
});
|
||||
|
||||
eventTypeGroups = ([] as EventTypeGroup[]).concat(
|
||||
eventTypeGroups,
|
||||
user.teams.map((membership) => ({
|
||||
teamId: membership.team.id,
|
||||
profile: {
|
||||
name: membership.team.name,
|
||||
image: `${CAL_URL}/team/${membership.team.slug}/avatar.png`,
|
||||
slug: "team/" + membership.team.slug,
|
||||
},
|
||||
metadata: {
|
||||
membershipCount: membership.team.members.length,
|
||||
readOnly: membership.role === MembershipRole.MEMBER,
|
||||
},
|
||||
eventTypes: membership.team.eventTypes.map(mapEventType),
|
||||
}))
|
||||
);
|
||||
return {
|
||||
viewer: {
|
||||
plan: user.plan,
|
||||
},
|
||||
// don't display event teams without event types,
|
||||
eventTypeGroups: eventTypeGroups.filter((groupBy) => !!groupBy.eventTypes?.length),
|
||||
// so we can show a dropdown when the user has teams
|
||||
profiles: eventTypeGroups.map((group) => ({
|
||||
teamId: group.teamId,
|
||||
...group.profile,
|
||||
...group.metadata,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
return await ctx.prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
team: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
description: true,
|
||||
length: true,
|
||||
schedulingType: true,
|
||||
slug: true,
|
||||
hidden: true,
|
||||
metadata: true,
|
||||
},
|
||||
});
|
||||
}),
|
||||
create: authedProcedure.input(createEventTypeInput).mutation(async ({ ctx, input }) => {
|
||||
const { schedulingType, teamId, ...rest } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
const data: Prisma.EventTypeCreateInput = {
|
||||
...rest,
|
||||
owner: teamId ? undefined : { connect: { id: userId } },
|
||||
users: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const appKeys = await getAppKeysFromSlug("daily-video");
|
||||
if (typeof appKeys.api_key === "string") {
|
||||
data.locations = [{ type: DailyLocationType }];
|
||||
}
|
||||
|
||||
if (teamId && schedulingType) {
|
||||
const hasMembership = await ctx.prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId: teamId,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasMembership?.role || !["ADMIN", "OWNER"].includes(hasMembership.role)) {
|
||||
console.warn(`User ${userId} does not have permission to create this new event type`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
}
|
||||
return event.userId === ctx.user.id || event.users.find((user) => user.id === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAuthorized) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an access an event ${event.id} they do not own.`);
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
data.team = {
|
||||
connect: {
|
||||
id: teamId,
|
||||
},
|
||||
};
|
||||
data.schedulingType = schedulingType;
|
||||
}
|
||||
|
||||
const inputUsers = (rawInput as any).users || [];
|
||||
|
||||
const isAllowed = (function () {
|
||||
if (event.team) {
|
||||
const allTeamMembers = event.team.members.map((member) => member.userId);
|
||||
return inputUsers.every((userId: string) => allTeamMembers.includes(Number.parseInt(userId)));
|
||||
try {
|
||||
const eventType = await ctx.prisma.eventType.create({ data });
|
||||
return { eventType };
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002" && Array.isArray(e.meta?.target) && e.meta?.target.includes("slug")) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "URL Slug already exists for given user." });
|
||||
}
|
||||
}
|
||||
return inputUsers.every((userId: string) => Number.parseInt(userId) === ctx.user.id);
|
||||
})();
|
||||
|
||||
if (!isAllowed) {
|
||||
console.warn(`User ${ctx.user.id} attempted to an create an event for users ${inputUsers.join(", ")}.`);
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
throw e;
|
||||
}
|
||||
|
||||
return next();
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
}),
|
||||
get: eventOwnerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const user = await ctx.prisma.user.findUnique({
|
||||
where: {
|
||||
id: ctx.user.id,
|
||||
@@ -252,152 +431,150 @@ export const eventTypesRouter = createProtectedRouter()
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: EventTypeUpdateInput.strict(),
|
||||
async resolve({ ctx, input }) {
|
||||
const {
|
||||
schedule,
|
||||
periodType,
|
||||
locations,
|
||||
bookingLimits,
|
||||
destinationCalendar,
|
||||
customInputs,
|
||||
recurringEvent,
|
||||
users,
|
||||
id,
|
||||
hashedLink,
|
||||
...rest
|
||||
} = input;
|
||||
const data: Prisma.EventTypeUpdateInput = {
|
||||
...rest,
|
||||
metadata: rest.metadata === null ? Prisma.DbNull : rest.metadata,
|
||||
}),
|
||||
update: eventOwnerProcedure.input(EventTypeUpdateInput.strict()).mutation(async ({ ctx, input }) => {
|
||||
const {
|
||||
schedule,
|
||||
periodType,
|
||||
locations,
|
||||
bookingLimits,
|
||||
destinationCalendar,
|
||||
customInputs,
|
||||
recurringEvent,
|
||||
users,
|
||||
id,
|
||||
hashedLink,
|
||||
...rest
|
||||
} = input;
|
||||
const data: Prisma.EventTypeUpdateInput = {
|
||||
...rest,
|
||||
metadata: rest.metadata === null ? Prisma.DbNull : rest.metadata,
|
||||
};
|
||||
data.locations = locations ?? undefined;
|
||||
if (periodType) {
|
||||
data.periodType = handlePeriodType(periodType);
|
||||
}
|
||||
|
||||
if (recurringEvent) {
|
||||
data.recurringEvent = {
|
||||
dstart: recurringEvent.dtstart as unknown as Prisma.InputJsonObject,
|
||||
interval: recurringEvent.interval,
|
||||
count: recurringEvent.count,
|
||||
freq: recurringEvent.freq,
|
||||
until: recurringEvent.until as unknown as Prisma.InputJsonObject,
|
||||
tzid: recurringEvent.tzid,
|
||||
};
|
||||
data.locations = locations ?? undefined;
|
||||
if (periodType) {
|
||||
data.periodType = handlePeriodType(periodType);
|
||||
}
|
||||
} else if (recurringEvent === null) {
|
||||
data.recurringEvent = Prisma.DbNull;
|
||||
}
|
||||
|
||||
if (recurringEvent) {
|
||||
data.recurringEvent = {
|
||||
dstart: recurringEvent.dtstart as unknown as Prisma.InputJsonObject,
|
||||
interval: recurringEvent.interval,
|
||||
count: recurringEvent.count,
|
||||
freq: recurringEvent.freq,
|
||||
until: recurringEvent.until as unknown as Prisma.InputJsonObject,
|
||||
tzid: recurringEvent.tzid,
|
||||
};
|
||||
} else if (recurringEvent === null) {
|
||||
data.recurringEvent = Prisma.DbNull;
|
||||
}
|
||||
if (destinationCalendar) {
|
||||
/** We connect or create a destination calendar to the event type instead of the user */
|
||||
await viewerRouter.createCaller(ctx).setDestinationCalendar({
|
||||
...destinationCalendar,
|
||||
eventTypeId: id,
|
||||
});
|
||||
}
|
||||
|
||||
if (destinationCalendar) {
|
||||
/** We connect or create a destination calendar to the event type instead of the user */
|
||||
await viewerRouter.createCaller(ctx).mutation("setDestinationCalendar", {
|
||||
...destinationCalendar,
|
||||
eventTypeId: id,
|
||||
});
|
||||
}
|
||||
if (customInputs) {
|
||||
data.customInputs = handleCustomInputs(customInputs, id);
|
||||
}
|
||||
|
||||
if (customInputs) {
|
||||
data.customInputs = handleCustomInputs(customInputs, id);
|
||||
}
|
||||
if (bookingLimits) {
|
||||
const isValid = validateBookingLimitOrder(bookingLimits);
|
||||
if (!isValid)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Booking limits must be in ascending order." });
|
||||
data.bookingLimits = bookingLimits;
|
||||
}
|
||||
|
||||
if (bookingLimits) {
|
||||
const isValid = validateBookingLimitOrder(bookingLimits);
|
||||
if (!isValid)
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Booking limits must be in ascending order." });
|
||||
data.bookingLimits = bookingLimits;
|
||||
}
|
||||
if (schedule) {
|
||||
data.schedule = {
|
||||
connect: {
|
||||
id: schedule,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (schedule) {
|
||||
data.schedule = {
|
||||
connect: {
|
||||
id: schedule,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (users) {
|
||||
data.users = {
|
||||
set: [],
|
||||
connect: users.map((userId: number) => ({ id: userId })),
|
||||
};
|
||||
}
|
||||
|
||||
if (users) {
|
||||
data.users = {
|
||||
set: [],
|
||||
connect: users.map((userId: number) => ({ id: userId })),
|
||||
};
|
||||
}
|
||||
|
||||
if (input?.price) {
|
||||
const paymentCredential = await ctx.prisma.credential.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
type: {
|
||||
contains: "_payment",
|
||||
},
|
||||
},
|
||||
select: {
|
||||
type: true,
|
||||
key: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (paymentCredential?.type === "stripe_payment") {
|
||||
const { default_currency } = stripeDataSchema.parse(paymentCredential.key);
|
||||
data.currency = default_currency;
|
||||
}
|
||||
}
|
||||
|
||||
const connectedLink = await ctx.prisma.hashedLink.findFirst({
|
||||
if (input?.price) {
|
||||
const paymentCredential = await ctx.prisma.credential.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
userId: ctx.user.id,
|
||||
type: {
|
||||
contains: "_payment",
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
type: true,
|
||||
key: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (hashedLink) {
|
||||
// check if hashed connection existed. If it did, do nothing. If it didn't, add a new connection
|
||||
if (!connectedLink) {
|
||||
// create a hashed link
|
||||
await ctx.prisma.hashedLink.upsert({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
update: {
|
||||
link: hashedLink,
|
||||
},
|
||||
create: {
|
||||
link: hashedLink,
|
||||
eventType: {
|
||||
connect: { id: input.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// check if hashed connection exists. If it does, disconnect
|
||||
if (connectedLink) {
|
||||
await ctx.prisma.hashedLink.delete({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (paymentCredential?.type === "stripe_payment") {
|
||||
const { default_currency } = stripeDataSchema.parse(paymentCredential.key);
|
||||
data.currency = default_currency;
|
||||
}
|
||||
}
|
||||
|
||||
const eventType = await ctx.prisma.eventType.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
const connectedLink = await ctx.prisma.hashedLink.findFirst({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return { eventType };
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
if (hashedLink) {
|
||||
// check if hashed connection existed. If it did, do nothing. If it didn't, add a new connection
|
||||
if (!connectedLink) {
|
||||
// create a hashed link
|
||||
await ctx.prisma.hashedLink.upsert({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
update: {
|
||||
link: hashedLink,
|
||||
},
|
||||
create: {
|
||||
link: hashedLink,
|
||||
eventType: {
|
||||
connect: { id: input.id },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// check if hashed connection exists. If it does, disconnect
|
||||
if (connectedLink) {
|
||||
await ctx.prisma.hashedLink.delete({
|
||||
where: {
|
||||
eventTypeId: input.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const eventType = await ctx.prisma.eventType.update({
|
||||
where: { id },
|
||||
data,
|
||||
});
|
||||
|
||||
return { eventType };
|
||||
}),
|
||||
delete: eventOwnerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
|
||||
await ctx.prisma.eventTypeCustomInput.deleteMany({
|
||||
@@ -415,5 +592,5 @@ export const eventTypesRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -5,15 +5,17 @@ import { samlProductID, samlTenantID, tenantPrefix, canAccess } from "@calcom/fe
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
export const samlRouter = createProtectedRouter()
|
||||
export const samlRouter = router({
|
||||
// Retrieve SAML Connection
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { connectionController, samlSPConfig } = await jackson();
|
||||
|
||||
const { teamId } = input;
|
||||
@@ -51,16 +53,16 @@ export const samlRouter = createProtectedRouter()
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
})
|
||||
|
||||
// Update the SAML Connection
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
encodedRawMetadata: z.string(),
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Update the SAML Connection
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
encodedRawMetadata: z.string(),
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { connectionController } = await jackson();
|
||||
|
||||
const { encodedRawMetadata, teamId } = input;
|
||||
@@ -86,15 +88,15 @@ export const samlRouter = createProtectedRouter()
|
||||
console.error("Error updating SAML connection", err);
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Updating SAML Connection failed." });
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
// Delete the SAML Connection
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Delete the SAML Connection
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.union([z.number(), z.null()]),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { connectionController } = await jackson();
|
||||
|
||||
const { teamId } = input;
|
||||
@@ -117,5 +119,5 @@ export const samlRouter = createProtectedRouter()
|
||||
console.error("Error deleting SAML connection", err);
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: "Deleting SAML Connection failed." });
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -17,7 +17,7 @@ import { TimeRange } from "@calcom/types/schedule";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createRouter } from "../../createRouter";
|
||||
import { router, publicProcedure } from "../../trpc";
|
||||
|
||||
const getScheduleSchema = z
|
||||
.object({
|
||||
@@ -97,11 +97,10 @@ const checkIfIsAvailable = ({
|
||||
};
|
||||
|
||||
/** This should be called getAvailableSlots */
|
||||
export const slotsRouter = createRouter().query("getSchedule", {
|
||||
input: getScheduleSchema,
|
||||
async resolve({ input, ctx }) {
|
||||
export const slotsRouter = router({
|
||||
getSchedule: publicProcedure.input(getScheduleSchema).query(async ({ input, ctx }) => {
|
||||
return await getSchedule(input, ctx);
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
async function getEventType(ctx: { prisma: typeof prisma }, input: z.infer<typeof getScheduleSchema>) {
|
||||
|
||||
@@ -24,15 +24,17 @@ import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { authedProcedure, router } from "../../trpc";
|
||||
|
||||
export const viewerTeamsRouter = createProtectedRouter()
|
||||
export const viewerTeamsRouter = router({
|
||||
// Retrieves team by id
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const team = await getTeamWithMembers(input.teamId, undefined, ctx.user.id);
|
||||
if (!team) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Team not found." });
|
||||
@@ -48,39 +50,38 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
},
|
||||
requiresUpgrade: HOSTED_CAL_FEATURES ? !!team.members.find((m) => m.plan !== UserPlan.PRO) : false,
|
||||
};
|
||||
},
|
||||
})
|
||||
// Returns teams I a member of
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
|
||||
return memberships.map(({ team, ...membership }) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...team,
|
||||
}));
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
slug: z.string().transform((val) => slugify(val.trim())),
|
||||
logo: z
|
||||
.string()
|
||||
.optional()
|
||||
.nullable()
|
||||
.transform((v) => v || null),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Returns teams I a member of
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
const memberships = await ctx.prisma.membership.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
orderBy: { role: "desc" },
|
||||
});
|
||||
|
||||
return memberships.map(({ team, ...membership }) => ({
|
||||
role: membership.role,
|
||||
accepted: membership.accepted,
|
||||
...team,
|
||||
}));
|
||||
}),
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
slug: z.string().transform((val) => slugify(val.trim())),
|
||||
logo: z
|
||||
.string()
|
||||
.optional()
|
||||
.nullable()
|
||||
.transform((v) => v || null),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { slug, name, logo } = input;
|
||||
|
||||
const nameCollisions = await ctx.prisma.team.findFirst({
|
||||
@@ -110,19 +111,20 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
closeComUpsertTeamUser(createTeam, ctx.user, MembershipRole.OWNER);
|
||||
|
||||
return createTeam;
|
||||
},
|
||||
})
|
||||
// Allows team owner to update team metadata
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
bio: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
logo: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
hideBranding: z.boolean().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
// Allows team owner to update team metadata
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
bio: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
logo: z.string().optional(),
|
||||
slug: z.string().optional(),
|
||||
hideBranding: z.boolean().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.id))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (input.slug) {
|
||||
@@ -169,13 +171,14 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
|
||||
// Sync Services: Close.com
|
||||
if (prevTeam) closeComUpdateTeam(prevTeam, updatedTeam);
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamOwner(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
if (IS_TEAM_BILLING_ENABLED) await cancelTeamSubscriptionFromStripe(input.teamId);
|
||||
@@ -195,15 +198,15 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
|
||||
// Sync Services: Close.cm
|
||||
closeComDeleteTeam(deletedTeam);
|
||||
},
|
||||
})
|
||||
// Allows owner to remove member from team
|
||||
.mutation("removeMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
removeMember: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const isAdmin = await isTeamAdmin(ctx.user?.id, input.teamId);
|
||||
if (!isAdmin && ctx.user?.id !== input.memberId) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only a team owner can remove another team owner.
|
||||
@@ -231,17 +234,18 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
closeComDeleteTeamMembership(membership.user);
|
||||
|
||||
if (HOSTED_CAL_FEATURES) await removeSeat(ctx.user.id, input.teamId, input.memberId);
|
||||
},
|
||||
})
|
||||
.mutation("inviteMember", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
usernameOrEmail: z.string(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
language: z.string(),
|
||||
sendEmailInvitation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
inviteMember: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
usernameOrEmail: z.string(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
language: z.string(),
|
||||
sendEmailInvitation: z.boolean(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
if (input.role === MembershipRole.OWNER && !(await isTeamOwner(ctx.user?.id, input.teamId)))
|
||||
throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
@@ -345,14 +349,15 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("acceptOrLeave", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
accept: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
acceptOrLeave: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
accept: z.boolean(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.accept) {
|
||||
const membership = await ctx.prisma.membership.update({
|
||||
where: {
|
||||
@@ -390,15 +395,16 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("changeMemberRole", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
changeMemberRole: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
role: z.nativeEnum(MembershipRole),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user?.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
// Only owners can award owner role.
|
||||
if (input.role === MembershipRole.OWNER && !(await isTeamOwner(ctx.user?.id, input.teamId)))
|
||||
@@ -449,17 +455,18 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
|
||||
// Sync Services: Close.com
|
||||
closeComUpsertTeamUser(membership.team, membership.user, membership.role);
|
||||
},
|
||||
})
|
||||
.query("getMemberAvailability", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
timezone: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
getMemberAvailability: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
timezone: z.string(),
|
||||
dateFrom: z.string(),
|
||||
dateTo: z.string(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const team = await isTeamMember(ctx.user?.id, input.teamId);
|
||||
if (!team) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
|
||||
@@ -488,14 +495,15 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
},
|
||||
{ user: member.user }
|
||||
);
|
||||
},
|
||||
})
|
||||
.query("getMembershipbyUser", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
getMembershipbyUser: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
@@ -511,15 +519,16 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("updateMembership", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
disableImpersonation: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
updateMembership: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
memberId: z.number(),
|
||||
disableImpersonation: z.boolean(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (ctx.user.id !== input.memberId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
@@ -538,13 +547,14 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
disableImpersonation: input.disableImpersonation,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("validateTeamSlug", {
|
||||
input: z.object({
|
||||
slug: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
validateTeamSlug: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
slug: z.string(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
slug: input.slug,
|
||||
@@ -552,13 +562,14 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
});
|
||||
|
||||
return !team;
|
||||
},
|
||||
})
|
||||
.mutation("publish", {
|
||||
input: z.object({
|
||||
teamId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
publish: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
teamId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (!(await isTeamAdmin(ctx.user.id, input.teamId))) throw new TRPCError({ code: "UNAUTHORIZED" });
|
||||
const { teamId: id } = input;
|
||||
|
||||
@@ -606,5 +617,5 @@ export const viewerTeamsRouter = createProtectedRouter()
|
||||
closeComUpdateTeam(prevTeam, updatedTeam);
|
||||
|
||||
return { url: `${WEBAPP_URL}/settings/teams/${updatedTeam.id}/profile` };
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
// Common data for all endpoints under webhook
|
||||
const webhookIdAndEventTypeIdSchema = z.object({
|
||||
@@ -19,62 +19,65 @@ const webhookIdAndEventTypeIdSchema = z.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
});
|
||||
|
||||
export const webhookRouter = createProtectedRouter()
|
||||
.middleware(async ({ ctx, rawInput, next }) => {
|
||||
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
|
||||
if (!rawInput) {
|
||||
return next();
|
||||
}
|
||||
const webhookIdAndEventTypeId = webhookIdAndEventTypeIdSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
}
|
||||
const { eventTypeId, id } = webhookIdAndEventTypeId.data;
|
||||
const webhookProcedure = authedProcedure.use(async ({ ctx, rawInput, next }) => {
|
||||
// Endpoints that just read the logged in user's data - like 'list' don't necessary have any input
|
||||
if (!rawInput) {
|
||||
return next();
|
||||
}
|
||||
const webhookIdAndEventTypeId = webhookIdAndEventTypeIdSchema.safeParse(rawInput);
|
||||
if (!webhookIdAndEventTypeId.success) {
|
||||
throw new TRPCError({ code: "PARSE_ERROR" });
|
||||
}
|
||||
const { eventTypeId, id } = webhookIdAndEventTypeId.data;
|
||||
|
||||
// A webhook is either linked to Event Type or to a user.
|
||||
if (eventTypeId) {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
eventTypes: {
|
||||
some: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
// A webhook is either linked to Event Type or to a user.
|
||||
if (eventTypeId) {
|
||||
const team = await ctx.prisma.team.findFirst({
|
||||
where: {
|
||||
eventTypes: {
|
||||
some: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Team should be available and the user should be a member of the team
|
||||
if (!team?.members.some((membership) => membership.userId === ctx.user.id)) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
} else if (id) {
|
||||
const authorizedHook = await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
id: id,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
// Team should be available and the user should be a member of the team
|
||||
if (!team?.members.some((membership) => membership.userId === ctx.user.id)) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
if (!authorizedHook) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
}
|
||||
return next();
|
||||
})
|
||||
.query("list", {
|
||||
input: z
|
||||
.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
async resolve({ ctx, input }) {
|
||||
} else if (id) {
|
||||
const authorizedHook = await ctx.prisma.webhook.findFirst({
|
||||
where: {
|
||||
id: id,
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
});
|
||||
if (!authorizedHook) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
});
|
||||
}
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
export const webhookRouter = router({
|
||||
list: webhookProcedure
|
||||
.input(
|
||||
z
|
||||
.object({
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional(),
|
||||
})
|
||||
.optional()
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const where: Prisma.WebhookWhereInput = {
|
||||
/* Don't mixup zapier webhooks with normal ones */
|
||||
AND: [{ appId: !input?.appId ? null : input.appId }],
|
||||
@@ -90,13 +93,14 @@ export const webhookRouter = createProtectedRouter()
|
||||
return await ctx.prisma.webhook.findMany({
|
||||
where,
|
||||
});
|
||||
},
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
webhookId: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
get: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
webhookId: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return await ctx.prisma.webhook.findUniqueOrThrow({
|
||||
where: {
|
||||
id: input.webhookId,
|
||||
@@ -110,19 +114,20 @@ export const webhookRouter = createProtectedRouter()
|
||||
secret: true,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
subscriberUrl: z.string().url(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
|
||||
active: z.boolean(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
create: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
subscriberUrl: z.string().url(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array(),
|
||||
active: z.boolean(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (input.eventTypeId) {
|
||||
return await ctx.prisma.webhook.create({
|
||||
data: {
|
||||
@@ -139,20 +144,21 @@ export const webhookRouter = createProtectedRouter()
|
||||
...input,
|
||||
},
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("edit", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
subscriberUrl: z.string().url().optional(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
|
||||
active: z.boolean().optional(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
edit: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
subscriberUrl: z.string().url().optional(),
|
||||
eventTriggers: z.enum(WEBHOOK_TRIGGER_EVENTS).array().optional(),
|
||||
active: z.boolean().optional(),
|
||||
payloadTemplate: z.string().nullable(),
|
||||
eventTypeId: z.number().optional(),
|
||||
appId: z.string().optional().nullable(),
|
||||
secret: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...data } = input;
|
||||
const webhook = input.eventTypeId
|
||||
? await ctx.prisma.webhook.findFirst({
|
||||
@@ -178,14 +184,15 @@ export const webhookRouter = createProtectedRouter()
|
||||
},
|
||||
data,
|
||||
});
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
delete: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
eventTypeId: z.number().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
input.eventTypeId
|
||||
? await ctx.prisma.eventType.update({
|
||||
@@ -215,15 +222,16 @@ export const webhookRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("testTrigger", {
|
||||
input: z.object({
|
||||
url: z.string().url(),
|
||||
type: z.string(),
|
||||
payloadTemplate: z.string().optional().nullable(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
testTrigger: webhookProcedure
|
||||
.input(
|
||||
z.object({
|
||||
url: z.string().url(),
|
||||
type: z.string(),
|
||||
payloadTemplate: z.string().optional().nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ input }) => {
|
||||
const { url, type, payloadTemplate = null } = input;
|
||||
const translation = await getTranslation("en", "common");
|
||||
const language = {
|
||||
@@ -264,5 +272,5 @@ export const webhookRouter = createProtectedRouter()
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -30,7 +30,7 @@ import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
import { createProtectedRouter } from "../../createRouter";
|
||||
import { router, authedProcedure } from "../../trpc";
|
||||
|
||||
function isSMSAction(action: WorkflowActions) {
|
||||
if (action === WorkflowActions.SMS_ATTENDEE || action === WorkflowActions.SMS_NUMBER) {
|
||||
@@ -38,39 +38,39 @@ function isSMSAction(action: WorkflowActions) {
|
||||
}
|
||||
}
|
||||
|
||||
export const workflowsRouter = createProtectedRouter()
|
||||
.query("list", {
|
||||
async resolve({ ctx }) {
|
||||
const workflows = await ctx.prisma.workflow.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
export const workflowsRouter = router({
|
||||
list: authedProcedure.query(async ({ ctx }) => {
|
||||
const workflows = await ctx.prisma.workflow.findMany({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
},
|
||||
include: {
|
||||
activeOn: {
|
||||
select: {
|
||||
eventType: {
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
steps: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
steps: true,
|
||||
},
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
|
||||
return { workflows };
|
||||
},
|
||||
})
|
||||
.query("get", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
return { workflows };
|
||||
}),
|
||||
get: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const workflow = await ctx.prisma.workflow.findFirst({
|
||||
where: {
|
||||
userId: ctx.user.id,
|
||||
@@ -100,18 +100,19 @@ export const workflowsRouter = createProtectedRouter()
|
||||
});
|
||||
}
|
||||
return workflow;
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
timeUnit: z.enum(TIME_UNIT).optional(),
|
||||
time: z.number().optional(),
|
||||
sendTo: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
create: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
timeUnit: z.enum(TIME_UNIT).optional(),
|
||||
time: z.number().optional(),
|
||||
sendTo: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { name, trigger, action, timeUnit, time, sendTo } = input;
|
||||
const userId = ctx.user.id;
|
||||
|
||||
@@ -138,42 +139,41 @@ export const workflowsRouter = createProtectedRouter()
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("createV2", {
|
||||
async resolve({ ctx }) {
|
||||
const userId = ctx.user.id;
|
||||
|
||||
try {
|
||||
const workflow = await ctx.prisma.workflow.create({
|
||||
data: {
|
||||
name: "",
|
||||
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
time: 24,
|
||||
timeUnit: TimeUnit.HOUR,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.workflowStep.create({
|
||||
data: {
|
||||
stepNumber: 1,
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
template: WorkflowTemplates.REMINDER,
|
||||
workflowId: workflow.id,
|
||||
},
|
||||
});
|
||||
return { workflow };
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("delete", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
createV2: authedProcedure.mutation(async ({ ctx }) => {
|
||||
const userId = ctx.user.id;
|
||||
|
||||
try {
|
||||
const workflow = await ctx.prisma.workflow.create({
|
||||
data: {
|
||||
name: "",
|
||||
trigger: WorkflowTriggerEvents.BEFORE_EVENT,
|
||||
time: 24,
|
||||
timeUnit: TimeUnit.HOUR,
|
||||
userId,
|
||||
},
|
||||
});
|
||||
|
||||
await ctx.prisma.workflowStep.create({
|
||||
data: {
|
||||
stepNumber: 1,
|
||||
action: WorkflowActions.EMAIL_HOST,
|
||||
template: WorkflowTemplates.REMINDER,
|
||||
workflowId: workflow.id,
|
||||
},
|
||||
});
|
||||
return { workflow };
|
||||
} catch (e) {
|
||||
throw e;
|
||||
}
|
||||
}),
|
||||
delete: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id } = input;
|
||||
|
||||
const workflowToDelete = await ctx.prisma.workflow.findFirst({
|
||||
@@ -217,31 +217,32 @@ export const workflowsRouter = createProtectedRouter()
|
||||
return {
|
||||
id,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("update", {
|
||||
input: z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
activeOn: z.number().array(),
|
||||
steps: z
|
||||
.object({
|
||||
id: z.number(),
|
||||
stepNumber: z.number(),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
workflowId: z.number(),
|
||||
sendTo: z.string().optional().nullable(),
|
||||
reminderBody: z.string().optional().nullable(),
|
||||
emailSubject: z.string().optional().nullable(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
numberRequired: z.boolean().nullable(),
|
||||
})
|
||||
.array(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
time: z.number().nullable(),
|
||||
timeUnit: z.enum(TIME_UNIT).nullable(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
update: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
activeOn: z.number().array(),
|
||||
steps: z
|
||||
.object({
|
||||
id: z.number(),
|
||||
stepNumber: z.number(),
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
workflowId: z.number(),
|
||||
sendTo: z.string().optional().nullable(),
|
||||
reminderBody: z.string().optional().nullable(),
|
||||
emailSubject: z.string().optional().nullable(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
numberRequired: z.boolean().nullable(),
|
||||
})
|
||||
.array(),
|
||||
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),
|
||||
time: z.number().nullable(),
|
||||
timeUnit: z.enum(TIME_UNIT).nullable(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { user } = ctx;
|
||||
const { id, name, activeOn, steps, trigger, time, timeUnit } = input;
|
||||
|
||||
@@ -802,17 +803,18 @@ export const workflowsRouter = createProtectedRouter()
|
||||
return {
|
||||
workflow,
|
||||
};
|
||||
},
|
||||
})
|
||||
.mutation("testAction", {
|
||||
input: z.object({
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
emailSubject: z.string(),
|
||||
reminderBody: z.string(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
sendTo: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
testAction: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
action: z.enum(WORKFLOW_ACTIONS),
|
||||
emailSubject: z.string(),
|
||||
reminderBody: z.string(),
|
||||
template: z.enum(WORKFLOW_TEMPLATES),
|
||||
sendTo: z.string().optional(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { action, emailSubject, reminderBody, template, sendTo } = input;
|
||||
try {
|
||||
const booking = await ctx.prisma.booking.findFirst({
|
||||
@@ -914,21 +916,23 @@ export const workflowsRouter = createProtectedRouter()
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("activateEventType", {
|
||||
input: z.object({
|
||||
eventTypeId: z.number(),
|
||||
workflowId: z.number(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
activateEventType: authedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
eventTypeId: z.number(),
|
||||
workflowId: z.number(),
|
||||
})
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { eventTypeId, workflowId } = input;
|
||||
|
||||
const eventType = await ctx.prisma.eventType.findFirst({
|
||||
where: {
|
||||
id: eventTypeId,
|
||||
},
|
||||
});
|
||||
// NOTE: This was unused
|
||||
// const eventType = await ctx.prisma.eventType.findFirst({
|
||||
// where: {
|
||||
// id: eventTypeId,
|
||||
// },
|
||||
// });
|
||||
|
||||
//check if event type is already active
|
||||
|
||||
@@ -954,5 +958,5 @@ export const workflowsRouter = createProtectedRouter()
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { initTRPC, TRPCError } from "@trpc/server";
|
||||
|
||||
import { Context } from "./createContext";
|
||||
|
||||
export const t = initTRPC.context<Context>().create({
|
||||
const t = initTRPC.context<Context>().create({
|
||||
transformer: superjson,
|
||||
});
|
||||
|
||||
@@ -29,5 +29,8 @@ const isAuthedMiddleware = t.middleware(({ ctx, next }) => {
|
||||
});
|
||||
});
|
||||
|
||||
export const router = t.router;
|
||||
export const mergeRouters = t.mergeRouters;
|
||||
export const middleware = t.middleware;
|
||||
export const publicProcedure = t.procedure.use(perfMiddleware);
|
||||
export const authedProcedure = t.procedure.use(perfMiddleware).use(isAuthedMiddleware);
|
||||
@@ -9,7 +9,7 @@ import { Dialog } from "@calcom/ui/v2/core/Dialog";
|
||||
|
||||
export default function TimezoneChangeDialog() {
|
||||
const { t } = useLocale();
|
||||
const { data: user, isLoading } = trpc.useQuery(["viewer.me"]);
|
||||
const { data: user, isLoading } = trpc.viewer.me.useQuery();
|
||||
const utils = trpc.useContext();
|
||||
const userTz = user?.timeZone;
|
||||
const currentTz = dayjs.tz.guess();
|
||||
@@ -18,7 +18,7 @@ export default function TimezoneChangeDialog() {
|
||||
// update user settings
|
||||
const onSuccessMutation = async () => {
|
||||
showToast(t("updated_timezone_to", { formattedCurrentTz }), "success");
|
||||
await utils.invalidateQueries(["viewer.me"]);
|
||||
await utils.viewer.me.invalidate();
|
||||
};
|
||||
|
||||
const onErrorMutation = () => {
|
||||
@@ -26,7 +26,7 @@ export default function TimezoneChangeDialog() {
|
||||
};
|
||||
|
||||
// update timezone in db
|
||||
const mutation = trpc.useMutation("viewer.updateProfile", {
|
||||
const mutation = trpc.viewer.updateProfile.useMutation({
|
||||
onSuccess: onSuccessMutation,
|
||||
onError: onErrorMutation,
|
||||
});
|
||||
|
||||
@@ -216,9 +216,9 @@ function UserDropdown({ small }: { small?: boolean }) {
|
||||
screenResolution: `${screen.width}x${screen.height}`,
|
||||
});
|
||||
});
|
||||
const mutation = trpc.useMutation("viewer.away", {
|
||||
const mutation = trpc.viewer.away.useMutation({
|
||||
onSettled() {
|
||||
utils.invalidateQueries("viewer.me");
|
||||
utils.viewer.me.invalidate();
|
||||
},
|
||||
});
|
||||
const utils = trpc.useContext();
|
||||
@@ -298,7 +298,7 @@ function UserDropdown({ small }: { small?: boolean }) {
|
||||
<button
|
||||
onClick={() => {
|
||||
mutation.mutate({ away: !user?.away });
|
||||
utils.invalidateQueries("viewer.me");
|
||||
utils.viewer.me.invalidate();
|
||||
}}
|
||||
className="flex min-w-max cursor-pointer items-center px-4 py-2 text-sm hover:bg-gray-100 hover:text-gray-900">
|
||||
<Icon.FiMoon
|
||||
@@ -554,9 +554,13 @@ const Navigation = () => {
|
||||
|
||||
function useShouldDisplayNavigationItem(item: NavigationItemType) {
|
||||
const { status } = useSession();
|
||||
const { data: routingForms } = trpc.useQuery(["viewer.appById", { appId: "routing-forms" }], {
|
||||
enabled: status === "authenticated" && requiredCredentialNavigationItems.includes(item.name),
|
||||
});
|
||||
const { data: routingForms } = trpc.viewer.appById.useQuery(
|
||||
{ appId: "routing-forms" },
|
||||
{
|
||||
enabled: status === "authenticated" && requiredCredentialNavigationItems.includes(item.name),
|
||||
trpc: {},
|
||||
}
|
||||
);
|
||||
return !requiredCredentialNavigationItems.includes(item.name) || routingForms?.isInstalled;
|
||||
}
|
||||
|
||||
|
||||
@@ -47,10 +47,10 @@ export default function InstalledAppsLayout({
|
||||
children,
|
||||
...rest
|
||||
}: { children: React.ReactNode } & ComponentProps<typeof Shell>) {
|
||||
const query = trpc.useQuery([
|
||||
"viewer.integrations",
|
||||
{ variant: InstalledAppVariants.payment, onlyInstalled: true },
|
||||
]);
|
||||
const query = trpc.viewer.integrations.useQuery({
|
||||
variant: InstalledAppVariants.payment,
|
||||
onlyInstalled: true,
|
||||
});
|
||||
let actualTabs = tabs;
|
||||
if (query.data?.items.length === 0) {
|
||||
actualTabs = tabs.filter((tab) => tab.name !== InstalledAppVariants.payment);
|
||||
|
||||
@@ -110,7 +110,7 @@ const SettingsSidebarContainer = ({ className = "" }) => {
|
||||
const [teamMenuState, setTeamMenuState] =
|
||||
useState<{ teamId: number | undefined; teamMenuOpen: boolean }[]>();
|
||||
|
||||
const { data: teams } = trpc.useQuery(["viewer.teams.list"]);
|
||||
const { data: teams } = trpc.viewer.teams.list.useQuery();
|
||||
|
||||
useEffect(() => {
|
||||
if (teams) {
|
||||
|
||||
@@ -25,7 +25,7 @@ export default function SAMLLogin({ samlTenantID, samlProductID, setErrorMessage
|
||||
const methods = useFormContext();
|
||||
const telemetry = useTelemetry();
|
||||
|
||||
const mutation = trpc.useMutation("viewer.public.samlTenantProduct", {
|
||||
const mutation = trpc.viewer.public.samlTenantProduct.useMutation({
|
||||
onSuccess: async (data) => {
|
||||
await signIn("saml", {}, { tenant: data.tenant, product: data.product });
|
||||
},
|
||||
|
||||
@@ -62,7 +62,7 @@ export default function CreateEventTypeButton(props: CreateEventTypeBtnProps) {
|
||||
const form = useForm<z.infer<typeof createEventTypeInput>>({
|
||||
resolver: zodResolver(createEventTypeInput),
|
||||
});
|
||||
const { setValue, watch, register } = form;
|
||||
const { setValue, register } = form;
|
||||
|
||||
useEffect(() => {
|
||||
if (!router.isReady) return;
|
||||
@@ -84,7 +84,7 @@ export default function CreateEventTypeButton(props: CreateEventTypeBtnProps) {
|
||||
// If query params change, update the form
|
||||
}, [router.isReady, router.query, setValue]);
|
||||
|
||||
const createMutation = trpc.useMutation("viewer.eventTypes.create", {
|
||||
const createMutation = trpc.viewer.eventTypes.create.useMutation({
|
||||
onSuccess: async ({ eventType }) => {
|
||||
await router.replace("/event-types/" + eventType.id);
|
||||
showToast(t("event_type_created_successfully", { eventTypeTitle: eventType.title }), "success");
|
||||
@@ -345,13 +345,10 @@ function CreateEventTeamsItem(props: {
|
||||
option: EventTypeParent;
|
||||
}) {
|
||||
const session = useSession();
|
||||
const membershipQuery = trpc.useQuery([
|
||||
"viewer.teams.getMembershipbyUser",
|
||||
{
|
||||
memberId: session.data?.user?.id as number,
|
||||
teamId: props.option.teamId as number,
|
||||
},
|
||||
]);
|
||||
const membershipQuery = trpc.viewer.teams.getMembershipbyUser.useQuery({
|
||||
memberId: session.data?.user?.id as number,
|
||||
teamId: props.option.teamId as number,
|
||||
});
|
||||
|
||||
const isDisabled = membershipQuery.data?.role === "MEMBER";
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ export default function DisconnectIntegration({
|
||||
const { t } = useLocale();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
|
||||
const mutation = trpc.useMutation("viewer.deleteCredential", {
|
||||
const mutation = trpc.viewer.deleteCredential.useMutation({
|
||||
onSuccess: () => {
|
||||
showToast(t("app_removed_successfully"), "success");
|
||||
setModalOpen(false);
|
||||
|
||||
@@ -21,16 +21,16 @@ export default function TeamSettingsRightSidebar(props: { team: TeamWithMembers;
|
||||
|
||||
const permalink = `${process.env.NEXT_PUBLIC_WEBSITE_URL}/team/${props.team?.slug}`;
|
||||
|
||||
const deleteTeamMutation = trpc.useMutation("viewer.teams.delete", {
|
||||
const deleteTeamMutation = trpc.viewer.teams.delete.useMutation({
|
||||
async onSuccess() {
|
||||
await utils.invalidateQueries(["viewer.teams.get"]);
|
||||
await utils.viewer.teams.get.invalidate();
|
||||
router.push(`/settings/teams`);
|
||||
showToast(t("your_team_updated_successfully"), "success");
|
||||
},
|
||||
});
|
||||
const acceptOrLeaveMutation = trpc.useMutation("viewer.teams.acceptOrLeave", {
|
||||
const acceptOrLeaveMutation = trpc.viewer.teams.acceptOrLeave.useMutation({
|
||||
onSuccess: () => {
|
||||
utils.invalidateQueries(["viewer.teams.list"]);
|
||||
utils.viewer.teams.list.invalidate();
|
||||
router.push(`/settings/teams`);
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user