统一甲屿云命名体系
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { buildDraftKey, readDraftForm, removeDraftForm, writeDraftForm } from '@/utils/appointment-draft'
|
||||
import type { AppointmentForm } from '@/types/manager'
|
||||
import type { UserInfo } from '@/types/common'
|
||||
|
||||
const buildForm = (): AppointmentForm => ({
|
||||
customerUserId: '',
|
||||
customerName: '王女士',
|
||||
phone: '13800138000',
|
||||
appointmentDate: '2026-06-29',
|
||||
appointmentTime: '13:00',
|
||||
productId: '',
|
||||
manualProductTitle: '法式护理',
|
||||
manualProductPrice: '199',
|
||||
manualProductDescription: '',
|
||||
manualProductTags: '',
|
||||
manualProductTargetAudience: '',
|
||||
manualProductPrecautions: '',
|
||||
manualProductImageFileIds: '',
|
||||
manualProductImageUrl: '',
|
||||
durationMinutes: '90',
|
||||
artistId: '7',
|
||||
remark: ''
|
||||
})
|
||||
|
||||
describe('appointment draft storage', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
window.sessionStorage.clear()
|
||||
})
|
||||
|
||||
it('scopes draft by user and shop', () => {
|
||||
const userInfo: UserInfo = { id: 10, shopId: 20 }
|
||||
|
||||
expect(buildDraftKey(userInfo)).toBe('managerAppointmentDraft:10:20')
|
||||
})
|
||||
|
||||
it('writes, reads and removes draft form', () => {
|
||||
const userInfo: UserInfo = { id: 10, shopId: 20 }
|
||||
const form = buildForm()
|
||||
|
||||
writeDraftForm(userInfo, form)
|
||||
expect(readDraftForm(userInfo)).toEqual(form)
|
||||
|
||||
removeDraftForm(userInfo)
|
||||
expect(readDraftForm(userInfo)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { AppointmentForm } from '@/types/manager'
|
||||
import type { UserInfo } from '@/types/common'
|
||||
import { readJson, removeStorage, writeJson } from '@/utils/storage'
|
||||
|
||||
const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft'
|
||||
|
||||
export const buildDraftKey = (userInfo: UserInfo | null): string => {
|
||||
return `${DRAFT_STORAGE_PREFIX}:${userInfo?.id || 'guest'}:${userInfo?.shopId || 'default'}`
|
||||
}
|
||||
|
||||
export const readDraftForm = (userInfo: UserInfo | null): AppointmentForm | null => {
|
||||
const draft = readJson<{ form?: AppointmentForm } | null>(buildDraftKey(userInfo), null)
|
||||
return draft?.form || null
|
||||
}
|
||||
|
||||
export const writeDraftForm = (userInfo: UserInfo | null, form: AppointmentForm): void => {
|
||||
writeJson(buildDraftKey(userInfo), { form, savedAt: Date.now() })
|
||||
}
|
||||
|
||||
export const removeDraftForm = (userInfo: UserInfo | null): void => {
|
||||
removeStorage(buildDraftKey(userInfo))
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildAvailableTimeGroups } from '@/utils/available-times'
|
||||
import type { AppointmentForm, PlanningCalendar } from '@/types/manager'
|
||||
|
||||
const buildForm = (): AppointmentForm => ({
|
||||
customerUserId: '',
|
||||
customerName: '王女士',
|
||||
phone: '13800138000',
|
||||
appointmentDate: '2026-06-29',
|
||||
appointmentTime: '',
|
||||
productId: '',
|
||||
manualProductTitle: '基础护理',
|
||||
manualProductPrice: '99',
|
||||
manualProductDescription: '',
|
||||
manualProductTags: '',
|
||||
manualProductTargetAudience: '',
|
||||
manualProductPrecautions: '',
|
||||
manualProductImageFileIds: '',
|
||||
manualProductImageUrl: '',
|
||||
durationMinutes: '60',
|
||||
artistId: '1',
|
||||
remark: ''
|
||||
})
|
||||
|
||||
describe('available time groups', () => {
|
||||
it('builds slots from active schedules and removes busy conflicts', () => {
|
||||
const calendar: PlanningCalendar = {
|
||||
schedules: [
|
||||
{ artistId: 1, date: '2026-06-29', startTime: '10:00', endTime: '12:45', status: 1 },
|
||||
{ artistId: 2, date: '2026-06-29', startTime: '10:00', endTime: '12:00', status: 1 },
|
||||
{ artistId: 1, date: '2026-06-30', startTime: '10:00', endTime: '12:00', status: 1 }
|
||||
],
|
||||
appointments: [
|
||||
{ orderItemId: 100, artistId: 1, date: '2026-06-29', startTime: '2026-06-29 10:30:00', endTime: '2026-06-29 11:30:00', status: 1 }
|
||||
]
|
||||
}
|
||||
|
||||
const groups = buildAvailableTimeGroups(calendar, buildForm())
|
||||
|
||||
expect(groups).toHaveLength(1)
|
||||
expect(groups[0]?.key).toBe('morning')
|
||||
expect(groups[0]?.times.map(item => item.value)).toEqual(['11:30', '11:45'])
|
||||
})
|
||||
|
||||
it('ignores cancelled appointments', () => {
|
||||
const calendar: PlanningCalendar = {
|
||||
schedules: [{ artistId: 1, date: '2026-06-29', startTime: '10:00', endTime: '11:00', status: 1 }],
|
||||
appointments: [{ orderItemId: 100, artistId: 1, date: '2026-06-29', startTime: '2026-06-29 10:00:00', endTime: '2026-06-29 11:00:00', status: 3 }]
|
||||
}
|
||||
|
||||
const groups = buildAvailableTimeGroups(calendar, buildForm())
|
||||
|
||||
expect(groups[0]?.times.map(item => item.value)).toEqual(['10:00'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { Appointment, AppointmentForm, ArtistSchedule, PlanningCalendar } from '@/types/manager'
|
||||
import { extractTimeText, normalizeDuration, resolveAppointmentDate, resolveAppointmentEndMinute, resolveAppointmentStartMinute } from '@/utils/planning'
|
||||
import { minutesOfDay, timeFromMinutes } from '@/utils/date'
|
||||
|
||||
const TIME_SLOT_MINUTES = 15
|
||||
|
||||
export interface AvailableTime {
|
||||
value: string
|
||||
rangeText: string
|
||||
}
|
||||
|
||||
export interface AvailableTimeGroup {
|
||||
key: string
|
||||
title: string
|
||||
times: AvailableTime[]
|
||||
}
|
||||
|
||||
const buildTimeRangeLabel = (startMinute: number, durationMinutes: number): string => {
|
||||
return `${timeFromMinutes(startMinute)}-${timeFromMinutes(startMinute + durationMinutes)}`
|
||||
}
|
||||
|
||||
const getTimePeriod = (minute: number): { key: string; title: string } => {
|
||||
if (minute < 12 * 60) {
|
||||
return { key: 'morning', title: '上午' }
|
||||
}
|
||||
if (minute < 18 * 60) {
|
||||
return { key: 'afternoon', title: '下午' }
|
||||
}
|
||||
return { key: 'evening', title: '晚上' }
|
||||
}
|
||||
|
||||
const isCancelledAppointment = (item: Appointment): boolean => item.status === 3 || item.statusText === '已取消'
|
||||
|
||||
const buildBusyRanges = (appointments: Appointment[], form: AppointmentForm): Array<{ startMinute: number; endMinute: number }> => {
|
||||
return appointments
|
||||
.filter(item => String(item.artistId) === String(form.artistId))
|
||||
.filter(item => resolveAppointmentDate(item) === form.appointmentDate)
|
||||
.filter(item => !isCancelledAppointment(item))
|
||||
.map(item => {
|
||||
const startMinute = resolveAppointmentStartMinute(item)
|
||||
return { startMinute, endMinute: resolveAppointmentEndMinute(item, startMinute) }
|
||||
})
|
||||
}
|
||||
|
||||
const hasBusyConflict = (startMinute: number, endMinute: number, ranges: Array<{ startMinute: number; endMinute: number }>): boolean => {
|
||||
return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute)
|
||||
}
|
||||
|
||||
export const buildAvailableTimeGroups = (calendar: PlanningCalendar, form: AppointmentForm): AvailableTimeGroup[] => {
|
||||
const durationMinutes = normalizeDuration(form.durationMinutes)
|
||||
if (!durationMinutes) {
|
||||
return []
|
||||
}
|
||||
const schedules = (calendar.schedules || [])
|
||||
.filter((item: ArtistSchedule) => String(item.artistId) === String(form.artistId))
|
||||
.filter(item => item.date === form.appointmentDate)
|
||||
.filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1)
|
||||
const busyRanges = buildBusyRanges(calendar.appointments || [], form)
|
||||
const groupMap: Record<string, AvailableTimeGroup> = {
|
||||
morning: { key: 'morning', title: '上午', times: [] },
|
||||
afternoon: { key: 'afternoon', title: '下午', times: [] },
|
||||
evening: { key: 'evening', title: '晚上', times: [] }
|
||||
}
|
||||
schedules.forEach(schedule => {
|
||||
const scheduleStart = minutesOfDay(extractTimeText(schedule.startTime))
|
||||
const scheduleEnd = minutesOfDay(extractTimeText(schedule.endTime))
|
||||
for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) {
|
||||
const endMinute = minute + durationMinutes
|
||||
if (!hasBusyConflict(minute, endMinute, busyRanges)) {
|
||||
const period = getTimePeriod(minute)
|
||||
const group = groupMap[period.key]
|
||||
if (group) {
|
||||
group.times.push({ value: timeFromMinutes(minute), rangeText: buildTimeRangeLabel(minute, durationMinutes) })
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return Object.values(groupMap)
|
||||
.map(group => ({
|
||||
...group,
|
||||
times: group.times.filter((item, index, array) => array.findIndex(candidate => candidate.value === item.value) === index)
|
||||
}))
|
||||
.filter(group => group.times.length > 0)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { endOfWeek, formatDate, monthGrid, startOfWeek, timeFromMinutes, minutesOfDay } from '@/utils/date'
|
||||
|
||||
describe('date utils', () => {
|
||||
it('uses Monday as the first day of a week', () => {
|
||||
expect(formatDate(startOfWeek('2026-06-28'))).toBe('2026-06-22')
|
||||
expect(formatDate(endOfWeek('2026-06-28'))).toBe('2026-06-28')
|
||||
})
|
||||
|
||||
it('builds a 42-cell month grid with surrounding days', () => {
|
||||
const grid = monthGrid('2026-06-15')
|
||||
|
||||
expect(grid).toHaveLength(42)
|
||||
expect(grid[0]).toEqual({ date: '2026-06-01', day: 1, isCurrentMonth: true })
|
||||
expect(grid[41]).toEqual({ date: '2026-07-12', day: 12, isCurrentMonth: false })
|
||||
})
|
||||
|
||||
it('converts time and minutes symmetrically', () => {
|
||||
expect(minutesOfDay('13:45')).toBe(825)
|
||||
expect(timeFromMinutes(825)).toBe('13:45')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
const pad = (value: number): string => String(value).padStart(2, '0')
|
||||
|
||||
export const toDate = (value: string | Date): Date => {
|
||||
if (value instanceof Date) {
|
||||
return new Date(value.getTime())
|
||||
}
|
||||
return new Date(String(value).replace(/-/g, '/'))
|
||||
}
|
||||
|
||||
export const formatDate = (value: string | Date): string => {
|
||||
const target = toDate(value)
|
||||
return `${target.getFullYear()}-${pad(target.getMonth() + 1)}-${pad(target.getDate())}`
|
||||
}
|
||||
|
||||
export const formatMonth = (value: string | Date): string => {
|
||||
const target = toDate(value)
|
||||
return `${target.getFullYear()}年${target.getMonth() + 1}月`
|
||||
}
|
||||
|
||||
export const formatCnDate = (value: string | Date): string => {
|
||||
const target = toDate(value)
|
||||
return `${target.getMonth() + 1}月${target.getDate()}日`
|
||||
}
|
||||
|
||||
export const addDays = (value: string | Date, days: number): Date => {
|
||||
const target = toDate(value)
|
||||
target.setDate(target.getDate() + days)
|
||||
return target
|
||||
}
|
||||
|
||||
export const addMonths = (value: string | Date, months: number): Date => {
|
||||
const target = toDate(value)
|
||||
target.setMonth(target.getMonth() + months)
|
||||
return target
|
||||
}
|
||||
|
||||
export const startOfWeek = (value: string | Date): Date => {
|
||||
const target = toDate(value)
|
||||
const day = target.getDay() || 7
|
||||
target.setDate(target.getDate() - day + 1)
|
||||
return target
|
||||
}
|
||||
|
||||
export const endOfWeek = (value: string | Date): Date => addDays(startOfWeek(value), 6)
|
||||
|
||||
export const startOfMonth = (value: string | Date): Date => {
|
||||
const target = toDate(value)
|
||||
return new Date(target.getFullYear(), target.getMonth(), 1)
|
||||
}
|
||||
|
||||
export const endOfMonth = (value: string | Date): Date => {
|
||||
const target = toDate(value)
|
||||
return new Date(target.getFullYear(), target.getMonth() + 1, 0)
|
||||
}
|
||||
|
||||
export const monthGrid = (value: string | Date): Array<{ date: string; day: number; isCurrentMonth: boolean }> => {
|
||||
const first = startOfMonth(value)
|
||||
const startOffset = (first.getDay() || 7) - 1
|
||||
const gridStart = addDays(first, -startOffset)
|
||||
return Array.from({ length: 42 }, (_item, index) => {
|
||||
const current = addDays(gridStart, index)
|
||||
return {
|
||||
date: formatDate(current),
|
||||
day: current.getDate(),
|
||||
isCurrentMonth: current.getMonth() === first.getMonth()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const minutesOfDay = (value: string): number => {
|
||||
const [hour, minute] = String(value || '00:00').split(':').map(Number)
|
||||
return (hour || 0) * 60 + (minute || 0)
|
||||
}
|
||||
|
||||
export const timeFromMinutes = (minutes: number): string => {
|
||||
const normalized = ((minutes % (24 * 60)) + 24 * 60) % (24 * 60)
|
||||
return `${pad(Math.floor(normalized / 60))}:${pad(normalized % 60)}`
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { UserInfo } from '@/types/common'
|
||||
|
||||
export const canCreateAppointment = (userInfo: UserInfo | null): boolean => Number(userInfo?.type) !== 3
|
||||
|
||||
export const resolveRoleText = (type: number | undefined): string => {
|
||||
const role = Number(type)
|
||||
if (role === 4) {
|
||||
return '平台管理员'
|
||||
}
|
||||
if (role === 3) {
|
||||
return '美甲师'
|
||||
}
|
||||
if (role === 2) {
|
||||
return '店长'
|
||||
}
|
||||
return '客户'
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Appointment, Artist, DaySummary, PlanningCalendar } from '@/types/manager'
|
||||
import { minutesOfDay, timeFromMinutes } from '@/utils/date'
|
||||
|
||||
export const resolveAppointmentDate = (item: Appointment): string => {
|
||||
if (item.date) {
|
||||
return item.date
|
||||
}
|
||||
return String(item.startTime || '').slice(0, 10)
|
||||
}
|
||||
|
||||
export const extractTimeText = (value: string | undefined): string => {
|
||||
const target = String(value || '')
|
||||
if (target.includes('T') || target.includes(' ')) {
|
||||
return target.slice(11, 16)
|
||||
}
|
||||
return target.slice(0, 5)
|
||||
}
|
||||
|
||||
export const resolveAppointmentStartMinute = (item: Appointment): number => {
|
||||
if (item.startMinute !== undefined && item.startMinute !== null) {
|
||||
return Number(item.startMinute)
|
||||
}
|
||||
return minutesOfDay(extractTimeText(item.startTime))
|
||||
}
|
||||
|
||||
export const resolveAppointmentEndMinute = (item: Appointment, startMinute: number): number => {
|
||||
if (item.endMinute !== undefined && item.endMinute !== null) {
|
||||
return Number(item.endMinute)
|
||||
}
|
||||
if (item.endTime) {
|
||||
return minutesOfDay(extractTimeText(item.endTime))
|
||||
}
|
||||
return startMinute + Number(item.durationMinutes || 60)
|
||||
}
|
||||
|
||||
export const resolveAppointmentTimeText = (item: Appointment): string => {
|
||||
const startMinute = resolveAppointmentStartMinute(item)
|
||||
const duration = Number(item.durationMinutes || 60)
|
||||
const startText = extractTimeText(item.startTime) || timeFromMinutes(startMinute)
|
||||
const endText = extractTimeText(item.endTime) || timeFromMinutes(startMinute + duration)
|
||||
return `${startText}-${endText}`
|
||||
}
|
||||
|
||||
export const summaryMap = (daySummaries: DaySummary[]): Record<string, DaySummary> => {
|
||||
return daySummaries.reduce<Record<string, DaySummary>>((result, item) => {
|
||||
result[item.date] = item
|
||||
return result
|
||||
}, {})
|
||||
}
|
||||
|
||||
export const getCalendarArtists = (calendar: PlanningCalendar): Artist[] => Array.isArray(calendar.artists) ? calendar.artists : []
|
||||
|
||||
export const normalizeDuration = (value: string | number): number => {
|
||||
const duration = Number(value)
|
||||
return Number.isFinite(duration) && duration > 0 ? Math.floor(duration) : 0
|
||||
}
|
||||
|
||||
export const buildClientRequestId = (prefix: string): string => {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { InternalAxiosRequestConfig } from 'axios'
|
||||
import { attachRequestSignature } from '@/utils/request-signature'
|
||||
|
||||
const buildConfig = (): InternalAxiosRequestConfig => ({
|
||||
headers: {},
|
||||
method: 'post',
|
||||
baseURL: '/admin/api',
|
||||
url: '/manager/planning/appointments',
|
||||
params: { b: 2, a: 1 },
|
||||
data: { name: 'test' }
|
||||
} as InternalAxiosRequestConfig)
|
||||
|
||||
describe('request signature', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('adds device and signature headers for protected unsafe requests', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(1_789_999_999_000)
|
||||
vi.spyOn(crypto, 'randomUUID').mockReturnValue('00000000-0000-4000-8000-000000000001')
|
||||
vi.spyOn(crypto, 'getRandomValues').mockImplementation(array => {
|
||||
const values = array as Uint32Array
|
||||
values[0] = 10
|
||||
values[1] = 20
|
||||
return array
|
||||
})
|
||||
|
||||
const config = await attachRequestSignature(buildConfig(), 'token-secret', { authFree: false })
|
||||
|
||||
expect(config.headers['X-Device-Id']).toBe('00000000-0000-4000-8000-000000000001')
|
||||
expect(config.headers['X-Timestamp']).toBe('1789999999000')
|
||||
expect(config.headers['X-Nonce']).toBe('1789999999000-00000000-0000-4000-8000-000000000001-ak')
|
||||
expect(config.headers['X-Sign-Version']).toBe('v1')
|
||||
expect(String(config.headers['X-Signature'])).toHaveLength(64)
|
||||
})
|
||||
|
||||
it('skips signature for auth-free requests but still attaches device id', async () => {
|
||||
vi.spyOn(crypto, 'randomUUID').mockReturnValue('00000000-0000-4000-8000-000000000001')
|
||||
|
||||
const config = await attachRequestSignature(buildConfig(), 'token-secret', { authFree: true })
|
||||
|
||||
expect(config.headers['X-Device-Id']).toBe('00000000-0000-4000-8000-000000000001')
|
||||
expect(config.headers['X-Signature']).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { InternalAxiosRequestConfig } from 'axios'
|
||||
|
||||
const HEADER_TIMESTAMP = 'X-Timestamp'
|
||||
const HEADER_NONCE = 'X-Nonce'
|
||||
const HEADER_SIGNATURE = 'X-Signature'
|
||||
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
|
||||
const DEVICE_ID_HEADER = 'X-Device-Id'
|
||||
const DEVICE_ID_STORAGE_KEY = 'jayu_salon_web_device_id'
|
||||
const SIGNATURE_VERSION = 'v1'
|
||||
|
||||
type HeaderContainer = Record<string, unknown>
|
||||
|
||||
export interface RequestSignatureOptions {
|
||||
authFree: boolean
|
||||
}
|
||||
|
||||
const isSafeMethod = (method: string): boolean => ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())
|
||||
|
||||
const toHex = (bytes: ArrayBuffer): string => {
|
||||
return Array.from(new Uint8Array(bytes)).map(value => value.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
const sha256Hex = async (message: string): Promise<string> => {
|
||||
const bytes = new TextEncoder().encode(message)
|
||||
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
||||
return toHex(digest)
|
||||
}
|
||||
|
||||
const hmacSha256Hex = async (secret: string, message: string): Promise<string> => {
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message))
|
||||
return toHex(signature)
|
||||
}
|
||||
|
||||
const randomNonce = (deviceId: string): string => {
|
||||
const randomPart = crypto.getRandomValues(new Uint32Array(2))
|
||||
const [first = 0, second = 0] = randomPart
|
||||
return `${Date.now()}-${deviceId}-${first.toString(36)}${second.toString(36)}`
|
||||
}
|
||||
|
||||
const getDeviceId = (): string => {
|
||||
const existing = window.localStorage.getItem(DEVICE_ID_STORAGE_KEY)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const generated = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
window.localStorage.setItem(DEVICE_ID_STORAGE_KEY, generated)
|
||||
return generated
|
||||
}
|
||||
|
||||
const setHeader = (headers: HeaderContainer, key: string, value: string): void => {
|
||||
headers[key] = value
|
||||
}
|
||||
|
||||
const extractPath = (value: string): string => {
|
||||
const target = String(value || '')
|
||||
if (!target) {
|
||||
return '/'
|
||||
}
|
||||
if (/^[a-z][a-z\d+\-.]*:\/\//i.test(target)) {
|
||||
const parsed = new URL(target)
|
||||
return parsed.pathname || '/'
|
||||
}
|
||||
return target.split('?')[0] || '/'
|
||||
}
|
||||
|
||||
const toBackendRequestPath = (config: InternalAxiosRequestConfig): string => {
|
||||
const baseURL = String(config.baseURL || '')
|
||||
const url = String(config.url || '')
|
||||
const basePath = extractPath(baseURL).replace(/\/+$/, '')
|
||||
const urlPath = extractPath(url)
|
||||
return `${basePath}${urlPath.startsWith('/') ? urlPath : `/${urlPath}`}`.replace(/^\/admin\/api/, '/admin')
|
||||
}
|
||||
|
||||
const buildCanonicalParams = (params: unknown): string => {
|
||||
if (!params || typeof params !== 'object') {
|
||||
return ''
|
||||
}
|
||||
return Object.entries(params as Record<string, unknown>)
|
||||
.filter(([, value]) => value !== undefined && value !== null && value !== '')
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
|
||||
.join('&')
|
||||
}
|
||||
|
||||
const buildJsonPayload = (data: unknown): string => {
|
||||
if (data === undefined || data === null || data instanceof FormData) {
|
||||
return ''
|
||||
}
|
||||
if (typeof data === 'string') {
|
||||
return data
|
||||
}
|
||||
return JSON.stringify(data)
|
||||
}
|
||||
|
||||
export const attachRequestSignature = async (
|
||||
config: InternalAxiosRequestConfig,
|
||||
accessToken: string,
|
||||
options: RequestSignatureOptions
|
||||
): Promise<InternalAxiosRequestConfig> => {
|
||||
config.headers = config.headers || {}
|
||||
const headers = config.headers as HeaderContainer
|
||||
const deviceId = getDeviceId()
|
||||
setHeader(headers, DEVICE_ID_HEADER, deviceId)
|
||||
const method = String(config.method || 'GET').toUpperCase()
|
||||
if (options.authFree || !accessToken || isSafeMethod(method)) {
|
||||
return config
|
||||
}
|
||||
const timestamp = String(Date.now())
|
||||
const nonce = randomNonce(deviceId)
|
||||
const payload = buildJsonPayload(config.data)
|
||||
const canonical = [
|
||||
method,
|
||||
toBackendRequestPath(config),
|
||||
buildCanonicalParams(config.params),
|
||||
await sha256Hex(payload),
|
||||
timestamp,
|
||||
nonce
|
||||
].join('\n')
|
||||
setHeader(headers, HEADER_TIMESTAMP, timestamp)
|
||||
setHeader(headers, HEADER_NONCE, nonce)
|
||||
setHeader(headers, HEADER_SIGNATURE_VERSION, SIGNATURE_VERSION)
|
||||
setHeader(headers, HEADER_SIGNATURE, await hmacSha256Hex(accessToken, canonical))
|
||||
return config
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export const readJson = <T>(key: string, fallbackValue: T): T => {
|
||||
const raw = window.localStorage.getItem(key)
|
||||
if (!raw) {
|
||||
return fallbackValue
|
||||
}
|
||||
return JSON.parse(raw) as T
|
||||
}
|
||||
|
||||
export const writeJson = <T>(key: string, value: T): void => {
|
||||
window.localStorage.setItem(key, JSON.stringify(value))
|
||||
}
|
||||
|
||||
export const removeStorage = (key: string): void => {
|
||||
window.localStorage.removeItem(key)
|
||||
window.sessionStorage.removeItem(key)
|
||||
}
|
||||
|
||||
const PLANNING_REFRESH_KEY = 'planningNeedRefresh'
|
||||
|
||||
export const markPlanningRefresh = (): void => {
|
||||
window.localStorage.setItem(PLANNING_REFRESH_KEY, '1')
|
||||
}
|
||||
|
||||
export const consumePlanningRefresh = (): boolean => {
|
||||
const marked = window.localStorage.getItem(PLANNING_REFRESH_KEY) === '1'
|
||||
if (marked) {
|
||||
window.localStorage.removeItem(PLANNING_REFRESH_KEY)
|
||||
}
|
||||
return marked
|
||||
}
|
||||
Reference in New Issue
Block a user