This commit is contained in:
lik
2026-11-06 19:51:44 +08:00
parent 6d90ebd07f
commit bfe451104d
696 changed files with 59664 additions and 1 deletions
+115
View File
@@ -0,0 +1,115 @@
export const formatDate = (value?: string | Date | null): string => {
if (!value) return '-'
const date = value instanceof Date ? value : new Date(value)
if (Number.isNaN(date.getTime())) return '-'
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
export const formatDateTime = (value?: string | Date | null): string => {
if (!value) return '-'
const date = value instanceof Date ? value : new Date(value)
if (Number.isNaN(date.getTime())) return '-'
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${formatDate(date)} ${hours}:${minutes}`
}
export const formatMoney = (value?: number | null): string => `¥${(Number(value) || 0).toFixed(2)}`
export const shortId = (value?: string | null): string => (value ? value.slice(-6) : '-')
export const today = (): string => formatDate(new Date())
export const STATUS_LABELS: Record<string, string> = {
pending: '待确认',
confirmed: '已确认',
in_progress: '服务中',
completed: '已完成',
cancelled: '已取消',
}
export const STATUS_VARIANTS: Record<string, string> = {
pending: 'warning',
confirmed: 'info',
in_progress: 'primary',
completed: 'success',
cancelled: 'secondary',
}
export const CANCEL_LABELS: Record<string, string> = {
none: '未取消',
requested: '取消申请',
cancelled: '已取消',
}
export const CANCEL_VARIANTS: Record<string, string> = {
none: 'secondary',
requested: 'danger',
cancelled: 'dark',
}
export const PAYMENT_LABELS: Record<string, string> = {
unpaid: '未支付',
partial: '部分支付',
paid: '已支付',
refunding: '退款中',
refunded: '已退款',
}
export const PAYMENT_VARIANTS: Record<string, string> = {
unpaid: 'secondary',
partial: 'warning',
paid: 'success',
refunding: 'danger',
refunded: 'info',
}
export const CHANNEL_LABELS: Record<string, string> = {
online_wechat: '线上微信',
offline: '线下支付',
}
export const METHOD_LABELS: Record<string, string> = {
'': '未记录',
online_wechat: '微信支付',
offline_cash: '线下现金',
offline_transfer: '线下转账',
}
export const ROLE_LABELS: Record<string, string> = {
attendant: '陪诊师',
nurse: '护士',
doctor: '医生',
admin: '管理员',
operator: '运营',
other: '其他',
}
export const EMPLOYEE_STATUS_LABELS: Record<string, string> = {
active: '在职',
inactive: '停用',
resigned: '离职',
suspended: '暂停',
}
export const EMPLOYEE_STATUS_VARIANTS: Record<string, string> = {
active: 'success',
inactive: 'secondary',
resigned: 'dark',
suspended: 'warning',
}
export const ACCOUNT_STATUS_LABELS: Record<string, string> = {
normal: '正常',
lock: '已锁定',
}
export const SEX_LABELS: Record<string, string> = {
male: '男',
female: '女',
other: '其他',
'': '-',
}
+96
View File
@@ -0,0 +1,96 @@
type ToggleDocumentAttributeType = (attribute: string, value: string, remove?: boolean, tag?: keyof HTMLElementTagNameMap) => void
export const toggleAttribute: ToggleDocumentAttributeType = (attribute, value, remove, tag = 'html'): void => {
if (document.documentElement) {
const element = document.getElementsByTagName(tag.toString())[0]
const hasAttribute = element?.getAttribute(attribute)
if (remove && hasAttribute) element?.removeAttribute(attribute)
else element?.setAttribute(attribute, value)
}
}
export const easeInOutQuad = (t: number, b: number, c: number, d: number) => {
t /= d / 2
if (t < 1) return (c / 2) * t * t + b
t--
return (-c / 2) * (t * (t - 2) - 1) + b
}
export const scrollToElement = (element: Element, to: number, duration: number) => {
const start = element.scrollTop,
change = to - start,
increment = 20
let currentTime = 0
const animateScroll = function () {
currentTime += increment
element.scrollTop = easeInOutQuad(currentTime, start, change, duration)
if (currentTime < duration) {
setTimeout(animateScroll, increment)
}
}
animateScroll()
}
export const toPascalCase = (value: string) =>
value
.replace(/[-_ ]+/g, ' ')
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ')
export const toTitleCase = (value: string) =>
value
.replace(/[-_]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ')
export const abbreviatedNumber = (val: number) => {
const s = ['', 'k', 'm', 'b', 't']
if (val === 0) return 0
const sNum = Math.floor(Math.log10(val) / 3)
let sVal = parseFloat((sNum != 0 ? val / Math.pow(1000, sNum) : val).toPrecision(2))
if (sVal % 1 != 0) {
sVal = Number.parseInt(sVal.toFixed(1))
}
return sVal + s[sNum]!
}
export function getColor(v: string, a: number = 1) {
if (typeof window === 'undefined') return ''
const html = document.documentElement
if (!html) return ''
const val = getComputedStyle(document.documentElement).getPropertyValue(`--theme-${v}`).trim()
return v.includes('-rgb') ? `rgba(${val}, ${a})` : val
}
export function getDefaultFontFamily(): string {
const body = document.body
if (!body) return ''
const font = getComputedStyle(body).fontFamily
return font ?? ''
}
export const formatBytes = (bytes: number, decimals: number = 2) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}
export const generateInitials = (name = ''): string => {
return name
.split(' ')
.map((word) => word[0])
.join('')
.toUpperCase()
}
+39
View File
@@ -0,0 +1,39 @@
import { reactive } from 'vue'
export type ToastVariant = 'success' | 'danger' | 'warning' | 'info'
type ToastItem = {
id: number
message: string
variant: ToastVariant
}
type NotifyFn = {
(message: string, variant?: ToastVariant, duration?: number): void
success: (message: string) => void
error: (message: string) => void
warning: (message: string) => void
info: (message: string) => void
}
export const toasts = reactive<ToastItem[]>([])
let seed = 0
export function dismiss(id: number) {
const index = toasts.findIndex((item) => item.id === id)
if (index >= 0) toasts.splice(index, 1)
}
const push = (message: string, variant: ToastVariant = 'success', duration = 3500) => {
const id = ++seed
toasts.push({ id, message, variant })
window.setTimeout(() => dismiss(id), duration)
}
export const notify = Object.assign(push, {
success: (message: string) => push(message, 'success'),
error: (message: string) => push(message, 'danger', 4500),
warning: (message: string) => push(message, 'warning', 4000),
info: (message: string) => push(message, 'info'),
}) as NotifyFn
+86
View File
@@ -0,0 +1,86 @@
import { notify } from '~/utils/notify'
let authToken = ''
let unauthorizedHandler: (() => void) | null = null
export const setAuthToken = (token: string) => {
authToken = token
}
export const setUnauthorizedHandler = (handler: () => void) => {
unauthorizedHandler = handler
}
export class ApiError extends Error {
code: number
constructor(message: string, code: number) {
super(message)
this.name = 'ApiError'
this.code = code
}
}
type RequestOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
query?: Record<string, unknown>
body?: unknown
silent?: boolean
}
const buildQuery = (query?: Record<string, unknown>) => {
if (!query) return ''
const params = new URLSearchParams()
Object.entries(query).forEach(([key, value]) => {
if (value === undefined || value === null || value === '') return
params.set(key, String(value))
})
const result = params.toString()
return result ? `?${result}` : ''
}
export async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { method = 'GET', query, body, silent = false } = options
const headers: Record<string, string> = { Accept: 'application/json' }
if (body !== undefined) headers['Content-Type'] = 'application/json'
if (authToken) headers.token = authToken
let response: Response
try {
response = await fetch(`${path}${buildQuery(query)}`, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
})
} catch {
const message = '网络异常,请检查服务是否启动后重试'
if (!silent) notify.error(message)
throw new ApiError(message, -1)
}
let payload: { code?: number; msg?: string; data?: unknown } | null = null
try {
payload = await response.json()
} catch {
const message = `响应解析失败(HTTP ${response.status})`
if (!silent) notify.error(message)
throw new ApiError(message, response.status)
}
if (!response.ok) {
const message = payload?.msg || `请求失败(HTTP ${response.status})`
if (!silent) notify.error(message)
throw new ApiError(message, response.status)
}
if (payload?.code === 0) {
return payload.data as T
}
const message = payload?.msg || '请求失败'
if (payload?.code === 401) {
unauthorizedHandler?.()
}
if (!silent) notify.error(message)
throw new ApiError(message, Number(payload?.code) || response.status)
}