import { getPropertyId, formatPropertyPath, executeReport } from "../../client.js";
import { periodToDateRange } from "../../utils/date.js";
import { formatDuration, roundToDecimal } from "../../utils/format.js";
import { formatPercentageFromDecimal } from "../../utils/percentage.js";
import type { GetTrafficSummaryInput, TrafficSummaryOutput } from "../../types.js";
/**
* トラフィックサマリーを取得
*/
export async function getTrafficSummary(
input: GetTrafficSummaryInput
): Promise<TrafficSummaryOutput> {
const propertyId = getPropertyId(input.propertyId);
const property = formatPropertyPath(propertyId);
const dateRange = periodToDateRange(input.period);
const response = await executeReport({
property,
dateRanges: [dateRange],
metrics: [
{ name: "screenPageViews" },
{ name: "totalUsers" },
{ name: "sessions" },
{ name: "newUsers" },
{ name: "averageSessionDuration" },
{ name: "bounceRate" },
{ name: "engagementRate" },
{ name: "screenPageViewsPerSession" },
],
});
// 結果からメトリクス値を取得
const metricValues = response.totals?.[0]?.metricValues || [];
const getValue = (index: number): number => {
const value = metricValues[index]?.value;
return value ? parseFloat(value) : 0;
};
return {
totalPageViews: Math.round(getValue(0)),
totalUsers: Math.round(getValue(1)),
totalSessions: Math.round(getValue(2)),
newUsers: Math.round(getValue(3)),
avgSessionDuration: formatDuration(getValue(4)),
bounceRate: formatPercentageFromDecimal(getValue(5)),
engagementRate: formatPercentageFromDecimal(getValue(6)),
pagesPerSession: roundToDecimal(getValue(7)),
period: dateRange,
};
}