2021-09-24 23:09:20 +00:00
|
|
|
import { Queue } from "quirrel/blitz";
|
|
|
|
|
2021-10-03 16:19:45 +00:00
|
|
|
import db, { MembershipRole, SubscriptionStatus } from "../../../../db";
|
2021-09-24 23:09:20 +00:00
|
|
|
import appLogger from "../../../../integrations/logger";
|
2021-10-01 18:07:00 +00:00
|
|
|
import { cancelPaddleSubscription } from "../../../../integrations/paddle";
|
2021-09-24 23:09:20 +00:00
|
|
|
|
|
|
|
const logger = appLogger.child({ queue: "delete-user-data" });
|
|
|
|
|
|
|
|
type Payload = {
|
|
|
|
userId: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
const deleteUserData = Queue<Payload>("api/queue/delete-user-data", async ({ userId }) => {
|
|
|
|
const user = await db.user.findFirst({
|
|
|
|
where: { id: userId },
|
|
|
|
include: {
|
|
|
|
memberships: {
|
|
|
|
include: {
|
|
|
|
organization: {
|
2021-10-03 16:19:45 +00:00
|
|
|
include: {
|
|
|
|
subscriptions: {
|
|
|
|
where: { status: { not: SubscriptionStatus.deleted } },
|
|
|
|
},
|
|
|
|
},
|
2021-09-24 23:09:20 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
if (!user) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
switch (user.memberships[0]!.role) {
|
|
|
|
case MembershipRole.OWNER: {
|
|
|
|
const organization = user.memberships[0]!.organization;
|
|
|
|
await db.organization.delete({ where: { id: organization.id } });
|
2021-09-24 23:56:25 +00:00
|
|
|
await db.user.delete({ where: { id: user.id } });
|
2021-10-01 18:07:00 +00:00
|
|
|
|
2021-10-03 16:19:45 +00:00
|
|
|
if (organization.subscriptions.length > 0) {
|
|
|
|
await Promise.all(
|
|
|
|
organization.subscriptions.map((subscription) =>
|
|
|
|
cancelPaddleSubscription({ subscriptionId: subscription.paddleSubscriptionId }),
|
|
|
|
),
|
|
|
|
);
|
2021-10-01 18:07:00 +00:00
|
|
|
}
|
|
|
|
|
2021-09-24 23:09:20 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
case MembershipRole.USER: {
|
2021-09-24 23:56:25 +00:00
|
|
|
await db.user.delete({ where: { id: user.id } });
|
2021-09-24 23:09:20 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
case MembershipRole.ADMIN:
|
|
|
|
// nothing to do here?
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
export default deleteUserData;
|