-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathprepareAutoSyncStripeCustomer.ts
More file actions
82 lines (80 loc) · 2.42 KB
/
Copy pathprepareAutoSyncStripeCustomer.ts
File metadata and controls
82 lines (80 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {
filterCustomerProductsByStripeSubscriptionId,
isCustomerProductOnStripeSubscriptionSchedule,
} from "@autumn/shared";
import { createStripeCli } from "@/external/connect/createStripeCli";
import type { AutumnContext } from "@/honoUtils/HonoEnv";
import { fetchStripeSyncSchedule } from "@/internal/billing/v2/providers/stripe/utils/sync/fetchStripeSyncObjects";
import { CusService } from "@/internal/customers/CusService";
import { ProductService } from "@/internal/products/ProductService";
import { subscriptionToSyncParams } from "../subscriptionToSyncParams";
export const prepareAutoSyncStripeCustomer = async ({
ctx,
customerId,
stripeCustomerId,
}: {
ctx: AutumnContext;
customerId: string;
stripeCustomerId: string;
}) => {
const stripeCli = createStripeCli({ org: ctx.org, env: ctx.env });
const [subscriptions, schedules, customer] = await Promise.all([
stripeCli.subscriptions
.list({ customer: stripeCustomerId, limit: 100 })
.autoPagingToArray({ limit: 10_000 }),
stripeCli.subscriptionSchedules
.list({ customer: stripeCustomerId, scheduled: true, limit: 100 })
.autoPagingToArray({ limit: 10_000 }),
CusService.getFull({ ctx, idOrInternalId: customerId }),
]);
const pendingSubscriptions = subscriptions.filter(
(subscription) =>
filterCustomerProductsByStripeSubscriptionId({
customerProducts: customer.customer_products,
stripeSubscriptionId: subscription.id,
}).length === 0,
);
const pendingSchedules = schedules.filter(
(schedule) =>
!customer.customer_products.some((customerProduct) =>
isCustomerProductOnStripeSubscriptionSchedule({
customerProduct,
stripeSubscriptionScheduleId: schedule.id,
}),
),
);
if (pendingSubscriptions.length === 0 && pendingSchedules.length === 0) {
return [];
}
const fullProducts = await ProductService.listFull({
db: ctx.db,
orgId: ctx.org.id,
env: ctx.env,
});
return Promise.all([
...pendingSubscriptions.map((subscription) =>
subscriptionToSyncParams({
ctx,
customerId,
subscription,
customerProducts: customer.customer_products,
fullProducts,
}),
),
...pendingSchedules.map(async ({ id }) => {
const schedule = await fetchStripeSyncSchedule({
stripeCli,
scheduleId: id,
});
return schedule
? subscriptionToSyncParams({
ctx,
customerId,
schedule,
customerProducts: customer.customer_products,
fullProducts,
})
: null;
}),
]);
};