import type { ApiError } from '@/api/core/handlers'
|
import { fetchMiniMe, loginByWx } from '@/api/auth'
|
import { normalizeLoginProfile, normalizeMeProfile } from '@/types/auth'
|
import { useMiniAuthStore } from '@/store/auth'
|
|
export const EMPLOYEE_SUBSCRIBE_TEMPLATE_IDS = [
|
'QlNwG99WXWztRDgtlLcE0fHxfY2VwaX8PRMrwGpEync',
|
'Wip0ODJgybZpeFpcvev_0GK1wQXEqZw-LHOjS-UyDLw',
|
]
|
|
export const MINI_PHONE_AUTH_REQUIRED = 10008
|
|
export function getApiErrorCode(error: unknown) {
|
return typeof error === 'object' && error != null && 'code' in error
|
? Number((error as ApiError).code)
|
: NaN
|
}
|
|
export async function getWxLoginCode() {
|
// #ifdef MP-WEIXIN
|
return await new Promise<string>((resolve, reject) => {
|
uni.login({
|
provider: 'weixin',
|
success: (res) => {
|
if (res.code) {
|
resolve(res.code)
|
return
|
}
|
reject(new Error('获取微信登录凭证失败'))
|
},
|
fail: () => reject(new Error('获取微信登录凭证失败')),
|
})
|
})
|
// #endif
|
// #ifndef MP-WEIXIN
|
throw new Error('当前环境暂不支持微信授权登录')
|
// #endif
|
}
|
|
export async function requestEmployeeSubscribeAuthorization(userType?: string | null) {
|
if (userType !== 'EMPLOYEE') {
|
return
|
}
|
// #ifdef MP-WEIXIN
|
try {
|
await new Promise<void>((resolve) => {
|
uni.requestSubscribeMessage({
|
tmplIds: EMPLOYEE_SUBSCRIBE_TEMPLATE_IDS,
|
complete: () => resolve(),
|
})
|
})
|
}
|
catch (error) {
|
console.warn('request employee subscribe message failed', error)
|
}
|
// #endif
|
}
|
|
export async function finishMiniLogin(loginData: Awaited<ReturnType<typeof loginByWx>>) {
|
const authStore = useMiniAuthStore()
|
authStore.setSession({
|
token: loginData.token,
|
profile: normalizeLoginProfile(loginData),
|
})
|
|
try {
|
const profile = await fetchMiniMe(loginData.token)
|
authStore.setProfile(normalizeMeProfile(profile))
|
}
|
catch (error) {
|
console.warn('load mini profile failed after login', error)
|
}
|
|
await requestEmployeeSubscribeAuthorization(authStore.profile?.userType)
|
}
|