Commit 16fbdc49 by 岑成威

feat:路径切换

1 parent 02971bd3
...@@ -13,6 +13,27 @@ ...@@ -13,6 +13,27 @@
userInfo: uni.getStorageSync('release_userInfo') userInfo: uni.getStorageSync('release_userInfo')
}, },
onLaunch: async function () { onLaunch: async function () {
// 先拉取/应用悬浮窗配置并 install,再合并,避免启动日志丢失
try {
await FloatLogConfig.refreshFromServer(true)
} catch (_) {
/* ignore */
}
// #ifdef APP-PLUS
console.log('[StoragePathMerge] 启动时开始路径合并')
try {
await StoragePathMerge.run()
} catch (e) {
console.error('[StoragePathMerge] 启动合并异常', e?.message || e)
uni.$logger?.local?.error('[StoragePathMerge] ' + (e?.message || e))
} finally {
uni.$resolveStorageMerge?.()
console.log('[StoragePathMerge] 启动合并流程结束,可继续初始化数据库')
}
// #endif
// #ifndef APP-PLUS
uni.$resolveStorageMerge?.()
// #endif
this.onKeep() this.onKeep()
// this.setAPPVersion() // this.setAPPVersion()
setTimeout(() => { setTimeout(() => {
...@@ -52,21 +73,10 @@ ...@@ -52,21 +73,10 @@
appCacheApi.clearAppCache() appCacheApi.clearAppCache()
this.$store.dispatch('setBackgroundState', false) this.$store.dispatch('setBackgroundState', false)
this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数 this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling() RecordSaveService.startPolling()
uni.onMemoryWarning(function () { uni.onMemoryWarning(function () {
console.log('onMemoryWarningReceive') console.log('onMemoryWarningReceive')
}) })
// const systemInfo = await uni.$api.systemApi.getMockData();
// if (systemInfo.isCheckedUpdate) {
// checkUpdate();
// }
// let version = plus.runtime.version;
// uni.$api.commonApi.getAPPVersion().then((res) => {
// if (res != version && !systemInfo.isCheckedUpdate)
// this.$store.dispatch("openUpdateModal");
// });
}, },
onHide: function () { onHide: function () {
this.$store.dispatch('setBackgroundState', true) this.$store.dispatch('setBackgroundState', true)
...@@ -168,4 +178,3 @@ ...@@ -168,4 +178,3 @@
left: 0rpx; left: 0rpx;
} }
</style> </style>
\ No newline at end of file \ No newline at end of file
...@@ -21,6 +21,11 @@ const getMockData = async (immediate = false) => { ...@@ -21,6 +21,11 @@ const getMockData = async (immediate = false) => {
const MOCKDATA = uni.$storage.get('mock_data') const MOCKDATA = uni.$storage.get('mock_data')
try { try {
if (!immediate && MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) { if (!immediate && MOCKDATA && Date.now() - MOCKDATA.createTime < 5 * 60e3) {
try {
require('@/utils/logger/FloatLogConfig.js').default.applyFromMockData(MOCKDATA)
} catch (e) {
/* ignore */
}
return Promise.resolve(MOCKDATA) return Promise.resolve(MOCKDATA)
} else { } else {
if (!serverConfig.mockRequestCount || immediate) { if (!serverConfig.mockRequestCount || immediate) {
...@@ -30,6 +35,11 @@ const getMockData = async (immediate = false) => { ...@@ -30,6 +35,11 @@ const getMockData = async (immediate = false) => {
data.createTime = Date.now() data.createTime = Date.now()
serverConfig.mockCache = data serverConfig.mockCache = data
uni.$storage.set('mock_data', data) uni.$storage.set('mock_data', data)
try {
require('@/utils/logger/FloatLogConfig.js').default.applyFromMockData(data)
} catch (e) {
/* ignore */
}
return Promise.resolve(data) return Promise.resolve(data)
} else { } else {
const key = Date.now() const key = Date.now()
......
...@@ -126,9 +126,12 @@ ...@@ -126,9 +126,12 @@
</view> </view>
</template> </template>
</ErrorOrderPopup> </ErrorOrderPopup>
<FloatLogPanel v-if="showFloatLog" />
</view> </view>
</template> </template>
<script> <script>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
import ReceptionCenter from './components/ReceptionCenter/index.vue' import ReceptionCenter from './components/ReceptionCenter/index.vue'
import SceneMarket from './components/SceneMarket/index.vue' import SceneMarket from './components/SceneMarket/index.vue'
// import myClick from '@/mixin/click' // import myClick from '@/mixin/click'
...@@ -166,8 +169,9 @@ import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue' ...@@ -166,8 +169,9 @@ import ErrorOrderPopup from '@/components/ErrorOrderPopup.vue'
import { FileUploadManager, UploadService } from '@/utils/recordManager/index.js' import { FileUploadManager, UploadService } from '@/utils/recordManager/index.js'
export default { export default {
// mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin], // mixins: [recorder, uploader, timeout, versionCheck, merge, interceptionMixin],
mixins: [recorder, versionCheck, interceptionMixin], mixins: [ recorder, versionCheck, interceptionMixin, merge],
components: { components: {
FloatLogPanel,
ReceptionCenter, ReceptionCenter,
StudyCenter, StudyCenter,
SceneMarket, SceneMarket,
...@@ -216,6 +220,7 @@ export default { ...@@ -216,6 +220,7 @@ export default {
}, },
data() { data() {
return { return {
showFloatLog: false,
studyUrl: '', studyUrl: '',
jumpUrl: '', jumpUrl: '',
transfer: '', transfer: '',
...@@ -254,12 +259,17 @@ export default { ...@@ -254,12 +259,17 @@ export default {
} }
}, },
beforeDestroy() { beforeDestroy() {
this._unsubFloatLog && this._unsubFloatLog()
// 组件销毁前移除监听 // 组件销毁前移除监听
uni.$logger.local.info('levelStudyPopup 移除监听') uni.$logger.local.info('levelStudyPopup 移除监听')
uni.$off('levelStudyPopup') uni.$off('levelStudyPopup')
uni.$off('pageBack') uni.$off('pageBack')
}, },
async mounted() { async mounted() {
this._syncShowFloatLog()
this._unsubFloatLog = FloatLogConfig.subscribe(() => {
this._syncShowFloatLog()
})
uni.$logger.local.info('levelStudyPopup 开始监听mounted') uni.$logger.local.info('levelStudyPopup 开始监听mounted')
uni.$on('levelStudyPopup', obj => { uni.$on('levelStudyPopup', obj => {
uni.$logger.local.info('接收到学习弹窗事件', obj) uni.$logger.local.info('接收到学习弹窗事件', obj)
...@@ -327,6 +337,9 @@ export default { ...@@ -327,6 +337,9 @@ export default {
}) })
}, },
methods: { methods: {
_syncShowFloatLog() {
this.showFloatLog = FloatLogConfig.isLogBallVisible()
},
// 处理开始测评(参考 detail.vue 的实现) // 处理开始测评(参考 detail.vue 的实现)
async handleStartAssessment() { async handleStartAssessment() {
this.showStudyPopup = false this.showStudyPopup = false
......
...@@ -19,13 +19,18 @@ ...@@ -19,13 +19,18 @@
{{ title }} {{ title }}
</view> </view>
<slot></slot> <slot></slot>
<FloatLogPanel v-if="showFloatLog" />
</view> </view>
</template> </template>
<script type='text/ecmascript-6'> <script type='text/ecmascript-6'>
import FloatLogPanel from '@/components/FloatLogPanel/FloatLogPanel.vue'
import FloatLogConfig from '@/utils/logger/FloatLogConfig.js'
export default { export default {
components: { FloatLogPanel },
props: { props: {
pageStyle:{ pageStyle: {
type: String, type: String,
default: '' default: ''
}, },
...@@ -49,14 +54,24 @@ export default { ...@@ -49,14 +54,24 @@ export default {
default: '' default: ''
} }
}, },
name: '', data() {
data () {
return { return {
showFloatLog: false
} }
}, },
mounted () { mounted() {
this._syncShowFloatLog()
this._unsubFloatLog = FloatLogConfig.subscribe(() => {
this._syncShowFloatLog()
})
},
beforeDestroy() {
this._unsubFloatLog && this._unsubFloatLog()
}, },
methods: { methods: {
_syncShowFloatLog() {
this.showFloatLog = FloatLogConfig.isLogBallVisible()
}
} }
} }
</script> </script>
...@@ -91,4 +106,4 @@ export default { ...@@ -91,4 +106,4 @@ export default {
} }
} }
} }
</style>
\ No newline at end of file \ No newline at end of file
</style>
...@@ -103,9 +103,13 @@ uni.signHttpConfig = { ...@@ -103,9 +103,13 @@ uni.signHttpConfig = {
if (!uni.$dbRecord) { if (!uni.$dbRecord) {
uni.$dbRecord = new DBRecord() uni.$dbRecord = new DBRecord()
} }
uni.$storageMergeDone = new Promise(resolve => {
uni.$resolveStorageMerge = resolve
})
// 导出数据库初始化 Promise,供其他模块等待 // 导出数据库初始化 Promise,供其他模块等待
if (!uni.$dbReady) { if (!uni.$dbReady) {
uni.$dbReady = (async _ => { uni.$dbReady = (async _ => {
await uni.$storageMergeDone
try { try {
await uni.$dbRecord.init() await uni.$dbRecord.init()
// await uni.$dbTempRecord.init() // 已废弃 // await uni.$dbTempRecord.init() // 已废弃
......
import { LogLevel } from './constants'
import { serializeIfObject } from '../utils'
import FloatLogConfig from './FloatLogConfig.js'
const MAX_LINES = 400
const PIN_TAG = '[StoragePathMerge]'
const MAX_PINNED_LINES = 60
function trimLines() {
if (lines.length <= MAX_LINES) return
const pinned = lines.filter(l => l.text.includes(PIN_TAG))
const normal = lines.filter(l => !l.text.includes(PIN_TAG))
const pinnedKeep = pinned.slice(-MAX_PINNED_LINES)
const normalBudget = Math.max(0, MAX_LINES - pinnedKeep.length)
const normalKeep = normal.slice(-normalBudget)
lines = [...normalKeep, ...pinnedKeep]
lines.sort((a, b) => {
const ta = parseInt(String(a.id).split('_')[0], 10) || 0
const tb = parseInt(String(b.id).split('_')[0], 10) || 0
return ta - tb
})
}
let lines = []
let listeners = new Set()
let installed = false
let originalConsole = null
function pad(n) {
return n < 10 ? '0' + n : String(n)
}
function nowTime() {
const d = new Date()
const ms = String(d.getMilliseconds())
const ms3 = ms.length >= 3 ? ms : ('00' + ms).slice(-3)
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms3}`
}
function normalizeLevel(level) {
const l = String(level || 'info').toLowerCase()
if (l === LogLevel.DEBUG || l === 'debug') return 'debug'
if (l === LogLevel.WARN || l === 'warn') return 'warn'
if (l === LogLevel.ERROR || l === 'error') return 'error'
return 'info'
}
function formatPayload(payload) {
if (payload == null) return ''
if (typeof payload === 'string') return payload
if (payload instanceof Error) {
return payload.stack || payload.message || String(payload)
}
if (typeof payload === 'object') {
if (payload.msg != null) {
const extra = payload.extra != null ? ` ${serializeIfObject(payload.extra)}` : ''
return String(payload.msg) + extra
}
try {
return serializeIfObject(payload)
} catch (e) {
return String(payload)
}
}
return String(payload)
}
function joinArgs(args) {
return args.map(a => formatPayload(a)).filter(Boolean).join(' ')
}
function pushLine(level, text) {
const msg = formatPayload(text)
if (!msg) return
const line = {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
time: nowTime(),
level: normalizeLevel(level),
text: msg
}
lines.push(line)
trimLines()
listeners.forEach(fn => {
try {
fn(line)
} catch (e) {
/* ignore */
}
})
}
function patchConsole() {
if (originalConsole) return
originalConsole = {
log: console.log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
debug: console.debug.bind(console)
}
console.log = (...args) => {
originalConsole.log(...args)
pushLine('info', joinArgs(args))
}
console.info = (...args) => {
originalConsole.info(...args)
pushLine('info', joinArgs(args))
}
console.warn = (...args) => {
originalConsole.warn(...args)
pushLine('warn', joinArgs(args))
}
console.error = (...args) => {
originalConsole.error(...args)
pushLine('error', joinArgs(args))
}
console.debug = (...args) => {
originalConsole.debug(...args)
pushLine('debug', joinArgs(args))
}
}
const FloatLogBus = {
isInstalled() {
return installed
},
install() {
if (installed) return
installed = true
patchConsole()
if (uni.$logger && typeof uni.$logger.setLogListener === 'function') {
uni.$logger.setLogListener((level, info) => {
pushLine(level, info)
})
}
pushLine('info', '[FloatLogBus] 日志悬浮窗已就绪')
},
isFloatLogEnabled() {
return FloatLogConfig.isLogBallVisible()
},
push(level, text) {
pushLine(level, text)
},
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
getLineCount() {
return lines.length
},
getLines() {
return lines.slice()
},
/** 取尾部日志,避免面板一次性拷贝/渲染过多 */
getRecentLines(limit = 200) {
if (!limit || lines.length <= limit) return lines.slice()
return lines.slice(lines.length - limit)
},
clearLines() {
lines = []
listeners.forEach(fn => {
try {
fn(null)
} catch (e) {
/* ignore */
}
})
}
}
export default FloatLogBus
import { index as envIndex } from '@/env'
const listeners = new Set()
let configLoaded = false
let serverAllows = false
function isNonProduction() {
return envIndex !== 3
}
/**
* app-tape 配置 isShowLogBall:仅显式 true 时展示,未配置/false 均隐藏
*/
export function parseIsShowLogBall(mockData) {
if (!mockData || mockData.isShowLogBall == null) return false
const v = mockData.isShowLogBall
if (v === true || v === 1) return true
if (typeof v === 'string') return v.toLowerCase() === 'true'
return false
}
function computeVisible() {
return isNonProduction() && serverAllows
}
function notify() {
const visible = computeVisible()
listeners.forEach(fn => {
try {
fn(visible)
} catch (e) {
/* ignore */
}
})
return visible
}
const FloatLogConfig = {
isNonProduction,
isLogBallVisible() {
return computeVisible()
},
isConfigLoaded() {
return configLoaded
},
applyFromMockData(mockData) {
if (!isNonProduction()) {
serverAllows = false
} else {
serverAllows = parseIsShowLogBall(mockData)
}
configLoaded = true
const visible = notify()
if (visible) {
const FloatLogBus = require('./FloatLogBus.js').default
FloatLogBus.install()
}
return visible
},
/**
* 拉取配置中心 app-tape 并更新悬浮球(uni.$api.systemApi.getMockData)
* 例: https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=app-tape&env=test
* 字段 isShowLogBall;生产环境不展示
*/
async refreshFromServer(immediate = false) {
if (!isNonProduction()) {
serverAllows = false
configLoaded = true
return notify()
}
const cached = uni.$storage?.get?.('mock_data')
if (cached) {
this.applyFromMockData(cached)
}
try {
if (uni.$api?.systemApi?.getMockData) {
const data = await uni.$api.systemApi.getMockData(immediate)
return this.applyFromMockData(data)
}
serverAllows = false
} catch (e) {
uni.$logger?.local?.warn?.(`[FloatLogConfig] 读取 app-tape 配置失败: ${e?.message || e}`)
serverAllows = false
}
configLoaded = true
return notify()
},
subscribe(fn) {
listeners.add(fn)
fn(computeVisible())
return () => listeners.delete(fn)
}
}
export default FloatLogConfig
import { TEMP_DB_FILE } from './constants.js'
import {
loadPathCache,
savePathCache,
createDefaultCache,
ensureDefaultRootsInCache,
getNonCurrentPaths
} from './pathCache.js'
import {
getCurrentPackageRoot,
findDbInPackageRoot,
getRuntimePackageName,
getPackageNamesForMerge
} from './pathResolver.js'
import { copyFileToDoc, removeFile, removeDocRelative } from './fileIo.js'
import {
openTempDb,
closeTempDb,
openMainDbIfNeeded,
selectTempRecords,
mergeRecordsToMain
} from './dbMerge.js'
import { logInfo, logError, waitForPlus } from './log.js'
function isAndroidApp(plusRef) {
const osName = plusRef?.os?.name
return !!plusRef && (osName === 'Android' || osName === 'android')
}
async function processPath(packageRoot) {
const dbPath = await findDbInPackageRoot(packageRoot)
if (!dbPath) {
logInfo(`该路径下未找到数据库:${packageRoot}`)
return
}
logInfo(`发现待合并数据库:${dbPath}`)
await removeDocRelative(TEMP_DB_FILE)
try {
await copyFileToDoc(dbPath, TEMP_DB_FILE)
} catch (e) {
logError(`复制数据库失败(来源 ${dbPath}):${e?.message || e}`)
return
}
try {
await openTempDb()
const rows = await selectTempRecords()
if (!rows || rows.length === 0) {
logInfo(`临时库无 records 数据,跳过:${packageRoot}`)
await closeTempDb()
await removeDocRelative(TEMP_DB_FILE)
return
}
await openMainDbIfNeeded()
const ok = await mergeRecordsToMain(rows)
await closeTempDb()
await removeDocRelative(TEMP_DB_FILE)
if (ok) {
try {
await removeFile(dbPath)
logInfo(`合并成功,已删除源库:${dbPath}`)
} catch (e) {
logError(`合并成功但删除源库失败:${e?.message || e}`)
}
} else {
logError(`合并失败:${packageRoot}`)
}
} catch (e) {
logError(`处理路径异常 ${packageRoot}:${e?.message || e}`)
try {
await closeTempDb()
} catch (_) {
/* ignore */
}
try {
await removeDocRelative(TEMP_DB_FILE)
} catch (_) {
/* ignore */
}
}
}
class StoragePathMerge {
static async run() {
logInfo('开始执行路径合并')
const plusRef = await waitForPlus()
if (!isAndroidApp(plusRef)) {
logInfo('跳过:非 Android APP-PLUS 环境', {
有Plus: !!plusRef,
系统: plusRef?.os?.name
})
return
}
try {
const currentRoot = await getCurrentPackageRoot()
const runtimePkg = getRuntimePackageName()
const mergePkgs = getPackageNamesForMerge()
logInfo(`当前运行包名:${runtimePkg};参与扫描的包名:${mergePkgs.join('、')}`)
logInfo(`当前包根目录(正在使用的路径,不会在此合并):${currentRoot}`)
let cache = loadPathCache()
if (!cache || !cache.length) {
cache = createDefaultCache(currentRoot)
} else {
cache = ensureDefaultRootsInCache(cache, currentRoot)
}
savePathCache(cache)
const paths = getNonCurrentPaths(cache)
const scanList = paths.map(p => p.path)
logInfo(`待扫描非当前路径 ${paths.length} 个`, { 路径列表: scanList })
for (const item of paths) {
try {
await processPath(item.path)
} catch (e) {
logError(`扫描路径出错 ${item.path}:${e?.message || e}`)
}
}
logInfo('路径合并执行完毕')
} catch (e) {
logError(`路径合并失败:${e?.message || e}`)
throw e
}
}
}
export default StoragePathMerge
export const PATH_CACHE_KEY = 'zyzs_storage_path_cache'
export const DB_FILE = 'zyzs.db'
export const TEMP_DB_FILE = '_zyzs_temp_.db'
export const MAIN_DB_NAME = 'zyzs'
export const TEMP_DB_NAME = 'zyzs_temp_merge'
/** 正式发包 Android 包名;自定义基座运行时为 io.dcloud.HBuilder 等 */
export const RELEASE_PACKAGE_NAME = 'uni.gltap'
/** @deprecated 使用 RELEASE_PACKAGE_NAME */
export const PACKAGE_NAME = RELEASE_PACKAGE_NAME
export const TABLE_NAME = 'records'
export const MAIN_DB_PATH = `_doc/${DB_FILE}`
export const TEMP_DB_PATH = `_doc/${TEMP_DB_FILE}`
export const RECORDS_TABLE_COLUMNS = [
'id TEXT PRIMARY KEY',
'staffUuid TEXT',
'staffName TEXT',
'serviceMerchantId INTEGER',
'carModel TEXT',
'endReasonType INTEGER',
'customerName TEXT',
'phoneNumber TEXT',
'appCode TEXT',
'loginPhone TEXT',
'salesName TEXT',
'salesUuid TEXT',
'receptionStatus INTEGER',
'receptionStartTime TEXT',
'receptionEndTime TEXT',
'receptionCustomerPaySourceList TEXT',
'merchantId INTEGER',
'merchantName TEXT',
'bussinessType INTEGER',
'channelType INTEGER',
'receptionCustomerMaterialPointList TEXT',
'recordUrlList TEXT',
'carBrand TEXT',
'carBrandId INTEGER',
'oneCarBrand TEXT',
'oneCarBrandId INTEGER',
'tempFilePath TEXT',
'recordStatus INTEGER DEFAULT 1'
]
import {
MAIN_DB_NAME,
TEMP_DB_NAME,
MAIN_DB_PATH,
TEMP_DB_PATH,
TABLE_NAME,
RECORDS_TABLE_COLUMNS
} from './constants.js'
import { logInfo, logError } from './log.js'
function formatValue(value) {
let strVal = ''
if (typeof value === 'object' && value !== null) {
strVal = JSON.stringify(value)
} else {
strVal = String(value)
}
return `'${strVal.replace(/'/g, "''")}'`
}
function openDatabase(name, path) {
return new Promise((resolve, reject) => {
const isOpen = plus.sqlite.isOpenDatabase({ name, path })
if (isOpen) {
resolve(true)
return
}
plus.sqlite.openDatabase({
name,
path,
success: resolve,
fail: e => {
if (e.code === -1402) {
resolve(e)
return
}
reject(e)
}
})
})
}
function closeDatabase(name) {
return new Promise((resolve, reject) => {
plus.sqlite.closeDatabase({
name,
success: resolve,
fail: err => {
if (err && err.code === -1402) {
resolve()
return
}
reject(err)
}
})
})
}
function selectSql(name, sql) {
return new Promise((resolve, reject) => {
plus.sqlite.selectSql({
name,
sql,
success: resolve,
fail: reject
})
})
}
function executeSql(name, sql) {
return new Promise((resolve, reject) => {
plus.sqlite.executeSql({
name,
sql,
success: resolve,
fail: reject
})
})
}
export async function isTableExists(dbName, tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' AND name='${tableName}'`
const result = await selectSql(dbName, sql)
return !!(result && result[0] && result[0].isTable)
}
export async function openTempDb() {
return openDatabase(TEMP_DB_NAME, TEMP_DB_PATH)
}
export async function closeTempDb() {
try {
if (plus.sqlite.isOpenDatabase({ name: TEMP_DB_NAME, path: TEMP_DB_PATH })) {
await closeDatabase(TEMP_DB_NAME)
}
} catch (e) {
logError(`closeTempDb: ${e?.message || e}`)
}
}
export async function openMainDbIfNeeded() {
return openDatabase(MAIN_DB_NAME, MAIN_DB_PATH)
}
export async function ensureMainTable() {
const sql = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (${RECORDS_TABLE_COLUMNS.join(', ')})`
await executeSql(MAIN_DB_NAME, sql)
}
export async function selectTempRecords() {
const exists = await isTableExists(TEMP_DB_NAME, TABLE_NAME)
if (!exists) return []
return selectSql(TEMP_DB_NAME, `SELECT * FROM ${TABLE_NAME}`)
}
async function recordExistsInMain(id) {
const escaped = String(id).replace(/'/g, "''")
const rows = await selectSql(MAIN_DB_NAME, `SELECT id FROM ${TABLE_NAME} WHERE id='${escaped}' LIMIT 1`)
return rows && rows.length > 0
}
function buildInsertSql(record) {
const keys = Object.keys(record).filter(k => record[k] !== undefined)
if (!keys.length) return null
const keyStr = keys.join(', ')
const valStr = keys.map(key => formatValue(record[key])).join(', ')
return `INSERT INTO ${TABLE_NAME} (${keyStr}) VALUES (${valStr})`
}
export async function mergeRecordsToMain(rows) {
await ensureMainTable()
let merged = 0
for (const record of rows) {
if (!record || !record.id) continue
try {
const exists = await recordExistsInMain(record.id)
if (exists) {
logInfo(`跳过已存在记录 id=${record.id}`)
continue
}
const sql = buildInsertSql(record)
if (!sql) continue
await executeSql(MAIN_DB_NAME, sql)
merged++
} catch (e) {
logError(`合并单条记录失败 id=${record.id}:${e?.message || e}`)
return false
}
}
logInfo(`已合并 ${merged} 条记录到主库`)
return true
}
function toFileUrl(path) {
if (!path) return path
const p = String(path).trim()
if (p.startsWith('file://')) return p
if (p.startsWith('_')) return p
if (p.startsWith('/')) return `file://${p}`
return `file:///${p}`
}
export function fileExists(path) {
return new Promise(resolve => {
if (!path || typeof plus === 'undefined') {
resolve(false)
return
}
plus.io.resolveLocalFileSystemURL(
toFileUrl(path),
() => resolve(true),
() => resolve(false)
)
})
}
export function copyFileToDoc(sourceAbsolutePath, destFileName) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(sourceAbsolutePath),
srcEntry => {
plus.io.resolveLocalFileSystemURL(
'_doc/',
docEntry => {
srcEntry.copyTo(
docEntry,
destFileName,
entry => resolve(entry.fullPath),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
export function removeFile(path) {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(path),
entry => {
entry.remove(
() => resolve(true),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
() => resolve(false)
)
})
}
export function removeDocRelative(relativePath) {
const path = relativePath.startsWith('_doc/') ? relativePath : `_doc/${relativePath}`
return removeFile(path).catch(() => false)
}
import StoragePathMerge from './StoragePathMerge.js'
export default StoragePathMerge
export { StoragePathMerge }
import FloatLogBus from '@/utils/logger/FloatLogBus.js'
const TAG = '[StoragePathMerge]'
function emit(level, msg, extra) {
const line = extra !== undefined ? `${msg} ${JSON.stringify(extra)}` : msg
const full = `${TAG} ${line}`
try {
// 始终写入悬浮窗缓冲区(启动早于 install 时也能在面板里看到)
FloatLogBus.push(level, full)
if (!FloatLogBus.isInstalled()) {
if (level === 'error') {
console.error(TAG, line)
} else {
console.log(TAG, line)
}
}
} catch (e) {
/* ignore */
}
try {
const fn = level === 'error' ? uni.$logger?.local?.error : uni.$logger?.local?.info
fn && fn(full)
} catch (e) {
/* ignore */
}
}
export function logInfo(msg, extra) {
emit('info', msg, extra)
}
export function logError(msg, extra) {
emit('error', msg, extra)
}
export function waitForPlus(timeoutMs = 5000) {
return new Promise(resolve => {
if (typeof plus !== 'undefined') {
resolve(plus)
return
}
let settled = false
const done = p => {
if (settled) return
settled = true
resolve(p || null)
}
if (typeof document !== 'undefined') {
document.addEventListener('plusready', () => done(typeof plus !== 'undefined' ? plus : null), {
once: true
})
}
setTimeout(() => done(typeof plus !== 'undefined' ? plus : null), timeoutMs)
})
}
import { RELEASE_PACKAGE_NAME } from './constants.js'
/**
* 当前安装包名(自定义基座多为 io.dcloud.HBuilder,正式包为 uni.gltap)
*/
export function getRuntimePackageName() {
try {
if (typeof plus !== 'undefined') {
const osName = plus.os?.name
if (osName === 'Android' || osName === 'android') {
const main = plus.android.runtimeMainActivity()
const pkg = main?.getPackageName?.()
if (pkg) return String(pkg)
}
}
} catch (_) {
/* ignore */
}
return RELEASE_PACKAGE_NAME
}
/** 参与路径合并扫描的包名:当前运行包 + 正式发包名(遗留数据) */
export function getPackageNamesForMerge() {
const names = new Set()
const runtime = getRuntimePackageName()
if (runtime) names.add(runtime)
if (RELEASE_PACKAGE_NAME) names.add(RELEASE_PACKAGE_NAME)
return [...names]
}
export function getDefaultPackageRoots() {
const roots = []
const seen = new Set()
for (const pkg of getPackageNamesForMerge()) {
for (const path of [
`/data/data/${pkg}`,
`/data/user/0/${pkg}`,
`/storage/emulated/0/Android/data/${pkg}`
]) {
if (!seen.has(path)) {
seen.add(path)
roots.push(path)
}
}
}
return roots
}
import { PATH_CACHE_KEY } from './constants.js'
import { getDefaultPackageRoots } from './packageName.js'
export function normalizePath(path) {
if (!path) return ''
let p = String(path).trim()
if (p.startsWith('file://')) {
p = p.replace(/^file:\/\//, '')
}
return p.replace(/\/+$/, '')
}
export function loadPathCache() {
try {
const raw = uni.getStorageSync(PATH_CACHE_KEY)
if (!raw) return null
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
if (!Array.isArray(parsed)) return null
return parsed
.filter(item => item && item.path)
.map(item => ({
path: normalizePath(item.path),
isCurrent: !!item.isCurrent
}))
} catch (e) {
return null
}
}
export function savePathCache(cache) {
uni.setStorageSync(PATH_CACHE_KEY, JSON.stringify(cache))
}
export function createDefaultCache(currentRoot) {
const roots = getDefaultPackageRoots()
const normalizedCurrent = normalizePath(currentRoot)
const seen = new Set()
const cache = []
for (const path of roots) {
const normalized = normalizePath(path)
if (!normalized || seen.has(normalized)) continue
seen.add(normalized)
cache.push({
path: normalized,
isCurrent: normalized === normalizedCurrent
})
}
if (normalizedCurrent && !seen.has(normalizedCurrent)) {
cache.push({ path: normalizedCurrent, isCurrent: true })
cache.forEach(item => {
if (item.path !== normalizedCurrent) item.isCurrent = false
})
}
if (!cache.some(item => item.isCurrent) && cache.length > 0) {
const match = cache.find(item => item.path === normalizedCurrent)
if (match) {
match.isCurrent = true
} else if (normalizedCurrent) {
cache.push({ path: normalizedCurrent, isCurrent: true })
cache.forEach(item => {
if (item.path !== normalizedCurrent) item.isCurrent = false
})
} else {
cache[0].isCurrent = true
}
}
return cache
}
/**
* 同步 CurrentPath 与 PathCache 的 isCurrent 标记
*/
export function syncCurrentFlag(cache, currentRoot) {
const normalizedCurrent = normalizePath(currentRoot)
if (!normalizedCurrent) return cache
let list = Array.isArray(cache) ? [...cache] : []
const existing = list.find(item => normalizePath(item.path) === normalizedCurrent)
if (existing) {
list = list.map(item => ({
...item,
path: normalizePath(item.path),
isCurrent: normalizePath(item.path) === normalizedCurrent
}))
} else {
list = list.map(item => ({
...item,
path: normalizePath(item.path),
isCurrent: false
}))
list.push({ path: normalizedCurrent, isCurrent: true })
}
return list
}
export function getNonCurrentPaths(cache) {
return (cache || []).filter(item => !item.isCurrent && item.path)
}
/**
* 将默认包根补进已有缓存(切换自定义基座 / 正式包后仍能扫到遗留路径)
*/
export function ensureDefaultRootsInCache(cache, currentRoot) {
const normalizedCurrent = normalizePath(currentRoot)
let list = Array.isArray(cache) ? cache.map(item => ({ ...item })) : []
const pathSet = new Set(list.map(item => normalizePath(item.path)))
for (const path of getDefaultPackageRoots()) {
const normalized = normalizePath(path)
if (!normalized || pathSet.has(normalized)) continue
pathSet.add(normalized)
list.push({
path: normalized,
isCurrent: normalized === normalizedCurrent
})
}
return syncCurrentFlag(list, currentRoot)
}
import { PathUtils } from '@/utils/recordManager/index.js'
import { DB_FILE } from './constants.js'
import { normalizePath } from './pathCache.js'
import { fileExists } from './fileIo.js'
import { getDefaultPackageRoots } from './packageName.js'
export { getDefaultPackageRoots, getRuntimePackageName, getPackageNamesForMerge } from './packageName.js'
export function getAppId() {
if (typeof plus !== 'undefined' && plus.runtime && plus.runtime.appid) {
return plus.runtime.appid
}
return '__UNI__D3BD3DF'
}
/**
* 从 doc 目录 fullPath 推导包根目录
*/
export function derivePackageRootFromDocPath(docPath) {
const normalized = normalizePath(docPath)
if (!normalized) return ''
const appId = getAppId()
const docSuffix = `/apps/${appId}/doc`
if (normalized.endsWith(docSuffix)) {
return normalized.substring(0, normalized.length - docSuffix.length)
}
const appsMarker = '/apps/'
const appsIdx = normalized.indexOf(appsMarker)
if (appsIdx > 0) {
return normalized.substring(0, appsIdx)
}
if (normalized.endsWith('/doc')) {
return normalized.substring(0, normalized.length - 4)
}
return normalized
}
export async function getCurrentPackageRoot() {
const docPath = await PathUtils.getFilePath()
return derivePackageRootFromDocPath(docPath)
}
/**
* 包根下 zyzs.db 的候选绝对路径(无 file:// 前缀)
*/
export function resolveDbFilePaths(packageRoot) {
const root = normalizePath(packageRoot)
const appId = getAppId()
return [
`${root}/${DB_FILE}`,
`${root}/apps/${appId}/doc/${DB_FILE}`
]
}
export async function findDbInPackageRoot(packageRoot) {
const candidates = resolveDbFilePaths(packageRoot)
for (const path of candidates) {
if (await fileExists(path)) {
return path
}
}
return null
}
import { DB_FILE, RECORDS_TABLE_COLUMNS, TABLE_NAME } from './constants.js'
import { getCurrentPackageRoot, getDefaultPackageRoots } from './pathResolver.js'
import { logInfo, logError, waitForPlus } from './log.js'
const SEED_DB_NAME = 'zyzs_seed_merge_manual'
const SEED_DB_FILE = '_zyzs_seed_merge_manual_.db'
const SEED_DB_PATH = `_doc/${SEED_DB_FILE}`
function toFileUrl(path) {
if (!path) return path
const p = String(path).trim()
if (p.startsWith('file://')) return p
if (p.startsWith('_')) return p
if (p.startsWith('/')) return `file://${p}`
return `file:///${p}`
}
function normalizeNoTrailingSlash(path) {
if (!path) return ''
return String(path).trim().replace(/^file:\/\//, '').replace(/\/+$/, '')
}
function openDb(name, path) {
return new Promise((resolve, reject) => {
const isOpen = plus.sqlite.isOpenDatabase({ name, path })
if (isOpen) {
resolve(true)
return
}
plus.sqlite.openDatabase({
name,
path,
success: resolve,
fail: e => {
if (e && e.code === -1402) {
resolve(e)
return
}
reject(e)
}
})
})
}
function closeDb(name) {
return new Promise(resolve => {
try {
plus.sqlite.closeDatabase({
name,
success: resolve,
fail: () => resolve()
})
} catch (_) {
resolve()
}
})
}
function execSql(name, sql) {
return new Promise((resolve, reject) => {
plus.sqlite.executeSql({
name,
sql,
success: resolve,
fail: reject
})
})
}
function removeDocRelative(relativePath) {
const path = relativePath.startsWith('_doc/') ? relativePath : `_doc/${relativePath}`
return new Promise(resolve => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(path),
entry => entry.remove(() => resolve(true), () => resolve(false)),
() => resolve(false)
)
})
}
function ensureDirForFile(absoluteFilePath) {
const abs = normalizeNoTrailingSlash(absoluteFilePath)
const idx = abs.lastIndexOf('/')
const dir = idx > 0 ? abs.substring(0, idx) : abs
const parentIdx = dir.lastIndexOf('/')
const parent = parentIdx > 0 ? dir.substring(0, parentIdx) : '/'
const leaf = parentIdx > 0 ? dir.substring(parentIdx + 1) : ''
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(parent),
parentEntry => {
if (!leaf) {
resolve(parentEntry)
return
}
parentEntry.getDirectory(
leaf,
{ create: true },
entry => resolve(entry),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
function copyDocDbToAbsolute(absoluteTargetFilePath) {
const abs = normalizeNoTrailingSlash(absoluteTargetFilePath)
const idx = abs.lastIndexOf('/')
const fileName = idx >= 0 ? abs.substring(idx + 1) : DB_FILE
return new Promise(async (resolve, reject) => {
try {
await ensureDirForFile(abs)
} catch (e) {
reject(e)
return
}
plus.io.resolveLocalFileSystemURL(
toFileUrl(SEED_DB_PATH),
srcEntry => {
plus.io.resolveLocalFileSystemURL(
toFileUrl(abs.substring(0, idx)),
dirEntry => {
srcEntry.copyTo(
dirEntry,
fileName,
entry => resolve(entry.fullPath),
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
},
err => reject(new Error(err?.message || JSON.stringify(err)))
)
})
}
async function createSeedDbWithOneRecord(recordId) {
await waitForPlus()
await removeDocRelative(SEED_DB_FILE)
await openDb(SEED_DB_NAME, SEED_DB_PATH)
const createSql = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (${RECORDS_TABLE_COLUMNS.join(', ')})`
await execSql(SEED_DB_NAME, createSql)
const escapedId = String(recordId).replace(/'/g, "''")
const insertSql = `INSERT INTO ${TABLE_NAME} (id, staffUuid, staffName, receptionStatus) VALUES ('${escapedId}', 'seed-merge', '手动写入合并测试', 1)`
await execSql(SEED_DB_NAME, insertSql)
await closeDb(SEED_DB_NAME)
}
function pickNonCurrentRoots(currentRoot) {
const current = normalizeNoTrailingSlash(currentRoot)
const roots = (getDefaultPackageRoots() || []).map(r => normalizeNoTrailingSlash(r)).filter(Boolean)
const unique = [...new Set(roots)]
const nonCurrent = unique.filter(r => r && r !== current)
// 优先外置 Android/data(更直观且常用于迁移)
nonCurrent.sort((a, b) => {
const ak = a.includes('/Android/data/') ? 0 : 1
const bk = b.includes('/Android/data/') ? 0 : 1
if (ak !== bk) return ak - bk
return a.localeCompare(b)
})
return nonCurrent
}
/**
* 一键生成一条 records,并把 zyzs.db 放到“非当前”包根(自动挑可写的那个)。
* 适合在自定义基座(io.dcloud.HBuilder)下模拟迁移合并。
*/
export async function seedOneRecordToNonCurrentPath() {
const plusRef = await waitForPlus()
const osName = plusRef?.os?.name
if (!plusRef || (osName !== 'Android' && osName !== 'android')) {
logInfo('写入测试库跳过:非 Android')
return { ok: false, reason: 'not-android' }
}
const currentRoot = await getCurrentPackageRoot()
const candidates = pickNonCurrentRoots(currentRoot)
if (!candidates.length) {
logError('写入测试库失败:没有可用的非当前路径')
return { ok: false, reason: 'no-non-current' }
}
const recordId = `__merge_seed_${Date.now()}_${Math.random().toString(36).slice(2, 8)}__`
await createSeedDbWithOneRecord(recordId)
const errors = []
for (const root of candidates) {
const target = `${root}/${DB_FILE}`
try {
const written = await copyDocDbToAbsolute(target)
logInfo(`测试库已写入非当前路径:${written}`, { 记录id: recordId })
return { ok: true, target: written, recordId }
} catch (e) {
errors.push({ target, error: e?.message || String(e) })
}
}
logError('写入测试库失败:所有候选路径均不可写', { 失败详情: errors })
return { ok: false, reason: 'all-failed', errors }
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!