初始化
This commit is contained in:
commit
3a4e81a070
43 files changed
+10871
No files matched your search
@@ -0,0 +1,54 @@
|
||||
export const AUTH_DAY_KEY = 'finance.auth-day'
|
||||
export const TOKEN_KEY = 'token'
|
||||
export const USER_INFO_KEY = 'userInfo'
|
||||
export const DEMO_SESSION_TOKEN = 'demo-local-session'
|
||||
|
||||
const SHANGHAI_TIME_ZONE = 'Asia/Shanghai'
|
||||
const SHANGHAI_OFFSET_MS = 8 * 60 * 60 * 1000
|
||||
|
||||
const shanghaiDateParts = (date: Date) => {
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: SHANGHAI_TIME_ZONE,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).formatToParts(date)
|
||||
|
||||
const values = Object.fromEntries(parts.map(part => [part.type, part.value]))
|
||||
return {
|
||||
year: Number(values.year),
|
||||
month: Number(values.month),
|
||||
day: Number(values.day),
|
||||
}
|
||||
}
|
||||
|
||||
/** The business day used by authentication, independent of the browser locale. */
|
||||
export const getBusinessDay = (date = new Date()): string => {
|
||||
const { year, month, day } = shanghaiDateParts(date)
|
||||
return `${year.toString().padStart(4, '0')}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export const saveAuthDay = (day = getBusinessDay()) => {
|
||||
localStorage.setItem(AUTH_DAY_KEY, day)
|
||||
}
|
||||
|
||||
export const clearStoredSession = () => {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(USER_INFO_KEY)
|
||||
localStorage.removeItem(AUTH_DAY_KEY)
|
||||
}
|
||||
|
||||
const millisecondsUntilNextBusinessDay = () => {
|
||||
const { year, month, day } = shanghaiDateParts(new Date())
|
||||
// Asia/Shanghai uses UTC+08:00. The next local midnight is therefore this
|
||||
// UTC timestamp minus eight hours.
|
||||
const nextMidnight = Date.UTC(year, month - 1, day + 1) - SHANGHAI_OFFSET_MS
|
||||
return Math.max(1000, nextMidnight - Date.now() + 25)
|
||||
}
|
||||
|
||||
/** Schedule exactly one callback. Call the returned disposer before rescheduling. */
|
||||
export const scheduleNextBusinessDay = (callback: () => void): (() => void) => {
|
||||
if (typeof window === 'undefined') return () => undefined
|
||||
const timer = window.setTimeout(callback, millisecondsUntilNextBusinessDay())
|
||||
return () => window.clearTimeout(timer)
|
||||
}
|
||||