Files
medical-mall/utils/akUserMapping.uts
2026-06-12 10:16:27 +08:00

167 lines
5.2 KiB
Plaintext
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.
import supa from '@/components/supadb/aksupainstance.uts'
// ─────────────────────────────────────────────────────────────
// akUserMapping - Supabase Auth ID 到业务用户 ID 的映射管理
//
// 核心概念:
// - authUserId: Supabase Auth 用户 IDsession.user.id
// - akUserId: 业务用户 IDak_users.id
// - 所有业务表ec_care_tasks.assigned_to、hc_dispatch_assignments.worker_id 等)
// 都使用 akUserId不是 authUserId
// ─────────────────────────────────────────────────────────────
const AUTH_USER_ID_KEY = 'auth_user_id' // Supabase Auth ID
const AK_USER_ID_KEY = 'ak_user_id' // 业务用户 ID
const AK_USER_PROFILE_KEY = 'current_ak_user' // 完整业务用户信息
export type AkUserProfile = {
id: string // ak_users.id业务用户 ID
auth_id: string // ak_users.auth_idSupabase Auth ID
username: string
email: string
role: string
user_type: string
status: string
}
/**
* 加载当前登录用户的业务账号信息
* 从 Supabase Auth 获取 authUserId然后查询 ak_users 表获取业务用户信息
*/
export async function loadCurrentAkUser(): Promise<AkUserProfile> {
// 1. 获取当前 Supabase Auth 用户
const session = supa.getSession()
if (session == null || session.user == null) {
throw new Error('未登录或登录状态失效')
}
const authUserId = session.user.getString('id') ?? ''
if (authUserId == '') {
throw new Error('未获取到 Supabase Auth 用户 ID')
}
// 2. 查询 ak_users 表,通过 auth_id 匹配
const { data: profiles, error } = await supa
.from('ak_users')
.select('id, auth_id, username, email, role, user_type, status')
.eq('auth_id', authUserId)
.single()
if (error != null || profiles == null) {
throw new Error('未找到当前用户的业务账号,请联系管理员绑定 ak_users.auth_id')
}
// 3. 存储到本地
const profile: AkUserProfile = {
id: profiles.getString('id') ?? '',
auth_id: profiles.getString('auth_id') ?? '',
username: profiles.getString('username') ?? '',
email: profiles.getString('email') ?? '',
role: profiles.getString('role') ?? '',
user_type: profiles.getString('user_type') ?? '',
status: profiles.getString('status') ?? ''
}
uni.setStorageSync(AUTH_USER_ID_KEY, profile.auth_id)
uni.setStorageSync(AK_USER_ID_KEY, profile.id)
uni.setStorageSync(AK_USER_PROFILE_KEY, JSON.stringify(profile))
console.log('[akUserMapping] 加载业务用户成功:', {
authUserId: profile.auth_id,
akUserId: profile.id,
username: profile.username,
role: profile.role
})
return profile
}
/**
* 获取当前业务用户 IDak_users.id
* 优先从本地缓存读取,如果缓存不存在则自动加载
*/
export async function getCurrentAkUserId(): Promise<string> {
// 1. 尝试从缓存读取
const cachedAkUserId = uni.getStorageSync(AK_USER_ID_KEY)
if (cachedAkUserId != null && String(cachedAkUserId).length > 0) {
return String(cachedAkUserId)
}
// 2. 缓存不存在,自动加载
const profile = await loadCurrentAkUser()
return profile.id
}
/**
* 获取当前业务用户完整信息
*/
export async function getCurrentAkUser(): Promise<AkUserProfile | null> {
// 1. 尝试从缓存读取
const cached = uni.getStorageSync(AK_USER_PROFILE_KEY)
if (cached != null && String(cached).length > 0) {
try {
return JSON.parse(cached) as AkUserProfile
} catch (e) {
// 解析失败,重新加载
}
}
// 2. 缓存不存在,自动加载
try {
return await loadCurrentAkUser()
} catch (e) {
return null
}
}
/**
* 获取当前 Supabase Auth 用户 ID
*/
export function getCurrentAuthUserId(): string {
const cached = uni.getStorageSync(AUTH_USER_ID_KEY)
if (cached != null && String(cached).length > 0) {
return String(cached)
}
// 尝试从 session 获取
try {
const session = supa.getSession()
if (session != null && session.user != null) {
return session.user.getString('id') ?? ''
}
} catch (e) {}
return ''
}
/**
* 清除本地存储的 ak_user 信息
*/
export function clearAkUserCache(): void {
uni.removeStorageSync(AUTH_USER_ID_KEY)
uni.removeStorageSync(AK_USER_ID_KEY)
uni.removeStorageSync(AK_USER_PROFILE_KEY)
}
/**
* 调试输出:打印当前用户信息
*/
export function debugCurrentUser(): void {
console.log('[akUserMapping] ========== 当前用户调试信息 ==========')
console.log('[akUserMapping] authUserId:', uni.getStorageSync(AUTH_USER_ID_KEY))
console.log('[akUserMapping] akUserId:', uni.getStorageSync(AK_USER_ID_KEY))
const profileRaw = uni.getStorageSync(AK_USER_PROFILE_KEY)
if (profileRaw != null && String(profileRaw).length > 0) {
try {
const profile = JSON.parse(profileRaw) as AkUserProfile
console.log('[akUserMapping] profile:', profile)
} catch (e) {
console.log('[akUserMapping] profile (raw):', profileRaw)
}
} else {
console.log('[akUserMapping] profile: (未缓存)')
}
console.log('[akUserMapping] ======================================')
}