67 lines
2.3 KiB
JavaScript
67 lines
2.3 KiB
JavaScript
import { reactive } from 'vue'
|
|
|
|
const STORAGE_KEY = 'overseas-pda-fulfillment-draft-v2'
|
|
|
|
const blankState = () => ({
|
|
scopeKey: '',
|
|
dispatch: { currentNo: '', palletCode: '', dispatchItemId: '', sourceKey: '', cartonCode: '', packages: 1 },
|
|
outbound: { currentTaskNo: '', scanCode: '', packages: 1 }
|
|
})
|
|
|
|
export const fulfillment = reactive(blankState())
|
|
|
|
function storageAvailable() {
|
|
return typeof uni !== 'undefined' && typeof uni.setStorageSync === 'function' && typeof uni.getStorageSync === 'function'
|
|
}
|
|
|
|
function safeDomain(value, fallback) { return Object.fromEntries(Object.keys(fallback).map(key => [key, value?.[key] ?? fallback[key]])) }
|
|
|
|
export function persistFulfillmentDraft() {
|
|
if (!storageAvailable() || !fulfillment.scopeKey) return
|
|
uni.setStorageSync(STORAGE_KEY, JSON.parse(JSON.stringify(fulfillment)))
|
|
}
|
|
|
|
export function restoreFulfillmentDraft(scopeKey) {
|
|
const expected = String(scopeKey || '')
|
|
if (!expected) return false
|
|
const saved = storageAvailable() ? uni.getStorageSync(STORAGE_KEY) : null
|
|
if (!saved || saved.scopeKey !== expected) {
|
|
Object.assign(fulfillment, blankState(), { scopeKey: expected })
|
|
if (storageAvailable()) uni.removeStorageSync(STORAGE_KEY)
|
|
return false
|
|
}
|
|
const fresh = blankState()
|
|
Object.assign(fulfillment, fresh, {
|
|
scopeKey: expected,
|
|
dispatch: safeDomain(saved.dispatch, fresh.dispatch),
|
|
outbound: safeDomain(saved.outbound, fresh.outbound)
|
|
})
|
|
return true
|
|
}
|
|
|
|
export function updateFulfillmentDraft(domain, patch) {
|
|
if (!fulfillment[domain]) throw new Error('未知海外 PDA 履约草稿')
|
|
Object.assign(fulfillment[domain], patch)
|
|
persistFulfillmentDraft()
|
|
}
|
|
|
|
function randomKey(domain, action) {
|
|
return `pda-${domain}-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
|
}
|
|
|
|
export function fulfillmentIdempotencyKey(domain, action, _payload = {}) {
|
|
if (!fulfillment[domain]) throw new Error('未知海外 PDA 履约类型')
|
|
return { value: randomKey(domain, action) }
|
|
}
|
|
|
|
export function resetFulfillmentDomain(domain) {
|
|
if (!fulfillment[domain]) return
|
|
fulfillment[domain] = blankState()[domain]
|
|
persistFulfillmentDraft()
|
|
}
|
|
|
|
export function resetFulfillmentSession() {
|
|
Object.assign(fulfillment, blankState())
|
|
if (typeof uni !== 'undefined' && typeof uni.removeStorageSync === 'function') uni.removeStorageSync(STORAGE_KEY)
|
|
}
|