Files
sign/apps/web/pages/api/documents/[id]/send.ts

61 lines
1.7 KiB
TypeScript
Raw Normal View History

import { NextApiRequest, NextApiResponse } from "next";
2023-02-01 18:32:59 +01:00
import { sendSigningRequest } from "@documenso/lib/mail";
import { getDocument } from "@documenso/lib/query";
2023-04-04 22:02:32 +00:00
import { defaultHandler, defaultResponder, getUserFromToken } from "@documenso/lib/server";
import prisma from "@documenso/prisma";
2023-02-07 12:54:31 +01:00
import { Document as PrismaDocument, SendStatus } from "@prisma/client";
async function postHandler(req: NextApiRequest, res: NextApiResponse) {
const user = await getUserFromToken(req, res);
const { id: documentId } = req.query;
2023-02-24 09:24:19 +01:00
const { resendTo: resendTo = [] } = req.body;
if (!user) return;
if (!documentId) {
res.status(400).send("Missing parameter documentId.");
return;
}
2023-02-01 19:15:43 +01:00
const document: PrismaDocument = await getDocument(+documentId, req, res);
2023-04-04 22:02:32 +00:00
if (!document) res.status(404).end(`No document with id ${documentId} found.`);
2023-02-24 09:24:19 +01:00
let recipientCondition: any = {
documentId: +documentId,
sendStatus: SendStatus.NOT_SENT,
};
if (resendTo.length) {
recipientCondition = {
documentId: +documentId,
id: { in: resendTo },
};
}
2023-02-07 12:54:31 +01:00
const recipients = await prisma.recipient.findMany({
2023-01-27 20:14:32 +01:00
where: {
2023-02-24 09:24:19 +01:00
...recipientCondition,
2023-01-27 20:14:32 +01:00
},
});
2023-02-07 12:54:31 +01:00
2023-02-24 09:24:19 +01:00
if (!recipients.length) return res.status(200).send(recipients.length);
2023-02-07 12:54:31 +01:00
let sentRequests = 0;
2023-02-18 13:19:37 +01:00
recipients.forEach(async (recipient) => {
await sendSigningRequest(recipient, document, user).catch((err) => {
console.log(err);
return res.status(502).end("Coud not send request for signing.");
});
sentRequests++;
if (sentRequests === recipients.length) {
2023-02-24 09:24:19 +01:00
return res.status(200).send(recipients.length);
}
});
}
export default defaultHandler({
POST: Promise.resolve({ default: defaultResponder(postHandler) }),
});