video-flow-b/hooks/useAppStartupAnalytics.ts
2025-09-28 18:11:29 +08:00

68 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 应用启动时用户属性设置Hook
* 确保在应用启动时为用户设置GA属性
*/
import { useEffect } from 'react';
import { getCurrentUser, isAuthenticated } from '@/lib/auth';
import { setUserProperties } from '@/utils/analytics';
/**
* 应用启动时设置用户GA属性
*/
export const useAppStartupAnalytics = () => {
useEffect(() => {
const initializeUserAnalytics = () => {
// 检查用户是否已认证
if (!isAuthenticated()) {
console.log('用户未认证跳过GA属性设置');
return;
}
// 获取本地存储的用户数据
const currentUser = getCurrentUser();
if (!currentUser || !currentUser.id) {
console.log('本地用户数据不存在跳过GA属性设置');
return;
}
try {
// 设置应用启动时的用户属性
// 基于实际userData结构: {"id":"8f61686734d340d0820f0fe980368629","userId":"8f61686734d340d0820f0fe980368629","username":"Orange","email":"moviflow68@test.com","isActive":1,"authType":"LOCAL","lastLogin":"2025-09-28T16:28:51.870731"}
setUserProperties(currentUser.id, {
// 基础用户信息
user_id: currentUser.id,
email: currentUser.email,
username: currentUser.username,
// 认证信息
auth_type: currentUser.authType || 'LOCAL',
is_active: currentUser.isActive || 1,
// 应用启动信息
last_login: currentUser.lastLogin || new Date().toISOString(),
// 用户状态
user_status: currentUser.isActive === 1 ? 'active' : 'inactive',
// 设备信息
user_agent: navigator.userAgent,
screen_resolution: `${screen.width}x${screen.height}`,
language: navigator.language,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
// 会话信息
session_id: `${currentUser.id}_${Date.now()}`,
});
} catch (error) {
console.error('❌ 应用启动时GA用户属性设置失败:', error);
}
};
// 延迟执行,确保应用完全加载
const timer = setTimeout(initializeUserAnalytics, 1000);
return () => clearTimeout(timer);
}, []);
};