功能:收口小程序前后台安全与防重复提交

This commit is contained in:
xiaowang
2026-04-20 16:02:57 +08:00
parent eb1c209d79
commit a3df262fae
237 changed files with 14068 additions and 728 deletions
@@ -0,0 +1,78 @@
const inflightScopes = new Map()
function resolveScopeId(scope) {
if (scope && typeof scope === 'string') {
return scope
}
if (scope && typeof scope.route === 'string' && scope.route) {
return scope.route
}
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const current = pages[pages.length - 1]
if (current && current.route) {
return current.route
}
return 'global'
}
function getScopeMap(scopeId) {
if (!inflightScopes.has(scopeId)) {
inflightScopes.set(scopeId, new Map())
}
return inflightScopes.get(scopeId)
}
function createGuardError(message, scopeId, actionKey) {
const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb')
error.isActionGuardError = true
error.scopeId = scopeId
error.actionKey = actionKey
return error
}
async function run(scope, actionKey, task, options) {
const scopeId = resolveScopeId(scope)
const normalizedKey = String(actionKey || 'default')
const scopeMap = getScopeMap(scopeId)
if (scopeMap.get(normalizedKey)) {
return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey))
}
scopeMap.set(normalizedKey, true)
try {
return await Promise.resolve().then(() => task())
} finally {
scopeMap.delete(normalizedKey)
if (!scopeMap.size) {
inflightScopes.delete(scopeId)
}
}
}
function isRunning(scope, actionKey) {
const scopeId = resolveScopeId(scope)
const scopeMap = inflightScopes.get(scopeId)
if (!scopeMap) {
return false
}
return Boolean(scopeMap.get(String(actionKey || 'default')))
}
function clearScope(scope) {
inflightScopes.delete(resolveScopeId(scope))
}
function isGuardError(error) {
return Boolean(error && error.isActionGuardError)
}
module.exports = {
run,
isRunning,
clearScope,
isGuardError,
createGuardError
}
+99
View File
@@ -0,0 +1,99 @@
const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage')
function getAccessToken() {
return getStorage(STORAGE_KEYS.ACCESS_TOKEN, '')
}
function getRefreshToken() {
return getStorage(STORAGE_KEYS.REFRESH_TOKEN, '')
}
function getStoredUserInfo() {
return getStorage(STORAGE_KEYS.USER_INFO, null)
}
function getStoredPermissions() {
return getStorage(STORAGE_KEYS.PERMISSIONS, [])
}
function getCurrentShop() {
return getStorage(STORAGE_KEYS.CURRENT_SHOP, null)
}
function isLoggedIn() {
return Boolean(getAccessToken())
}
function setSession(payload) {
if (!payload || !payload.accessToken || !payload.refreshToken) {
return
}
setStorage(STORAGE_KEYS.ACCESS_TOKEN, payload.accessToken)
setStorage(STORAGE_KEYS.REFRESH_TOKEN, payload.refreshToken)
if (payload.userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, payload.userInfo)
if (payload.userInfo.shopId) {
setCurrentShop({
id: payload.userInfo.shopId,
shopName: payload.userInfo.shopName || ''
})
} else {
removeStorage(STORAGE_KEYS.CURRENT_SHOP)
}
}
}
function updateStoredUserInfo(userInfo) {
if (!userInfo) {
removeStorage(STORAGE_KEYS.USER_INFO)
return
}
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
}
function setPermissions(permissions) {
setStorage(STORAGE_KEYS.PERMISSIONS, Array.isArray(permissions) ? permissions : [])
}
function clearPermissions() {
removeStorage(STORAGE_KEYS.PERMISSIONS)
}
function setCurrentShop(shop) {
if (!shop || !shop.id) {
removeStorage(STORAGE_KEYS.CURRENT_SHOP)
return
}
setStorage(STORAGE_KEYS.CURRENT_SHOP, {
id: shop.id,
shopName: shop.shopName || ''
})
}
function clearSession() {
removeStorage(STORAGE_KEYS.ACCESS_TOKEN)
removeStorage(STORAGE_KEYS.REFRESH_TOKEN)
removeStorage(STORAGE_KEYS.USER_INFO)
removeStorage(STORAGE_KEYS.PERMISSIONS)
removeStorage(STORAGE_KEYS.CURRENT_SHOP)
}
module.exports = {
getAccessToken,
getRefreshToken,
getStoredUserInfo,
getStoredPermissions,
getCurrentShop,
isLoggedIn,
setSession,
updateStoredUserInfo,
setPermissions,
clearPermissions,
setCurrentShop,
clearSession
}
+83
View File
@@ -0,0 +1,83 @@
const CACHE_PREFIX = 'adminMiniCache:'
const memoryCache = {}
const inflightCache = {}
function buildKey(key) {
return `${CACHE_PREFIX}${key}`
}
function now() {
return Date.now()
}
function getCache(key, defaultValue) {
if (!key) {
return defaultValue
}
const memoryEntry = memoryCache[key]
if (memoryEntry && (!memoryEntry.expireAt || memoryEntry.expireAt > now())) {
return memoryEntry.value
}
delete memoryCache[key]
try {
const storedEntry = wx.getStorageSync(buildKey(key))
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
memoryCache[key] = storedEntry
return storedEntry.value
}
wx.removeStorageSync(buildKey(key))
} catch (error) {}
return defaultValue
}
function setCache(key, value, ttlMs) {
if (!key) {
return value
}
const entry = {
value,
expireAt: ttlMs && ttlMs > 0 ? now() + ttlMs : 0
}
memoryCache[key] = entry
try {
wx.setStorageSync(buildKey(key), entry)
} catch (error) {}
return value
}
function removeCache(key) {
if (!key) {
return
}
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
function remember(key, ttlMs, loader) {
const cached = getCache(key, undefined)
if (cached !== undefined) {
return Promise.resolve(cached)
}
if (inflightCache[key]) {
return inflightCache[key]
}
inflightCache[key] = Promise.resolve()
.then(() => loader())
.then(value => setCache(key, value, ttlMs))
.finally(() => {
delete inflightCache[key]
})
return inflightCache[key]
}
module.exports = {
getCache,
setCache,
removeCache,
remember
}
+107
View File
@@ -0,0 +1,107 @@
function safeRequire(modulePath) {
try {
return require(modulePath)
} catch (error) {
return {}
}
}
function getEnvVersion() {
if (typeof wx === 'undefined') {
return 'develop'
}
try {
if (typeof wx.getAccountInfoSync === 'function') {
const accountInfo = wx.getAccountInfoSync()
const miniProgram = accountInfo && accountInfo.miniProgram
if (miniProgram && miniProgram.envVersion) {
return miniProgram.envVersion
}
}
} catch (error) {}
return 'develop'
}
function getRuntimePlatform() {
if (typeof wx === 'undefined') {
return 'devtools'
}
try {
const systemInfo = wx.getSystemInfoSync()
if (systemInfo && systemInfo.platform) {
return systemInfo.platform
}
} catch (error) {}
return 'unknown'
}
function normalizeDomain(value, fallbackValue) {
const target = String(value || fallbackValue || '').trim()
return target.replace(/\/+$/, '')
}
function ensureHttps(value, envVersion) {
if (!value) {
throw new Error(`Missing API domain for ${envVersion}`)
}
if (envVersion !== 'develop' && !value.startsWith('https://')) {
throw new Error(`${envVersion} environment must use HTTPS`)
}
return value
}
const localOverride = safeRequire('./config.local')
const ENV_VERSION = getEnvVersion()
const RUNTIME_PLATFORM = getRuntimePlatform()
const IS_DEVTOOLS = RUNTIME_PLATFORM === 'devtools'
const DEFAULT_DOMAINS = {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
const DOMAIN_MAP = {
...DEFAULT_DOMAINS,
...(localOverride.domains || {})
}
const DEFAULT_DEVELOP_TARGET = IS_DEVTOOLS ? 'local' : 'dev-remote'
const DEVELOP_TARGET = String(localOverride.developTarget || DEFAULT_DEVELOP_TARGET)
const API_DOMAIN = ensureHttps(
ENV_VERSION === 'develop'
? normalizeDomain(DOMAIN_MAP[DEVELOP_TARGET], DOMAIN_MAP['dev-remote'])
: normalizeDomain(DOMAIN_MAP[ENV_VERSION], DOMAIN_MAP.release),
ENV_VERSION
)
module.exports = {
ENV_VERSION,
RUNTIME_PLATFORM,
IS_DEVTOOLS,
DEVELOP_TARGET,
API_DOMAIN,
ADMIN_API_BASE_URL: `${API_DOMAIN}/admin/api`,
IS_DEV_ENV: ENV_VERSION === 'develop',
REQUEST_TIMEOUT: Number(localOverride.requestTimeout || 10000),
ENABLE_REQUEST_SIGNING: localOverride.enableRequestSigning !== false,
IDLE_TIMEOUT_MS: 30 * 60 * 1000,
IDLE_WARNING_MS: 2 * 60 * 1000,
CACHE_TTL: {
permissions: 2 * 60 * 1000,
dict: 5 * 60 * 1000,
workbench: 60 * 1000
},
TAB_PAGES: [
'/pages/workbench/index',
'/pages/orders/index',
'/pages/manage/index',
'/pages/profile/index'
]
}
@@ -0,0 +1,12 @@
module.exports = {
developTarget: 'local',
requestTimeout: 10000,
enableRequestSigning: true,
domains: {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
}
+177
View File
@@ -0,0 +1,177 @@
function utf8ToBytes(text) {
const encoded = unescape(encodeURIComponent(String(text || '')))
const bytes = []
for (let index = 0; index < encoded.length; index += 1) {
bytes.push(encoded.charCodeAt(index))
}
return bytes
}
function bytesToHex(bytes) {
return (Array.isArray(bytes) ? bytes : []).map(item => item.toString(16).padStart(2, '0')).join('')
}
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount))
}
function sha256Bytes(messageBytes) {
const k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
const h = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]
const bytes = Array.isArray(messageBytes) ? messageBytes.slice() : []
const bitLength = BigInt(bytes.length) * 8n
bytes.push(0x80)
while ((bytes.length % 64) !== 56) {
bytes.push(0)
}
for (let index = 7; index >= 0; index -= 1) {
bytes.push(Number((bitLength >> BigInt(index * 8)) & 0xffn))
}
const words = new Array(64)
for (let offset = 0; offset < bytes.length; offset += 64) {
for (let index = 0; index < 16; index += 1) {
const start = offset + index * 4
words[index] = (
(bytes[start] << 24) |
(bytes[start + 1] << 16) |
(bytes[start + 2] << 8) |
bytes[start + 3]
) >>> 0
}
for (let index = 16; index < 64; index += 1) {
const s0 = (rightRotate(words[index - 15], 7) ^ rightRotate(words[index - 15], 18) ^ (words[index - 15] >>> 3)) >>> 0
const s1 = (rightRotate(words[index - 2], 17) ^ rightRotate(words[index - 2], 19) ^ (words[index - 2] >>> 10)) >>> 0
words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0
}
let a = h[0]
let b = h[1]
let c = h[2]
let d = h[3]
let e = h[4]
let f = h[5]
let g = h[6]
let innerH = h[7]
for (let index = 0; index < 64; index += 1) {
const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0
const choice = ((e & f) ^ ((~e) & g)) >>> 0
const temp1 = (innerH + s1 + choice + k[index] + words[index]) >>> 0
const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0
const majority = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
const temp2 = (s0 + majority) >>> 0
innerH = g
g = f
f = e
e = (d + temp1) >>> 0
d = c
c = b
b = a
a = (temp1 + temp2) >>> 0
}
h[0] = (h[0] + a) >>> 0
h[1] = (h[1] + b) >>> 0
h[2] = (h[2] + c) >>> 0
h[3] = (h[3] + d) >>> 0
h[4] = (h[4] + e) >>> 0
h[5] = (h[5] + f) >>> 0
h[6] = (h[6] + g) >>> 0
h[7] = (h[7] + innerH) >>> 0
}
const output = []
h.forEach(value => {
output.push((value >>> 24) & 0xff)
output.push((value >>> 16) & 0xff)
output.push((value >>> 8) & 0xff)
output.push(value & 0xff)
})
return output
}
function sha256Hex(text) {
return bytesToHex(sha256Bytes(utf8ToBytes(text)))
}
function hmacSha256Hex(secret, message) {
let keyBytes = utf8ToBytes(secret)
if (keyBytes.length > 64) {
keyBytes = sha256Bytes(keyBytes)
}
while (keyBytes.length < 64) {
keyBytes.push(0)
}
const outer = []
const inner = []
for (let index = 0; index < 64; index += 1) {
outer[index] = keyBytes[index] ^ 0x5c
inner[index] = keyBytes[index] ^ 0x36
}
const innerDigest = sha256Bytes(inner.concat(utf8ToBytes(message)))
return bytesToHex(sha256Bytes(outer.concat(innerDigest)))
}
function buildCanonicalParams(input) {
const source = input || {}
const keys = Object.keys(source)
.filter(key => source[key] !== undefined && source[key] !== null && source[key] !== '')
.sort()
return keys.map(key => {
const rawValue = source[key]
const values = Array.isArray(rawValue) ? rawValue.slice() : [rawValue]
const normalized = values
.map(item => String(item))
.sort()
.join(',')
return `${key}=${normalized}`
}).join('&')
}
function buildJsonPayload(data) {
if (data === undefined || data === null || data === '') {
return ''
}
if (typeof data === 'string') {
return data
}
return JSON.stringify(data)
}
function randomNonce() {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
module.exports = {
sha256Hex,
hmacSha256Hex,
buildCanonicalParams,
buildJsonPayload,
randomNonce
}
+20
View File
@@ -0,0 +1,20 @@
const { STORAGE_KEYS, getStorage, setStorage } = require('./storage')
function createDeviceId() {
const randomText = Math.random().toString(36).slice(2, 10)
return `admin-mini-device-${Date.now()}-${randomText}`
}
function getDeviceId() {
let value = getStorage(STORAGE_KEYS.DEVICE_ID, '')
if (value) {
return value
}
value = createDeviceId()
setStorage(STORAGE_KEYS.DEVICE_ID, value)
return value
}
module.exports = {
getDeviceId
}
@@ -0,0 +1,68 @@
const DRAFT_PREFIX = 'adminMiniDraft:'
function buildDraftKey(key) {
return `${DRAFT_PREFIX}${key}`
}
function getDraftValue(key, defaultValue) {
if (!key) {
return defaultValue
}
try {
const record = wx.getStorageSync(buildDraftKey(key))
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
return defaultValue
}
return record.value
} catch (error) {
return defaultValue
}
}
function saveDraft(key, value) {
if (!key) {
return
}
try {
wx.setStorageSync(buildDraftKey(key), {
savedAt: Date.now(),
value
})
} catch (error) {}
}
function clearDraft(key) {
if (!key) {
return
}
try {
wx.removeStorageSync(buildDraftKey(key))
} catch (error) {}
}
function scheduleDraftSave(context, key, buildValue, delay) {
if (!context) {
return
}
if (context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
}
context.__draftSaveTimer = setTimeout(() => {
saveDraft(key, buildValue())
}, delay || 300)
}
function clearDraftTimer(context) {
if (context && context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
context.__draftSaveTimer = null
}
}
module.exports = {
getDraftValue,
saveDraft,
clearDraft,
scheduleDraftSave,
clearDraftTimer
}
+148
View File
@@ -0,0 +1,148 @@
function toIdString(value) {
return value === undefined || value === null ? '' : String(value)
}
function sameId(left, right) {
return toIdString(left) === toIdString(right)
}
function splitCsv(value) {
return String(value || '')
.split(',')
.map(item => item.trim())
.filter(Boolean)
}
function formatPrice(value) {
return Number(value || 0).toFixed(2)
}
function formatDateTime(value) {
if (!value) {
return ''
}
return String(value).replace('T', ' ').slice(0, 16)
}
function formatDate(value) {
return formatDateTime(value).slice(0, 10)
}
function maskPhone(phone) {
const value = String(phone || '')
if (value.length !== 11) {
return value
}
return `${value.slice(0, 3)}****${value.slice(7)}`
}
function truncateText(value, limit) {
const text = String(value || '')
if (!limit || text.length <= limit) {
return text
}
return `${text.slice(0, limit)}...`
}
function buildShopName(record) {
if (!record) {
return '未绑定店铺'
}
if (Array.isArray(record.shopNames) && record.shopNames.length) {
return record.shopNames.join(' / ')
}
if (record.shopName) {
return record.shopName
}
return '未绑定店铺'
}
function getUserStatusText(status) {
return Number(status) === 0 ? '已停用' : '正常'
}
function getUserTypeText(type) {
const value = Number(type)
if (value === 4) {
return '平台管理员'
}
if (value === 2) {
return '店长'
}
if (value === 3) {
return '美甲师'
}
return '普通用户'
}
function getOrderStatusText(order) {
if (order && order.statusText) {
return order.statusText
}
const status = Number(order && order.status)
if (status === 1) {
return '待服务'
}
if (status === 2) {
return '已完成'
}
return '已取消'
}
function getCouponTypeText(type) {
return Number(type) === 1 ? '折扣券' : '满减券'
}
function getCouponValueText(coupon) {
if (Number(coupon && coupon.couponType) === 1) {
return `${coupon && coupon.discountValue ? coupon.discountValue : '--'} 折`
}
return `满 ${formatPrice(coupon && coupon.minAmount)} 减 ${formatPrice(coupon && coupon.reduceAmount)}`
}
function parseDateTimeToPicker(value) {
const text = formatDateTime(value)
if (!text) {
return {
date: '',
time: ''
}
}
const parts = text.split(' ')
return {
date: parts[0] || '',
time: (parts[1] || '').slice(0, 5)
}
}
function buildDateTime(date, time) {
if (!date || !time) {
return ''
}
return `${date} ${time}:00`
}
module.exports = {
toIdString,
sameId,
splitCsv,
formatPrice,
formatDateTime,
formatDate,
maskPhone,
truncateText,
buildShopName,
getUserStatusText,
getUserTypeText,
getOrderStatusText,
getCouponTypeText,
getCouponValueText,
parseDateTimeToPicker,
buildDateTime
}
@@ -0,0 +1,165 @@
let options = null
let timer = null
let warningShown = false
let loggingOut = false
let hiddenAt = 0
let lastActiveAt = Date.now()
let pagePatched = false
function shouldTrackMethod(name) {
return ![
'onHide',
'onUnload',
'onShareAppMessage',
'onShareTimeline'
].includes(name)
}
function ensurePagePatched() {
if (pagePatched || typeof Page !== 'function') {
return
}
const originalPage = Page
Page = function wrappedPage(definition) {
const nextDefinition = {}
Object.keys(definition || {}).forEach(key => {
const value = definition[key]
if (typeof value !== 'function') {
nextDefinition[key] = value
return
}
nextDefinition[key] = function wrappedHandler(...args) {
if (shouldTrackMethod(key)) {
markActive()
}
return value.apply(this, args)
}
})
return originalPage(nextDefinition)
}
pagePatched = true
}
function start() {
stop()
if (!options) {
return
}
timer = setInterval(check, 15000)
}
function stop() {
if (timer) {
clearInterval(timer)
timer = null
}
}
function isLoggedIn() {
return options && typeof options.isLoggedIn === 'function' ? Boolean(options.isLoggedIn()) : false
}
function markActive() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
lastActiveAt = Date.now()
warningShown = false
}
function onAppShow() {
if (!options) {
return
}
if (hiddenAt > 0 && isLoggedIn()) {
const hiddenDuration = Date.now() - hiddenAt
if (hiddenDuration >= options.timeoutMs) {
forceLogout()
return
}
}
hiddenAt = 0
markActive()
start()
}
function onAppHide() {
hiddenAt = Date.now()
stop()
}
function check() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
const idleMs = Date.now() - lastActiveAt
if (idleMs >= options.timeoutMs) {
forceLogout()
return
}
if (idleMs >= options.timeoutMs - options.warningMs && !warningShown) {
showWarning()
}
}
function showWarning() {
if (!options || warningShown || loggingOut) {
return
}
warningShown = true
wx.showModal({
title: options.warningTitle || '登录即将过期',
content: options.warningContent || '长时间未操作,即将退出登录。',
confirmText: options.confirmText || '继续使用',
cancelText: options.cancelText || '退出登录',
success: result => {
warningShown = false
if (result.confirm) {
markActive()
if (typeof options.onContinue === 'function') {
options.onContinue()
}
return
}
forceLogout()
},
fail: () => {
warningShown = false
}
})
}
function forceLogout() {
if (!options || loggingOut) {
return
}
loggingOut = true
Promise.resolve()
.then(() => (typeof options.onLogout === 'function' ? options.onLogout() : undefined))
.catch(() => undefined)
.finally(() => {
loggingOut = false
warningShown = false
hiddenAt = 0
lastActiveAt = Date.now()
})
}
function init(nextOptions) {
options = nextOptions || null
lastActiveAt = Date.now()
warningShown = false
loggingOut = false
hiddenAt = 0
ensurePagePatched()
start()
}
module.exports = {
init,
start,
stop,
markActive,
onAppShow,
onAppHide
}
+51
View File
@@ -0,0 +1,51 @@
let activeLoadingCount = 0
function showLoading(options) {
const config = options || {}
activeLoadingCount += 1
if (activeLoadingCount > 1) {
return
}
wx.showLoading({
title: config.title || '加载中',
mask: config.mask !== false
})
}
function hideLoading() {
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
if (activeLoadingCount > 0) {
return
}
wx.hideLoading({
fail() {}
})
}
function resetLoading() {
activeLoadingCount = 0
wx.hideLoading({
fail() {}
})
}
function runWithLoading(task, options) {
showLoading(options)
return Promise.resolve()
.then(() => task())
.finally(() => {
hideLoading()
})
}
module.exports = {
showLoading,
hideLoading,
resetLoading,
runWithLoading
}
+146
View File
@@ -0,0 +1,146 @@
const auth = require('./auth')
const { TAB_PAGES } = require('./config')
function buildUrl(path, params) {
const query = Object.keys(params || {})
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&')
return query ? `${path}?${query}` : path
}
function getCurrentPageUrl() {
const pages = getCurrentPages()
const current = pages[pages.length - 1]
if (!current) {
return '/pages/workbench/index'
}
return buildUrl(`/${current.route}`, current.options || {})
}
function isTabPage(path) {
const purePath = String(path || '').split('?')[0]
return TAB_PAGES.includes(purePath)
}
function navigate(path, params) {
return new Promise((resolve, reject) => {
wx.navigateTo({
url: buildUrl(path, params),
success: resolve,
fail: reject
})
})
}
function redirect(path, params) {
return new Promise((resolve, reject) => {
wx.redirectTo({
url: buildUrl(path, params),
success: resolve,
fail: reject
})
})
}
function switchTab(path) {
return new Promise((resolve, reject) => {
wx.switchTab({
url: path,
success: resolve,
fail: reject
})
})
}
function goBack(fallbackPath) {
const pages = getCurrentPages()
if (pages.length > 1) {
wx.navigateBack()
return
}
const target = fallbackPath || '/pages/workbench/index'
if (isTabPage(target)) {
wx.switchTab({ url: target })
return
}
wx.redirectTo({ url: target })
}
function decodeRedirectValue(value) {
let current = String(value || '')
for (let index = 0; index < 3; index += 1) {
try {
const decoded = decodeURIComponent(current)
if (decoded === current) {
return decoded
}
current = decoded
} catch (error) {
return current
}
}
return current
}
function redirectAfterLogin(redirectValue) {
const target = redirectValue ? decodeRedirectValue(redirectValue) : ''
if (!target) {
return switchTab('/pages/workbench/index')
}
const purePath = target.split('?')[0]
if (isTabPage(target)) {
return switchTab(purePath)
}
return new Promise((resolve, reject) => {
wx.redirectTo({
url: target,
success: resolve,
fail: reject
})
})
}
function openLogin(redirectPath) {
return navigate('/pages/login/index', {
redirect: redirectPath || getCurrentPageUrl()
})
}
function ensureLogin(actionText) {
if (auth.isLoggedIn()) {
return true
}
wx.showToast({
title: `${actionText || '继续操作'}前请先登录`,
icon: 'none'
})
setTimeout(() => {
openLogin()
}, 160)
return false
}
module.exports = {
buildUrl,
getCurrentPageUrl,
isTabPage,
navigate,
redirect,
switchTab,
goBack,
redirectAfterLogin,
openLogin,
ensureLogin
}
@@ -0,0 +1,28 @@
function ensureStore() {
const app = getApp()
app.globalData.pageDirtyFlags = app.globalData.pageDirtyFlags || {}
return app.globalData.pageDirtyFlags
}
function markDirty(key) {
if (!key) {
return
}
const store = ensureStore()
store[key] = true
}
function consumeDirty(key) {
if (!key) {
return false
}
const store = ensureStore()
const value = Boolean(store[key])
delete store[key]
return value
}
module.exports = {
markDirty,
consumeDirty
}
+189
View File
@@ -0,0 +1,189 @@
const MANAGE_MODULES = [
{
key: 'users',
title: '用户管理',
description: '用户资料、停用删除、解绑、余额与 VIP',
path: '/pages/users/index',
permissionCodes: ['user:view'],
requiresShopContext: true
},
{
key: 'products',
title: '作品管理',
description: '作品新增、编辑、图片上传、点赞收藏维护',
path: '/pages/products/index',
permissionCodes: ['product:view'],
requiresShopContext: true
},
{
key: 'coupons',
title: '优惠券',
description: '普通券、VIP 自动券、发放与活动配置',
path: '/pages/coupons/index',
permissionCodes: ['coupon:view'],
requiresShopContext: true
},
{
key: 'tags',
title: '标签管理',
description: '店铺标签、颜色配置与作品关联',
path: '/pages/tags/index',
permissionCodes: ['tag:view'],
requiresShopContext: true
},
{
key: 'artists',
title: '美甲师',
description: '美甲师资料、档期信息与作品绑定',
path: '/pages/artists/index',
permissionCodes: ['nail_artist:view'],
requiresShopContext: true
},
{
key: 'shops',
title: '店铺管理',
description: '门店创建、启停、轮播图与店铺信息维护',
path: '/pages/shops/index',
permissionCodes: ['shop:view'],
requiresShopContext: false
},
{
key: 'permissions',
title: '权限管理',
description: '权限字典、用户授权与范围控制',
path: '/pages/permissions/index',
permissionCodes: ['permission:view'],
requiresShopContext: false
}
]
function getPermissionCodes(source) {
const list = Array.isArray(source) ? source : []
return list
.map(item => {
if (typeof item === 'string') {
return item
}
return item && item.permissionCode ? item.permissionCode : ''
})
.filter(Boolean)
}
function hasPermission(source, permissionCode) {
if (!permissionCode) {
return true
}
const codes = getPermissionCodes(source)
return codes.includes(permissionCode)
}
function hasAnyPermission(source, permissionCodes) {
const codes = Array.isArray(permissionCodes) ? permissionCodes : []
if (!codes.length) {
return true
}
return codes.some(code => hasPermission(source, code))
}
function hasAllPermissions(source, permissionCodes) {
const codes = Array.isArray(permissionCodes) ? permissionCodes : []
if (!codes.length) {
return true
}
return codes.every(code => hasPermission(source, code))
}
function isPlatformAdmin(userInfo) {
return Number(userInfo && userInfo.type) === 4
}
function isShopManager(userInfo) {
return Number(userInfo && userInfo.type) === 2
}
function isNailArtist(userInfo) {
return Number(userInfo && userInfo.type) === 3
}
function getRoleLabel(type) {
const value = Number(type)
if (value === 4) {
return '平台管理员'
}
if (value === 2) {
return '店长'
}
if (value === 3) {
return '美甲师'
}
return '用户'
}
function groupPermissionsByGroup(permissions) {
return (Array.isArray(permissions) ? permissions : []).reduce((result, item) => {
const group = item && item.permissionGroup ? item.permissionGroup : '未分组'
if (!result[group]) {
result[group] = []
}
result[group].push(item)
return result
}, {})
}
function checkModuleAccess(module, userInfo, permissionCodes, currentShop) {
if (!hasAnyPermission(permissionCodes, module.permissionCodes)) {
return {
allowed: false,
reason: '当前账号没有该板块权限'
}
}
if (module.requiresShopContext && !currentShop) {
if (isPlatformAdmin(userInfo)) {
return {
allowed: false,
reason: '当前为无店铺登录,请先创建或切换店铺'
}
}
return {
allowed: false,
reason: '当前账号没有可用店铺'
}
}
return {
allowed: true,
reason: ''
}
}
function getManageModules(userInfo, permissionCodes, currentShop) {
return MANAGE_MODULES.map(module => {
const access = checkModuleAccess(module, userInfo, permissionCodes, currentShop)
return {
...module,
allowed: access.allowed,
disabledReason: access.reason
}
})
}
module.exports = {
MANAGE_MODULES,
getPermissionCodes,
hasPermission,
hasAnyPermission,
hasAllPermissions,
isPlatformAdmin,
isShopManager,
isNailArtist,
getRoleLabel,
groupPermissionsByGroup,
checkModuleAccess,
getManageModules
}
+401
View File
@@ -0,0 +1,401 @@
const auth = require('./auth')
const actionGuard = require('./action-guard')
const idleSession = require('./idle-session')
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
const DEVICE_ID_HEADER = 'X-Device-Id'
const HEADER_TIMESTAMP = 'X-Timestamp'
const HEADER_NONCE = 'X-Nonce'
const HEADER_SIGNATURE = 'X-Signature'
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
let isRefreshing = false
let requestQueue = []
let redirectingToLogin = false
const inflightRequests = {}
function buildRequestUrl(url, params) {
const query = Object.keys(params || {})
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&')
const target = `${ADMIN_API_BASE_URL}${url}`
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
}
function isAuthFreePath(url) {
return [
'/auth/login',
'/auth/refresh',
'/auth/login-shops/'
].some(path => String(url || '').includes(path))
}
function normalizeError(message, statusCode, raw) {
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
error.statusCode = statusCode
error.raw = raw
return error
}
function rawRequest(options) {
idleSession.markActive()
return new Promise((resolve, reject) => {
wx.request({
...options,
success: resolve,
fail: reject
})
})
}
function queueRequest(retry) {
return new Promise((resolve, reject) => {
requestQueue.push({
resolve,
reject,
retry
})
})
}
function flushQueue(error) {
const queue = requestQueue.slice()
requestQueue = []
queue.forEach(item => {
if (error) {
item.reject(error)
return
}
item.retry().then(item.resolve).catch(item.reject)
})
}
function redirectToLogin() {
if (redirectingToLogin) {
return
}
const pages = getCurrentPages()
const current = pages[pages.length - 1]
if (current && current.route === 'pages/login/index') {
return
}
redirectingToLogin = true
const currentPath = current ? `/${current.route}` : '/pages/workbench/index'
const query = current && current.options ? current.options : {}
const queryString = Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&')
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
wx.showToast({
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
icon: 'none'
})
setTimeout(() => {
wx.reLaunch({
url: `/pages/login/index?redirect=${encodeURIComponent(redirect)}`,
complete() {
redirectingToLogin = false
}
})
}, 240)
}
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isAuthFreePath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isAuthFreePath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return headers
}
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
const payload = contentType.includes('application/json')
? buildJsonPayload(options.data)
: buildCanonicalParams(options.formData || options.data || options.params)
const timestamp = String(Date.now())
const nonce = randomNonce()
const canonical = [
method,
options.url,
timestamp,
nonce,
sha256Hex(payload)
].join('\n')
headers[HEADER_TIMESTAMP] = timestamp
headers[HEADER_NONCE] = nonce
headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical)
headers[HEADER_SIGNATURE_VERSION] = 'v1'
return headers
}
async function refreshToken() {
const refreshTokenValue = auth.getRefreshToken()
if (!refreshTokenValue) {
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
}
const response = await rawRequest({
url: `${ADMIN_API_BASE_URL}/auth/refresh`,
method: 'POST',
timeout: REQUEST_TIMEOUT,
header: {
'Content-Type': 'application/json',
[DEVICE_ID_HEADER]: getDeviceId()
},
data: {
refreshToken: refreshTokenValue
}
})
if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) {
auth.setSession(response.data.data)
const app = getApp()
if (app && typeof app.bootstrapSession === 'function') {
app.bootstrapSession()
}
return response.data.data
}
throw normalizeError(
(response.data && response.data.message) || '\u5237\u65b0\u540e\u53f0\u767b\u5f55\u6001\u5931\u8d25',
response.statusCode,
response
)
}
async function handleUnauthorized(options) {
if (options._retry || isAuthFreePath(options.url)) {
const app = getApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
} else {
auth.clearSession()
}
redirectToLogin()
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
}
if (isRefreshing) {
return queueRequest(() => request({
...options,
_retry: true
}))
}
isRefreshing = true
try {
await refreshToken()
flushQueue(null)
return await request({
...options,
_retry: true
})
} catch (error) {
flushQueue(error)
const app = getApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
} else {
auth.clearSession()
}
redirectToLogin()
throw error
} finally {
isRefreshing = false
}
}
async function unwrapResponse(response, options) {
idleSession.markActive()
if (response.statusCode === 401) {
return handleUnauthorized(options)
}
if (response.statusCode === 403) {
throw normalizeError(
(response.data && response.data.message) || '\u6743\u9650\u4e0d\u8db3',
response.statusCode,
response
)
}
if (response.statusCode >= 400) {
throw normalizeError(
(response.data && response.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
response.statusCode,
response
)
}
const payload = response.data
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
if (payload.code === 200) {
return payload.data
}
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
}
return payload
}
function buildDedupeKey(options, method) {
if (options.skipDedupe) {
return ''
}
if (options.dedupeKey) {
return `${method}:${options.dedupeKey}`
}
if (method === 'GET') {
return `${method}:${options.url}:${buildCanonicalParams(options.params)}`
}
return ''
}
function isSafeMethod(method) {
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
}
function buildActionFingerprint(options, method) {
const paramsText = buildCanonicalParams(options.params)
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
return sha256Hex([
options.url || '',
paramsText,
payloadText
].join('\n'))
}
function resolveRepeatMessage(url) {
const path = String(url || '')
if (path.includes('/auth/login')) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/auth/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/auth/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/coupon/distribute') || path.includes('/coupon/assign') || path.includes('/order/update-status')) {
return '\u64cd\u4f5c\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (
path.includes('/user/create')
|| path.includes('/user/update')
|| path.includes('/product/create')
|| path.includes('/product/update')
|| path.includes('/shops/create')
|| path.includes('/shops/update')
|| path.includes('/tag/create')
|| path.includes('/tag/update')
|| path.includes('/permission/create')
|| path.includes('/permission/update')
|| path.includes('/nail-artist/save')
) {
return '\u4fdd\u5b58\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
function buildActionGuardConfig(options, method) {
if (options.skipActionGuard || isSafeMethod(method)) {
return null
}
return {
scope: options.guardScope,
key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`,
message: options.repeatMessage || resolveRepeatMessage(options.url)
}
}
function request(options) {
const method = String(options.method || 'GET').toUpperCase()
const dedupeKey = buildDedupeKey(options, method)
if (dedupeKey && inflightRequests[dedupeKey]) {
return inflightRequests[dedupeKey]
}
const signatureHeaders = buildSignatureHeaders({
url: options.url,
method,
data: options.data,
params: options.params,
header: options.header
})
const header = {
'Content-Type': 'application/json',
...signatureHeaders,
...(options.header || {})
}
const requestOptions = {
...options,
method,
header
}
const actionGuardConfig = buildActionGuardConfig(options, method)
const executeRequest = () => new Promise((resolve, reject) => {
wx.request({
url: buildRequestUrl(options.url, options.params),
method,
timeout: options.timeout || REQUEST_TIMEOUT,
header,
data: method === 'GET' ? undefined : options.data,
success: async response => {
try {
const data = await unwrapResponse(response, requestOptions)
resolve(data)
} catch (error) {
reject(error)
}
},
fail: error => {
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
}
})
})
const task = (actionGuardConfig
? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, {
message: actionGuardConfig.message
})
: executeRequest()
).finally(() => {
if (dedupeKey) {
delete inflightRequests[dedupeKey]
}
})
if (dedupeKey) {
inflightRequests[dedupeKey] = task
}
return task
}
request.buildSignatureHeaders = buildSignatureHeaders
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
module.exports = request
+49
View File
@@ -0,0 +1,49 @@
const STORAGE_KEYS = {
ACCESS_TOKEN: 'adminAccessToken',
REFRESH_TOKEN: 'adminRefreshToken',
USER_INFO: 'adminUserInfo',
PERMISSIONS: 'adminPermissions',
CURRENT_SHOP: 'adminCurrentShop',
DEVICE_ID: 'adminMiniDeviceId'
}
const TEMP_RECORD_PREFIX = 'adminTempRecord:'
function getStorage(key, defaultValue) {
try {
const value = wx.getStorageSync(key)
return value === '' || value === undefined ? defaultValue : value
} catch (error) {
return defaultValue
}
}
function setStorage(key, value) {
wx.setStorageSync(key, value)
}
function removeStorage(key) {
wx.removeStorageSync(key)
}
function setTempRecord(name, value) {
setStorage(`${TEMP_RECORD_PREFIX}${name}`, value)
}
function getTempRecord(name, defaultValue) {
return getStorage(`${TEMP_RECORD_PREFIX}${name}`, defaultValue)
}
function clearTempRecord(name) {
removeStorage(`${TEMP_RECORD_PREFIX}${name}`)
}
module.exports = {
STORAGE_KEYS,
getStorage,
setStorage,
removeStorage,
setTempRecord,
getTempRecord,
clearTempRecord
}
+198
View File
@@ -0,0 +1,198 @@
const fileApi = require('../api/file')
function getFileSystemManager() {
return wx.getFileSystemManager()
}
function getFileInfo(filePath) {
return new Promise((resolve, reject) => {
wx.getFileInfo({
filePath,
success: resolve,
fail: reject
})
})
}
function readFileBuffer(filePath) {
return new Promise((resolve, reject) => {
getFileSystemManager().readFile({
filePath,
success: result => resolve(result.data),
fail: reject
})
})
}
function writeChunkFile(filePath, data) {
return new Promise((resolve, reject) => {
getFileSystemManager().writeFile({
filePath,
data,
encoding: 'binary',
success: resolve,
fail: reject
})
})
}
function removeFile(filePath) {
return new Promise(resolve => {
getFileSystemManager().unlink({
filePath,
success: resolve,
fail: resolve
})
})
}
function normalizeSelectedFiles(files) {
return (Array.isArray(files) ? files : []).map((item, index) => {
if (typeof item === 'string') {
return {
tempFilePath: item,
fileName: `image-${index + 1}.jpg`
}
}
return {
tempFilePath: item.tempFilePath || item.path || '',
fileName: item.fileName || item.name || `image-${index + 1}.jpg`
}
}).filter(item => item.tempFilePath)
}
function createFingerprint(seed) {
let hash = 0
const text = String(seed || '')
for (let index = 0; index < text.length; index += 1) {
hash = ((hash << 5) - hash) + text.charCodeAt(index)
hash |= 0
}
return `mini-${Math.abs(hash)}`
}
function resolveContentType(fileName) {
const value = String(fileName || '').toLowerCase()
if (value.endsWith('.png')) {
return 'image/png'
}
if (value.endsWith('.webp')) {
return 'image/webp'
}
if (value.endsWith('.gif')) {
return 'image/gif'
}
return 'image/jpeg'
}
async function uploadSingleFile(file, scene, onProgress) {
const fileInfo = await getFileInfo(file.tempFilePath)
const buffer = await readFileBuffer(file.tempFilePath)
const contentType = resolveContentType(file.fileName)
const session = await fileApi.initChunkUpload({
fileName: file.fileName,
fileSize: fileInfo.size,
contentType,
fileFingerprint: createFingerprint(`${file.fileName}|${fileInfo.size}|${file.tempFilePath}`),
scene
})
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = 0
const chunkSize = Number(session.chunkSize || 0)
const totalChunks = Number(session.totalChunks || 0)
if (!chunkSize || !totalChunks) {
throw new Error('上传会话初始化失败')
}
Array.from(uploadedChunkSet).forEach(chunkIndex => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileInfo.size)
uploadedBytes += Math.max(end - start, 0)
})
onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 100))
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) {
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileInfo.size)
const chunkBuffer = buffer.slice(start, end)
const chunkPath = `${wx.env.USER_DATA_PATH}/${session.uploadId}-${chunkIndex}.part`
await writeChunkFile(chunkPath, chunkBuffer)
try {
await fileApi.uploadChunkFile({
filePath: chunkPath,
uploadId: session.uploadId,
chunkIndex,
totalChunks,
onProgress(progress) {
const loaded = Number(progress && progress.totalBytesSent) || 0
const currentBytes = Math.min(loaded, end - start)
const percent = ((uploadedBytes + currentBytes) / Math.max(fileInfo.size, 1)) * 100
onProgress(Math.min(percent, 99.9))
}
})
} finally {
await removeFile(chunkPath)
}
uploadedBytes += (end - start)
onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 99.9))
}
const result = await fileApi.completeChunkUpload(session.uploadId)
onProgress(100)
return result
}
async function uploadImageFiles(options) {
const files = normalizeSelectedFiles(options && options.files)
const scene = options && options.scene ? options.scene : 'admin-product-image'
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {}
const results = []
for (let index = 0; index < files.length; index += 1) {
const basePercent = (index / Math.max(files.length, 1)) * 100
const filePercentSize = 100 / Math.max(files.length, 1)
const result = await uploadSingleFile(files[index], scene, percent => {
onProgress(Math.min(basePercent + (percent / 100) * filePercentSize, 100))
})
results.push(result)
}
onProgress(100)
return results
}
function chooseImageFiles(options) {
const config = options || {}
return new Promise((resolve, reject) => {
wx.chooseMedia({
count: config.count || 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: result => {
resolve(normalizeSelectedFiles(result.tempFiles || []))
},
fail: reject
})
})
}
module.exports = {
chooseImageFiles,
uploadImageFiles
}