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 { 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!