import { getPropertyId, formatPropertyPath, executeReport } from "../../client.js";
import { periodToDateRange } from "../../utils/date.js";
import { calculatePercentage } from "../../utils/percentage.js";
import type {
GetGeoBreakdownInput,
GetGeoBreakdownOutput,
LocationData,
} from "../../types.js";
/**
* 地域別アクセス分析
*/
export async function getGeoBreakdown(
input: GetGeoBreakdownInput
): Promise<GetGeoBreakdownOutput> {
const propertyId = getPropertyId(input.propertyId);
const property = formatPropertyPath(propertyId);
const dateRange = periodToDateRange(input.period);
const limit = input.limit || 10;
// level に応じてディメンションを選択
const dimension = input.level === "city" ? "city" : "country";
const response = await executeReport({
property,
dateRanges: [dateRange],
dimensions: [{ name: dimension }],
metrics: [{ name: "totalUsers" }, { name: "sessions" }],
orderBys: [{ metric: { metricName: "totalUsers" }, desc: true }],
limit,
});
// 合計ユーザー数を取得
const totalUsers =
response.totals?.[0]?.metricValues?.[0]?.value
? parseFloat(response.totals[0].metricValues[0].value)
: 0;
const locations: LocationData[] = [];
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;
};
const users = Math.round(getValue(0));
locations.push({
name: dimensionValues[0]?.value || "(不明)",
users,
sessions: Math.round(getValue(1)),
percentage: calculatePercentage(users, totalUsers),
});
}
return { locations };
}