Commit a18fcb44 by 前端

记录合并

1 parent 9a46b99e
...@@ -157,5 +157,12 @@ module.exports = { ...@@ -157,5 +157,12 @@ module.exports = {
projectName: 'boutique', projectName: 'boutique',
...data ...data
}) })
},
checkAppUpload(data) {
return http.post({
method: 'dj.api.smartcarlife.recepiton.customer.checkAppUpload',
projectName: 'boutique',
...data
})
} }
} }
<template> <template>
<view class="record-box"> <view class="record-box">
<view <view class="record-content" v-if="showRecord">
class="record-content"
v-if="showRecord"
>
<view class="data-box"> <view class="data-box">
<template v-for="(i, index) in dataList"> <template v-for="(i, index) in dataList">
<view <view :class="['data-item', i.type]" :key="index">
:class="['data-item', i.type]" <image :src="i.icon" class="data-item-bg" />
:key="index"
>
<image
:src="i.icon"
class="data-item-bg"
/>
<view class="title">{{ dateList[index].text }}</view> <view class="title">{{ dateList[index].text }}</view>
<view class="content"> <view class="content">
<view class="total"> <view class="total">
...@@ -37,75 +28,35 @@ ...@@ -37,75 +28,35 @@
</view> </view>
<view class="data-container"> <view class="data-container">
<view :class="['type-box']"> <view :class="['type-box']">
<view <view class="tab-item" v-for="(i, index) in typeList" :key="index" @click="changeType(index, 'firstIndex')">
class="tab-item" <view class="sprite-icon" :class="[firstIndex == index ? `icon-${firstClass[index]} active` : '', firstLeft[index]]"></view>
v-for="(i, index) in typeList" <view class="text" :class="[firstIndex == index ? `active` : '']">
:key="index"
@click="changeType(index, 'firstIndex')"
>
<view
class="sprite-icon"
:class="[firstIndex == index ? `icon-${firstClass[index]} active` : '',firstLeft[index]
]"
></view>
<view
class="text"
:class="[firstIndex == index ? `active` : '']"
>
{{ i.tabName }} {{ i.tabName }}
<template v-if="index == 1 && i.num && recordFailList.length > 0">({{ recordFailList.length }})</template> <template v-if="index == 1 && i.num && recordFailList.length > 0">({{ recordFailList.length }})</template>
<template v-if="index == 2 && i.num && preRecordFailList.length > 0">({{ preRecordFailList.length }})</template> <template v-if="index == 2 && i.num && preRecordFailList.length > 0">({{ preRecordFailList.length }})</template>
<div <div class="dot" v-if="index == 2 && i.num && preRecordFailList.length > 0"></div>
class="dot"
v-if="index == 2 && i.num && preRecordFailList.length > 0"
></div>
</view> </view>
</view> </view>
</view> </view>
<view class="tabs-bottom"></view> <view class="tabs-bottom"></view>
<view <view v-if="firstIndex == 0" class="data-tabs-box">
v-if="firstIndex == 0"
class="data-tabs-box"
>
<view class="data-tabs"> <view class="data-tabs">
<template v-for="(i, index) in dateList"> <template v-for="(i, index) in dateList">
<view <view :class="['tab flex', { active: dateIndex == index }]" :key="index" @click="changeIndex(index)">{{ i.text }}</view>
:class="['tab flex', { active: dateIndex == index }]"
:key="index"
@click="changeIndex(index)"
>{{ i.text }}</view>
</template> </template>
<view :class="['active-btn', `active-btn-${dateIndex}`]"></view> <view :class="['active-btn', `active-btn-${dateIndex}`]"></view>
</view> </view>
</view> </view>
<scroll-view <scroll-view :class="['record-list', { 'type-1': firstIndex == 1 }]" scroll-y @scrolltolower="pageonReachBottom" @scroll="scroll">
:class="['record-list', { 'type-1': firstIndex == 1 }]" <div class="record-tips" v-if="firstIndex == 2 && list.length && list[0] && list[0].length">以下非正常结束的接待记录,需要进行信息确认后才能提交到系统。</div>
scroll-y
@scrolltolower="pageonReachBottom"
@scroll="scroll"
>
<div
class="record-tips"
v-if="firstIndex == 2 && list.length && list[0] && list[0].length"
>以下非正常结束的接待记录,需要进行信息确认后才能提交到系统。</div>
<view class="list"> <view class="list">
<template v-if="flag"> <template v-if="flag">
<template v-if="list.length && list[0] && list[0].length"> <template v-if="list.length && list[0] && list[0].length">
<template v-for="i in list"> <template v-for="i in list">
<template v-for="item in i"> <template v-for="item in i">
<view <view class="item" :key="item.id" @click="jumpDetail(item)">
class="item" <view class="status flex disabled" v-if="item.receptionStatus === '' || item.receptionStatus === undefined">未知</view>
:key="item.id" <view :class="['status flex', { deal: item.receptionStatus == 1 }]" v-else>
@click="jumpDetail(item)"
>
<view
class="status flex disabled"
v-if="item.receptionStatus === '' || item.receptionStatus === undefined"
>未知</view>
<view
:class="['status flex', { deal: item.receptionStatus == 1 }]"
v-else
>
{{ {{
{ {
1: '成交', 1: '成交',
...@@ -118,10 +69,7 @@ ...@@ -118,10 +69,7 @@
</view> </view>
<view class="goods-name">{{ item.carModel ? item.carModel : '未选择车型' }}</view> <view class="goods-name">{{ item.carModel ? item.carModel : '未选择车型' }}</view>
<template v-for="(k, ind) in itemObject"> <template v-for="(k, ind) in itemObject">
<view <view class="info flex" :key="ind">
class="info flex"
:key="ind"
>
<view class="label">{{ k.label }}</view> <view class="label">{{ k.label }}</view>
<view class="value">{{ formatValue(item[k.key], k.key) || '-' }}</view> <view class="value">{{ formatValue(item[k.key], k.key) || '-' }}</view>
</view> </view>
...@@ -132,10 +80,7 @@ ...@@ -132,10 +80,7 @@
</template> </template>
<template v-else> <template v-else>
<view class="nothing flex"> <view class="nothing flex">
<image <image class="icon" src="../../../assets/images/home/nothing.webp" />
class="icon"
src="../../../assets/images/home/nothing.webp"
/>
暂无接待记录 暂无接待记录
</view> </view>
</template> </template>
...@@ -147,12 +92,7 @@ ...@@ -147,12 +92,7 @@
</scroll-view> </scroll-view>
</view> </view>
</view> </view>
<save-record <save-record v-else @cancel="handleCancel" @submit="handleSubmit" :customerInfoVal="customerInfo"></save-record>
v-else
@cancel="handleCancel"
@submit="handleSubmit"
:customerInfoVal="customerInfo"
></save-record>
</view> </view>
</template> </template>
<script type="text/ecmascript-6"> <script type="text/ecmascript-6">
...@@ -229,10 +169,11 @@ export default { ...@@ -229,10 +169,11 @@ export default {
this.getPreRecordNum() this.getPreRecordNum()
}, },
methods: { methods: {
formatValue (val, k) { formatValue(val,k) {
if (!val) return if(!val) return
if (k == 'phoneNumber') { if(k == 'phoneNumber') {
return val.slice(0, 3) + " " + val.slice(3, 7) + " " + val.slice(7) val = val.toString()
return val.slice(0, 3) + " " + val.slice(3, 7) + " " + val.slice(7)
} }
return val return val
}, },
...@@ -241,7 +182,8 @@ export default { ...@@ -241,7 +182,8 @@ export default {
}, },
async handleSubmit (val) { async handleSubmit (val) {
this.showRecord = true; this.showRecord = true;
uni.$recordManager.addRecord(val) // uni.$recordManager.addRecord(val)
await uni.$dbManager.addRecord(val)
uni.$logger.local.info(`添加记录${JSON.stringify(val)}`) uni.$logger.local.info(`添加记录${JSON.stringify(val)}`)
interruptRecord.removePreRecord(val.id) interruptRecord.removePreRecord(val.id)
this.getRecordNum() this.getRecordNum()
...@@ -282,8 +224,9 @@ export default { ...@@ -282,8 +224,9 @@ export default {
scroll (e) { scroll (e) {
this.sticky = e.detail.scrollTop >= 148 this.sticky = e.detail.scrollTop >= 148
}, },
getRecordNum () { async getRecordNum () {
let recordFailListAll = uni.$recordManager.getRecords(); // let recordFailListAll = uni.$recordManager.getRecords();
let recordFailListAll = await uni.$dbManager.getRecords();
if (typeof recordFailListAll == 'string') { if (typeof recordFailListAll == 'string') {
recordFailListAll = JSON.parse(recordFailListAll || '[]') recordFailListAll = JSON.parse(recordFailListAll || '[]')
} }
...@@ -567,7 +510,7 @@ export default { ...@@ -567,7 +510,7 @@ export default {
z-index: 4; z-index: 4;
} }
.type-1 { .type-1 {
height: calc(100% - #{toRpx(128)}); height: calc(100% - #{toRpx(128)});
margin-top: toMinusRpx(48); margin-top: toMinusRpx(48);
.list { .list {
padding-top: toRpx(48); padding-top: toRpx(48);
......
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-16 09:55:40
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-30 17:30:24
* @FilePath: \gl-tape\lib\index.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import sha1 from './sha1.js' import sha1 from './sha1.js'
import qs from './qs' import qs from './qs'
module.exports ={ sha1,qs }
\ No newline at end of file \ No newline at end of file
import SQLite from './sqlite.js'
module.exports = { sha1, qs, SQLite }
class SQLite {
constructor(name, version, description, size) {
this.name = name
this.version = version || '1.0'
this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null
}
init() {
return new Promise((resolve, reject) => {
plus.sqlite.openDatabase({
name: this.name, // 数据库名称
path: `_doc/${this.name}.db`, // 数据库地址
success: resolve, // 直接使用 resolve
fail: reject // 直接使用 reject
})
})
}
selectSql(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.info(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({
name: this.name,
sql,
success: result => {
// 处理查询结果,尝试还原数组或对象字符串
const processedRows = result.map(row =>
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
try {
// 尝试将字符串解析为对象或数组
return [key, JSON.parse(value)]
} catch {
// 如果解析失败,保留原始值
return [key, value]
}
})
)
)
resolve(processedRows)
},
fail: reject
})
})
}
executeSql(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.info(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({
name: this.name,
sql,
success: resolve,
fail: reject
})
})
}
async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
try {
const result = await this.selectSql(sql)
return result[0].isTable ? true : false
} catch (error) {
console.error('检查表是否存在出错: ', error)
throw error
}
}
// 创建新表示例
createTable(tableName, columns) {
const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(', ')})`
return this.executeSql(sql)
}
// 查询示例
select(tabName, where, order) {
let sql = `SELECT * FROM ${tabName}`
if (where) {
const dataKeys = Object.keys(where)
const conditions = dataKeys.map(key => `${key}=${JSON.stringify(where[key])}`).join(' AND ')
sql += ` WHERE ${conditions}`
}
if (order) {
const orderKey = Object.keys(order)[0] // 获取排序字段
const orderType = order[orderKey] // 获取排序类型
sql += ` ORDER BY ${orderKey} ${orderType}`
}
return this.selectSql(sql)
}
// 插入示例
insert(tabName, keyValues) {
const keys = Object.keys(keyValues)
const keyStr = keys.join(', ')
const valStr = keys
.map(key => {
const value = keyValues[key]
// 使用公共方法进行格式化
return `${this.formatValue(value)}`
})
.join(', ')
const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr})`
return this.executeSql(sql)
}
// 更新示例
update(tabName, setData, where) {
const dataKeys = Object.keys(setData)
const setStr = dataKeys
.map(key => {
const value = setData[key]
return `${key} = ${this.formatValue(value)}`
})
.join(', ')
const whereKeys = Object.keys(where)
const whereStr = whereKeys
.map(key => {
const value = where[key]
return `${key} = ${this.formatValue(value)}`
})
.join(' AND ')
const sql = `UPDATE ${tabName} SET ${setStr} WHERE ${whereStr}`
return this.executeSql(sql)
}
// 删除示例
delete(tabName, where) {
const whereKeys = Object.keys(where)
const whereStr = whereKeys
.map(key => {
const value = where[key]
return `${key} = ${this.formatValue(value)}`
})
.join(' AND ')
const sql = `DELETE FROM ${tabName} WHERE ${whereStr}`
return this.executeSql(sql)
}
isOpen() {
let isopen = plus.sqlite.isOpenDatabase({
name: this.name,
path: `_doc/${this.name}.db`
})
return isopen
}
close() {
if (this.db) {
this.db.close()
this.db = null
console.log('数据库连接已关闭')
}
}
drop(tabName) {
const sql = `DROP TABLE ${tabName}`
return this.executeSql(sql)
}
formatValue(value) {
return typeof value === 'object' && value !== null ? `'${JSON.stringify(value)}'` : `'${value}'`
}
}
export default SQLite
// 使用示例
/* const db = new SQLite('mydb', '1.0', 'Test DB', 1 * 1024 * 1024);
db.init().then(() => {
// 进行数据库操作
}).catch(error => {
console.error('数据库初始化失败: ', error);
});*/
...@@ -25,9 +25,13 @@ Vue.component('MessageBox', MessageBox) ...@@ -25,9 +25,13 @@ Vue.component('MessageBox', MessageBox)
Vue.component('wnCanvas', wnCanvas) Vue.component('wnCanvas', wnCanvas)
Vue.component('UpdateBox', UpdateBox) Vue.component('UpdateBox', UpdateBox)
import RecordManager from '@/utils/RecordManager' import RecordManager from '@/utils/RecordManager'
import DBManager from '@/utils/DBManager'
const dbManager = new DBManager()
dbManager.init()
const recordManager = RecordManager.getInstance() const recordManager = RecordManager.getInstance()
recordManager.compatible() recordManager.compatible()
uni.$recordManager = recordManager uni.$recordManager = recordManager
uni.$dbManager = dbManager
uni.$api = api uni.$api = api
uni.$lock = false uni.$lock = false
uni.$storage = new Storage() uni.$storage = new Storage()
......
...@@ -23,7 +23,8 @@ ...@@ -23,7 +23,8 @@
"Camera" : {}, "Camera" : {},
"Record" : {}, "Record" : {},
"VideoPlayer" : {}, "VideoPlayer" : {},
"AudioPlayer" : {} "AudioPlayer" : {},
"SQLite" : {}
}, },
/* 应用发布信息 */ /* 应用发布信息 */
"distribute" : { "distribute" : {
......
/* /*
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-22 15:07:59
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-30 20:17:43
* @FilePath: \gl-tape\mixin\click.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48 * @Date: 2024-04-08 11:28:48
* @LastEditors: 前端 qianduan01@didihu.com.cn * @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-21 09:54:21 * @LastEditTime: 2024-11-28 10:03:22
* @FilePath: \gl_tape\mixin\click.js * @FilePath: \gl_tape\mixin\click.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
*/ */
...@@ -73,7 +81,6 @@ export default { ...@@ -73,7 +81,6 @@ export default {
}, },
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setAudioInfo']), ...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setAudioInfo']),
handleCheck() { handleCheck() {
const { textList, tempFileURL, version } = uni.$storage.get('mock_data') const { textList, tempFileURL, version } = uni.$storage.get('mock_data')
const res = utils.compareVersions(plus?.runtime?.version, version) const res = utils.compareVersions(plus?.runtime?.version, version)
...@@ -141,9 +148,7 @@ export default { ...@@ -141,9 +148,7 @@ export default {
staffName: name staffName: name
}) })
}) })
let version = plus.runtime.version
let params = { let params = {
appVersion: version,
staffUuid: uuid, staffUuid: uuid,
staffName: name, staffName: name,
serviceMerchantId: merchantId, serviceMerchantId: merchantId,
...@@ -205,7 +210,6 @@ export default { ...@@ -205,7 +210,6 @@ export default {
) )
}) })
}, },
//开始录音 //开始录音
startAudio: utils.throttle(async function () { startAudio: utils.throttle(async function () {
if (this.audioInfo.audioStatus == AUDIO_STATUS.START) return if (this.audioInfo.audioStatus == AUDIO_STATUS.START) return
...@@ -308,7 +312,6 @@ export default { ...@@ -308,7 +312,6 @@ export default {
} }
}) })
}, },
/** /**
* 删除待提交记录 * 删除待提交记录
* @returns {void} * @returns {void}
...@@ -326,7 +329,7 @@ export default { ...@@ -326,7 +329,7 @@ export default {
uni.$logger.local.info(`添加记录${JSON.stringify(record)}`) uni.$logger.local.info(`添加记录${JSON.stringify(record)}`)
const unlock = await uni.$recordManager.lock() const unlock = await uni.$recordManager.lock()
console.log('record', record) console.log('record', record)
uni.$recordManager.addRecord(record) await uni.$dbManager.addRecord(record)
interruptRecord.removePreRecord(record.id) interruptRecord.removePreRecord(record.id)
unlock() unlock()
}, },
......
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js' import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js' import Queue from '@/utils/Queue.js'
import OperationQueue from '@/utils/OperationQueue.js'
import { Command } from '../ws/constants' import { Command } from '../ws/constants'
import { isInteger, serializeIfObject } from '@/utils/utils.js' import { isInteger, deepClone } from '@/utils/utils.js'
import { FileStatus } from '../utils/common'
import { serializeIfObject } from '../utils/utils'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import TimeoutManager from '@/utils/TimeoutManager.js'
export default { export default {
onLoad() {}, onLoad() {},
data() { data() {
return { return {
// WebView 实例
wv: null, wv: null,
// 上传文件快照
snapshot: null, snapshot: null,
// 轮询间隔(秒)
interval: 60 * 5, interval: 60 * 5,
timer: null, operationQueue: null, // 添加操作队列
_isUploading: false updateResolve: null
} }
}, },
mounted() { mounted() {
this.init() this.init()
this.subscribe() this.subscribe()
// uni.$dbManager.updateRecord({"recordUrlList": [
// {
// "status": 4,
// "file": "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save/5727_17321755265103.mp3"
// },
// {
// "status": 5,
// "file": "http://glsk-oss.oss-cn-shenzhen.aliyuncs.com/quality/5727_17321755265894.mp3",
// "filePathOnClient": "file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save/5727_17321755265894.mp3"
// }
// ],salesName:'王欣伟'},{id:'14B558C5-284E-4567-878B-6B1511C8B790'}).then(res => {
// console.log(111,res)
// uni.$dbManager.getRecordById('14B558C5-284E-4567-878B-6B1511C8B790').then(res => {
// console.log(222,res)
// })
// })
// uni.$dbManager.removeRecord(null).then(res => {
// console.log(111,res)
// uni.$dbManager.drop().then(res => {
// console.log(222,res)
// })
// })
}, },
methods: { methods: {
/**
* 初始化函数
* 这个函数在对象创建时被调用,它执行一系列的初始化任务
*
* @async
* @returns {Promise<void>} 当初始化完成时,Promise 将解析为 undefined
* @throws {Error} 如果初始化过程中出现错误,将抛出错误
*/
async init() { async init() {
await this.checkDB()
// 初始化 WebView
this.wv = await this.initWebview() this.wv = await this.initWebview()
// 初始化操作队列
this.operationQueue = new OperationQueue()
this.timeoutManager = new TimeoutManager()
// 开始轮询
this.startPolling() this.startPolling()
// uni.$logger.local.error({ extra : { key: 'data', value: {'abc':123,'sss':456,'GDF':888} }, msg:'test', tag : { key: 'tag', value: 'tagtest' } }) // uni.$logger.local.error({ extra : { key: 'data', value: {'abc':123,'sss':456,'GDF':888} }, msg:'test', tag : { key: 'tag', value: 'tagtest' } })
// uni.$logger.local.getFiles('20240905','2024-09/05') // uni.$logger.local.getFiles('20240905','2024-09/05')
// uni.$logger.local.removeOverDays(1) // uni.$logger.local.removeOverDays(1)
}, },
/**
* 订阅事件
* 这个函数用于订阅事件
* @returns {void} - 没有返回值
*/
subscribe() { subscribe() {
// 订阅停止轮询事件
uni.$on(Command.StopPolling, this.stopPolling) uni.$on(Command.StopPolling, this.stopPolling)
// 订阅开始轮询事件
uni.$on(Command.StartPolling, this.startPolling) uni.$on(Command.StartPolling, this.startPolling)
// 订阅设置轮询间隔事件
uni.$on(Command.SetPollingInterval, this.setInterval) uni.$on(Command.SetPollingInterval, this.setInterval)
}, },
/** /**
* 处理消息函数 * webview文件上传完成后执行的函数
* 此函数用于处理接收到的消息 * @param {*} data
* 它解构参数对象,获取代码、文件名、数据、记录 ID、文件路径和客户端文件路径等信息
* 根据代码值决定下一步操作:若为 0,则上传成功,调用 uploadSuccess 函数;否则,开始轮询,调用 polling 函数
*
* @param {Object} result - 包含消息详情的对象
* @throws {Error} 如果解构对象时缺少关键属性,将抛出错误
*/ */
async handlerMessage(result) { handlerMessage(data) {
const { code, fileName, data, recordId, filePath, filePathOnClient = filePath + fileName } = result.detail.data[0] this.save(data)
},
async checkDB() {
try { try {
if (code == 0) { const isSuccess = uni.$dbManager.init()
const filePathOnServer = data.oss.res.requestUrls[0].split('?')[0] if (!isSuccess) {
await this.uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) this.toLogin()
} else { return
this.reportError(recordId, fileName, data) }
} catch (error) {
uni.$logger.error(`初始化数据库失败:${error.message}`)
this.toLogin()
}
},
/**
* 保存文件信息并更新记录
* 这个函数用于保存文件信息并更新记录
* @param {Object} data - 包含文件信息的对象
* @returns {Promise<void>} - 一个 Promise,当文件信息保存并记录更新完成时解析,没有返回值
* @throws {Error} 如果在保存或更新过程中出现错误,将抛出错误
*/
async save(data) {
try {
const fileInfo = this.parseFileInfo(data)
if (!fileInfo || !fileInfo.recordId) {
uni.$logger.local.error(`未解析出文件信息或者没有记录ID`)
return
} }
} catch (e) { const record = await uni.$dbManager.getRecordById(fileInfo.recordId)
this.reportError(recordId, fileName, e) const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord)
} catch (error) {
this.reportError(`保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName)
} finally { } finally {
uni.$logger.local.info('本次任务完成,开启下一次上传任务!') uni.$logger.local.info('本次任务完成,开启下一次上传任务!')
this.polling() this.endTask()
}
},
/**
* 解析文件信息
* 这个函数用于解析文件信息
* @param {Object} data - 包含文件信息的对象
* @returns {Object} - 解析后的文件信息对象
*/
parseFileInfo(data) {
// 如果是无文件状态,直接返回基础信息
if ([FileStatus.NoFile, FileStatus.NotExist].includes(data.status)) {
let { recordId, filePath, fileName, status } = data
status = status == FileStatus.NotExist ? FileStatus.Completed : FileStatus.NoFile
return { recordId, clientPath: filePath + fileName, serverPath: null, fileName, status }
}
// 获取上传结果,如果失败直接返回 null
const { recordId, fileName, filePath, code, data: fileData } = data.detail.data[0]
if (code !== 0) {
this.reportError('解析上传文件信息异常', data, recordId, filePath + fileName)
return null
}
// 返回成功上传的文件信息
return { recordId, fileName, clientPath: filePath + fileName, serverPath: fileData.oss.res.requestUrls[0].split('?')[0], status: FileStatus.Uploaded }
},
/**
* 将文件路径更改为服务器路径
* 这个函数用于将接待记录中的文件路径更新为服务器路径
* @param {Object} record - 接待记录对象
* @param {Object} fileInfo - 文件信息对象
* @returns {Object} - 更新后的接待记录对象
*/
_changeFilePathToServer(record, fileInfo) {
try {
// record = Array.isArray(record) ? record[0] : record // sqlite 返回数组
// 深度克隆记录对象,以避免修改原始数据
const _record = deepClone(record)
uni.$logger.local.info(`开始将接待记录的文件路径改成服务器路径!! record.recordUrlList-> ${JSON.stringify(_record.recordUrlList)}`)
// 如果是无文件状态,直接返回基础信息
if (fileInfo.status === FileStatus.NoFile) {
_record.status = FileStatus.NoFile
// 如果接待结束时间不存在,则设置为接待开始时间
_record.receptionEndTime = _record.receptionEndTime || record.receptionStartTime
uni.$logger.local.info(`当前记录没有接待语音文件,已将状态设置为无文件状态: ${JSON.stringify(_record)}`)
return _record
}
// console.log(_record)
// 正常文件上传和文件丢失的记录执行此逻辑
_record.recordUrlList.forEach(item => {
if (item.file === fileInfo.clientPath || item.file.endsWith(fileInfo.fileName)) {
let info2Update = {
status: fileInfo.status
}
if (info2Update.status === FileStatus.Uploaded) {
// 正常文件上传的数据才更新服务器文件和本地文件路径 后面删除本地文件的时候 现过滤出正常上传的文件然后再获取到对应的文件删除
Object.assign(info2Update, {
file: fileInfo.serverPath,
filePathOnClient: fileInfo.clientPath
})
}
Object.assign(item, info2Update)
uni.$logger.local.info(`修改文件路径完成!!`)
}
})
uni.$logger.local.info(`替换完成!! record.recordUrlList-> ${JSON.stringify(_record.recordUrlList)}`)
return _record
} catch (error) {
uni.$logger.error(`修改文件路径失败!! error-> ${error.message}`)
throw new Error('修改文件路径失败!!')
} }
}, },
/** /**
* 上报文件上传失败日志 * 报告错误
* 这个函数用于报告上传文件失败的错误
* @param {string} recordId - 记录ID
* @param {string} filePath - 文件路径
* @param {Object} res - 响应对象
* @param {string} message - 错误消息
* @returns {void} - 没有返回值
*/ */
async reportError(recordId, filePath, res, message = '上传文件失败!!') { async reportError(message, res, recordId, filePath) {
try { try {
const record = uni.$recordManager.getRecordById(recordId) || {} const record = await uni.$dbManager.getRecordById(recordId)
const userInfo = uni.$storage.get('userInfo') const userInfo = uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = record || {} const { customerName, phoneNumber, carModel, salesName } = record || {}
const { name } = userInfo || {} const { name } = userInfo || {}
...@@ -78,6 +205,7 @@ export default { ...@@ -78,6 +205,7 @@ export default {
msg: `${now}-${message},员工: ${name}, 客户: ${customerName}`, msg: `${now}-${message},员工: ${name}, 客户: ${customerName}`,
extra: { extra: {
'手机号: ': phoneNumber, '手机号: ': phoneNumber,
'员工: ': name,
'姓名: ': customerName, '姓名: ': customerName,
'销售: ': salesName, '销售: ': salesName,
'车型: ': carModel, '车型: ': carModel,
...@@ -97,22 +225,37 @@ export default { ...@@ -97,22 +225,37 @@ export default {
* @async * @async
* @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。 * @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。
*/ */
initWebview() { async initWebview() {
return new Promise((resolve, reject) => { const MAX_RETRIES = 500 // 最多尝试500次,每次间隔100ms,总共50秒
var currentWebview = this.$parent.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效 const INTERVAL = 100
let i = setInterval(() => { try {
var wv = currentWebview.children()[0] const currentWebview = this.$parent.$scope.$getAppWebview()
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
const wv = currentWebview.children()[0]
if (wv) { if (wv) {
clearInterval(i)
wv.setStyle({ top: '100%', height: 300 }) wv.setStyle({ top: '100%', height: 300 })
resolve(wv) return wv
} }
}, 100) await new Promise(resolve => setTimeout(resolve, INTERVAL))
// setTimeout(function () { }
// var wv = currentWebview.children()[0] throw new Error('WebView initialization timeout')
// wv.setStyle({ top: '100%', height: 300 }) } catch (error) {
// resolve(wv) this.reportError(`初始化Webview失败 error:${error.message}`, error.message)
// }, 1000) //如果是页面初始化调用时,需要延时一下 // this.toLogin()
throw error
}
},
toLogin() {
uni.hideLoading()
uni.showModal({
title: '错误',
content: '初始化失败,请重新登录系统',
showCancel: false,
success(res) {
uni.reLaunch({
url: '/pages/common/login'
})
}
}) })
}, },
/** /**
...@@ -127,12 +270,13 @@ export default { ...@@ -127,12 +270,13 @@ export default {
* @throws {Error} 如果获取快照失败或扁平化数据失败,将抛出错误 * @throws {Error} 如果获取快照失败或扁平化数据失败,将抛出错误
*/ */
async enQueue() { async enQueue() {
// uni.$logger.remote.error({ extra : { key: 'data', value: {test:'test'} }, msg:'test', tag : { key: 'test', value: 'test' } }) try {
// uni.$logger.local.info('开始创建上传文件快照.') const _snapshot = await this.getRecordsSnapshotFlatten()
const _snapshot = await this.getRecordsSnapshotFlatten() this.snapshot = new Queue(_snapshot)
this.snapshot = new Queue(_snapshot) uni.$logger.local.info('创建快照成功! 文件个数:' + this.snapshot.size)
uni.$logger.local.info('创建快照成功! 文件个数:' + this.snapshot.size) } catch (error) {
// console.log('创建任务快照.下一轮快照文件个数:', this.snapshot.size) uni.$logger.error
}
}, },
/** /**
* 获取记录快照并展平数据 * 获取记录快照并展平数据
...@@ -144,212 +288,210 @@ export default { ...@@ -144,212 +288,210 @@ export default {
* @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误 * @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误
*/ */
async getRecordsSnapshotFlatten() { async getRecordsSnapshotFlatten() {
const _records = await this.getRecordsSnapshot() const _records = await uni.$dbManager.getRecords()
const _snapshot = this.flattenData(_records || []) const _snapshot = this.flattenData(_records || [])
return _snapshot return _snapshot
}, },
/** /**
* 将指定记录上传到服务器 * 上传记录
* 此函数使用 WebView 的 evalJS 方法,将 OSS 令牌信息和记录详情传递给 UniApp 应用,以便进行文件上传 * 这个函数用于上传文件
* * @param {Object} record - 要上传的文件记录
* @async * @returns {Promise<void>} - 一个 Promise,当文件上传完成时解析,没有返回值
* @param {Object} record - 要上传的记录对象,包含 fileName 和 filePath 属性 * @throws {Error} 如果文件上传失败,将抛出错误
* @returns {void} - 此函数不返回任何值
* @throws {Error} - 如果获取 OSS 令牌的过程中出现错误,将抛出错误
*/ */
async uploadRecord(record) { async uploadRecord(record) {
if (record.filePath) { // 如果文件状态是没有文件或者不存在,则直接保存记录
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken() uni.$logger.local.info(`开始上传文件!! record: ${JSON.stringify(record)}`)
console.log('获取Token成功!!', `lsaccessKeySecret: ${lsaccessKeySecret}, lsaccessKeyId: ${lsaccessKeyId}`) if (record.status === FileStatus.NoFile || record.status === FileStatus.NotExist) {
this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`) uni.$logger.local.info(`记录中有未上传文件,或文件不存在, 直接保存记录!!`)
this.save(record)
} else { } else {
this._saveOrUpdateFail(record.recordId) try {
} const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
}, uni.$logger.local.info(`获取Token成功!!', lsaccessKeySecret: ${lsaccessKeySecret}`)
/** // 通过WebView的evalJS方法,将密钥和ID等信息传递给WebView中的JavaScript代码 执行文件上传
* 文件上传成功后的处理逻辑 this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
* 这个函数在文件上传成功后执行,它接受四个参数:recordId、filePathOnServer、filePathOnClient 和 fileName } catch (error) {
* 函数首先获取记录锁,然后尝试获取对应的记录。如果记录存在,它将客户端路径的文件记录更新为服务器路径,并移除 client 文件。 this.reportError(`上传文件时发生异常(uploadRecord): ${error.message}`, error.message)
* 接着,它调用一个名为 _saveOrUpdate 的私有方法,这个方法可能会上传记录。 throw error
* 无论是尝试获取记录失败,还是在处理过程中出现任何其他错误,都会被捕获并作为 error 参数传递给 Promise.reject 方法,表明发生错误。
* 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。
*
* @async
* @param {string} recordId - 要更新的记录的 ID
* @param {string} filePathOnServer - 文件在服务器上的新路径
* @param {string} filePathOnClient - 文件在客户端的旧路径
* @param {string} fileName - 文件的原始名称
* @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误
*/
async uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) {
const unlock = await uni.$recordManager.lock()
try {
uni.$logger.local.info(`文件上传完成回调(uploadSuccess)!!', filePathOnServer-> ${filePathOnServer}, filePathOnClient-> ${filePathOnClient} , fileName-> ${fileName}`)
const record = uni.$recordManager.getRecordById(recordId)
if (!record) return uni.$logger.local.info(`未找到接待记录!!`)
this._changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName)
await this._saveOrUpdate(record)
} catch (err) {
throw new Error(err)
} finally {
unlock()
}
},
/**
* 将记录中的文件路径更改为服务器路径
* 此函数遍历记录中的每个文件信息对象
* 将文件信息对象中的 file 属性值与 filePathOnClient 或 fileName 进行比较
* 如果匹配,则将 file 属性更新为 filePathOnServer,并删除 status 属性
*
* @param {Object} record - 包含文件信息列表的记录对象
* @param {string} filePathOnClient - 需要替换的客户端文件路径
* @param {string} filePathOnServer - 需要更新的服务器文件路径
* @param {string} fileName - 需要替换的文件名
* @throws {Error} 如果 record 参数无效或 recordFileList 属性不存在,将抛出错误
*/
_changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) {
uni.$logger.local.info(`开始将接待记录的文件路径改成服务器路径!! record.recordUrlList-> ${JSON.stringify(record.recordUrlList)}`)
record.recordUrlList?.forEach(fileInfo => {
if (fileInfo.file === filePathOnClient || fileInfo.file.endsWith(fileName)) {
fileInfo.file = filePathOnServer
fileInfo.filePathOnClient = filePathOnClient
delete fileInfo.status
uni.$logger.local.info(`修改文件路径完成并删除文件status属性!! fileInfo.file-> ${fileInfo.file} fileInfo.status-> ${fileInfo.status}`)
} }
}) }
uni.$logger.local.info(`替换完成!! record.recordUrlList-> ${JSON.stringify(record.recordUrlList)}`)
}, },
/** /**
* 从客户端移除文件 * 从客户端删除文件
* 此函数使用 uni.removeSavedFile 方法删除指定路径的文件。该方法是一个异步操作,完成时会调用传入的 complete 回调函数。 * 这个函数用于从客户端的本地存储中删除指定的文件
* * @param {string} filePathOnClient - 要删除的文件在客户端的路径
* @param {string} filePathOnClient - 要删除的文件在客户端的文件路径 * @returns {Promise<boolean>} - 一个 Promise,当文件删除成功时解析为 true,否则抛出错误
* @param {Object} complete - (可选) uni.removeSavedFile 完成时调用的回调函数。函数参数是一个包含 statusCode 和 errMsg 的对象。
* @throws {Error} 如果 filePathOnClient 参数无效或文件删除过程中发生错误,将抛出错误
*/ */
_removeFileOnClient(filePathOnClient) { _removeFileOnClient(filePathOnClient) {
uni.$logger.local.info(`开始删除客户端的文件!! 路径-> ${filePathOnClient}`) uni.$logger.local.info(`开始删除客户端的文件!! 路径-> ${filePathOnClient}`)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!filePathOnClient) {
uni.$logger.local.info(`要删除的文件为空`)
resolve(true)
return
}
uni.removeSavedFile({ uni.removeSavedFile({
filePath: filePathOnClient, filePath: filePathOnClient,
complete: function (res) { complete: function (res) {
uni.$logger.local.info(`${filePathOnClient}->删除成功!!`) uni.$logger.local.info(`${filePathOnClient}->code:${res.code} msg:${res.errMsg}`)
resolve(res) resolve(res)
} }
}) })
}) })
}, },
/** /**
* 保存或更新记录 * 异步保存或更新接待记录
* 这个函数检查记录中的文件列表,以确定是保存还是更新记录 * 这个函数用于保存或更新接待记录
* 如果所有文件记录条目状态都为未定义,函数将创建一个新的记录对象,调用保存 API,并在成功时移除记录 * @param {Object} data - 要保存或更新的接待记录数据
* 如果文件记录条目状态不全为未定义,函数将更新记录 * @throws {Error} 如果保存或更新接待记录失败,将抛出错误
*
* @async
* @param {Object} record - 要保存或更新的记录对象
* @throws {Error} 如果在保存或更新记录时发生错误,将抛出错误
*/ */
async _saveOrUpdate(record) { async _saveOrUpdate(data) {
uni.$logger.local.info(`开始保存或更新接待记录!! record-> ${JSON.stringify(record)}`) uni.$logger.local.info(`开始保存或更新接待记录!! record-> ${JSON.stringify(data)}`)
if (record.recordUrlList?.every(i => i.status == undefined)) { try {
const pathArr = record.recordUrlList.map(i => i.file) const { status, ...record } = data
const originalFileArr = record.recordUrlList.map(i => i.filePathOnClient) const fileList = record.recordUrlList || []
const params = { ...record, recordUrlList: pathArr } // 判断接待记录的状态,如果是没有文件或者所有文件都已经上传或完成
uni.$logger.local.info(`记录中的文件已全部上传,开始向服务器保存接待记录!!`) if (status === FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i.status))) {
if (!params.receptionEndTime) { // 过滤出状态为已上传的文件,提取其文件路径 并更新记录的 recordUrlList
const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList: pathArr, receptionStartTime: params.receptionStartTime.replace(/\//g, '-') }) const updatedFile = fileList.filter(file => file.status == FileStatus.Uploaded)
params.receptionEndTime = endTime.replace(/\-/g, '/') const pathArr = updatedFile.map(i => i.file)
} // 过滤出存在本地文件路径的文件,提取其本地文件路径 以便记录保存完成后 删除
console.log(params, 'params') const originalFileArr = updatedFile.map(i => i.filePathOnClient) //正常上传的文件才删除本地文件
const res = await uni.$api.commonApi.saveRecCustomer(params) uni.$logger.local.info(`本条接待所有文件已经上传和处理完毕!! 已上传的文件: ${JSON.stringify(pathArr)} 本地文件: ${JSON.stringify(originalFileArr)}`)
uni.$logger.local.info(`服务器返回结果: ${res}`) const params = Object.assign(record, { recordUrlList: pathArr })
if (res) { // 如果接待结束时间不存在,则向服务器请求接待结束时间
uni.$logger.local.info(`保存接待记录成功,开始删除本地接待记录!!`) if (!params.receptionEndTime) {
uni.$recordManager.removeRecord(record.id) params.receptionEndTime = await this._requestReceptionEndTime(pathArr, params.receptionStartTime)
while (originalFileArr.length > 0) { }
const file = originalFileArr.shift() uni.$logger.local.info(`开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`)
await this._removeFileOnClient(file) //向服务器发送请求,保存接待记录
const res = await uni.$api.commonApi.saveRecCustomer(params)
uni.$logger.local.info(`服务器返回结果: ${JSON.stringify(res)}`)
// 如果服务器返回结果成功
if (res) {
// 移除本地文件
await this._removeRecordFiles(originalFileArr)
// 从记录管理器中移除记录
await this._removeRecordById(record.id)
} }
// await this._removeFileOnClient(filePathOnClient) } else {
// 如果记录中还有未处理文件,记录日志并更新记录
uni.$logger.local.info(`记录中有未上传文件,开始更新记录!!`)
// 更新接待记录
await uni.$dbManager.updateRecord(record)
} }
} else { } catch (error) {
uni.$logger.local.info(`记录中有未上传文件,开始更新记录!!`) // 如果保存或更新接待记录失败,记录错误信息并抛出错误
uni.$recordManager.updateRecord(record) this.reportError(`上传接待记录异常,error:${error.message}`, error.message, data.id, data.filePath + data.fileName)
// await this._removeFileOnClient(filePathOnClient)
} }
}, },
async _saveOrUpdateFail(recordId) { /**
const unlock = await uni.$recordManager.lock() * 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间
* @param {Array} recordUrlList - 包含文件URL的数组
* @param {string} receptionStartTime - 接待开始时间
* @returns {Promise<string>} - 一个 Promise,成功时解析为接待结束时间
*/
async _requestReceptionEndTime(recordUrlList, receptionStartTime) {
if (!recordUrlList || recordUrlList.length === 0) return receptionStartTime
try { try {
const record = uni.$recordManager.getRecordById(recordId) // 记录日志,显示正在向服务器请求结束接待时间,包括文件URL列表和接待开始时间
const params = { ...record, recordUrlList: [] } uni.$logger.local.info(`向服务器获取结束接待时间: recordUrlList ->${serializeIfObject(recordUrlList)} receptionStartTime: -> ${receptionStartTime}`)
if (!params.receptionEndTime) { // 调用 uni.$api.commonApi.searchRecordingEndTime 方法,向服务器发送请求,获取接待结束时间
params.receptionEndTime = params.receptionStartTime const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTime.replace(/\//g, '-') })
} // 记录日志,显示服务器返回的接待结束时间
const res = await uni.$api.commonApi.saveRecCustomer(params) uni.$logger.local.info(`服务器返回结束接待时间: endTime ->${endTime}`)
if (res) { // 返回接待结束时间,将日期格式中的连字符替换为斜杠,以保持一致性
uni.$recordManager.removeRecord(record.id) return endTime.replace(/\-/g, '/')
} } catch (error) {
} catch (e) { // 如果请求失败,记录错误信息并抛出错误
this.reportError(recordId, '无文件', e) this.reportError(`向服务器获取结束接待时间异常: error ->${error.message}`, error.message)
} finally {
unlock()
this.polling()
} }
}, },
/** /**
* 获取记录快照的异步函数 * 删除指定id的接待记录
* 此函数获取当前记录列表的快照,并返回这些记录 * @param {string} recordId - 要删除的接待记录的id
* * @throws {Error} 如果删除接待记录失败,将抛出错误
* @async */
* @returns {Promise<Array>} 解析为包含记录列表的 Promise async _removeRecordById(recordId) {
try {
await uni.$dbManager.removeRecord(recordId)
uni.$logger.local.info(`删除接待记录成功: recordId ->${recordId}`)
} catch (error) {
this.reportError(`删除接待记录异常: error ->${error.message}`, { message: error.message, recordId })
}
},
/**
* 异步删除接待记录中的文件
* @param {Array} fileArr - 要删除的文件数组
* @throws {Error} 如果删除文件失败,将抛出错误
*/ */
async getRecordsSnapshot() { async _removeRecordFiles(fileArr) {
const unlock = await uni.$recordManager.lock() try {
const records = uni.$recordManager.getRecords() while (fileArr.length > 0) {
unlock() const file = fileArr.shift()
return records await this._removeFileOnClient(file)
}
uni.$logger.local.info(`删除接待文件完成!`)
} catch (error) {
this.reportError(`删除接待文件异常: error ->${error.message}`, { message: error.message, fileArr })
}
}, },
/** /**
* 展开数据 * 扁平化数据
* 将嵌套的记录列表转换为平面的文件对象列表,其中每个文件对象都包含一个 recordId 属性 * 这个函数用于处理一个记录数组,检查每个记录的文件列表,并将文件信息扁平化
* 如果文件不存在或状态为已上传或已完成,则跳过该文件
* 如果文件存在,则将其状态设置为待上传,并将其添加到结果数组中
* 如果在处理文件过程中发生错误,则记录错误信息并继续处理下一个文件
* *
* @param {Array} records - 要展开的记录列表 * @param {Array} records - 要处理的记录数组
* @returns {Array} - 展开后包含文件对象的列表,每个文件对象都包含一个 recordId 属性 * @returns {Promise<Array>} - 返回一个 Promise,当所有记录处理完成时解析为包含所有处理后记录的数组
*/ */
async flattenData(records) { async flattenData(records) {
const result = [] const result = []
for (const cur of records) { for (const cur of records) {
// 确保 recordUrlList 是一个数组
cur.recordUrlList = cur.recordUrlList || [] cur.recordUrlList = cur.recordUrlList || []
// 如果记录没有文件,添加一个空记录
if (cur.recordUrlList.length == 0) { if (cur.recordUrlList.length == 0) {
result.push({ recordId: cur.id }) // 如果记录中没有文件,则将其状态设置为 NoFile,并添加到结果数组中
this.reportError(cur.id, '', cur, '记录中不存在接待语音文件') //记录中不存在接待语音文件 result.push(Object.assign({ status: FileStatus.NoFile, recordId: cur.id }, cur))
this.reportError('记录中不存在接待语音文件', { record: cur }, cur.id) //记录中不存在接待语音文件
continue continue
} }
// 处理每个记录的文件列表 // 处理每个记录的文件列表
for (const file of cur.recordUrlList) { for (const file of cur.recordUrlList) {
if (!file.status) continue try {
const aFullPath = file.file.split('/') // 如果文件状态为已上传或已完成,则跳过该文件
const fileName = aFullPath.pop() if (!file.status || file.status == FileStatus.Uploaded || file.status == FileStatus.Completed) continue
const filePath = aFullPath.join('/') + '/' const aFullPath = file.file.split('/')
// 检查文件是否存在 const fileName = aFullPath.pop()
const fileExists = await this.checkFileExists(file.file) const filePath = aFullPath.join('/') + '/'
if (!fileExists) { const file2Up = { ...file, recordId: cur.id, fileName, filePath }
this.reportError(cur.id, fileName, cur, '记录中有语音文件地址,但是文件不存在') //记录中语音文件不存在 // 检查文件是否存在
const fileExists = await this.checkFileExists(file.file)
if (!fileExists) {
// 如果文件不存在,则将其状态设置为 NotExist,并记录错误信息
this.reportError('记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file) //记录中语音文件不存在
file2Up.status = FileStatus.NotExist
}
result.push(file2Up)
} catch (error) {
// 如果在处理文件过程中发生错误,则记录错误信息并继续处理下一个文件
this.reportError(`解析处理文件异常 error: ${error.message}`, { record: cur, file })
continue continue
} }
result.push({ ...file, recordId: cur.id, fileName, filePath })
} }
} }
return result return result
}, },
/** /**
* 检查文件是否存在 * 检查文件是否存在
* 此函数检查指定路径的文件是否存在 * 这个函数用于检查指定文件路径是否存在
* * 如果文件路径为空,则返回 false
* @param {string} filePath - 要检查的文件路径 * 如果文件路径不为空,则使用 uni.getFileInfo 方法获取文件信息
* @returns {Promise<boolean>} - 返回一个 Promise,当文件存在时解析为 true,否则解析为 false * 如果获取成功,则返回 true
* 如果获取失败,则返回 false
*/ */
async checkFileExists(filePath) { async checkFileExists(filePath) {
return new Promise(resolve => { return new Promise(resolve => {
...@@ -370,58 +512,106 @@ export default { ...@@ -370,58 +512,106 @@ export default {
}, },
/** /**
* 轮询函数 * 轮询函数
* 这个函数用于检查一个队列的大小,并在需要时执行文件上传操作 * 这个函数会检查网络连接状态,如果网络在线,则执行上传操作
* 如果队列大小为 0,则调用 enQueue() 函数来获取新的文件进行上传,并延迟一段时间后再次轮询 * 如果网络不在线,则记录错误信息并在指定的时间间隔后重试
* 如果队列不为 0,则从队列中取出一个记录并调用 uploadRecord(record) 函数进行上传
* 如果在获取网络状态或上传过程中出现错误,它将捕获错误并在指定的时间间隔后重新开始轮询
*
* @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
*/ */
polling() { async polling() {
// uni.$logger.local.info(`当前待上传文件快照数量-> ${this.snapshot.size}`) try {
// console.log(this.snapshot.size, '当前待上传文件快照数量') // 如果快照对象不存在,则立即返回 轮询会停止
if (this.snapshot === null) return if (this.snapshot === null) return console.log('stooooooooooooop')
// prettier-ignore // 检查网络是否在线
uni.$isNetWork().then(this.upload).catch(e => { const isOnline = await uni.$isNetWork()
this.reportError('', '异常', e) // 如果网络在线,则执行上传操作
this.pollingLater(this.interval) if (isOnline) {
}) await this.upload()
} else {
this.onerror('网络异常,稍后再试')
}
} catch (error) {
this.onerror(`异常,error->${error.message}`)
}
},
async onerror(message) {
this.reportError(message)
await this.wait() //添加等待 解决异常情况下,无间隔死循环
this.polling()
},
async wait(time = 15 * 60 * 1000) {
const msg = await this.timeoutManager.addTimeout(this.interval, time)
if (msg === 'abort') this.snapshot = null
}, },
/** /**
* 上传文件或执行队列操作 * 执行上传操作
* 检查队列大小,以确定是上传单个文件还是通过 enQueue() 函数获取新的文件进行上传 * 这个函数用于执行上传操作
* * 首先,获取当前记录的快照
* @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling * 然后,调用 flattenData 方法将快照扁平化
* 最后,调用 uploadRecord 方法上传记录
*/ */
async upload() { async upload() {
if (this._isUploading) return if (this.snapshot.size == 0) {
try { await this.enQueue()
this._isUploading = true await this.wait()
if (this.snapshot.size == 0) { this.polling()
await this.enQueue() } else {
this.pollingLater(this.interval) let record = this.snapshot.dequeue()
} else { this.beginTask(record)
let record = this.snapshot.dequeue()
await this.uploadRecord(record)
}
} finally {
this._isUploading = false
} }
}, },
/** /**
* 停止轮询并清除队列 * 开始处理任务
* 这个函数用于停止轮询操作,并清除队列中的所有记录 * 这个函数用于将一个任务加入到操作队列中,并在任务完成后进行轮询
* 首先,它调用 snapshot.clear() 方法清除队列 * @param {Object} record - 要处理的记录对象
* 然后,它将 snapshot 对象设置为 null,以释放资源并停止轮询 * @returns {void} - 此函数不返回任何值
*/
async beginTask(record) {
// 将任务函数加入到操作队列中,并在任务完成后调用 polling 函数进行下一轮轮询
this.operationQueue.enqueue(() => this.task(record), `文件ID:${record.recordId}`).finally(this.polling)
},
/**
* 处理单个记录的任务
* 这个函数用于处理单个记录的上传任务
* @param {Object} record - 要处理的记录对象
* @returns {Promise} - 当任务完成时解析的 Promise
*/
task(record) {
return new Promise(resolve => {
this.updateResolve = resolve
this.uploadRecord(record)
})
},
/**
* 结束任务
* 这个函数用于结束当前的任务
* 调用 resolve 方法来解决 Promise,标记任务完成
* @returns {void} - 此函数不返回任何值
*/
endTask() {
this.updateResolve && this.updateResolve(), (this.updateResolve = null)
},
/**
* 停止文件上传轮询并清除队列
* 这个方法会停止正在进行的轮询,并清除所有待处理的操作和快照数据
* 释放所有资源,确保没有任何后台任务在运行
*/ */
stopPolling() { stopPolling() {
if (this.snapshot) { if (this.snapshot) {
this.snapshot.clear() this.snapshot.clear()
this.snapshot = null this.snapshot = null
} }
this.clearTimer() if (this.operationQueue) {
this.operationQueue.clear() // 取消所有待处理的操作
}
this.canclePromises()
uni.$logger.local.info(`停止文件上传轮询并清除队列`) uni.$logger.local.info(`停止文件上传轮询并清除队列`)
}, },
/**
* 设置轮询的时间间隔
* 这个方法用于设置文件上传轮询的时间间隔
* 如果 interval 不是整数,则会记录错误信息并返回
* 如果 isForce 为 true,则会强制重启轮询
* @param {number} interval - 轮询的时间间隔(秒)
* @param {boolean} [isForce=false] - 是否强制重启轮询
*/
setInterval(interval, isForce = false) { setInterval(interval, isForce = false) {
if (!isInteger(interval)) { if (!isInteger(interval)) {
const error = `参数错误!interval 必需为数字! interval -> ${interval} ` const error = `参数错误!interval 必需为数字! interval -> ${interval} `
...@@ -434,54 +624,59 @@ export default { ...@@ -434,54 +624,59 @@ export default {
} }
uni.$logger.local.info(`轮询间隔已设置为 ${interval} 秒`) uni.$logger.local.info(`轮询间隔已设置为 ${interval} 秒`)
}, },
/**
* 启动文件上传轮询
* 这个方法用于启动文件上传轮询
* 如果 timer 已经存在且 isForce 为 false,则不会强制重启轮询
* 如果 isForce 为 true,则会强制重启轮询
* @param {boolean} [isForce=false] - 是否强制重启轮询
*/
async startPolling(isForce = false) { async startPolling(isForce = false) {
if (this.timer) { if (this.timeoutManager.isProcessing || this.updateResolve) {
if (!isForce) { if (!isForce) {
uni.$logger.local.info(`非强制模式下,timer正在运行,不强制重启轮询`) uni.$logger.local.info(`非强制模式下,不强制重启轮询`)
return return
} else { } else {
uni.$logger.local.info(`强制模式下,timer正在运行,强制重启轮询`) uni.$logger.local.info(`强制模式下,立即完成promise,强制重启轮询`)
this.clearTimer() this.canclePromises()
} }
} }
await this.enQueue() setTimeout(async () => {
this.polling() await this.enQueue()
this.polling()
}, 0)
// setTimeout(() => {
// this.startPolling(true)
// }, 1000)
uni.$logger.local.info(`=========开始轮询========`) uni.$logger.local.info(`=========开始轮询========`)
}, },
clearTimer() {
if (this.timer) {
clearTimeout(this.timer)
this.timer = null
}
},
/** /**
* 在指定的时间间隔后启动轮询 * 清除 timer
* 这个函数用于在指定的时间间隔后执行轮询操作
* @param {number} [interval=60*10] - 轮询间隔(默认为10分钟)
* @returns {void} - 此函数不返回任何值
*/ */
pollingLater(interval = 60 * 10) { canclePromises() {
this.clearTimer() this.timeoutManager.cancelAllTasks()
this.timer = setTimeout(() => { this.endTask()
this.polling()
}, interval * 1000)
console.log(interval + 's后开始下一轮上传!')
} }
}, },
/** /**
* 在组件销毁之前执行的生命周期函数 * 组件销毁前执行的生命周期函数
* 这个函数在组件被销毁之前被调用,可以在这里进行一些清理工作 * 这个函数会在组件销毁前被调用,用于执行一些清理工作
* 在这个例子中,使用 console.log 输出 'topPolling',并调用 this.stopPolling() 方法 * 包括停止文件上传轮询、清除 WebView 组件、取消事件监听以及记录日志
*
* @private
* @returns {void} 没有返回值
* @throws {Error} 调用 this.stopPolling() 时可能出现的错误
*/ */
beforeDestroy() { beforeDestroy() {
// 停止文件上传轮询并清除队列
this.stopPolling() this.stopPolling()
// 如果存在 WebView 实例,重置为 null
if (this.wv) {
this.wv = null
}
// 取消监听停止轮询事件
uni.$off(Command.StopPolling, this.stopPolling) uni.$off(Command.StopPolling, this.stopPolling)
// 取消监听开始轮询事件
uni.$off(Command.StartPolling, this.startPolling) uni.$off(Command.StartPolling, this.startPolling)
// 取消监听设置轮询间隔事件
uni.$off(Command.SetPollingInterval, this.setInterval) uni.$off(Command.SetPollingInterval, this.setInterval)
// 记录组件销毁前的日志信息
uni.$logger.local.info(`组件销毁前执行的生命周期函数`) uni.$logger.local.info(`组件销毁前执行的生命周期函数`)
} }
} }
import { unix } from 'dayjs'
import { SQLite } from '../lib'
/**
* 记录管理器类
* 用于管理记录列表
*/
class DBManager {
db = null
db_name = 'zyzs'
db_version = '1.0'
db_table_name = 'records'
db_description = 'zyzs db'
db_size = 50 * 1024 * 1024
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']
sqlite = null
isTableExists = false
constructor(table_name, table_columns) {
this.table_name = table_name || this.db_table_name
this.table_columns = table_columns || this.table_columns
this.db = new SQLite(this.db_name, this.db_version, this.db_description, this.db_size)
}
async init() {
try {
const isOpen = await this.db.isOpen()
if (!isOpen) {
await this.db.init()
}
const isTableExists = await this.db.isTableExists(this.table_name)
if (!isTableExists) {
await this.db.createTable(this.db_table_name, this.table_columns)
}
return true
} catch (error) {
uni.$logger.error(`初始化数据库失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
/**
* 将一条新记录添加到当前对象的记录列表中
*
* @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record) {
await this.db.insert(this.db_table_name, record)
}
/**
* 移除一个ID对应的记录
*
* @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表
*/
async removeRecord(id) {
return this.db.delete(this.db_table_name, { id })
}
/**
* 根据给定的 ID 获取一条记录
*
* @param {number} id - 要获取的记录的 ID
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
*
*/
async getRecordById(id) {
const records = await this.db.select(this.db_table_name, { id })
return Array.isArray(records) ? records[0] : records // sqlite 返回数组
}
/**
* 获取记录列表
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
async getRecords() {
return this.db.select(this.db_table_name)
}
/**
* 设置记录列表
*
* @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值
*/
async setRecords(records) {
return records.forEach(async record => {
this.addRecord(record)
})
}
/**
* 更新记录数组中的记录
* 这个函数用于更新给定记录数组中的特定记录
* 它接受一个参数 record,该参数是要更新的记录对象
*
* @param {Object} record - 要更新的记录对象,必须包含一个唯一的 id 属性
* @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误
*/
async updateRecord(setData, where) {
const { id, ...record } = setData
if (!where) {
where = { id }
}
return this.db.update(this.db_table_name, record, where)
}
async isOpen() {
return this.db.isOpen()
}
async isTableExists() {
return this.db.isTableExists(this.db_table_name)
}
/**
* 清除所有记录
*
* @returns {void} - 此函数不返回任何值
*/
async clearRecords() {
this.db.delete(this.db_table_name)
}
async drop() {
this.db.drop(this.db_table_name)
}
}
export default DBManager
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-30 11:27:18
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-30 20:10:04
* @FilePath: \gl-tape\utils\OperationQueue.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
class OperationQueue {
constructor(options = {}) {
this.queue = []
this.processing = false
this.maxQueueSize = options.maxQueueSize || 1000
this.operationTimeout = options.operationTimeout || 5 * 60 * 1000 // 5分钟超时
}
async enqueue(operation, context = '') {
if (this.queue.length >= this.maxQueueSize) {
throw new Error('Queue capacity exceeded')
}
return new Promise((resolve, reject) => {
this.queue.push({
operation,
context,
resolve,
reject,
timestamp: Date.now()
})
uni.$logger.local.info(`【操作入列】 [${context}], 当前队列长度: ${this.queue.length}`)
this.processQueue().catch(error => {
uni.$logger.local.error(`【操作队列】 队列处理发生错误: ${error.message}`)
})
})
}
async processQueue() {
if (this.processing) return
this.processing = true
try {
while (this.queue.length > 0) {
const { operation, context, resolve, reject, timestamp } = this.queue[0] // 使用peek而不是shift
uni.$logger.local.info(`【操作队列】 开始处理操作 [${context}], 等待时间: ${Date.now() - timestamp}ms`)
try {
// 添加超时处理
const result = await Promise.race([operation(), new Promise(resolve => setTimeout(() => resolve('Operation timeout'), this.operationTimeout))])
resolve(result)
uni.$logger.local.info(`【操作完成】 [${context}],耗时: ${Date.now() - timestamp}ms`)
} catch (error) {
uni.$logger.local.error(`【操作失败】 [${context}]: ${error.message}`)
reject(error)
} finally {
this.queue.shift() // 确保任务一定会被移除
uni.$logger.local.info(`【操作出列】 [${context}], 当前队列长度: ${this.queue.length}`)
}
// 添加任务间隔,避免过度占用CPU
await new Promise(resolve => setTimeout(resolve, 0))
}
} finally {
this.processing = false
}
}
// 新增:清空队列方法
clear() {
const rejectedItems = this.queue.splice(0, this.queue.length)
rejectedItems.forEach(item => {
item.reject(new Error('Queue was cleared'))
})
uni.$logger.local.warn(`【操作队列】 队列已清空,丢弃了 ${rejectedItems.length} 个任务`)
}
// 新增:获取队列状态
getStatus() {
return {
queueLength: this.queue.length,
processing: this.processing,
oldestTaskAge: this.queue[0] ? Date.now() - this.queue[0].timestamp : 0
}
}
}
export default OperationQueue
import { storageApi } from './cache' import { storageApi } from './cache'
import fileManager from "@/utils/file/FileManager.js"; import fileManager from '@/utils/file/FileManager.js'
import utils from './utils' import utils from './utils'
/** /**
* 记录管理器类 * 记录管理器类
...@@ -52,17 +52,16 @@ class RecordManager { ...@@ -52,17 +52,16 @@ class RecordManager {
unlock() { unlock() {
this.locker = false this.locker = false
} }
/** /**
* 将一条新记录添加到当前对象的记录列表中 * 将一条新记录添加到当前对象的记录列表中
* *
* @param {Object} record - 要添加的新记录对象 * @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表 * @returns {Array} - 包含新记录的更新后的记录列表
*/ */
async addRecord(record) { async addRecord(record, key) {
const records = this.getRecords() || [] const records = this.getRecords(key) || []
records.push(record) records.push(record)
this.setRecords(records) this.setRecords(records, key)
return records return records
} }
/** /**
...@@ -71,8 +70,8 @@ class RecordManager { ...@@ -71,8 +70,8 @@ class RecordManager {
* @param {number} id - 要移除的记录的ID * @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表 * @returns {Array} - 移除记录后的更新后的记录列表
*/ */
async removeRecord(id) { async removeRecord(id, key) {
let records = this.getRecords() let records = this.getRecords(key)
records = records.filter(i => i.id !== id) records = records.filter(i => i.id !== id)
this.setRecords(records) this.setRecords(records)
return records return records
...@@ -82,8 +81,8 @@ class RecordManager { ...@@ -82,8 +81,8 @@ class RecordManager {
* *
* @returns {Object} - 被移除的最后一条记录对象,如果记录列表为空,则返回 undefined * @returns {Object} - 被移除的最后一条记录对象,如果记录列表为空,则返回 undefined
*/ */
getRecord() { getRecord(key) {
const records = this.getRecords() const records = this.getRecords(key)
return records.pop() return records.pop()
} }
/** /**
...@@ -93,8 +92,8 @@ class RecordManager { ...@@ -93,8 +92,8 @@ class RecordManager {
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined * @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
* *
*/ */
getRecordById(id) { getRecordById(id, key) {
const records = this.getRecords() const records = this.getRecords(key)
return records.find(i => i.id === id) return records.find(i => i.id === id)
} }
/** /**
...@@ -102,10 +101,10 @@ class RecordManager { ...@@ -102,10 +101,10 @@ class RecordManager {
* *
* @returns {Array} - 从 storageApi 获取的记录列表 * @returns {Array} - 从 storageApi 获取的记录列表
*/ */
getRecords() { getRecords(key) {
// console.log(888) // console.log(888)
// fileManager.writeFile("123.txt", storageApi.getRecords()); // fileManager.writeFile("123.txt", storageApi.getRecords());
return storageApi.getRecords() return storageApi.getRecords(key)
} }
/** /**
* 设置记录列表 * 设置记录列表
...@@ -113,8 +112,8 @@ class RecordManager { ...@@ -113,8 +112,8 @@ class RecordManager {
* @param {Array} records - 要设置的记录列表 * @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值 * @returns {void} - 此函数不返回任何值
*/ */
setRecords(records) { setRecords(records, key) {
storageApi.setRecords(records) storageApi.setRecords(records, key)
} }
/** /**
* 更新记录数组中的记录 * 更新记录数组中的记录
...@@ -124,36 +123,36 @@ class RecordManager { ...@@ -124,36 +123,36 @@ class RecordManager {
* @param {Object} record - 要更新的记录对象,必须包含一个唯一的 id 属性 * @param {Object} record - 要更新的记录对象,必须包含一个唯一的 id 属性
* @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误 * @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误
*/ */
updateRecord(record) { updateRecord(record, key) {
const records = this.getRecords() const records = this.getRecords(key)
const index = records.findIndex(i => i.id === record.id) const index = records.findIndex(i => i.id === record.id)
if (index !== -1) { if (index !== -1) {
records[index] = record records[index] = record
this.setRecords(records) this.setRecords(records)
} }
} }
/** /**
* 兼容模式的异步处理函数 * 兼容模式的异步处理函数
* 这个函数用于处理在兼容模式下的文件路径转换和记录属性的修正 * 这个函数用于处理在兼容模式下的文件路径转换和记录属性的修正
* 它首先获取一个锁,以确保在操作过程中数据的一致性 * 它首先获取一个锁,以确保在操作过程中数据的一致性
* 然后,它获取客户端文件保存文件夹的路径,并检查是否获取成功 * 然后,它获取客户端文件保存文件夹的路径,并检查是否获取成功
* 接着,它获取所有的记录,并对每个记录执行以下操作: * 接着,它获取所有的记录,并对每个记录执行以下操作:
* - 检查记录的 recordUrlList 是否存在且不为空,对于每个 URL,判断其是否以 'file://' 开头 * - 检查记录的 recordUrlList 是否存在且不为空,对于每个 URL,判断其是否以 'file://' 开头
* - 如果不是,使用路径中的文件名构建一个新的客户端文件路径,并替换掉原来的 URL * - 如果不是,使用路径中的文件名构建一个新的客户端文件路径,并替换掉原来的 URL
* - 如果记录没有 id 属性,随机生成一个 UUID 并设置为记录的 id * - 如果记录没有 id 属性,随机生成一个 UUID 并设置为记录的 id
* *
* 在处理过程中,如果发生任何错误,它将抛出该错误 * 在处理过程中,如果发生任何错误,它将抛出该错误
* 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。 * 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。
* *
* @async * @async
* @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误 * @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误
*/ */
async compatible() { async compatible() {
const unlock = await this.lock() const unlock = await this.lock()
let path = await utils.getFileSaveFolderOnClient() let path = await utils.getFileSaveFolderOnClient()
try { try {
let records = this.getRecords() let records = this.getRecords()
if(typeof records === 'string') { if (typeof records === 'string') {
records = JSON.parse(records) records = JSON.parse(records)
} }
records.forEach(i => { records.forEach(i => {
...@@ -176,7 +175,6 @@ class RecordManager { ...@@ -176,7 +175,6 @@ class RecordManager {
unlock() unlock()
} }
} }
/** /**
* 清除所有记录 * 清除所有记录
* *
......
class TimeoutManager {
constructor() {
this.tasks = []
}
addTimeout(waitTime, outTime = 15 * 60 * 1000) {
this.tasks = []
const timeout = new Promise(resolve => {
this.tasks.push(resolve)
setTimeout(resolve, outTime, 'timeout')
})
const promises = [this.delay(waitTime), timeout]
return Promise.race(promises)
}
cancelAllTasks() {
while (this.tasks.length) {
const abort = this.tasks.shift()
abort('abort')
}
uni.$logger.local.info('强制取消轮询.')
}
get isProcessing() {
return this.tasks.length > 0
}
delay(interval = 60 * 10) {
return new Promise(resolve => {
this.tasks.push(resolve)
setTimeout(resolve, interval * 1000)
console.log(interval + 's后开始下一轮上传!')
})
}
}
export default TimeoutManager
...@@ -2,6 +2,7 @@ import LogsWorker from './workers/LogsWorker' ...@@ -2,6 +2,7 @@ import LogsWorker from './workers/LogsWorker'
import CommonWorker from './workers/CommonWorker' import CommonWorker from './workers/CommonWorker'
import MessageWorker from './workers/MessageWorker' import MessageWorker from './workers/MessageWorker'
import StorageWorker from './workers/StorageWorker' import StorageWorker from './workers/StorageWorker'
import RecordsWorker from './workers/RecordsWorker'
import RemoveLogWorker from './workers/RemoveLogWorker' import RemoveLogWorker from './workers/RemoveLogWorker'
import GetLogListWorker from './workers/GetLogListWorker' import GetLogListWorker from './workers/GetLogListWorker'
import StopPollingWorker from './workers/StopPollingWorker' import StopPollingWorker from './workers/StopPollingWorker'
...@@ -11,6 +12,7 @@ import SetPollingIntervalWorker from './workers/SetPollingIntervalWorker' ...@@ -11,6 +12,7 @@ import SetPollingIntervalWorker from './workers/SetPollingIntervalWorker'
import { Command } from './constants' import { Command } from './constants'
const Workers = { const Workers = {
[Command.GetLog]: LogsWorker, [Command.GetLog]: LogsWorker,
[Command.Records]: RecordsWorker,
[Command.Message]: MessageWorker, [Command.Message]: MessageWorker,
[Command.RemoveLog]: RemoveLogWorker, [Command.RemoveLog]: RemoveLogWorker,
[Command.GetStorage]: StorageWorker, [Command.GetStorage]: StorageWorker,
......
...@@ -32,30 +32,47 @@ export class Ws { ...@@ -32,30 +32,47 @@ export class Ws {
uni.$logger.local.error(`登录失败 -> ${serializeIfObject({ code, data, o })}`) uni.$logger.local.error(`登录失败 -> ${serializeIfObject({ code, data, o })}`)
} }
} }
async login() { async login(retryCount = 3, retryDelay = 2000) {
const sysInfo = uni.getSystemInfoSync() const tryLogin = async (attemptCount) => {
// const userInfo = uni.$storage.get('userInfo') try {
// ;(userInfo.name = '胡悦'), (userInfo.phone = '18754575574') const sysInfo = uni.getSystemInfoSync()
if (!sysInfo?.deviceId) return uni.$logger.local.error('未获取到系统设备信息') if (!sysInfo?.deviceId) {
// sysInfo.deviceId='4DF8801064461802495A2452CCD04EE4' throw new Error('未获取到系统设备信息')
// const { name: user, phone: mobile, merchantName } = userInfo }
uni.$logger.local.info(`========WS,用户登录 ${JSON.stringify({deviceId:sysInfo.deviceId})}========`) // sysInfo.deviceId = '4DF8801064461802495A2452CCD04EE4'
console.log(this.loginAddress) uni.$logger.local.info(`========WS,用户登录(第${attemptCount}次尝试) ${JSON.stringify({deviceId:sysInfo.deviceId})}========`)
return new Promise((resolve, reject) => {
uni.request({
url: this.loginAddress,
data: { sn: sysInfo.deviceId },
method: 'POST',
dataType: 'json',
success(response) {
resolve(response.data)
},
fail(err) {
reject(err)
}
})
})
} catch (error) {
throw error
}
}
return new Promise((resolve, reject) => { for (let attempt = 1; attempt <= retryCount; attempt++) {
uni.request({ try {
url: this.loginAddress, return await tryLogin(attempt)
data: { sn: sysInfo.deviceId }, } catch (err) {
method: 'POST', if (attempt === retryCount) {
dataType: 'json', uni.$logger.local.error(`登录失败(已重试${retryCount}次), 请检查网络或联系管理员! err->${serializeIfObject(err)}`)
success(response) { throw err
resolve(response.data)
},
fail(err) {
uni.$logger.local.error(`登录失败, 请检查网络或联系管理员! err->${serializeIfObject(err)}`)
} }
}) uni.$logger.local.warn(`登录失败(第${attempt}次), ${retryDelay/1000}秒后重试... err->${serializeIfObject(err)}`)
}) await new Promise(resolve => setTimeout(resolve, retryDelay))
}
}
} }
subscribe() { subscribe() {
this.ws.on(WsTyps.Connected, () => { this.ws.on(WsTyps.Connected, () => {
......
...@@ -7,6 +7,7 @@ const Command = { ...@@ -7,6 +7,7 @@ const Command = {
RemoveRecord:'removeRecord', RemoveRecord:'removeRecord',
StopPolling:'stopPolling', StopPolling:'stopPolling',
StartPolling:'startPolling', StartPolling:'startPolling',
SetPollingInterval:'setPollingInterval' SetPollingInterval:'setPollingInterval',
Records:'records',
} }
export { Command } export { Command }
...@@ -9,7 +9,7 @@ export default class GetLogListWorker { ...@@ -9,7 +9,7 @@ export default class GetLogListWorker {
uni.$logger.local.info(`获取日志列表成功! beginDate ->${beginDate} endDate-> ${endDate} res->${serializeIfObject(LogList)}`) uni.$logger.local.info(`获取日志列表成功! beginDate ->${beginDate} endDate-> ${endDate} res->${serializeIfObject(LogList)}`)
ws.send({ LogList }) ws.send({ LogList })
} catch (error) { } catch (error) {
uni.$logger.local.error(`获取日志列表失败! beginDate ->${beginDate} endDate-> ${endDate} error->${serializeIfObject(error)}`) uni.$logger.local.error(`获取日志列表失败! beginDate ->${beginDate} endDate-> ${endDate} error->${serializeIfObject(error.message)}`)
} }
} }
} }
import { serializeIfObject } from '@/utils/utils.js'
export default class RecordsWorker {
constructor() {}
async work(deviceId, data, ws) {
try {
const records = await uni.$dbManager.getRecords()
const msg = `记录获取成功 records -> ${records}`
uni.$logger.local.info(msg)
ws.send({ code: 200, msg })
} catch (error) {
const msg = `获取记录失败 error -> ${error.message}`
uni.$logger.local.error(msg)
ws.send({ error: msg })
}
}
}
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-22 20:45:05
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-06 09:42:35
* @FilePath: \gl-tape\ws\workers\RemoveRecordWorker.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { serializeIfObject } from '@/utils/utils.js' import { serializeIfObject } from '@/utils/utils.js'
export default class RemoveRecordWorker { export default class RemoveRecordWorker {
constructor() {} constructor() {}
...@@ -9,26 +17,23 @@ export default class RemoveRecordWorker { ...@@ -9,26 +17,23 @@ export default class RemoveRecordWorker {
ws.send({ error: msg }) ws.send({ error: msg })
return return
} }
const unlock = await uni.$recordManager.lock()
try { try {
const records = uni.$recordManager.getRecords() const record = await uni.$dbManager.getRecordById(recordId)
const record = records.find(item => item.id === recordId) console.log(record, 'record')
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
} }
uni.$recordManager.removeRecord(recordId) await uni.$dbManager.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 })
} catch (error) { } catch (error) {
const msg = `记录删除异常 id -> ${recordId} error -> ${serializeIfObject(error)}` const msg = `记录删除异常 id -> ${recordId} error -> ${serializeIfObject(error.message)}`
uni.$logger.local.error(msg) uni.$logger.local.error(msg)
ws.send({ error: error,recordId }) ws.send({ error: error, recordId })
} finally {
unlock()
} }
} }
} }
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-11-22 20:45:05
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-12-06 09:31:10
* @FilePath: \gl-tape\ws\workers\StorageWorker.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { constData } from '../../utils/cache' import { constData } from '../../utils/cache'
import { serializeIfObject } from '@/utils/utils.js' import { serializeIfObject } from '@/utils/utils.js'
export default class StorageWorker { export default class StorageWorker {
constructor() {} constructor() {}
work(deviceId, data, ws) { async work(deviceId, data, ws) {
let key = data.key let key = data.key
if (!constData.STORAGE_OBJECTKEY[key]) { if (!constData.STORAGE_OBJECTKEY[key]) {
uni.$logger.local.error(`不存在的 Storage Key->${key}. data->${serializeIfObject(data)}`) uni.$logger.local.error(`不存在的 Storage Key->${key}. data->${serializeIfObject(data)}`)
console.log(`不存在的 Storage Key->${key}.`) console.log(`不存在的 Storage Key->${key}.`)
return return
} }
const value = uni.$storage.get(key) let value = uni.$storage.get(key)
if (key == 'recordList') {
value = await uni.$dbManager.getRecords()
}
const msg = `获取本地缓存! key->${key} value->${serializeIfObject(value)}` const msg = `获取本地缓存! key->${key} value->${serializeIfObject(value)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ [key]: value }) ws.send({ [key]: value })
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!