Commit af5ea84a by liimin

refactor(record): 重构录音和记录管理为单表架构

- 合并临时记录表到主记录表,通过 receptionStatus 区分状态
- 实现数据库迁移逻辑,自动将旧临时表数据迁移到主表
- 重构录音服务为单例模式,优化状态管理和防抖处理
- 添加 SQLite 任务队列防止并发冲突
- 优化日志服务和上传服务的性能和稳定性
1 parent 7d77f96e
...@@ -293,17 +293,13 @@ export default { ...@@ -293,17 +293,13 @@ export default {
}, },
async loadRecords () { async loadRecords () {
let records = await uni.$dbRecord.getRecords(); // 适配单表架构:只获取已完成 (receptionStatus=1) 的记录
let records = await uni.$dbRecord.getCompletedRecords();
this.recordList = this.sortByTime(records); this.recordList = this.sortByTime(records);
}, },
async loadTempRecords () { async loadTempRecords () {
if (!this.recorder) { const tempRecordsList = await uni.$dbRecord.getTempRecords()
this.recorder = this.getRecorder() this.tempRecordList = this.formatRecordList(tempRecordsList || [])
}
if (!this.recorder) return
const preRecordList = await this.recorder.getRecords()
this.tempRecordList = this.formatRecordList(preRecordList || [])
}, },
formatRecordList(list) { formatRecordList(list) {
if (!list) return [] if (!list) return []
......
...@@ -189,8 +189,8 @@ export default { ...@@ -189,8 +189,8 @@ export default {
} }
}, },
initUploader() { initUploader() {
// 初始化上传服务 // 初始化上传服务 (移除 init 调用,交由 App.vue 统一管理)
UploadService.init() // UploadService.init()
// 注入 Webview 实例 // 注入 Webview 实例
this.injectWebview() this.injectWebview()
}, },
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
* @LastEditTime: 2025-12-25 14:49:12 * @LastEditTime: 2025-12-25 14:49:12
* @FilePath: \simgle_app\init.js * @FilePath: \simgle_app\init.js
*/ */
import { DBRecord, DBTempRecord } from './utils/recordManager/index' import { DBRecord } from './utils/recordManager/index'
import utils from './utils/utils' import utils from './utils/utils'
import logger from './utils/logger' import logger from './utils/logger'
import { Storage } from './utils/cache/index' import { Storage } from './utils/cache/index'
...@@ -18,11 +18,23 @@ uni.$storage = new Storage() ...@@ -18,11 +18,23 @@ uni.$storage = new Storage()
uni.$throttle = utils.throttle uni.$throttle = utils.throttle
uni.$isNetWork = utils.isNetWork uni.$isNetWork = utils.isNetWork
uni.$logger = logger uni.$logger = logger
uni.$dbTempRecord = new DBTempRecord() // uni.$dbTempRecord = new DBTempRecord() // 已废弃,合并至 dbRecord
uni.$dbRecord = new DBRecord() if (!uni.$dbRecord) {
uni.$dbRecord = new DBRecord()
}
// uni.$track = new Track() // uni.$track = new Track()
!(async _ => { // 导出数据库初始化 Promise,供其他模块等待
await uni.$dbRecord.init() if (!uni.$dbReady) {
await uni.$dbTempRecord.init() uni.$dbReady = (async _ => {
})() try {
await uni.$dbRecord.init()
// await uni.$dbTempRecord.init() // 已废弃
uni.$logger.local.info('数据库初始化完成')
return true
} catch (e) {
uni.$logger.local.error('数据库初始化失败: ' + e.message)
return false
}
})()
}
import TaskQueue from '../utils/TaskQueue'
class SQLite { class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
constructor(name, version, description, size) { constructor(name, version, description, size) {
this.name = name this.name = name
this.version = version || '1.0' this.version = version || '1.0'
this.description = description || 'SQLite DB' this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null this.db = null
// 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
}
}
_enqueue(task) {
// 使用共享的队列实例
const queueInstance = SQLite._queues[this.name]
return queueInstance.enqueue(task)
} }
init() { init() {
...@@ -19,7 +33,7 @@ class SQLite { ...@@ -19,7 +33,7 @@ class SQLite {
} }
selectSql(sql) { selectSql(sql) {
return new Promise((resolve, reject) => { return this._enqueue(() => new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`) uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({ plus.sqlite.selectSql({
name: this.name, name: this.name,
...@@ -46,11 +60,11 @@ class SQLite { ...@@ -46,11 +60,11 @@ class SQLite {
}, },
fail: reject fail: reject
}) })
}) }))
} }
executeSql(sql) { executeSql(sql) {
return new Promise((resolve, reject) => { return this._enqueue(() => new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`) uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({ plus.sqlite.executeSql({
name: this.name, name: this.name,
...@@ -58,7 +72,7 @@ class SQLite { ...@@ -58,7 +72,7 @@ class SQLite {
success: resolve, success: resolve,
fail: reject fail: reject
}) })
}) }))
} }
async isTableExists(tableName) { async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'` const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48 * @Date: 2024-04-08 11:28:48
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-25 09:19:58 * @LastEditTime: 2026-01-13 18:13:46
* @FilePath: \simgle_app\mixin\timeout.js * @FilePath: \simgle_app\mixin\timeout.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -31,7 +31,6 @@ export default { ...@@ -31,7 +31,6 @@ export default {
this.__counter = 0 this.__counter = 0
this.__timer = null this.__timer = null
this.__timer = setInterval(() => { this.__timer = setInterval(() => {
uni.$logger.local.info('== 未触碰平板计时 ==' + this.__counter + '分钟' + '== __timer:' + this.__timer)
if (this.__counter >= TIMER_TIMEOUT) { if (this.__counter >= TIMER_TIMEOUT) {
//关闭录音 //关闭录音
uni.$logger.local.info(`== ${TIMER_DURATION / 60000} 分钟未触碰平板 == __timer:${this.__timer} __counter:${this.__counter}分钟`) uni.$logger.local.info(`== ${TIMER_DURATION / 60000} 分钟未触碰平板 == __timer:${this.__timer} __counter:${this.__counter}分钟`)
...@@ -40,6 +39,9 @@ export default { ...@@ -40,6 +39,9 @@ export default {
return return
} }
this.__counter++ this.__counter++
if (this.__counter % 10 === 0) {
uni.$logger.local.info('== 未触碰平板计时 ==' + this.__counter + '分钟' + '== __timer:' + this.__timer)
}
}, TIMER_INTERVAL) }, TIMER_INTERVAL)
}, },
endWatchClick() { endWatchClick() {
......
/**
* 通用任务队列类
* 实现了串行执行、超时控制、异常隔离等功能
*/
export default class TaskQueue {
constructor(name = 'TaskQueue') {
this.name = name
this.queue = Promise.resolve()
}
/**
* 将任务加入队列
* @param {Function} task - 返回 Promise 的任务函数
* @param {number} timeout - 超时时间(ms),默认 20000
* @returns {Promise}
*/
enqueue(task, timeout = 20000) {
const taskWithTimeout = () => this._withTimeout(task, timeout)
// 将任务追加到队列末尾
const next = this.queue.then(taskWithTimeout).catch(err => {
// 队列自身的错误不应中断后续任务,但这里的 err 已经被 taskWithTimeout 内部捕获并处理了
// 这里再次抛出是为了让调用者能捕获到错误
throw err
})
// 更新队列指针,确保队列始终指向最新的 Promise,且永远是 resolved 状态(catch 了错误)
// 这样后续任务不会因为前一个任务失败而无法执行
this.queue = next.catch(() => {})
return next
}
/**
* 带超时控制的任务执行器
* @private
*/
_withTimeout(task, timeout) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
const error = new Error(`${this.name}操作超时(${timeout}ms)`)
// 尝试打印日志,如果环境中有 logger
if (typeof uni !== 'undefined' && uni.$logger && uni.$logger.local) {
uni.$logger.local.error(error.message)
} else {
console.error(error.message)
}
reject(error)
}, timeout)
// 使用 Promise.resolve().then(task) 确保即使 task() 同步抛错也能被捕获并进入 finally
Promise.resolve().then(task)
.then(resolve)
.catch(reject)
.finally(() => clearTimeout(timeoutId))
})
}
}
\ No newline at end of file \ No newline at end of file
import { getTime } from './util' import { getTime } from './util'
import { serializeIfObject } from '../utils' import { serializeIfObject } from '../utils'
import TaskQueue from '../TaskQueue'
class LogCat { class LogCat {
main = plus.android.runtimeMainActivity() main = plus.android.runtimeMainActivity()
File = plus.android.importClass('java.io.File') File = plus.android.importClass('java.io.File')
...@@ -11,15 +13,58 @@ class LogCat { ...@@ -11,15 +13,58 @@ class LogCat {
// FileInputStream = plus.android.importClass('java.io.FileInputStream') // FileInputStream = plus.android.importClass('java.io.FileInputStream')
// InputStreamReader = plus.android.importClass('java.io.InputStreamReader') // InputStreamReader = plus.android.importClass('java.io.InputStreamReader')
LogPath = '' LogPath = ''
// 日志写入队列,确保串行写入
taskQueue = new TaskQueue('LogCat')
// 记录上一次检查清理的日期,用于跨天触发清理
lastCleanDate = ''
constructor(folderName = '_zyzs_log') { constructor(folderName = '_zyzs_log') {
if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) { try {
this.LogPath = this.main.getExternalFilesDir(null).getPath() + folderName let file = null
} else { if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
this.LogPath = this.main.getFilesDir().getPath() + folderName file = this.main.getExternalFilesDir(null)
}
if (file) {
this.LogPath = file.getPath() + folderName
} else {
this.LogPath = this.main.getFilesDir().getPath() + folderName
}
// 初始化日志目录对象,避免每次写入都 new
this.logDirFile = new this.File(this.LogPath)
if (!this.logDirFile.exists()) {
this.logDirFile.mkdirs()
}
// 启动自动清理(清理7天前的日志)
this._cleanOldLogs(7)
this.lastCleanDate = getTime('YYYY-MM-DD')
} catch (e) {
console.error('LogCat init error:', e)
this.LogPath = ''
} }
console.log('日志文件存放路径->', this.LogPath) console.log('日志文件存放路径->', this.LogPath)
} }
writeLog(tag, messages) { writeLog(tag, messages) {
// 将写入任务加入队列
this.taskQueue.enqueue(() => {
return new Promise((resolve) => {
// 延迟一小段时间执行,避免阻塞 UI 渲染
setTimeout(() => {
this._doWriteLog(tag, messages)
resolve()
}, 0)
})
})
}
// 真正的写入逻辑(私有方法)
_doWriteLog(tag, messages) {
// 如果路径初始化失败,直接放弃写入,避免报错
if (!this.LogPath) return
let msg = '' let msg = ''
try { try {
if (messages instanceof Error) { if (messages instanceof Error) {
...@@ -32,8 +77,14 @@ class LogCat { ...@@ -32,8 +77,14 @@ class LogCat {
} catch (e) { } catch (e) {
msg = String(messages) msg = String(messages)
} }
let date = getTime('YYYY-MM-DD') let date = getTime('YYYY-MM-DD')
// 检查跨天:如果当前日期与上次清理日期不同,触发一次清理
if (this.lastCleanDate && date !== this.lastCleanDate) {
this.lastCleanDate = date
this._cleanOldLogs(7)
}
let datetime = getTime() let datetime = getTime()
//文件名 //文件名
let fileName = this.LogPath + '/' + date + '.txt' let fileName = this.LogPath + '/' + date + '.txt'
...@@ -43,11 +94,18 @@ class LogCat { ...@@ -43,11 +94,18 @@ class LogCat {
// 使用对应的 console 方法输出 // 使用对应的 console 方法输出
const logFunc = console[tag] || console.log const logFunc = console[tag] || console.log
logFunc(content.replace(/\n/g, '')) logFunc(content.replace(/\n/g, ''))
let path = new this.File(this.LogPath) // 移除重复的目录检查,仅在必要时(如目录被意外删除)才尝试重建
if (!path.exists()) { // let path = new this.File(this.LogPath)
path.mkdirs() //创建父路径 // if (!path.exists()) {
// path.mkdirs()
// }
// 双重保险:虽然构造函数里创建了,但防止运行时目录被误删
if (this.logDirFile && !this.logDirFile.exists()) {
this.logDirFile.mkdirs()
} }
let fos = null let fos = null
let bw = null let bw = null
try { try {
...@@ -60,112 +118,83 @@ class LogCat { ...@@ -60,112 +118,83 @@ class LogCat {
} finally { } finally {
try { try {
if (bw != null) { if (bw != null) {
bw.close() //关闭缓冲流 bw.close() //关闭缓冲流(会自动关闭底层fos)
fos.close() //关闭文件输出流 } else if (fos != null) {
fos.close() //如果缓冲流创建失败,手动关闭文件流
} }
} catch (closeEx) { } catch (closeEx) {
console.log('closeEx->', closeEx) console.log('closeEx->', closeEx)
} }
} }
} }
// 自动清理旧日志
_cleanOldLogs(daysToKeep) {
// 放入队列异步执行,不影响启动速度
this.taskQueue.enqueue(() => {
return new Promise((resolve) => {
setTimeout(() => {
try {
const list = this.getLogFileList()
const now = new Date().getTime()
const oneDay = 24 * 60 * 60 * 1000
list.forEach(file => {
// 文件名格式:YYYY-MM-DD.txt
const match = file.name.match(/^(\d{4}-\d{2}-\d{2})\.txt$/)
if (match) {
const fileDate = new Date(match[1]).getTime()
// 如果文件日期早于 (当前时间 - 保留天数),则删除
if (now - fileDate > daysToKeep * oneDay) {
this.removeLogFile(file.path)
}
}
})
} catch (e) {
console.error('清理旧日志失败:', e)
} finally {
resolve()
}
}, 1000) // 延迟1秒执行,避开App启动高峰
})
})
}
// 删除日志 // 删除日志
removeLogFile(fileName) { removeLogFile(fileName) {
let file = new this.File(fileName) try {
let fos = new this.FileOutputStream(fileName, true) let file = new this.File(fileName)
fos.close() if (file.exists()) {
file.delete() file.delete()
console.log('删除------' + fileName) console.log('删除------' + fileName)
}
} catch (e) {
console.error('删除日志失败:', e)
}
} }
// 获取所有日志文件列表 // 获取所有日志文件列表
getLogFileList() { getLogFileList() {
let file = new this.File(this.LogPath) try {
let tempList = file.listFiles() if (!this.LogPath) return []
if (!tempList || tempList.length === 0) return [] let file = new this.File(this.LogPath)
const list = tempList.map(file => { if (!file.exists()) return []
return {
name: file.getName(), let tempList = file.listFiles()
path: file.getPath() if (!tempList || tempList.length === 0) return []
// 注意:Java数组在NativeJS中可能没有map方法,建议使用循环
const list = []
for (let i = 0; i < tempList.length; i++) {
const f = tempList[i]
list.push({
name: f.getName(),
path: f.getPath()
})
} }
}) return list
return list } catch (e) {
console.error('获取日志列表失败:', e)
return []
}
} }
} }
export default LogCat export default LogCat
// import { getTime } from './util'
// import { serializeIfObject } from '../utils'
// class LogCat {
// // main = plus.android.runtimeMainActivity()
// // File = plus.android.importClass('java.io.File')
// // Environment = plus.android.importClass('android.os.Environment')
// // BufferedWriter = plus.android.importClass('java.io.BufferedWriter')
// // FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
// // OutputStreamWriter = plus.android.importClass('java.io.OutputStreamWriter')
// // BufferedReader = plus.android.importClass('java.io.BufferedReader')
// // FileInputStream = plus.android.importClass('java.io.FileInputStream')
// // InputStreamReader = plus.android.importClass('java.io.InputStreamReader')
// LogPath = ''
// constructor(folderName = '_zyzs_log') {
// // if (this.Environment.MEDIA_MOUNTED || !this.Environment.isExternalStorageRemovable()) {
// // this.LogPath = this.main.getExternalFilesDir(null).getPath() + folderName
// // } else {
// // this.LogPath = this.main.getFilesDir().getPath() + folderName
// // }
// // console.log('日志文件存放路径->', this.LogPath)
// }
// writeLog(tag, messages) {
// return
// let msg = serializeIfObject(messages)
// let date = getTime('YYYY-MM-DD')
// let datetime = getTime()
// //文件名
// let fileName = this.LogPath + '/' + date + '.txt'
// //写入的内容
// let content = `${datetime} [${tag}] : ${msg}\n`
// console.log(content.replace(/\n/g, ''))
// let path = new this.File(this.LogPath)
// if (!path.exists()) {
// path.mkdirs() //创建父路径
// }
// let fos = null
// let bw = null
// try {
// fos = new this.FileOutputStream(fileName, true)
// bw = new this.BufferedWriter(new this.OutputStreamWriter(fos))
// //bw.write(log);
// bw.append(content)
// } catch (e) {
// console.log('e->', e)
// } finally {
// try {
// if (bw != null) {
// bw.close() //关闭缓冲流
// fos.close() //关闭文件输出流
// }
// } catch (closeEx) {
// console.log('closeEx->', closeEx)
// }
// }
// }
// // 删除日志
// removeLogFile(fileName) {
// let file = new this.File(fileName)
// let fos = new this.FileOutputStream(fileName, true)
// fos.close()
// file.delete()
// console.log('删除------' + fileName)
// }
// // 获取所有日志文件列表
// getLogFileList() {
// let file = new this.File(this.LogPath)
// let tempList = file.listFiles()
// if (!tempList || tempList.length === 0) return []
// const list = tempList.map(file => {
// return {
// name: file.getName(),
// path: file.getPath()
// }
// })
// return list
// }
// }
// export default LogCat
\ No newline at end of file \ No newline at end of file
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2024-11-22 08:18:23 * @Date: 2024-11-22 08:18:23
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-23 09:34:35 * @LastEditTime: 2026-01-13 09:30:46
* @FilePath: \simgle_app\utils\recordManager\DBManager.js * @FilePath: \simgle_app\utils\recordManager\DBManager.js
*/ */
import { SQLite } from '../../lib' import { SQLite } from '../../lib'
...@@ -87,6 +87,14 @@ class DBManager { ...@@ -87,6 +87,14 @@ class DBManager {
return Array.isArray(records) ? records[0] : records // sqlite 返回数组 return Array.isArray(records) ? records[0] : records // sqlite 返回数组
} }
/** /**
* 根据条件获取记录列表
* @param {Object} where - 查询条件
* @returns {Array} - 记录列表
*/
async getRecordsByWhere(where) {
return this.db.select(this.table_name, where)
}
/**
* 获取记录列表 * 获取记录列表
* *
* @returns {Array} - 从 storageApi 获取的记录列表 * @returns {Array} - 从 storageApi 获取的记录列表
......
...@@ -4,13 +4,13 @@ ...@@ -4,13 +4,13 @@
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:49:17 * @Date: 2025-01-02 18:49:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-01-12 11:30:31 * @LastEditTime: 2026-01-13 16:39:09
* @FilePath: \simgle_app\utils\recordManager\TempRecord.js * @FilePath: \simgle_app\utils\recordManager\TempRecord.js
*/ */
import utils from '../utils' import utils from '../utils'
import helpler from './helpler' import helpler from './helpler'
import { FileStatus } from '../common/constants' import { FileStatus } from '../common/constants'
import UploadService from './UploadService.js' import UploadService from './UploadService.js' // 修改引用路径,使用相对路径
// import { Command } from '../../ws/constants' // import { Command } from '../../ws/constants'
class TempRecord { class TempRecord {
...@@ -29,7 +29,7 @@ class TempRecord { ...@@ -29,7 +29,7 @@ class TempRecord {
*/ */
constructor(record, onTempRecordNumberChanged, attributesProvider) { constructor(record, onTempRecordNumberChanged, attributesProvider) {
this.newRecord = record this.newRecord = record
this.recordManager = uni.$dbTempRecord // this.recordManager = uni.$dbRecord // 直接使用正式表管理器
this.dbRecord = uni.$dbRecord this.dbRecord = uni.$dbRecord
this.onTempRecordNumberChanged = onTempRecordNumberChanged this.onTempRecordNumberChanged = onTempRecordNumberChanged
this.attributesProvider = attributesProvider this.attributesProvider = attributesProvider
...@@ -38,8 +38,9 @@ class TempRecord { ...@@ -38,8 +38,9 @@ class TempRecord {
* 获取全部临时记录 * 获取全部临时记录
* @returns {Array} 临时记录列表 * @returns {Array} 临时记录列表
*/ */
getRecords() { async getRecords() {
return this.recordManager.getRecords() // 从正式表中筛选出接待中的记录 (使用 SQL 过滤)
return this.dbRecord.getTempRecords()
} }
/** /**
* 根据 id 获取单条临时记录 * 根据 id 获取单条临时记录
...@@ -47,7 +48,7 @@ class TempRecord { ...@@ -47,7 +48,7 @@ class TempRecord {
* @returns {Object|null} 找到则返回记录,否则返回 null * @returns {Object|null} 找到则返回记录,否则返回 null
*/ */
getRecord(id) { getRecord(id) {
return this.recordManager.getRecordById(id) return this.dbRecord.getRecordById(id)
} }
/** /**
* 添加一条临时记录并触发数量变化通知 * 添加一条临时记录并触发数量变化通知
...@@ -56,7 +57,7 @@ class TempRecord { ...@@ -56,7 +57,7 @@ class TempRecord {
*/ */
async addRecord(record = this.record) { async addRecord(record = this.record) {
try { try {
await this.recordManager.addRecord(record) await this.dbRecord.addRecord(record)
uni.$logger.local.info('〖接待记录Record〗 == 新增临时记录 id: ' + record.id) uni.$logger.local.info('〖接待记录Record〗 == 新增临时记录 id: ' + record.id)
this.triggleRecordNumChanged() this.triggleRecordNumChanged()
} catch (e) { } catch (e) {
...@@ -70,7 +71,7 @@ class TempRecord { ...@@ -70,7 +71,7 @@ class TempRecord {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
updateRecord(item, where) { updateRecord(item, where) {
return this.recordManager.updateRecord(item, where) return this.dbRecord.updateRecord(item, where)
} }
/** /**
* 删除一条临时记录并触发数量变化通知 * 删除一条临时记录并触发数量变化通知
...@@ -78,7 +79,7 @@ class TempRecord { ...@@ -78,7 +79,7 @@ class TempRecord {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async removeRecord(id) { async removeRecord(id) {
await this.recordManager.removeRecord(id) await this.dbRecord.removeRecord(id)
uni.$logger.local.info('〖接待记录Record〗 == 删除临时记录 id: ' + id) uni.$logger.local.info('〖接待记录Record〗 == 删除临时记录 id: ' + id)
this.triggleRecordNumChanged() this.triggleRecordNumChanged()
} }
...@@ -125,27 +126,25 @@ class TempRecord { ...@@ -125,27 +126,25 @@ class TempRecord {
await this.saveTempFile(record) await this.saveTempFile(record)
const { urlList, tempFilePath, endReasonType,...__record } = record const { urlList, tempFilePath, endReasonType,...__record } = record
const recordLongList = await this.__analysisUrlList(urlList) const recordLongList = await this.__analysisUrlList(urlList)
// const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
// if (recordLongList.length > maxUploadNum) {
// const userInfo = uni.$storage.get('userInfo')
// const { customerName, phoneNumber, carModel, salesName } = record || {}
// const { name } = userInfo || {}
// uni.$logger.error({
// msg: `员工: ${name}, 客户: ${customerName}`,
// extra: {
// '手机号: ': phoneNumber,
// '姓名: ': customerName,
// '销售: ': salesName,
// '车型: ': carModel,
// '原因: ': '录音文件过长,数量' + recordLongList.length
// }
// })
// }
// __record.urlList = recordLongList.slice(0, maxUploadNum)
__record.urlList = recordLongList __record.urlList = recordLongList
// 更新为已完成状态 (receptionStatus = 1)
const updateData = {
...__record,
receptionStatus: 1,
tempFilePath: '' // 清除临时路径字段
}
uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!') uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
await this.dbRecord.addRecord(__record)
await this.clearLocalRecord(record) // 直接更新原记录,不再插入新记录
await this.dbRecord.updateRecord(updateData, { id: record.id })
// 删除本地临时文件 (不再删除数据库记录,因为已经转正)
await this.clearLocalRecord(record, false) // 传入 false 表示不删除数据库记录
this.triggleRecordNumChanged()
// 触发轮询开始事件,通知上传管理重新开始轮询 // 触发轮询开始事件,通知上传管理重新开始轮询
UploadService.startPolling() UploadService.startPolling()
} catch (error) { } catch (error) {
...@@ -170,17 +169,20 @@ class TempRecord { ...@@ -170,17 +169,20 @@ class TempRecord {
} }
// 2. 删除当前记录的临时文件和数据库记录 // 2. 删除当前记录的临时文件和数据库记录
// 注意:clearLocalRecord 内部会处理 tempFilePath 的删除和数据库记录的移除 // 注意:clearLocalRecord 内部会处理 tempFilePath 的删除和数据库记录的移除
await this.clearLocalRecord(record) await this.clearLocalRecord(record, true) // 传入 true 表示需要删除数据库记录
uni.$logger.local.warn('〖接待记录Record〗 == 记录彻底删除完成') uni.$logger.local.warn('〖接待记录Record〗 == 记录彻底删除完成')
} }
async clearLocalRecord(record = this.record) { async clearLocalRecord(record = this.record, removeDbRecord = true) {
const { id, tempFilePath } = record || {} const { id, tempFilePath } = record || {}
uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath) uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
await this.removeFile(tempFilePath) await this.removeFile(tempFilePath)
if (id) {
// 只有明确要求删除数据库记录时才执行 (save 时传 false)
if (id && removeDbRecord) {
await this.removeRecord(id) await this.removeRecord(id)
} }
this.record = null this.record = null
this.path = '' this.path = ''
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录') uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
...@@ -252,7 +254,8 @@ class TempRecord { ...@@ -252,7 +254,8 @@ class TempRecord {
...dynamicAttributes, ...dynamicAttributes,
startTime: this.getTimeNow(), startTime: this.getTimeNow(),
endTime: '', endTime: '',
urlList: [] urlList: [],
receptionStatus:0
} }
} }
/** /**
......
...@@ -145,39 +145,31 @@ class UploadService { ...@@ -145,39 +145,31 @@ class UploadService {
parseFileInfo(data) { parseFileInfo(data) {
try { try {
// data 结构: { detail: { data: [payload] } } /// 1. 尝试从 Webview 回调结构中提取 payload
// payload: { fileName, recordId, filePath, ...result }
// 注意: 在 _setupWebview 中我们构造了 data,但其中的 payload 可能是原始对象
// 为了复用代码,我们需要确保 input 能够被 serializeIfObject 处理
// 但这里我们主要关注 payload
const payload = data?.detail?.data?.[0] const payload = data?.detail?.data?.[0]
if (!payload) return null
// const {data,...obj} = payload // CASE 1: Webview 回调
const input = serializeIfObject(payload) if (payload) {
uni.$logger.local.info(`【上传服务】 == 开始文件信息解析-> ${input}`) const { data: d, ...o } = payload
const input = serializeIfObject(o)
// status 在 payload 中可能不存在(如果是成功上传回调),或者存在(如果是NoFile等) uni.$logger.local.warn(`【上传服务】 == 开始文件信息解析-> ${input}`)
// 原逻辑中 data 是直接传入的参数,可能是 { status: 'NoFile' ... } 或者 { detail: ... } return this._parseUploadedFile(data)
// 这里的 data 参数如果是来自 handlerMessage,那么它肯定是 { detail: { data: [...] } } 格式
// 但是如果是 save({ status: FileStatus.NoFile ... }) 调用的(例如 uploadRecord 中直接调用),则不是。
// 需要兼容两种调用方式
let status = payload?.status
if (!status && data.status) status = data.status
if ([FileStatus.NoFile, FileStatus.NotExist].includes(status)) {
// 如果是直接调用的 save(record),data 就是 record
return this._parseNoFileStatus(data.status ? data : payload)
} }
return this._parseUploadedFile(data)
// CASE 2: 直接调用 (data 是 record 对象)
// 检查是否包含特定状态 (NoFile / NotExist)
if (data && (data.status === FileStatus.NoFile || data.status === FileStatus.NotExist)) {
return this._parseNoFileStatus(data)
}
return null
} catch (error) { } catch (error) {
uni.$logger.local.error(`【上传服务】 == 解析文件信息异常: ${error.message}`) uni.$logger.local.error(`【上传服务】 == 解析文件信息异常: ${error.message}`)
return null return null
} }
} }
_parseNoFileStatus(data) { _parseNoFileStatus(data) {
const { recordId, fileName, filePath, status } = data const { recordId, fileName, filePath, status } = data
const clientPath = (filePath || '') + (fileName || '') const clientPath = (filePath || '') + (fileName || '')
if (!recordId) { if (!recordId) {
...@@ -308,7 +300,8 @@ class UploadService { ...@@ -308,7 +300,8 @@ class UploadService {
} }
async getRecordsSnapshotFlatten() { async getRecordsSnapshotFlatten() {
const _records = await uni.$dbRecord.getRecords() await uni.$dbReady // 双重保险
let _records = await uni.$dbRecord.getCompletedRecords()
return await this.flattenData(_records || []) return await this.flattenData(_records || [])
} }
...@@ -381,7 +374,7 @@ class UploadService { ...@@ -381,7 +374,7 @@ class UploadService {
async _saveOrUpdate(data) { async _saveOrUpdate(data) {
uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`) uni.$logger.local.info(`【上传服务】 == 开始保存或更新接待记录!!`)
try { try {
const { status, ...record } = data const { status,tempFilePath,receptionStatus, ...record } = data
const fileList = Array.isArray(record.urlList) ? record.urlList : [] const fileList = Array.isArray(record.urlList) ? record.urlList : []
const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status)) const isAllCompleted = status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))
if (isAllCompleted) { if (isAllCompleted) {
...@@ -457,6 +450,14 @@ class UploadService { ...@@ -457,6 +450,14 @@ class UploadService {
const aFullPath = file.file.split('/') const aFullPath = file.file.split('/')
const fileName = aFullPath.pop() const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
// [关键修复] 在处理文件前优先检查黑名单,避免无效检查和日志刷屏
const taskKey = this._getTaskKey(cur.id, fileName)
if (this._blackList.has(taskKey)) {
// uni.$logger.local.info(`【上传服务】 == 快照生成时过滤黑名单任务: ${taskKey}`)
continue
}
const file2Up = { ...file, recordId: cur.id, fileName, filePath } const file2Up = { ...file, recordId: cur.id, fileName, filePath }
const fileExists = await this.checkFileExists(file.file) const fileExists = await this.checkFileExists(file.file)
...@@ -566,6 +567,9 @@ class UploadService { ...@@ -566,6 +567,9 @@ class UploadService {
} }
async startPolling(isForce = false) { async startPolling(isForce = false) {
// 确保数据库已初始化
await uni.$dbReady
this._blackList.clear() this._blackList.clear()
if (this._pumpRunning || this.updateResolve) { if (this._pumpRunning || this.updateResolve) {
if (!isForce) { if (!isForce) {
...@@ -576,13 +580,13 @@ class UploadService { ...@@ -576,13 +580,13 @@ class UploadService {
this.canclePromises() this.canclePromises()
} }
} }
setTimeout(async () => { // 防止重复启动的定时器
if (this._pumpTimer) { if (this._pumpTimer) {
clearTimeout(this._pumpTimer) clearTimeout(this._pumpTimer)
this._pumpTimer = null this._pumpTimer = null
} }
await this.enQueue() this._pumpTimer = setTimeout(() => {
this._scheduleNext(0) this._schedulerPump()
}, 0) }, 0)
uni.$logger.local.info(`【上传服务】 =========开始轮询========`) uni.$logger.local.info(`【上传服务】 =========开始轮询========`)
} }
...@@ -678,10 +682,6 @@ class UploadService { ...@@ -678,10 +682,6 @@ class UploadService {
await this.enQueue() await this.enQueue()
} }
if (this.snapshot && this.snapshot.size > 0) {
this.snapshot.filter(item => !this._blackList.has(this._getTaskKey(item.recordId, item.fileName)))
}
if (!this.snapshot || this.snapshot.size === 0) { if (!this.snapshot || this.snapshot.size === 0) {
return '队列为空,等待新任务唤醒' return '队列为空,等待新任务唤醒'
} }
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @Author: limin * @Author: limin
* @Date: 2025-01-07 18:34:39 * @Date: 2025-01-07 18:34:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-25 10:26:38 * @LastEditTime: 2026-01-13 10:12:26
* @FilePath: \simgle_app\utils\recordManager\dbRecord.js * @FilePath: \simgle_app\utils\recordManager\dbRecord.js
*/ */
import DBManager from './DBManager.js' import DBManager from './DBManager.js'
...@@ -26,9 +26,110 @@ class DBRecord extends DBManager { ...@@ -26,9 +26,110 @@ class DBRecord extends DBManager {
'startTime TEXT', 'startTime TEXT',
'endTime TEXT', 'endTime TEXT',
'materialId INTEGER', 'materialId INTEGER',
'urlList TEXT' 'urlList TEXT',
'tempFilePath TEXT',
'receptionStatus INTEGER DEFAULT 1' // 0: recording, 1: completed
] ]
super(table_name, table_columns) super(table_name, table_columns)
this._initPromise = null
}
async init() {
if (this._initPromise) return this._initPromise
this._initPromise = (async () => {
try {
await super.init()
await this.ensureColumns()
await this.migrateTempRecords()
return true
} catch (e) {
uni.$logger.local.error('DBRecord: init failed ' + e.message)
throw e
}
})()
return this._initPromise
}
/**
* 确保表字段存在(用于版本升级)
*/
async ensureColumns() {
try {
// 优化:只查询一次表结构
const columnInfo = await this.db.selectSql(`PRAGMA table_info(${this.table_name})`)
const existingColumns = columnInfo.map(col => col.name)
const columnsToAdd = this.table_columns.reduce((acc, colDef) => {
const [name, ...def] = colDef.trim().split(/\s+/)
if (name && !existingColumns.includes(name)) {
acc.push({ name, definition: def.join(' ') })
}
return acc
}, [])
if (columnsToAdd.length > 0) {
await this.db.addColumns(this.table_name, columnsToAdd)
uni.$logger.local.info(`DBRecord: Added columns ${columnsToAdd.map(c => c.name).join(', ')}`)
}
} catch (e) {
uni.$logger.local.error('DBRecord: ensureColumns failed ' + e.message)
}
}
/**
* 将旧的临时表数据迁移到正式表
*/
async migrateTempRecords() {
const tempTableName = 'temp_records'
try {
const exists = await this.db.isTableExists(tempTableName)
if (!exists) return
uni.$logger.local.warn('DBRecord: Found temp_records table, starting migration...')
// 获取所有临时记录
const tempRecords = await this.db.selectSql(`SELECT * FROM ${tempTableName}`)
if (tempRecords && tempRecords.length > 0) {
for (const record of tempRecords) {
if (!record.id) continue
// 标记为进行中
record.receptionStatus = 0
// 检查是否已存在
const existing = await this.getRecordById(record.id)
if (existing) {
// 如果存在,说明正式表已有记录,temp_records 中的是残留数据,直接跳过
uni.$logger.local.warn(`DBRecord: Temp record ${record.id} already exists in records, skipping migration.`)
} else {
// 如果不存在,插入它
await this.addRecord(record)
uni.$logger.local.info(`DBRecord: Migrated temp record ${record.id}`)
}
}
}
// 迁移完成后删除旧表
await this.db.drop(tempTableName)
uni.$logger.local.warn('DBRecord: Migration completed, temp_records table dropped.')
} catch (e) {
uni.$logger.local.error('DBRecord: Migration failed ' + e.message)
}
}
/**
* 获取已完成的接待记录 (receptionStatus = 1)
*/
async getCompletedRecords() {
return this.getRecordsByWhere({ receptionStatus: 1 })
}
/**
* 获取进行中/临时的接待记录 (receptionStatus = 0)
*/
async getTempRecords() {
return this.getRecordsByWhere({ receptionStatus: 0 })
} }
} }
export default DBRecord export default DBRecord
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
*/ */
// import { singleton } from '../utils.js' // import { singleton } from '../utils.js'
import AudioManager from './AudioManager.js' import AudioManager from './AudioManager.js'
import DBTempRecord from './dbTempRecord.js' // import DBTempRecord from './dbTempRecord.js' // 已废弃
import DBRecord from './dbRecord.js' import DBRecord from './dbRecord.js'
import DBManager from './DBManager.js' import DBManager from './DBManager.js'
// import Record from './Record.js' // import Record from './Record.js'
...@@ -17,4 +17,4 @@ import RecordDto from './RecordDto.js' ...@@ -17,4 +17,4 @@ import RecordDto from './RecordDto.js'
import TempRecord from './TempRecord.js' import TempRecord from './TempRecord.js'
import helpler from './helpler.js' import helpler from './helpler.js'
// const SingleDBTempRecord = singleton(TempRecord) // const SingleDBTempRecord = singleton(TempRecord)
module.exports = { AudioManager, DBRecord, DBTempRecord, DBManager, RecordDto, TempRecord, helpler } module.exports = { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler }
...@@ -76,7 +76,7 @@ export class Ws { ...@@ -76,7 +76,7 @@ export class Ws {
} }
subscribe() { subscribe() {
this.ws.on(WsTyps.Connected, () => { this.ws.on(WsTyps.Connected, () => {
uni.$logger.local.info('========WebSocket 连接成功========') uni.$logger.local.warn('========WebSocket 连接成功========')
}) })
this.ws.on( this.ws.on(
WsTyps.MessageTypes.Private, WsTyps.MessageTypes.Private,
...@@ -89,12 +89,12 @@ export class Ws { ...@@ -89,12 +89,12 @@ export class Ws {
this.onMessage && this.onMessage(_data) this.onMessage && this.onMessage(_data)
}.bind(this) }.bind(this)
) )
this.ws.on(WsTyps.MessageTypes.System, function (data) { // this.ws.on(WsTyps.MessageTypes.System, function (data) {
uni.$logger.local.info(`========WebSocket 收到系统消息 ${serializeIfObject(data)}========`) // uni.$logger.local.info(`========WebSocket 收到系统消息 ${serializeIfObject(data)}========`)
}) // })
this.ws.on(WsTyps.Disconnected, () => { this.ws.on(WsTyps.Disconnected, () => {
CommandFactory.getInstance().clear() CommandFactory.getInstance().clear()
uni.$logger.local.info(`========WebSocket 断开连接 device_id->${this.deviceId}========`) uni.$logger.local.warn(`========WebSocket 断开连接 device_id->${this.deviceId}========`)
}) })
this.ws.on(WsTyps.Eroor, msg => { this.ws.on(WsTyps.Eroor, msg => {
CommandFactory.getInstance().clear() CommandFactory.getInstance().clear()
......
...@@ -15,7 +15,9 @@ export default class AddTempRecordWorker { ...@@ -15,7 +15,9 @@ export default class AddTempRecordWorker {
throw new Error(`数据格式错误,表中没有 ${key} 字段`) throw new Error(`数据格式错误,表中没有 ${key} 字段`)
} }
}) })
await uni.$dbTempRecord.addRecord(record) // 标记为接待中
record.receptionStatus = 0
await uni.$dbRecord.addRecord(record)
const msg = `写入待提交记录成功 temp record -> ${JSON.stringify(record)}` const msg = `写入待提交记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '写入待提交记录成功', data:record }) ws.send({ code: 200,msg: '写入待提交记录成功', data:record })
......
...@@ -18,14 +18,14 @@ export default class RemoveTempRecordWorker { ...@@ -18,14 +18,14 @@ export default class RemoveTempRecordWorker {
return return
} }
try { try {
const record = await uni.$dbTempRecord.getRecordById(recordId) const record = await uni.$dbRecord.getRecordById(recordId)
if (!record) { if (!record) {
const msg = `待提交记录不存在 id -> ${recordId}` const msg = `待提交记录不存在 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ error: msg }) ws.send({ error: msg })
return return
} }
await uni.$dbTempRecord.removeRecord(recordId) await uni.$dbRecord.removeRecord(recordId)
const msg = `待提交记录删除成功 id -> ${recordId}` const msg = `待提交记录删除成功 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg }) ws.send({ code: 200, msg })
......
...@@ -2,10 +2,10 @@ export default class TempRecordsWorker { ...@@ -2,10 +2,10 @@ export default class TempRecordsWorker {
constructor() {} constructor() {}
async work(deviceId, data, ws) { async work(deviceId, data, ws) {
try { try {
const records = await uni.$dbTempRecord.getRecords() const tempRecords = await uni.$dbRecord.getTempRecords()
const msg = `记录获取待提交记录成功 temp records -> ${JSON.stringify(records)}` const msg = `记录获取待提交记录成功 temp records -> ${JSON.stringify(tempRecords)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '获取待提交记录成功', data:records }) ws.send({ code: 200,msg: '获取待提交记录成功', data:tempRecords })
} catch (error) { } catch (error) {
const msg = `获取待提交记录失败 error -> ${error.message}` const msg = `获取待提交记录失败 error -> ${error.message}`
uni.$logger.local.error(msg) uni.$logger.local.error(msg)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!