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 {
GetEngagementMetricsInput,
GetEngagementMetricsOutput,
} from "../../types.js";
/**
* エンゲージメント関連の詳細指標を取得
*/
export async function getEngagementMetrics(
input: GetEngagementMetricsInput
): Promise<GetEngagementMetricsOutput> {
const propertyId = getPropertyId(input.propertyId);
const property = formatPropertyPath(propertyId);
const dateRange = periodToDateRange(input.period);
const response = await executeReport({
property,
dateRanges: [dateRange],
metrics: [
{ name: "engagementRate" },
{ name: "userEngagementDuration" },
{ name: "engagedSessions" },
{ name: "totalUsers" },
{ name: "eventCount" },
{ name: "sessions" },
],
});
const metricValues = response.totals?.[0]?.metricValues || [];
const getValue = (index: number): number => {
const value = metricValues[index]?.value;
return value ? parseFloat(value) : 0;
};
const engagementRate = getValue(0);
const userEngagementDuration = getValue(1);
const engagedSessions = getValue(2);
const totalUsers = getValue(3);
const eventCount = getValue(4);
const sessions = getValue(5);
// エンゲージセッション/ユーザー
const engagedSessionsPerUser =
totalUsers > 0 ? roundToDecimal(engagedSessions / totalUsers) : 0;
// イベント/セッション
const eventsPerSession =
sessions > 0 ? roundToDecimal(eventCount / sessions) : 0;
// 平均エンゲージメント時間
const avgEngagementTime =
totalUsers > 0
? formatDuration(userEngagementDuration / totalUsers)
: "0秒";
return {
engagementRate: formatPercentageFromDecimal(engagementRate),
avgEngagementTime,
engagedSessionsPerUser,
eventsPerSession,
// スクロール深度は別途イベントベースの設定が必要なため省略
};
}