Commit 85128def by liimin

refactor: 重构数据库管理和记录处理模块

重构数据库管理模块,将DBManager拆分为DBManager基类和DBRecord、DBTempRecord子类
移除未使用的mixin和工具类,清理废弃代码
优化记录处理逻辑,统一使用$dbRecord替代$dbManager
调整录音时长默认值为10分钟,修复潜在问题
1 parent 93226274
import commonApi from './common' import commonApi from './common'
import systemApi from './systemApi' import systemApi from './systemApi'
import userApi from './userApi' // import userApi from './userApi'
import boutiqueApi from './boutique' // import boutiqueApi from './boutique'
import customerApi from './customerApi' // import customerApi from './customerApi'
import sceneMarketApi from './sceneMarketApi' // import sceneMarketApi from './sceneMarketApi'
import loginApi from './loginApi' import loginApi from './loginApi'
import reception from './reception' import reception from './reception'
module.exports = { module.exports = {
commonApi, commonApi,
systemApi, systemApi,
userApi, // userApi,
boutiqueApi, // boutiqueApi,
customerApi, // customerApi,
sceneMarketApi, // sceneMarketApi,
loginApi, loginApi,
reception reception
} }
...@@ -4,17 +4,17 @@ ...@@ -4,17 +4,17 @@
* @Author: limin * @Author: limin
* @Date: 2025-01-03 18:53:43 * @Date: 2025-01-03 18:53:43
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-01-07 15:34:10 * @LastEditTime: 2025-12-25 10:53:47
* @FilePath: \gl_tape\init.js * @FilePath: \simgle_app\init.js
*/ */
import { DBRecord } from './utils/recordManager/index' import { DBRecord, DBTempRecord } from './utils/recordManager/index'
// import RecordManager from '@/utils/RecordManager' // import RecordManager from '@/utils/RecordManager'
import DBManager from '@/utils/DBManager' // import DBManager from '@/utils/DBManager'
import utils from './utils/utils' import utils from './utils/utils'
import logger from './utils/logger' import logger from './utils/logger'
import { Storage } from './utils/cache/index' import { Storage } from './utils/cache/index'
import api from './api/index' import api from './api/index'
import Track from './utils/Track' // import Track from './utils/Track'
import { signSecretKey, pathEnum, domain, djDomain, evaluationDomain, merchantDomain } from './env' import { signSecretKey, pathEnum, domain, djDomain, evaluationDomain, merchantDomain } from './env'
const HOST = { const HOST = {
scrm: domain, scrm: domain,
...@@ -30,9 +30,9 @@ uni.$throttle = utils.throttle ...@@ -30,9 +30,9 @@ uni.$throttle = utils.throttle
uni.$isNetWork = utils.isNetWork uni.$isNetWork = utils.isNetWork
uni.$logger = logger uni.$logger = logger
// uni.$recordManager = RecordManager.getInstance() // uni.$recordManager = RecordManager.getInstance()
uni.$dbTempRecord = new DBRecord() uni.$dbTempRecord = new DBTempRecord()
uni.$dbManager = new DBManager() uni.$dbRecord = new DBRecord()
uni.$track = new Track() // uni.$track = new Track()
console.log('init.js', HOST['eva']) console.log('init.js', HOST['eva'])
uni.signHttpConfig = { uni.signHttpConfig = {
baseURL: `${HOST['eva']}${pathEnum.evaluation}`, baseURL: `${HOST['eva']}${pathEnum.evaluation}`,
...@@ -93,6 +93,6 @@ uni.signHttpConfig = { ...@@ -93,6 +93,6 @@ uni.signHttpConfig = {
} }
!(async _ => { !(async _ => {
await uni.$dbManager.init() await uni.$dbRecord.init()
await uni.$dbTempRecord.init() await uni.$dbTempRecord.init()
})() })()
import receptionTrackMixin from './receptionTrackMixin' module.exports = {}
module.exports = {
receptionTrackMixin,
}
export default {
methods: {
// 获取园区店下4s店数据
get4SStoreList (loginUserObj) {
console.log(loginUserObj, '-=-')
try {
let { merchantId, isSuper, uuid } = loginUserObj
if (isSuper) {
this.$emit('chooseAccount', loginUserObj)
return
}
uni.$api.userApi.getSceneMerchantRefStoreList({
merchantId,
staffUUID: uuid
}).then(result => {
console.log(result, 'result')
// 仅一家4s店
if (result?.length == 1) {
let { merchantName, merchantId } = result[0]
this.$emit('chooseAccount', {
...loginUserObj,
shopMerchantName: merchantName,
shopMerchantId: merchantId,
default4SStoreInfo: {
merchantId: merchantId,
merchantName: merchantName
},
default4SStoreInfo_crowdFunding: {
merchantId: merchantId,
merchantName: merchantName
},
default4SStoreInfo_newCarConversion: {
merchantId: merchantId,
merchantName: merchantName
}
})
} else if (!result?.length) {
return uni.showToast({
title: '园区店关联的4s店商户账号无效,请联系总部管理员',
icon: 'none',
})
} else {
this.$emit('chooseAccount', loginUserObj)
}
})
} catch (error) {
console.log(error)
}
},
}
}
\ No newline at end of file \ No newline at end of file
// mediaResourceMixin.js - 提供预加载功能的mixin
import mediaResourceManager from '../utils/mediaResourceManager/mediaResourceManager.js'
export default {
methods: {
/**
* 预加载资源
* @param {string|string[]} urls - 资源URL或URL数组
* @param {number} maxConcurrent - 最大并发数
* @returns {Promise<Array<{url: string, success: boolean, result: any}>>}
*/
async preloadMediaResources(urls, maxConcurrent = 3) {
const urlList = Array.isArray(urls) ? urls : [urls]
return await mediaResourceManager.preloadResources(urlList, maxConcurrent)
},
/**
* 获取单个资源(支持优先级控制)
* @param {string} url - 资源URL
* @param {boolean} immediate - 是否立即获取(高优先级)
* @returns {Promise<string>} - 本地资源路径
*/
async getMediaResource(url, immediate = false) {
return await mediaResourceManager.getResource(url, immediate)
},
/**
* 检查资源是否已缓存
* @param {string} url - 资源URL
* @returns {boolean} - 是否已缓存
*/
hasMediaResourceCached(url) {
return mediaResourceManager.hasValidCache(url)
},
/**
* 清理过期的媒体资源缓存
* @returns {number} - 清理的资源数量
*/
cleanupExpiredMediaResources() {
return mediaResourceManager.cleanupExpired()
}
}
}
export default {
watch: {
id: {
immediate: true,
handler (key) {
try {
if (!key || this.type == 'preview') return
let { moduleList } = this,
array = moduleList
if (!Array.isArray(array) || array.length === 0) return
let item = array.find(e => e.id == key),
value = this.receptionTrack[key]
if (value) {
value.openCount += 1
value.entryTime = Date.now()
} else {
value = {
openCount: 1,
materialName: item.materialName || '',
materialId: item.id,
stayDuration: 0,
entryTime: Date.now()
}
}
this.$store.dispatch("setReceptionTrack", { key, value })
} catch (error) {
console.log(error)
}
}
},
moduleList: {
immediate: true,
handler (list) {
try {
const key = this.id
if (!key || this.type == 'preview') return
if (!Array.isArray(list) || list.length === 0) return
let value = this.receptionTrack[key]
if (value) return
const item = list.find(e => e.id == key)
if (!item) return
value = {
openCount: 1,
materialName: item.materialName || '',
materialId: item.id,
stayDuration: 0,
entryTime: Date.now()
}
this.$store.dispatch("setReceptionTrack", { key, value })
} catch (error) {
console.log(error)
}
}
}
},
computed: {
receptionTrack () {
return this.$store.state.user.receptionTrack
}
},
methods: {
receptionTrackLeave (keyName = 'id') {
if (this.type == 'preview') return
let key = this[keyName],
value = this.receptionTrack[key]
value.stayDuration += Number(Date.now() - value.entryTime)
this.$store.dispatch("setReceptionTrack", { key, value })
if (keyName == 'id' && key == 1) { //轻改才会触发
let [receptionRef] = this.$refs.media1
receptionRef.previewLeave && receptionRef.previewLeave(receptionRef.currentItem)
}
}
}
}
...@@ -95,7 +95,7 @@ export default { ...@@ -95,7 +95,7 @@ export default {
if (!isCurrentTask) { if (!isCurrentTask) {
uni.$logger.local.warn(`【上传管理Uploader】 == 收到非当前任务回调: ${callbackKey} (当前: ${this._currentKey}),仅更新状态,不结束任务`) uni.$logger.local.warn(`【上传管理Uploader】 == 收到非当前任务回调: ${callbackKey} (当前: ${this._currentKey}),仅更新状态,不结束任务`)
} }
const record = await uni.$dbManager.getRecordById(fileInfo.recordId) const record = await uni.$dbRecord.getRecordById(fileInfo.recordId)
const modifiedRecord = this._changeFilePathToServer(record, fileInfo) const modifiedRecord = this._changeFilePathToServer(record, fileInfo)
await this._saveOrUpdate(modifiedRecord) await this._saveOrUpdate(modifiedRecord)
...@@ -259,7 +259,7 @@ export default { ...@@ -259,7 +259,7 @@ export default {
*/ */
async reportError(message, res, recordId, filePath) { async reportError(message, res, recordId, filePath) {
try { try {
const record = recordId ? await uni.$dbManager.getRecordById(recordId) : {} const record = recordId ? await uni.$dbRecord.getRecordById(recordId) : {}
// const userInfo = this.userInfo //uni.$storage.get('userInfo') // const userInfo = this.userInfo //uni.$storage.get('userInfo')
const { customerName, customerPhone, carType } = record || {} const { customerName, customerPhone, carType } = record || {}
const { user: { userName } = {} } = this.userInfo || {} const { user: { userName } = {} } = this.userInfo || {}
...@@ -334,7 +334,7 @@ export default { ...@@ -334,7 +334,7 @@ export default {
* @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误 * @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误
*/ */
async getRecordsSnapshotFlatten() { async getRecordsSnapshotFlatten() {
const _records = await uni.$dbManager.getRecords() const _records = await uni.$dbRecord.getRecords()
const _snapshot = await this.flattenData(_records || []) const _snapshot = await this.flattenData(_records || [])
return _snapshot return _snapshot
}, },
...@@ -476,7 +476,7 @@ export default { ...@@ -476,7 +476,7 @@ export default {
*/ */
async _handleIncompleteRecord(record) { async _handleIncompleteRecord(record) {
uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`) uni.$logger.local.info(`【上传管理Uploader】 == 记录中有未上传文件,开始更新记录!!`)
await uni.$dbManager.updateRecord({ urlList: record.urlList }, { id: record.id }) await uni.$dbRecord.updateRecord({ urlList: record.urlList }, { id: record.id })
}, },
/** /**
...@@ -509,7 +509,7 @@ export default { ...@@ -509,7 +509,7 @@ export default {
*/ */
async _removeRecordById(recordId) { async _removeRecordById(recordId) {
try { try {
await uni.$dbManager.removeRecord(recordId) await uni.$dbRecord.removeRecord(recordId)
uni.$logger.local.info(`【上传管理Uploader】 == 删除接待记录成功: recordId ->${recordId}`) uni.$logger.local.info(`【上传管理Uploader】 == 删除接待记录成功: recordId ->${recordId}`)
} catch (error) { } catch (error) {
this.reportError(`【上传管理Uploader】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId }) this.reportError(`【上传管理Uploader】 == 删除接待记录异常: error ->${error.message}`, { message: error.message, recordId })
......
import dayjs from 'dayjs'
export default {
data () {
return {
systemInfo: {},
timer: null,
id: null
}
},
onLoad (options) {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
const { row } = options
const _row = JSON.parse(row)
this.systemInfo = _row
this.systemInfo.time = dayjs(new Date(_row.actualSendTime)).format("YYYY-MM-DD HH:mm:ss")
this.addTrack(_row)
this.timer = setInterval(() => {
this.leaveTrack(this.id)
}, 3000)
},
methods: {
// 进入埋点事件
addTrack(row) {
try {
const {phone} = uni.$storage.get("userInfo")
const entryData = {
taskId: row.id,
phoneNumber: phone
}
uni.$api.commonApi.addSystemInfo(entryData).then(res => {
if (res) {
this.leaveTrack(res)
this.id = res
}
})
} catch (error) {
console.error('进入埋点发生错误', error);
}
},
// 离开埋点事件
async leaveTrack(id) {
if (!id) return
await uni.$api.commonApi.leaveSystemInfo({id})
}
},
onUnload () {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
* @Author: huyue * @Author: huyue
* @Date: 2024-04-08 11:30:30 * @Date: 2024-04-08 11:30:30
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-22 17:16:50 * @LastEditTime: 2025-12-25 10:46:39
--> -->
<template> <template>
<view class="detail-box" :key="dateilKey"> <view class="detail-box" :key="dateilKey">
...@@ -77,7 +77,7 @@ import FinishStep from '@/components/FinishStep.vue' ...@@ -77,7 +77,7 @@ import FinishStep from '@/components/FinishStep.vue'
import { mapMutations } from 'vuex' import { mapMutations } from 'vuex'
import informationEntry from './components/informationEntry.vue' import informationEntry from './components/informationEntry.vue'
// import insurance from '@/components/Insurance/Insurance.vue' // import insurance from '@/components/Insurance/Insurance.vue'
import { receptionTrackMixin } from '@/mixin/index.js' // import { receptionTrackMixin } from '@/mixin/index.js'
export default { export default {
components: { components: {
ToolBox, ToolBox,
......
...@@ -13,9 +13,7 @@ import user from './modules/user' ...@@ -13,9 +13,7 @@ import user from './modules/user'
import audio from './modules/audio' import audio from './modules/audio'
import update from './modules/update' import update from './modules/update'
import sys from './modules/sys' import sys from './modules/sys'
import point from './modules/point'
import material from './modules/material' import material from './modules/material'
// import boutique from './modules/boutique'
Vue.use(Vuex) Vue.use(Vuex)
const store = new Vuex.Store({ const store = new Vuex.Store({
...@@ -25,8 +23,6 @@ const store = new Vuex.Store({ ...@@ -25,8 +23,6 @@ const store = new Vuex.Store({
update, update,
material, material,
sys, sys,
point,
// boutique
}, },
getters getters
}) })
......
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2025-01-17 15:40:18
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2025-01-17 15:41:00
* @FilePath: \gl-tape\store\modules\point.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
export default {
state() {
return {
tabIndex: 0
}
},
mutations: {
SET_Tab(state, value) {
state.tabIndex = value
}
},
actions: {
setTab({ commit }, value) {
commit('SET_Tab', value)
}
}
}
// 本文件用于,使用JQL语法操作项目关联的uniCloud空间的数据库,方便开发调试和远程数据库管理
// 编写clientDB的js API(也支持常规js语法,比如var),可以对云数据库进行增删改查操作。不支持uniCloud-db组件写法
// 可以全部运行,也可以选中部分代码运行。点击工具栏上的运行按钮或者按下【F5】键运行代码
// 如果文档中存在多条JQL语句,只有最后一条语句生效
// 如果混写了普通js,最后一条语句需是数据库操作语句
// 此处代码运行不受DB Schema的权限控制,移植代码到实际业务中注意在schema中配好permission
// 不支持clientDB的action
// 数据库查询有最大返回条数限制,详见:https://uniapp.dcloud.net.cn/uniCloud/cf-database.html#limit
// 详细JQL语法,请参考:https://uniapp.dcloud.net.cn/uniCloud/jql.html
// 下面示例查询uni-id-users表的所有数据
db.collection('uni-id-users').get();
const TRACK_INTERVAL_TIME = 30 * 1e3
let TRACK_TIME
import dayjs from 'dayjs'
class Track {
constructor() {
console.log('---------------- 埋点初始化 ----------------')
// this.sendTrack()
}
add (data = {}) {
const {
phone: phoneNumber,
name: loginAccount,
uuid,
sceneType: scene,
userType
} = uni.$storage.get('userInfo') || {},
trackList = uni.getStorageSync('TRACK_LIST') || []
let pages = getCurrentPages(),
currentPage = pages[pages.length - 1],
prePage = {}
if (pages.length > 1) prePage = pages[pages.length - 2]
let item = {
userType,
loginAccount,
phoneNumber,
uuid,
scene,
prePagePath: data.prePagePath || prePage.route || '/',
pagePath: data.pagePath || currentPage.route || '/',
eventTime: dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
systemSource: 3,
eventType: data.eventType || 0
}
if (data.batchId) item.batchId = data.batchId
if (data.eventCode) item.eventCode = data.eventCode
if (data.businessParam) item.businessParam = JSON.stringify(data.businessParam)
if (data.businessId) item.businessId = data.businessId
trackList.push(item)
uni.setStorageSync('TRACK_LIST', trackList)
if (!TRACK_TIME) {
console.log('---------------- 重新打开定时埋点 ----------------')
// this.sendTrack() //开启定时埋点
}
// if (trackList.length > 9) this.sendTrackData()
}
/**定时发送埋点数据 */
sendTrack () {
// TRACK_TIME = setInterval(() => {
// this.sendTrackData()
// }, TRACK_INTERVAL_TIME)
}
async sendTrackData () {
const recordList = uni.getStorageSync('TRACK_LIST') || []
if (recordList.length) {
const res = await uni.$api.commonApi.recordInsert({ recordList })
if (res) uni.setStorageSync('TRACK_LIST', [])
} else {
clearInterval(TRACK_TIME)
TRACK_TIME = null
console.log('---------------- 暂停定时埋点 ----------------')
}
}
}
export default Track
class RecorderManager {
constructor(options) {
const { duration, callback, isEndCallback } = options || {};
this.recorderManager = uni.getRecorderManager();
this.start(duration);
this.isEndCallback = isEndCallback;
this.recorderManager.onStop((res) => {
console.log("结束录音", res);
callback(res.tempFilePath);
const isEnd = this.isEndCallback(); // 获取最新的 isEnd 值
if (!isEnd) {
this.start(); // 重新开始录音
}
});
}
start(duration = 60000) {
console.log("开始录音");
this.recorderManager.start({
duration,
sampleRate: 16000,
numberOfChannels: 1,
});
}
stop() {
this.recorderManager.stop();
}
}
// utils/debounce.js
const debounce = {
bind(el, binding) {
// 支持函数、数组[函数, 参数...]或对象{fn: 函数, params: 参数数组, delay: 延迟时间}格式
if (typeof binding.value !== 'function' && !Array.isArray(binding.value) && (!binding.value || typeof binding.value !== 'object')) {
console.warn('v-debounce binding value must be a function, array or object')
return
}
// 解析参数
let fn,
params = [],
delay = 300
const stopPropagation = binding.modifiers && binding.modifiers.stop
if (typeof binding.value === 'function') {
fn = binding.value
} else if (Array.isArray(binding.value)) {
;[fn, ...params] = binding.value
} else if (typeof binding.value === 'object') {
fn = binding.value.fn
params = binding.value.params || []
delay = binding.value.delay || delay
}
// 如果没有提供函数,直接返回
if (typeof fn !== 'function') {
console.warn('v-debounce: function is required')
return
}
// 获取延迟时间
if (binding.arg) {
delay = parseInt(binding.arg) || delay
}
let timer = null
const debounceFn = function (event) {
// 处理.stop修饰符
if (stopPropagation && event && typeof event.stopPropagation === 'function') {
event.stopPropagation()
}
if (timer) {
clearTimeout(timer)
}
// 收集事件参数
const eventArgs = arguments.length ? Array.from(arguments) : []
timer = setTimeout(() => {
// 合并预设参数和事件参数
const allParams = [...params, ...eventArgs]
fn.apply(this, allParams)
timer = null
}, delay)
}
el._debounceFn = debounceFn
el.addEventListener('click', debounceFn)
},
update(el, binding) {
// 当绑定值发生变化时重新绑定
if (binding.value !== binding.oldValue) {
// 移除旧的事件监听
if (el._debounceFn) {
el.removeEventListener('click', el._debounceFn)
el._debounceFn = null
}
// 重新绑定,逻辑与bind相同
if (typeof binding.value !== 'function' && !Array.isArray(binding.value) && (!binding.value || typeof binding.value !== 'object')) {
console.warn('v-debounce binding value must be a function, array or object')
return
}
let fn,
params = [],
delay = 300
const stopPropagation = binding.modifiers && binding.modifiers.stop
if (typeof binding.value === 'function') {
fn = binding.value
} else if (Array.isArray(binding.value)) {
;[fn, ...params] = binding.value
} else if (typeof binding.value === 'object') {
fn = binding.value.fn
params = binding.value.params || []
delay = binding.value.delay || delay
}
if (typeof fn !== 'function') {
console.warn('v-debounce: function is required')
return
}
if (binding.arg) {
delay = parseInt(binding.arg) || delay
}
let timer = null
const debounceFn = function (event) {
if (stopPropagation && event && typeof event.stopPropagation === 'function') {
event.stopPropagation()
}
if (timer) {
clearTimeout(timer)
}
const eventArgs = arguments.length ? Array.from(arguments) : []
timer = setTimeout(() => {
const allParams = [...params, ...eventArgs]
fn.apply(this, allParams)
timer = null
}, delay)
}
el._debounceFn = debounceFn
el.addEventListener('click', debounceFn)
}
},
unbind(el) {
if (el._debounceFn) {
el.removeEventListener('click', el._debounceFn)
el._debounceFn = null
}
}
}
export default debounce
class FileManager {
writeFile(addr, data) {
plus.io.requestFileSystem(
plus.io.PUBLIC_DOCUMENTS, // 程序公用文档目录常量
(fs) => {
// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
fs.root.getFile(
addr,
{
create: true, // 文件不存在则创建
},
(fileEntry) => {
// 文件在手机中的路径
console.log(fileEntry.fullPath);
fileEntry.createWriter((writer) => {
// 写入文件成功完成的回调函数
writer.onwrite = (e) => {
console.log("写入成功");
};
// 向文件中写入数据
writer.write(JSON.stringify(data));
});
},
(e) => {
console.log("getFile failed: " + e.message);
}
);
},
(e) => {
console.log(e.message);
}
);
}
readFile(addr) {
let that = this;
return new Promise((resolve, reject) => {
plus.io.requestFileSystem(
plus.io.PUBLIC_DOCUMENTS,
(fs) => {
fs.root.getFile(
addr,
{
create: true,
},
(fileEntry) => {
fileEntry.file(function (file) {
console.log("文件大小:" + file.size + "-- 文件名:" + file.name);
//创建读取文件对象
let fileReader = new plus.io.FileReader();
//以文本格式读取文件数据内容
fileReader.readAsText(file, "utf-8");
//文件读取操作完成时的回调函数
fileReader.onloadend = function (evt) {
resolve(evt.target.result);
//console.log("提取的服务器地址:", sURL);
};
});
},
(e) => {
reject(e);
console.log(e);
}
);
},
(e) => {
reject(e);
console.log(e.message);
}
);
});
}
}
export default new FileManager();
\ No newline at end of file \ No newline at end of file
let modalQueue = []
import api from '@/api/index.js'
let eventRequest = []
export const checkDailyReport = async sceneType => {
let userInfo = uni.$storage.get('userInfo')
// debugger
// 判读是否要填写日报
if (!(userInfo?.isSuper || userInfo?.loginRole == 3 || userInfo.loginRole == 5 || userInfo?.loginRole == 6)) {
// 判断员工是否已打卡上班
eventRequest.push(clockedIntoWork())
eventRequest.push(sceneType ? equityStaffDailyReport(userInfo) : staffDailyReport(userInfo))
}
return new Promise(resolve => {
Promise.all(eventRequest).then(results => {
// const [reportStatus] = results;
results = results.slice(-2)
// console.log(reportStatus, results, results.length, results[results.length - 1], 'reportStatus');
let resultFlag = results.some(item => item)
showNextModal()
console.log(resultFlag, 'resultFlag')
resolve(resultFlag)
})
})
}
export const showNextModal = () => {
let _this = this
if (modalQueue.length > 0) {
const modalInfo = modalQueue.pop()
if (uni.__HAS_SHOW_MODAL) return
uni.__HAS_SHOW_MODAL = true
uni.showModal({
title: modalInfo.title,
content: modalInfo.content,
showCancel: modalInfo.showCancel,
cancelColor: '#292D33',
confirmText: modalInfo.confirmText,
confirmColor: '#347BFF',
success: function (res) {
uni.__HAS_SHOW_MODAL = false
// if (res.cancel) _this.showNextModal();
if (res.cancel) showNextModal()
modalInfo.eventCallback(res)
}
})
}
}
const staffDailyReport = userInfo => {
return new Promise((resolve, reject) => {
api.boutiqueApi
.staffDailyReportMerchantValid({
merchantId: userInfo.shopMerchantId,
yqMerchantId: userInfo.merchantId,
staffUuid: userInfo.uuid,
sceneType: 1
})
.then(res => {
if (res.data) {
// 获取当前日期
let currentDate = new Date()
// 获取上一天的日期
let previousDate = new Date(currentDate)
previousDate.setDate(currentDate.getDate() - 1)
// toISOString 方法会丢失时区 导致与北京时间差八小时
let hour = previousDate.getHours() + 8
previousDate.setHours(hour)
// 格式化日期为"yyyy-mm-dd"
let formattedDate = previousDate.toISOString().split('T')[0]
if (wx.__HAS_NOTLOGIN_MODAL) return false
addModalToQueue('日报提醒', '您有未填写的日报,请点击前往。', '前往填写', false, 2, res => {
if (res.confirm) {
wx.$router.go('tabWorkOrder.upgradeStaffDaily', {
reportDate: formattedDate
})
}
})
resolve(true)
} else {
resolve(false)
}
})
.catch(err => {
resolve()
console.log(err)
})
})
}
const equityStaffDailyReport = userInfo => {
return new Promise((resolve, reject) => {
api.boutiqueApi
.staffDailyReportMerchantValid({
merchantId: userInfo?.shopMerchantId,
yqMerchantId: userInfo?.merchantId,
staffUuid: userInfo?.uuid,
sceneType: 0
})
.then(res => {
if (res.data) {
// 获取当前日期
let currentDate = new Date()
// 获取上一天的日期
let previousDate = new Date(currentDate)
previousDate.setDate(currentDate.getDate() - 1)
console.log(previousDate, 'previousDate')
// toISOString 方法会丢失时区 导致与北京时间差八小时
let hour = previousDate.getHours() + 8
previousDate.setHours(hour)
// 格式化日期为"yyyy-mm-dd"
let formattedDate = previousDate.toISOString().split('T')[0]
console.log('formattedDate', formattedDate)
if (wx.__HAS_NOTLOGIN_MODAL || userInfo?.isSuper || userInfo?.loginRole == 3 || userInfo.loginRole == 5 || userInfo?.loginRole == 6) return false
addModalToQueue('日报提醒', '您有未填写的日报,请点击前往。', '前往填写', false, 4, res => {
if (res.confirm) {
wx.$router.go('tabWorkOrder.staffDaily', {
reportDate: formattedDate
})
}
})
resolve(true)
} else {
resolve(false)
}
})
.catch(err => {
resolve(false)
})
})
}
export const clockedIntoWork = userInfo => {
return new Promise((resolve, reject) => {
api.boutiqueApi
.clockInConfigPhone({})
.then(res => {
let { need, clockIn } = res.data
// console.log(res, need == 0 && clockIn == 0, "clockInConfigPhone");
// 已配置未打卡
if (need == 1 && clockIn == 0) {
// 有配置并且没有打卡就提示
addModalToQueue('打卡提醒', '您当前企微未打卡,无法录单,请前往企微打卡后再试,如有异议请联系管理员。', '知道了', false, 4, res => {
if (res.confirm) {
// wx.$router.go("tabWorkOrder.staffDaily", {
// // reportDate: formattedDate,
// });
}
})
resolve(true)
} else {
resolve(false)
}
})
.catch(err => {
resolve(false)
})
})
}
const addModalToQueue = (title, content, confirmText, showCancel, priority, eventCallback) => {
if (modalQueue.findIndex(val => val.content == content) < 0)
modalQueue.push({
title,
content,
confirmText,
showCancel,
priority,
eventCallback
})
modalQueue.sort((a, b) => a.priority - b.priority)
}
...@@ -4,12 +4,12 @@ ...@@ -4,12 +4,12 @@
* @Author: limin * @Author: limin
* @Date: 2024-12-04 18:17:23 * @Date: 2024-12-04 18:17:23
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-24 18:55:23 * @LastEditTime: 2025-12-25 11:00:13
* @FilePath: \simgle_app\utils\recordManager\AudioManager.js * @FilePath: \simgle_app\utils\recordManager\AudioManager.js
*/ */
class AudioManager { class AudioManager {
startOptions = { startOptions = {
duration: 1 * 60 * 1000, //默认10分钟 duration: 10 * 60 * 1000, //默认10分钟
sampleRate: 16000, sampleRate: 16000,
numberOfChannels: 1 numberOfChannels: 1
} }
......
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
* @Date: 2024-11-22 08:18:23 * @Date: 2024-11-22 08:18:23
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-23 09:34:35 * @LastEditTime: 2025-12-23 09:34:35
* @FilePath: \simgle_app\utils\DBManager.js * @FilePath: \simgle_app\utils\recordManager\DBManager.js
*/ */
import { SQLite } from '../lib' import { SQLite } from '../../lib'
/** /**
* 记录管理器类 * 记录管理器类
* 用于管理记录列表 * 用于管理记录列表
...@@ -19,27 +19,11 @@ class DBManager { ...@@ -19,27 +19,11 @@ class DBManager {
db_table_name = 'records' db_table_name = 'records'
db_description = 'zyzs db' db_description = 'zyzs db'
db_size = 50 * 1024 * 1024 db_size = 50 * 1024 * 1024
table_columns = [
`id TEXT PRIMARY KEY`,
'typeCode TEXT',
'carType TEXT',
'customerType TEXT',
'result TEXT',
'merchantId INTEGER',
'machineCode TEXT',
'customerName TEXT',
'customerPhone TEXT',
`userId INTEGER`,
`userName TEXT`,
'startTime TEXT',
'endTime TEXT',
'materialId INTEGER',
'urlList TEXT']
sqlite = null sqlite = null
isTableExists = false isTableExists = false
constructor(table_name, table_columns) { constructor(table_name, table_columns) {
this.table_name = table_name || this.db_table_name this.table_name = table_name || this.db_table_name
this.table_columns = table_columns || this.table_columns this.table_columns = table_columns
this.db = new SQLite(this.db_name, this.db_version, this.db_description, this.db_size) this.db = new SQLite(this.db_name, this.db_version, this.db_description, this.db_size)
} }
async init() { async init() {
......
...@@ -25,7 +25,7 @@ class TempRecord { ...@@ -25,7 +25,7 @@ class TempRecord {
constructor(record, onTempRecordNumberChanged) { constructor(record, onTempRecordNumberChanged) {
this.newRecord = record this.newRecord = record
this.recordManager = uni.$dbTempRecord this.recordManager = uni.$dbTempRecord
this.dbManager = uni.$dbManager this.dbRecord = uni.$dbRecord
this.onTempRecordNumberChanged = onTempRecordNumberChanged this.onTempRecordNumberChanged = onTempRecordNumberChanged
} }
/** /**
...@@ -127,10 +127,10 @@ class TempRecord { ...@@ -127,10 +127,10 @@ class TempRecord {
} }
__record.urlList = recordLongList.slice(0, maxUploadNum) __record.urlList = recordLongList.slice(0, maxUploadNum)
uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!') uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
await this.dbManager.addRecord(__record) await this.dbRecord.addRecord(__record)
await this.clearLocalRecord(record) await this.clearLocalRecord(record)
} catch (error) { } catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message) uni.$logger.local.error('〖接待记录Record〗 == 保存记录异常' + error.message)
} }
} }
async clearLocalRecord(record = this.record) { async clearLocalRecord(record = this.record) {
...@@ -149,10 +149,10 @@ class TempRecord { ...@@ -149,10 +149,10 @@ class TempRecord {
* @param {Object} options - 配置参数 * @param {Object} options - 配置参数
* @param {Array} options.urlList - 录音文件列表,默认为当前记录的urlList * @param {Array} options.urlList - 录音文件列表,默认为当前记录的urlList
*/ */
clearSavedFiles({ urlList = [] } = this.record || {}) { clearSavedFiles({ urlList = [] } = this.record) {
// 遍历录音文件列表并删除每个文件 // 遍历录音文件列表并删除每个文件
urlList.forEach(item => { urlList.forEach(item => {
uni.$logger.local.info('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file) uni.$logger.local.warn('〖接待记录Record〗 == 清除已保存文件 -> ' + item.file)
this.removeFile(item.file) this.removeFile(item.file)
}) })
} }
...@@ -180,7 +180,7 @@ class TempRecord { ...@@ -180,7 +180,7 @@ class TempRecord {
} }
return list return list
} catch (error) { } catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message) uni.$logger.local.error('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message) throw new Error(error.message)
} }
} }
...@@ -201,7 +201,7 @@ class TempRecord { ...@@ -201,7 +201,7 @@ class TempRecord {
this.addAudio() this.addAudio()
} }
reset() { reset() {
this._isDestroyed = false this._isDestroyed = false
} }
/** /**
* 构造一条新的接待记录的初始对象 * 构造一条新的接待记录的初始对象
...@@ -287,7 +287,7 @@ class TempRecord { ...@@ -287,7 +287,7 @@ class TempRecord {
uni.$logger.local.warn('〖接待记录Record〗 == 未找到录音文件,跳过添加') uni.$logger.local.warn('〖接待记录Record〗 == 未找到录音文件,跳过添加')
return return
} }
uni.$logger.local.info('〖接待记录Record〗 == 添加一个新的录音' + lastAudio) uni.$logger.local.warn('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
const savedPath = await this.saveFilePath(lastAudio) const savedPath = await this.saveFilePath(lastAudio)
if (savedPath && this.record) { if (savedPath && this.record) {
this.record.tempFilePath = lastAudio this.record.tempFilePath = lastAudio
...@@ -296,7 +296,7 @@ class TempRecord { ...@@ -296,7 +296,7 @@ class TempRecord {
uni.$logger.local.warn('〖接待记录Record〗 == 录音未变化,跳过添加 -> ' + savedPath) uni.$logger.local.warn('〖接待记录Record〗 == 录音未变化,跳过添加 -> ' + savedPath)
} else { } else {
this.record.urlList.push({ file: savedPath }) this.record.urlList.push({ file: savedPath })
uni.$logger.local.info('〖接待记录Record〗 == 添加新录音成功:' + savedPath) uni.$logger.local.warn('〖接待记录Record〗 == 添加新录音成功:' + savedPath)
} }
} }
} catch (e) { } catch (e) {
...@@ -349,7 +349,7 @@ class TempRecord { ...@@ -349,7 +349,7 @@ class TempRecord {
let { tempFilePath, urlList } = record let { tempFilePath, urlList } = record
if (!tempFilePath || urlList.length === 0) { if (!tempFilePath || urlList.length === 0) {
if (!this.timer) { if (!this.timer) {
uni.$logger.local.info('〖接待记录Record〗 == 无可保存的临时录音,当前未在轮询中,跳过自动补录') uni.$logger.local.warn('〖接待记录Record〗 == 无可保存的临时录音,当前未在轮询中,跳过自动补录')
return return
} }
uni.$logger.local.warn('〖接待记录Record〗 == 无可保存的临时录音,轮询中尝试添加新录音') uni.$logger.local.warn('〖接待记录Record〗 == 无可保存的临时录音,轮询中尝试添加新录音')
...@@ -443,7 +443,7 @@ class TempRecord { ...@@ -443,7 +443,7 @@ class TempRecord {
uni.$logger.local.info('〖接待记录Record〗 == 轮询已启动,跳过') uni.$logger.local.info('〖接待记录Record〗 == 轮询已启动,跳过')
return return
} }
if (this._isDestroyed) { if(this._isDestroyed) {
uni.$logger.local.warn('〖接待记录Record〗 == 组件已销毁,忽略 startSaveAudioLoop') uni.$logger.local.warn('〖接待记录Record〗 == 组件已销毁,忽略 startSaveAudioLoop')
return return
} }
......
...@@ -2,35 +2,33 @@ ...@@ -2,35 +2,33 @@
* @Descripttion: * @Descripttion:
* @version: 1.0.0 * @version: 1.0.0
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:34:39 * @Date: 2025-01-07 18:34:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-12-23 11:11:04 * @LastEditTime: 2025-12-25 10:26:38
* @FilePath: \simgle_app\utils\recordManager\dbRecord.js * @FilePath: \simgle_app\utils\recordManager\dbRecord.js
*/ */
import DBManager from '../DBManager.js' import DBManager from './DBManager.js'
class DBRecord { class DBRecord extends DBManager {
table_columns = [
`id TEXT PRIMARY KEY`,
'typeCode TEXT',
'carType TEXT',
'customerType TEXT',
'result TEXT',
'merchantId INTEGER',
'machineCode TEXT',
'customerName TEXT',
'customerPhone TEXT',
`userId INTEGER`,
`userName TEXT`,
'startTime TEXT',
'endTime TEXT',
'materialId INTEGER',
'urlList TEXT',
'tempFilePath TEXT',
]
table_name = 'temp_records'
constructor() { constructor() {
this.db = new DBManager(this.table_name, this.table_columns) const table_name = 'records'
return this.db const table_columns = [
`id TEXT PRIMARY KEY`,
'typeCode TEXT',
'carType TEXT',
'customerType TEXT',
'result TEXT',
'merchantId INTEGER',
'machineCode TEXT',
'customerName TEXT',
'customerPhone TEXT',
`userId INTEGER`,
`userName TEXT`,
'startTime TEXT',
'endTime TEXT',
'materialId INTEGER',
'urlList TEXT'
]
super(table_name, table_columns)
} }
} }
export default DBRecord export default DBRecord
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:34:39
* @LastEditors: limin
* @LastEditTime: 2025-12-25 10:20:04
* @FilePath: \simgle_app\utils\recordManager\dbTempRecord.js
*/
import DBManager from './DBManager.js'
class DBTempRecord extends DBManager {
constructor() {
const table_name = 'temp_records'
const table_columns = [
`id TEXT PRIMARY KEY`,
'typeCode TEXT',
'carType TEXT',
'customerType TEXT',
'result TEXT',
'merchantId INTEGER',
'machineCode TEXT',
'customerName TEXT',
'customerPhone TEXT',
`userId INTEGER`,
`userName TEXT`,
'startTime TEXT',
'endTime TEXT',
'materialId INTEGER',
'urlList TEXT',
'tempFilePath TEXT',
]
super(table_name, table_columns)
}
}
export default DBTempRecord
...@@ -9,10 +9,12 @@ ...@@ -9,10 +9,12 @@
*/ */
// import { singleton } from '../utils.js' // import { singleton } from '../utils.js'
import AudioManager from './AudioManager.js' import AudioManager from './AudioManager.js'
import DBTempRecord from './dbTempRecord.js'
import DBRecord from './dbRecord.js' import DBRecord from './dbRecord.js'
import DBManager from './DBManager.js'
// import Record from './Record.js' // import Record from './Record.js'
import RecordDto from './RecordDto.js' import RecordDto from './RecordDto.js'
import TempRecord from './TempRecord.js' import TempRecord from './TempRecord.js'
import helpler from './helpler.js' import helpler from './helpler.js'
// const SingleDBTempRecord = singleton(TempRecord) // const SingleDBTempRecord = singleton(TempRecord)
module.exports = { AudioManager, DBRecord, RecordDto, TempRecord, helpler } module.exports = { AudioManager, DBRecord, DBTempRecord, DBManager, RecordDto, TempRecord, helpler }
import defaultStorage from './storage';
/**
* 日期格式化
* let time = new Date().format('yyyy-MM-dd hh:mm:ss')
*/
Date.prototype.format = function (fmt) {
let o = {
'M+': this.getMonth() + 1, //月份
'd+': this.getDate(), //日
'h+': this.getHours(), //小时
'm+': this.getMinutes(), //分
's+': this.getSeconds(), //秒
//季度
'q+': Math.floor((this.getMonth() + 3) / 3),
S: this.getMilliseconds() //毫秒
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
}
}
return fmt
}
export default defaultStorage;
\ No newline at end of file \ No newline at end of file
export default {
// 设置永久缓存
set(key, value) {
uni.setStorageSync(key, value);
},
// 获取永久缓存
get(key) {
return uni.getStorageSync(key);
},
// 移除永久缓存
remove(key) {
uni.removeStorageSync(key);
},
// 移除全部永久缓存
clear() {
uni.clearStorageSync();
},
};
\ No newline at end of file \ No newline at end of file
...@@ -23,7 +23,7 @@ export default class AddRecordWorker { ...@@ -23,7 +23,7 @@ export default class AddRecordWorker {
throw new Error(`数据格式错误,表中没有 ${key} 字段`) throw new Error(`数据格式错误,表中没有 ${key} 字段`)
} }
}) })
await uni.$dbManager.addRecord(record) await uni.$dbRecord.addRecord(record)
const msg = `写入待上传记录成功 temp record -> ${JSON.stringify(record)}` const msg = `写入待上传记录成功 temp record -> ${JSON.stringify(record)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200,msg: '写入待上传记录成功', data: record }) ws.send({ code: 200,msg: '写入待上传记录成功', data: record })
......
...@@ -3,7 +3,7 @@ export default class RecordsWorker { ...@@ -3,7 +3,7 @@ export default class RecordsWorker {
constructor() {} constructor() {}
async work(deviceId, data, ws) { async work(deviceId, data, ws) {
try { try {
const records = await uni.$dbManager.getRecords() const records = await uni.$dbRecord.getRecords()
const msg = `记录获取成功 records -> ${JSON.stringify(records)}` const msg = `记录获取成功 records -> ${JSON.stringify(records)}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg: '获取记录成功', data:records }) ws.send({ code: 200, msg: '获取记录成功', data:records })
......
...@@ -18,14 +18,14 @@ export default class RemoveRecordWorker { ...@@ -18,14 +18,14 @@ export default class RemoveRecordWorker {
return return
} }
try { try {
const record = await uni.$dbManager.getRecordById(recordId) const record = await uni.$dbRecord.getRecordById(recordId)
if (!record) { if (!record) {
const msg = `记录不存在 id -> ${recordId}` const msg = `记录不存在 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ error: msg }) ws.send({ error: msg })
return return
} }
await uni.$dbManager.removeRecord(recordId) await uni.$dbRecord.removeRecord(recordId)
const msg = `记录删除成功 id -> ${recordId}` const msg = `记录删除成功 id -> ${recordId}`
uni.$logger.local.info(msg) uni.$logger.local.info(msg)
ws.send({ code: 200, msg }) ws.send({ code: 200, msg })
......
...@@ -18,7 +18,7 @@ export default class StorageWorker { ...@@ -18,7 +18,7 @@ export default class StorageWorker {
} }
let value = uni.$storage.get(key) let value = uni.$storage.get(key)
if (key == 'recordList') { if (key == 'recordList') {
value = await uni.$dbManager.getRecords() value = await uni.$dbRecord.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)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!