2021-10-03 18:24:46 +00:00
|
|
|
import { paginate, resolver } from "blitz";
|
|
|
|
import { z } from "zod";
|
2021-09-30 22:59:35 +00:00
|
|
|
|
2021-10-01 21:05:07 +00:00
|
|
|
import db from "db";
|
2021-09-30 22:59:35 +00:00
|
|
|
import { getPayments } from "integrations/paddle";
|
|
|
|
|
2021-10-03 18:24:46 +00:00
|
|
|
const Body = z.object({
|
|
|
|
skip: z.number().optional(),
|
|
|
|
take: z.number().optional(),
|
|
|
|
});
|
|
|
|
|
|
|
|
export default resolver.pipe(resolver.zod(Body), resolver.authorize(), async ({ skip, take }, { session }) => {
|
2021-09-30 22:59:35 +00:00
|
|
|
if (!session.orgId) {
|
2021-10-03 18:24:46 +00:00
|
|
|
return {
|
|
|
|
payments: [],
|
|
|
|
nextPage: null,
|
|
|
|
hasMore: false,
|
|
|
|
count: 0,
|
|
|
|
};
|
2021-09-30 22:59:35 +00:00
|
|
|
}
|
|
|
|
|
2021-10-01 21:05:07 +00:00
|
|
|
const subscriptions = await db.subscription.findMany({ where: { organizationId: session.orgId } });
|
|
|
|
if (subscriptions.length === 0) {
|
2021-10-03 18:24:46 +00:00
|
|
|
return {
|
|
|
|
payments: [],
|
|
|
|
nextPage: null,
|
|
|
|
hasMore: false,
|
|
|
|
count: 0,
|
|
|
|
};
|
2021-09-30 22:59:35 +00:00
|
|
|
}
|
|
|
|
|
2021-10-01 21:05:07 +00:00
|
|
|
const paymentsBySubscription = await Promise.all(
|
|
|
|
subscriptions.map((subscription) => getPayments({ subscriptionId: subscription.paddleSubscriptionId })),
|
|
|
|
);
|
2021-10-03 18:24:46 +00:00
|
|
|
const unsortedPayments = paymentsBySubscription.flat();
|
|
|
|
const allPayments = Array.from(unsortedPayments).sort((a, b) => b.payout_date.localeCompare(a.payout_date));
|
|
|
|
|
|
|
|
const {
|
|
|
|
items: payments,
|
|
|
|
hasMore,
|
|
|
|
nextPage,
|
|
|
|
count,
|
|
|
|
} = await paginate({
|
|
|
|
skip,
|
|
|
|
take,
|
|
|
|
count: () => Promise.resolve(allPayments.length),
|
|
|
|
query: ({ skip, take }) => Promise.resolve(allPayments.slice(skip, skip + take)),
|
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
payments,
|
|
|
|
nextPage,
|
|
|
|
hasMore,
|
|
|
|
count,
|
|
|
|
};
|
2021-09-30 22:59:35 +00:00
|
|
|
});
|