2021-10-01 21:04:12 +00:00
|
|
|
import { Queue } from "quirrel/blitz";
|
|
|
|
import type { PaddleSdkSubscriptionCancelledEvent } from "@devoxa/paddle-sdk";
|
|
|
|
|
|
|
|
import db from "db";
|
|
|
|
import appLogger from "integrations/logger";
|
2021-10-03 18:56:31 +00:00
|
|
|
import type { Metadata } from "integrations/paddle";
|
2021-10-01 21:04:12 +00:00
|
|
|
import { translateSubscriptionStatus } from "integrations/paddle";
|
|
|
|
|
|
|
|
const logger = appLogger.child({ queue: "subscription-cancelled" });
|
|
|
|
|
|
|
|
type Payload = {
|
2021-10-03 18:56:31 +00:00
|
|
|
event: PaddleSdkSubscriptionCancelledEvent<Metadata>;
|
2021-10-01 21:04:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const subscriptionCancelledQueue = Queue<Payload>("api/queue/subscription-cancelled", async ({ event }) => {
|
|
|
|
const paddleSubscriptionId = event.subscriptionId;
|
|
|
|
const subscription = await db.subscription.findFirst({ where: { paddleSubscriptionId } });
|
|
|
|
if (!subscription) {
|
2021-10-20 17:25:07 +00:00
|
|
|
// user deleted their account, no need to update their subscription
|
|
|
|
return;
|
2021-10-01 21:04:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const lastEventTime = event.eventTime;
|
|
|
|
const isEventOlderThanLastUpdate = subscription.lastEventTime > lastEventTime;
|
|
|
|
if (isEventOlderThanLastUpdate) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
await db.subscription.update({
|
|
|
|
where: { paddleSubscriptionId },
|
|
|
|
data: {
|
|
|
|
paddleSubscriptionId,
|
|
|
|
paddlePlanId: event.productId,
|
|
|
|
paddleCheckoutId: event.checkoutId,
|
|
|
|
status: translateSubscriptionStatus(event.status),
|
|
|
|
lastEventTime,
|
|
|
|
currency: event.currency,
|
|
|
|
unitPrice: event.unitPrice,
|
2021-10-03 18:56:31 +00:00
|
|
|
cancellationEffectiveDate: event.cancelledFrom,
|
2021-10-01 21:04:12 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
export default subscriptionCancelledQueue;
|