fix: 🐛 only counted row instead of value

This commit is contained in:
amianthus
2025-09-16 14:47:04 +01:00
parent e7f6dffe34
commit 7e201dae41

View File

@@ -1,8 +1,10 @@
import { ClickHouseClient } from "@clickhouse/client";
import { ErrCode, FullCustomer } from "@autumn/shared";
import { ExtendedRequest } from "@/utils/models/Request.js";
import RecaseError from "@/utils/errorUtils.js";
/** biome-ignore-all lint/complexity/noStaticOnlyClass: wrap it up buddy */
import { ErrCode, type FullCustomer } from "@autumn/shared";
import type { ClickHouseClient } from "@clickhouse/client";
import { StatusCodes } from "http-status-codes";
import RecaseError from "@/utils/errorUtils.js";
import type { ExtendedRequest } from "@/utils/models/Request.js";
import {
generateEventCountExpressions,
getBillingCycleStartDate,
@@ -136,13 +138,15 @@ WHERE
const { clickhouseClient, org, env, db } = req;
const query = `
SELECT org_id, env, COUNT(*) AS total_events
FROM events
WHERE org_id = {org_id: String}
AND env = {env: String}
${eventName ? `AND event_name = {eventName: String}` : ""}
GROUP BY org_id, env
LIMIT 1;
SELECT SUM(
CASE
WHEN JSONHas(properties, 'value') THEN toInt64(JSONExtractFloat(properties, 'value'))
WHEN value IS NOT NULL THEN toInt64(value)
ELSE 1
END
) AS total_events
FROM org_events_view(org_id={org_id:String}, org_slug='', env={env:String})
WHERE event_name = {eventName:String}
`;
const result = await clickhouseClient.query({
@@ -205,20 +209,20 @@ WHERE org_id = {org_id:String}
AnalyticsService.handleEarlyExit();
// Skip billing cycle calculation if aggregating all customers
let getBCResults =
const getBCResults =
isBillingCycle && !aggregateAll && customer
? ((await getBillingCycleStartDate(
env,
org?.id,
customer,
db,
intervalType as "1bc" | "3bc"
intervalType as "1bc" | "3bc",
)) as { startDate: string; endDate: string; gap: number } | null)
: null;
const countExpressions = generateEventCountExpressions(
params.event_names,
params.no_count
params.no_count,
);
if (AnalyticsService.clickhouseAvailable) {
@@ -293,7 +297,7 @@ order by dr.period;
},
});
let resultJson = await result.json();
const resultJson = await result.json();
resultJson.data.forEach((row: any) => {
Object.keys(row).forEach((key: string) => {
@@ -322,19 +326,19 @@ order by dr.period;
AnalyticsService.handleEarlyExit();
let startDate = new Date();
const startDate = new Date();
const intervalType = params.interval || "day";
const isBillingCycle = intervalType === "1bc" || intervalType === "3bc";
// Skip billing cycle calculation if aggregating all customers
let getBCResults =
const getBCResults =
isBillingCycle && !aggregateAll && customer
? ((await getBillingCycleStartDate(
env,
org?.id,
customer,
db,
intervalType as "1bc" | "3bc"
intervalType as "1bc" | "3bc",
)) as { startDate: string; endDate: string; gap: number } | null)
: null;