-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathanalyticsUtils.ts
More file actions
422 lines (365 loc) · 11.8 KB
/
Copy pathanalyticsUtils.ts
File metadata and controls
422 lines (365 loc) · 11.8 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import {
cusProductToProduct,
EntInterval,
ErrCode,
type FullCusProduct,
type FullCustomer,
type FullProduct,
RecaseError,
type Subscription,
} from "@autumn/shared";
import { UTCDate } from "@date-fns/utc";
import { format, startOfDay, startOfHour, sub } from "date-fns";
import type Stripe from "stripe";
import type { DrizzleCli } from "@/db/initDrizzle.js";
import { createStripeCli } from "@/external/connect/createStripeCli.js";
import { subToPeriodStartEnd } from "@/external/stripe/stripeSubUtils/convertSubUtils.js";
import type { AutumnContext } from "@/honoUtils/HonoEnv.js";
import { ACTIVE_STATUSES } from "@/internal/customers/cusProducts/CusProductService.js";
import { isFreeProduct } from "../products/productUtils.js";
export const STANDARD_INTERVAL_DAYS: Record<string, number> = {
"24h": 1,
"7d": 7,
"30d": 30,
"90d": 90,
};
const CLICKHOUSE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
/** Resolves the start/end window the event-name ranking should query so it
* matches the chart's visible range. A custom range takes precedence; otherwise
* a standard interval is resolved with the same boundary alignment the chart
* uses — hour for 24h, day for 7d/30d/90d. Returns undefined when neither
* applies (e.g. billing-cycle intervals), leaving callers on all-time ranking. */
export const getEventRankingWindow = ({
interval,
customRange,
}: {
interval?: string;
customRange?: { start: number; end: number };
}): { startDate: string; endDate: string } | undefined => {
if (customRange) {
return {
startDate: format(new UTCDate(customRange.start), CLICKHOUSE_DATE_FORMAT),
endDate: format(new UTCDate(customRange.end), CLICKHOUSE_DATE_FORMAT),
};
}
const days = interval ? STANDARD_INTERVAL_DAYS[interval] : undefined;
if (!days) {
return undefined;
}
const now = new UTCDate();
const unaligned = sub(now, { days });
const start =
interval === "24h" ? startOfHour(unaligned) : startOfDay(unaligned);
return {
startDate: format(start, CLICKHOUSE_DATE_FORMAT),
endDate: format(now, CLICKHOUSE_DATE_FORMAT),
};
};
export async function getBillingCycleStartDate({
customer,
db,
intervalType,
ctx,
}: {
customer?: FullCustomer;
db?: DrizzleCli;
intervalType?: "1bc" | "3bc" | "last_cycle";
ctx: AutumnContext;
}) {
if (!customer || !db || !intervalType) {
return {};
}
const subscriptions = customer.subscriptions || [];
const cusProducts = customer.customer_products.filter(
(product: FullCusProduct) => ACTIVE_STATUSES.includes(product.status),
);
if (cusProducts.length === 0) {
return {};
}
const fullProducts = cusProducts.map((cp: FullCusProduct) =>
cusProductToProduct({ cusProduct: cp }),
);
const areAllProductsFree = checkIfAllProductsAreFree(fullProducts);
let { startDates, endDates, createdDates } = areAllProductsFree
? getDateRangesFromEntitlements(customer.customer_products)
: getDateRangesFromSubscriptions(cusProducts, subscriptions);
// If we have subscription_ids but no matching subscriptions in DB, fallback to Stripe
const hasMissingSubscriptions =
!areAllProductsFree &&
startDates.length === 0 &&
cusProducts.some(
(p) => p.subscription_ids && p.subscription_ids.length > 0,
);
if (hasMissingSubscriptions) {
const stripeSubs = await fetchMissingSubscriptionsFromStripe({
cusProducts,
dbSubscriptions: subscriptions,
ctx,
});
// Re-calculate date ranges with Stripe subscriptions
const stripeDateRanges = getDateRangesFromStripeSubscriptions(
cusProducts,
stripeSubs,
);
startDates = stripeDateRanges.startDates;
endDates = stripeDateRanges.endDates;
createdDates = stripeDateRanges.createdDates;
}
if (startDates.length === 0 || endDates.length === 0) {
return {};
}
return calculateBillingCycleResult(
startDates,
endDates,
createdDates,
intervalType,
);
}
async function fetchMissingSubscriptionsFromStripe({
cusProducts,
dbSubscriptions,
ctx,
}: {
cusProducts: FullCusProduct[];
dbSubscriptions: Subscription[];
ctx: AutumnContext;
}): Promise<Stripe.Subscription[]> {
// Collect all subscription IDs from products that aren't in the DB
const missingSubIds: string[] = [];
for (const product of cusProducts) {
for (const subId of product.subscription_ids || []) {
const foundInDb = dbSubscriptions.some((s) => s.stripe_id === subId);
if (!foundInDb && subId) {
missingSubIds.push(subId);
}
}
}
if (missingSubIds.length === 0) {
return [];
}
const stripe = createStripeCli({ org: ctx.org, env: ctx.env });
const stripeSubs: Stripe.Subscription[] = [];
for (const subId of missingSubIds) {
try {
const stripeSub = await stripe.subscriptions.retrieve(subId);
stripeSubs.push(stripeSub);
} catch (error) {
throw new RecaseError({
message: `Failed to fetch subscription ${subId} from Stripe: ${error instanceof Error ? error.message : "Unknown error"}`,
code: ErrCode.StripeError,
statusCode: 500,
});
}
}
return stripeSubs;
}
function getDateRangesFromStripeSubscriptions(
customerProductsFiltered: FullCusProduct[],
stripeSubscriptions: Stripe.Subscription[],
): { startDates: string[]; endDates: string[]; createdDates: string[] } {
const startDates: string[] = [];
const endDates: string[] = [];
const createdDates: string[] = [];
for (const product of customerProductsFiltered) {
for (const subscriptionId of product.subscription_ids || []) {
const subscription = stripeSubscriptions.find(
(s) => s.id === subscriptionId,
);
if (subscription) {
// Use utility to extract period dates from subscription items
const period = subToPeriodStartEnd({ sub: subscription });
startDates.push(formatDateToString(new Date(period.start * 1000)));
endDates.push(formatDateToString(new Date(period.end * 1000)));
createdDates.push(
formatDateToString(new Date(subscription.created * 1000)),
);
}
}
}
return { startDates, endDates, createdDates };
}
function checkIfAllProductsAreFree(fullProducts: FullProduct[]): boolean {
return fullProducts.every((product: FullProduct) => {
const isFree = isFreeProduct(product.prices);
return isFree;
});
}
function formatDateToString(date: Date): string {
return date.toISOString().replace("T", " ").split(".")[0];
}
function getDateRangesFromSubscriptions(
customerProductsFiltered: FullCusProduct[],
subscriptions: Subscription[],
): { startDates: string[]; endDates: string[]; createdDates: string[] } {
const startDates: string[] = [];
const endDates: string[] = [];
const createdDates: string[] = [];
for (const product of customerProductsFiltered) {
for (const subscriptionId of product.subscription_ids || []) {
const subscription = subscriptions.find(
(subscription: Subscription) =>
subscription.stripe_id === subscriptionId,
);
if (subscription) {
startDates.push(
formatDateToString(
new Date((subscription.current_period_start ?? 0) * 1000),
),
);
endDates.push(
formatDateToString(
new Date((subscription.current_period_end ?? 0) * 1000),
),
);
createdDates.push(
formatDateToString(new Date((subscription.created_at ?? 0) * 1000)),
);
}
}
}
return { startDates, endDates, createdDates };
}
function getDateRangesFromEntitlements(customerProducts?: FullCusProduct[]): {
startDates: string[];
endDates: string[];
createdDates: string[];
} {
const startDates: string[] = [];
const endDates: string[] = [];
const createdDates: string[] = [];
if (!customerProducts || customerProducts.length < 1) {
return { startDates, endDates, createdDates };
}
for (const product of customerProducts) {
if (
!product.customer_entitlements ||
product.customer_entitlements.length < 1
) {
continue;
}
for (const entitlement of product.customer_entitlements) {
if (entitlement.next_reset_at) {
endDates.push(formatDateToString(new Date(entitlement.next_reset_at)));
}
const startDate = calculateStartDateFromInterval(
entitlement.entitlement.interval,
entitlement.next_reset_at,
entitlement.created_at,
);
if (startDate) {
startDates.push(startDate);
}
createdDates.push(formatDateToString(new Date(entitlement.created_at)));
}
}
return { startDates, endDates, createdDates };
}
function calculateBillingCycleResult(
startDates: string[],
endDates: string[],
createdDates: string[],
intervalType: "1bc" | "3bc" | "last_cycle",
) {
const currentStartDate = new Date(startDates[0]);
const currentEndDate = new Date(endDates[0]);
const gap = currentEndDate.getTime() - currentStartDate.getTime();
const gapDays = Math.floor(gap / (1000 * 60 * 60 * 24));
if (intervalType === "1bc") {
return {
startDate: startDates[0],
endDate: endDates[0],
gap: gapDays,
};
}
if (intervalType === "last_cycle") {
const earliestCreation = createdDates.reduce((earliest, current) => {
const currentDate = new Date(current);
const earliestDate = new Date(earliest);
return currentDate < earliestDate ? current : earliest;
}, createdDates[0]);
const createdAt = new Date(earliestCreation);
const isSubscriptionCreatedDuringOrAfterCurrentPeriod =
createdAt >= currentStartDate;
if (isSubscriptionCreatedDuringOrAfterCurrentPeriod) {
return {
startDate: startDates[0],
endDate: endDates[0],
gap: gapDays,
};
}
const previousEndDate = new Date(currentStartDate.getTime());
const previousStartDate = new Date(currentStartDate.getTime() - gap);
return {
startDate: formatDateToString(previousStartDate),
endDate: formatDateToString(previousEndDate),
gap: gapDays,
};
}
const gapMultiplier = 3;
const now = new Date();
// For analytics, we look BACKWARD from today for N billing cycles
// End date is today, start date is today - (gap * multiplier)
const adjustedStartDate = new Date(now.getTime() - gap * gapMultiplier);
return {
startDate: formatDateToString(adjustedStartDate),
endDate: formatDateToString(now),
gap: gapDays * gapMultiplier,
};
}
function calculateStartDateFromInterval(
interval: EntInterval | null | undefined,
nextResetAt: number | null | undefined,
createdAt: number,
): string | null {
if (!nextResetAt && interval !== EntInterval.Lifetime) {
return null;
}
switch (interval) {
case EntInterval.Lifetime:
return formatDateToString(new Date(createdAt));
case EntInterval.Minute:
return formatDateToString(new Date(nextResetAt! - 60 * 1000));
case EntInterval.Hour:
return formatDateToString(new Date(nextResetAt! - 60 * 60 * 1000));
case EntInterval.Day:
return formatDateToString(new Date(nextResetAt! - 24 * 60 * 60 * 1000));
case EntInterval.Week:
return formatDateToString(
new Date(nextResetAt! - 7 * 24 * 60 * 60 * 1000),
);
case EntInterval.Month: {
const monthResetDate = new Date(nextResetAt!);
monthResetDate.setMonth(monthResetDate.getMonth() - 1);
return formatDateToString(monthResetDate);
}
case EntInterval.Quarter: {
const quarterResetDate = new Date(nextResetAt!);
quarterResetDate.setMonth(quarterResetDate.getMonth() - 3);
return formatDateToString(quarterResetDate);
}
case EntInterval.SemiAnnual: {
const semiAnnualResetDate = new Date(nextResetAt!);
semiAnnualResetDate.setMonth(semiAnnualResetDate.getMonth() - 6);
return formatDateToString(semiAnnualResetDate);
}
case EntInterval.Year: {
const yearResetDate = new Date(nextResetAt!);
yearResetDate.setFullYear(yearResetDate.getFullYear() - 1);
return formatDateToString(yearResetDate);
}
default:
return null;
}
}
export function generateEventCountExpressions(
eventNames: string[],
noCount: boolean = false,
): string {
const expressions = eventNames.map((eventName) => {
// Escape single quotes for SQL safety
const escapedEventName = eventName.replace(/'/g, "''");
const columnName = noCount ? eventName : `${eventName}_count`;
return `coalesce(sumIf(e.value, e.event_name = '${escapedEventName}'), 0) as \`${columnName}\``;
});
return expressions.join(",\n");
}