207 lines
6.3 KiB
TypeScript
207 lines
6.3 KiB
TypeScript
import { API_CLIENT_ID, request } from '@/api/request'
|
|
import type { ApiResponse } from '@/types/api'
|
|
import { getStoredToken } from '@/utils/auth-token'
|
|
import { ApiError, isApiSuccess, unwrapApiData } from '@/utils/api-error'
|
|
import {
|
|
isSessionEnded,
|
|
normalizeSessionId,
|
|
normalizeSessionResponse,
|
|
unwrapCsActionResponse,
|
|
} from './support.utils'
|
|
import type {
|
|
CsAppActionVo,
|
|
CsClickButtonBody,
|
|
CsChatImageUploadVo,
|
|
CzCsUploadVo,
|
|
CsCreateSessionBody,
|
|
CsMessageVo,
|
|
CsResolvedSession,
|
|
CsSendMessageBody,
|
|
CsSessionListQuery,
|
|
CsSessionVo,
|
|
CsTableData,
|
|
} from './support.types'
|
|
|
|
function buildSessionPath(sessionId: string, suffix = '') {
|
|
return `/app/cs/session/${encodeURIComponent(sessionId)}${suffix}`
|
|
}
|
|
|
|
function resolveUploadBaseUrl(): string {
|
|
const envUrl = import.meta.env.VITE_API_BASE_URL ?? ''
|
|
// #ifdef H5
|
|
if (import.meta.env.DEV) return ''
|
|
// #endif
|
|
return envUrl
|
|
}
|
|
|
|
function normalizeCsUploadVo(data: unknown): CzCsUploadVo {
|
|
const raw = data && typeof data === 'object' ? (data as Record<string, unknown>) : {}
|
|
const ossId = raw.ossId
|
|
const url = raw.url != null ? String(raw.url).trim() : ''
|
|
if (ossId === undefined || ossId === null || ossId === '') {
|
|
throw new ApiError('上传失败,未返回 ossId')
|
|
}
|
|
if (!url) {
|
|
throw new ApiError('上传失败,未返回访问地址')
|
|
}
|
|
return {
|
|
ossId: typeof ossId === 'number' ? String(ossId) : String(ossId),
|
|
url,
|
|
fileName: raw.fileName != null ? String(raw.fileName) : undefined,
|
|
}
|
|
}
|
|
|
|
function unwrapRows<T>(data: T[] | CsTableData<T> | undefined): T[] {
|
|
if (!data) return []
|
|
if (Array.isArray(data)) return data
|
|
return data.rows ?? []
|
|
}
|
|
|
|
/** POST /app/cs/session — 创建客服会话;已有未结束会话时返回原会话 */
|
|
export function createCsSession(data: CsCreateSessionBody = {}) {
|
|
return request<CsAppActionVo | CsSessionVo | string | null>({
|
|
url: '/app/cs/session',
|
|
method: 'POST',
|
|
data,
|
|
})
|
|
}
|
|
|
|
async function fetchActiveCsSession(): Promise<CsSessionVo | null> {
|
|
const list = await fetchCsSessionList({ pageNum: 1, pageSize: 20 })
|
|
const active = list.find((item) => !isSessionEnded(item)) ?? list[0]
|
|
if (!active || !normalizeSessionId(active)) return null
|
|
return normalizeSessionResponse(active)
|
|
}
|
|
|
|
/** 创建或获取当前客服会话(兼容 action 包装、id 字段、需二次查询列表) */
|
|
export async function resolveCsSession(): Promise<CsResolvedSession> {
|
|
let resolved = unwrapCsActionResponse(await createCsSession())
|
|
let session = resolved.session
|
|
let messages = resolved.messages
|
|
let sessionId = normalizeSessionId(session)
|
|
|
|
if (!sessionId) {
|
|
const active = await fetchActiveCsSession()
|
|
if (active) {
|
|
session = active
|
|
sessionId = normalizeSessionId(active)
|
|
messages = undefined
|
|
}
|
|
}
|
|
|
|
if (!sessionId) {
|
|
throw new ApiError('未获取客服会话,请确认已登录后重试')
|
|
}
|
|
|
|
if (session.status === undefined && session.sessionStatus === undefined) {
|
|
try {
|
|
session = normalizeSessionResponse(await fetchCsSessionDetail(sessionId))
|
|
} catch {
|
|
session = { ...session, sessionId }
|
|
}
|
|
}
|
|
|
|
return { session, messages }
|
|
}
|
|
|
|
/** GET /app/cs/session/list — 查询自己的会话 */
|
|
export function fetchCsSessionList(query: CsSessionListQuery = {}) {
|
|
return request<CsSessionVo[] | CsTableData<CsSessionVo>>({
|
|
url: '/app/cs/session/list',
|
|
method: 'GET',
|
|
data: query,
|
|
}).then(unwrapRows)
|
|
}
|
|
|
|
/** GET /app/cs/session/{sessionId} — 查询会话详情 */
|
|
export function fetchCsSessionDetail(sessionId: string) {
|
|
return request<CsAppActionVo | CsSessionVo | string | null>({
|
|
url: buildSessionPath(sessionId),
|
|
method: 'GET',
|
|
}).then((data) => normalizeSessionResponse(unwrapCsActionResponse(data).session))
|
|
}
|
|
|
|
/** GET /app/cs/session/{sessionId}/messages — 拉取会话消息 */
|
|
export function fetchCsMessages(sessionId: string, afterSeq = 0) {
|
|
return request<CsMessageVo[] | CsTableData<CsMessageVo>>({
|
|
url: buildSessionPath(sessionId, '/messages'),
|
|
method: 'GET',
|
|
data: { afterSeq },
|
|
}).then(unwrapRows)
|
|
}
|
|
|
|
/** POST /app/cs/upload — 上传聊天图片 */
|
|
export function uploadCsChatImage(filePath: string): Promise<CsChatImageUploadVo> {
|
|
return new Promise((resolve, reject) => {
|
|
const token = getStoredToken()
|
|
uni.uploadFile({
|
|
url: `${resolveUploadBaseUrl()}/app/cs/upload`,
|
|
filePath,
|
|
name: 'file',
|
|
header: {
|
|
clientId: API_CLIENT_ID,
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
},
|
|
success: (res) => {
|
|
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
reject(new ApiError(`上传失败(${res.statusCode})`, res.statusCode))
|
|
return
|
|
}
|
|
let body: ApiResponse<CzCsUploadVo>
|
|
try {
|
|
body = JSON.parse(res.data) as ApiResponse<CzCsUploadVo>
|
|
} catch {
|
|
reject(new ApiError('上传响应解析失败'))
|
|
return
|
|
}
|
|
if (!isApiSuccess(body)) {
|
|
reject(new ApiError(body.msg || body.message || '上传失败', body.code))
|
|
return
|
|
}
|
|
try {
|
|
resolve(normalizeCsUploadVo(unwrapApiData(body)))
|
|
} catch (err) {
|
|
reject(err instanceof ApiError ? err : new ApiError('上传响应无效'))
|
|
}
|
|
},
|
|
fail: (err) => {
|
|
reject(new ApiError(err.errMsg || '上传失败'))
|
|
},
|
|
})
|
|
})
|
|
}
|
|
|
|
/** POST /app/cs/session/{sessionId}/message — 发送消息 */
|
|
export function sendCsMessage(sessionId: string, data: CsSendMessageBody) {
|
|
return request<CsAppActionVo>({
|
|
url: buildSessionPath(sessionId, '/message'),
|
|
method: 'POST',
|
|
data,
|
|
})
|
|
}
|
|
|
|
/** POST /app/cs/session/{sessionId}/transfer — 转人工 */
|
|
export function transferCsSession(sessionId: string) {
|
|
return request<CsAppActionVo | CsSessionVo | null>({
|
|
url: buildSessionPath(sessionId, '/transfer'),
|
|
method: 'POST',
|
|
})
|
|
}
|
|
|
|
/** POST /app/cs/session/{sessionId}/end — 结束会话 */
|
|
export function endCsSession(sessionId: string) {
|
|
return request<void>({
|
|
url: buildSessionPath(sessionId, '/end'),
|
|
method: 'POST',
|
|
})
|
|
}
|
|
|
|
/** POST /app/cs/session/{sessionId}/button — 点击机器人按钮 */
|
|
export function clickCsButton(sessionId: string, data: CsClickButtonBody) {
|
|
return request<void>({
|
|
url: buildSessionPath(sessionId, '/button'),
|
|
method: 'POST',
|
|
data,
|
|
})
|
|
}
|