import { getPropertyId, formatPropertyPath, executeReport } from "../../client.js";
import { periodToDateRange } from "../../utils/date.js";
import { formatDuration } from "../../utils/format.js";
import { formatPercentageFromDecimal } from "../../utils/percentage.js";
import type {
GetLandingPagesInput,
GetLandingPagesOutput,
LandingPage,
} from "../../types.js";
/**
* ランディングページ分析
*/
export async function getLandingPages(
input: GetLandingPagesInput
): Promise<GetLandingPagesOutput> {
const propertyId = getPropertyId(input.propertyId);
const property = formatPropertyPath(propertyId);
const dateRange = periodToDateRange(input.period);
const limit = input.limit || 10;
const response = await executeReport({
property,
dateRanges: [dateRange],
dimensions: [{ name: "landingPage" }],
metrics: [
{ name: "sessions" },
{ name: "totalUsers" },
{ name: "bounceRate" },
{ name: "averageSessionDuration" },
],
orderBys: [{ metric: { metricName: "sessions" }, desc: true }],
limit,
});
const landingPages: LandingPage[] = [];
for (const row of response.rows || []) {
const dimensionValues = row.dimensionValues || [];
const metricValues = row.metricValues || [];
const getValue = (index: number): number => {
const value = metricValues[index]?.value;
return value ? parseFloat(value) : 0;
};
landingPages.push({
pagePath: dimensionValues[0]?.value || "",
entrances: Math.round(getValue(0)),
users: Math.round(getValue(1)),
bounceRate: formatPercentageFromDecimal(getValue(2)),
avgSessionDuration: formatDuration(getValue(3)),
});
}
return { landingPages };
}