Commit acc4d200 by 前端

Merge branch 'SAAS+V5.6.4' into 'master'

上线合并

See merge request !70
2 parents 32f322be 0820532f
Showing 126 changed files with 2725 additions and 823 deletions
<!-- <!--
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-07 17:09:53 * @Date: 2024-04-07 17:09:53
* @LastEditors: 前端 qianduan01@didihu.com.cn * @LastEditors: limin
* @LastEditTime: 2025-01-14 11:27:04 * @LastEditTime: 2026-02-05 17:52:25
* @FilePath: \gl_tape\App.vue * @FilePath: \gl_tape\App.vue
* @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
--> -->
...@@ -11,6 +11,7 @@ const PATH = ['/pages/common/caseDetail'] ...@@ -11,6 +11,7 @@ const PATH = ['/pages/common/caseDetail']
const keepAlive = uni.requireNativePlugin('Ba-KeepAliveSuit') const keepAlive = uni.requireNativePlugin('Ba-KeepAliveSuit')
import { mapState } from 'vuex' import { mapState } from 'vuex'
import { Ws } from '@/ws/Ws.js' import { Ws } from '@/ws/Ws.js'
import { RecordSaveService, UploadService } from '@/utils/recordManager/index.js'
export default { export default {
computed: { computed: {
...mapState('audio', ['isEnd', 'isStart']) ...mapState('audio', ['isEnd', 'isStart'])
...@@ -58,6 +59,12 @@ export default { ...@@ -58,6 +59,12 @@ export default {
onShow: async function () { onShow: async function () {
this.$store.dispatch('setBackgroundState', false) this.$store.dispatch('setBackgroundState', false)
this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数 this.$store.dispatch('setActivityWindowPopCount', 1) //冷启动重置活动弹框次数
// 触发轮询开始事件,通知上传管理重新开始轮询
// UploadService.startPolling()
RecordSaveService.startPolling()
uni.onMemoryWarning(function () {
console.log('onMemoryWarningReceive')
})
// const systemInfo = await uni.$api.systemApi.getMockData(); // const systemInfo = await uni.$api.systemApi.getMockData();
// if (systemInfo.isCheckedUpdate) { // if (systemInfo.isCheckedUpdate) {
// checkUpdate(); // checkUpdate();
...@@ -73,9 +80,35 @@ export default { ...@@ -73,9 +80,35 @@ export default {
}, },
onError: function (e) { onError: function (e) {
try { try {
uni.$logger?.error({ msg: e.message || '捕获全局异常', extra: { error: typeof e == 'string' ? e : JSON.stringify(e) } }) const msg = typeof e === 'string' ? e : e.message || '捕获全局异常'
const stack = typeof e === 'object' ? e.stack || JSON.stringify(e) : ''
uni.$logger?.error({
msg: `[全局异常] ${msg}`,
extra: {
stack,
raw: e,
url: this.$route?.path || 'unknown'
}
})
} catch (error) {
console.error('日志上报失败:', error)
}
},
onUnhandledRejection: function (res) {
try {
const reason = res.reason
const msg = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : '未处理的 Promise 拒绝'
const stack = reason instanceof Error ? reason.stack : JSON.stringify(reason)
uni.$logger?.error({
msg: `[UnhandledRejection] ${msg}`,
extra: {
stack,
reason: reason,
url: this.$route?.path || 'unknown'
}
})
} catch (error) { } catch (error) {
console.log(error) console.error('Promise 异常上报失败:', error)
} }
} }
} }
......
...@@ -91,7 +91,8 @@ module.exports = { ...@@ -91,7 +91,8 @@ module.exports = {
*/ */
getEmployeeList(data) { getEmployeeList(data) {
return http.post({ return http.post({
method: 'dj.api.smartcarlife.employee.getByMerchantId', // method: 'dj.api.smartcarlife.employee.getByMerchantId',
method: 'dj.api.smartcarlife.employee.getByMerchantId.new',
projectName: 'boutique', projectName: 'boutique',
sceneList: [0], sceneList: [0],
...data ...data
......
...@@ -35,6 +35,7 @@ class Request { ...@@ -35,6 +35,7 @@ class Request {
title: '网络异常', title: '网络异常',
icon: 'none' icon: 'none'
}) })
uni.$logger.locale.error('网络异常')
reject('网络异常') reject('网络异常')
return return
} }
...@@ -59,44 +60,87 @@ class Request { ...@@ -59,44 +60,87 @@ class Request {
responseType: 'text', responseType: 'text',
timeout: timeout || 60000, timeout: timeout || 60000,
success(response) { success(response) {
/**业务代码 */ // /**业务代码 */
let { data, statusCode } = response // let { data, statusCode } = response
if (!data || statusCode != 200) { // if (!data || statusCode != 200) {
uni.hideLoading() // uni.hideLoading()
let errMsg = '' // let errMsg = ''
if (!data) errMsg = '获取数据失败,请重试。' // if (!data) errMsg = '获取数据失败,请重试。'
else errMsg = '服务器暂时不可用,请稍后再次尝试。' // else errMsg = '服务器暂时不可用,请稍后再次尝试。'
return reject(errMsg) // return reject(errMsg)
} // }
let { code, message } = data // let { code, message } = data
if (returnAll) { // if (returnAll) {
resolve(data) // resolve(data)
return // return
} // }
if (code == 20 || code == 21) { // if (code == 20 || code == 21) {
console.log(params.method) // console.log(params.method)
const pages = getCurrentPages(), // const pages = getCurrentPages(),
currentPage = pages[pages.length - 1] // currentPage = pages[pages.length - 1]
uni.hideLoading() // uni.hideLoading()
if (currentPage.route != 'pages/common/login') // if (currentPage.route != 'pages/common/login')
uni.reLaunch({ // uni.reLaunch({
url: '/pages/common/login' // url: '/pages/common/login'
}) // })
} else { // } else {
if (code == '0') { // if (code == '0') {
resolve(data.data) // resolve(data.data)
} else { // } else {
// uni.hideLoading()
// uni.showToast({
// title: message || '系统异常',
// icon: 'none'
// })
// }
// }
try {
/**业务代码 */
let { data, statusCode } = response
if (!data || statusCode != 200) {
uni.hideLoading() uni.hideLoading()
uni.showToast({ let errMsg = ''
title: message || '系统异常', if (!data) errMsg = '获取数据失败,请重试。'
icon: 'none' else errMsg = '服务器暂时不可用,请稍后再次尝试。'
}) uni.$logger.error(`${params.method}接口异常:${errMsg}`)
return reject(errMsg)
}
let { code, message } = data
if (returnAll) {
resolve(data)
return
}
if (code == 20 || code == 21) {
uni.$logger.local.info(`触发系统登出-> ${params.method}:${message || '系统异常'} code:${code}`)
const pages = getCurrentPages(),
currentPage = pages[pages.length - 1]
uni.hideLoading()
if (currentPage.route != 'pages/common/login')
uni.reLaunch({
url: '/pages/common/login'
})
} else {
if (code == '0') {
resolve(data.data)
} else {
uni.hideLoading()
uni.$logger.error(`${params.method}接口异常:${message || '系统异常'}`)
uni.showToast({
title: message || '系统异常',
icon: 'none'
})
reject(message || '系统异常')
}
} }
} catch (error) {
uni.$logger.error(`${params.method}处理异常:${error.message}`)
reject(error)
} }
}, },
fail(error) { fail(error) {
uni.hideLoading() uni.hideLoading()
console.error(`${params.method}接口异常:`, error) // console.error(`${params.method}接口异常:`, error)
uni.$logger.error(`${params.method}接口异常:${error.errMsg || error.message || JSON.stringify(error)}`)
uni.showToast({ uni.showToast({
title: typeof error == 'string' ? error : error.errMsg ? error.errMsg : JSON.stringify(error) || '系统异常', title: typeof error == 'string' ? error : error.errMsg ? error.errMsg : JSON.stringify(error) || '系统异常',
icon: 'error' icon: 'error'
......
...@@ -65,6 +65,11 @@ ...@@ -65,6 +65,11 @@
{{item.orderFinishFlag? '成交': '战败'}} {{item.orderFinishFlag? '成交': '战败'}}
</view> </view>
</template> </template>
<template v-else>
<view @click.stop="handleDelete(item)">
<uni-icons type="trash" :size="18" color="#999"></uni-icons>
</view>
</template>
<!-- <template v-else> <!-- <template v-else>
<view :class="[ <view :class="[
'status flex', 'status flex',
...@@ -239,7 +244,8 @@ export default { ...@@ -239,7 +244,8 @@ export default {
}, },
async getRecordNum () { async getRecordNum () {
let recordFailListAll = await uni.$dbManager.getRecords(); // let recordFailListAll = await uni.$dbManager.getRecords();
let recordFailListAll = await uni.$dbRecord.getCompletedRecords();
if (typeof recordFailListAll == 'string') { if (typeof recordFailListAll == 'string') {
recordFailListAll = JSON.parse(recordFailListAll || '[]') recordFailListAll = JSON.parse(recordFailListAll || '[]')
} }
...@@ -251,24 +257,34 @@ export default { ...@@ -251,24 +257,34 @@ export default {
}, },
async getPreRecordFail () { async getPreRecordFail () {
await this.getPreRecordNum() await this.getPreRecordNum()
this.list[0] = this.preRecordFailList.map(i => { // this.list[0] = this.preRecordFailList.map(i => {
// return Object.assign(i, {
// duration: 0,
// startTime: i.receptionStartTime && i.receptionStartTime.replace(/\//g, '.')
// })
// })
const list = this.preRecordFailList.map(i => {
return Object.assign(i, { return Object.assign(i, {
duration: 0, duration: 0,
startTime: i.receptionStartTime && i.receptionStartTime.replace(/\//g, '.') startTime: i.receptionStartTime && i.receptionStartTime.replace(/\//g, '.')
}) })
}) })
this.$set(this.list, 0, list)
this.isPrePage = true this.isPrePage = true
this.flag = true this.flag = true
this.nothing = this.preRecordFailList.length ? true : false this.nothing = this.preRecordFailList.length ? true : false
}, },
async getPreRecordNum () { async getPreRecordNum () {
const preRecordList = await this.recorder.getRecords() // const preRecordList = await this.recorder.getRecords()
const preRecordList = await uni.$dbRecord.getTempRecords();
this.preRecordFailList = preRecordList.reverse() this.preRecordFailList = preRecordList.reverse()
}, },
getRecordFail () { async getRecordFail () {
this.getRecordNum() await this.getRecordNum()
this.list[0] = this.recordFailList.map(i => { // this.list[0] = this.recordFailList.map(i => {
const list = this.recordFailList.map(i => {
return { return {
id: i.id,
receptionStatus: i.receptionStatus, receptionStatus: i.receptionStatus,
phoneNumber: i.phoneNumber, phoneNumber: i.phoneNumber,
salesName: i.salesName, salesName: i.salesName,
...@@ -279,6 +295,7 @@ export default { ...@@ -279,6 +295,7 @@ export default {
endTime: i.receptionEndTime.replace(/\//g, '.') endTime: i.receptionEndTime.replace(/\//g, '.')
} }
}) })
this.$set(this.list, 0, list)
this.flag = true this.flag = true
this.isPrePage = false this.isPrePage = false
this.nothing = this.recordFailList.length ? true : false this.nothing = this.recordFailList.length ? true : false
...@@ -292,7 +309,8 @@ export default { ...@@ -292,7 +309,8 @@ export default {
await uni.$isNetWork() await uni.$isNetWork()
} catch (error) { } catch (error) {
const recordSuccessList = JSON.parse(uni.$storage.get("recordSuccessList") || "{}") const recordSuccessList = JSON.parse(uni.$storage.get("recordSuccessList") || "{}")
this.list[0] = recordSuccessList[this.tabIndex] || [] // this.list[0] = recordSuccessList[this.tabIndex] || []
this.$set(this.list, 0, recordSuccessList[this.tabIndex] || [])
this.flag = true this.flag = true
return return
} }
...@@ -370,29 +388,35 @@ export default { ...@@ -370,29 +388,35 @@ export default {
if (index == 0) this.getRecordFail() if (index == 0) this.getRecordFail()
else this.getPreRecordFail() else this.getPreRecordFail()
}, },
// async submitRecord (val) {
// this.flag = false
// delete val.duration
// delete val.startTime
// const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
// if (val.recordUrlList.length > maxUploadNum) {
// const userInfo = uni.$storage.get('userInfo')
// const { customerName, phoneNumber, carModel, salesName } = val || {}
// const { name } = userInfo || {}
// uni.$logger.error({
// msg: `员工: ${name}, 客户: ${customerName}`,
// extra: {
// '手机号: ': phoneNumber,
// '姓名: ': customerName,
// '销售: ': salesName,
// '车型: ': carModel,
// '原因: ': '录音文件过长,数量' + val.recordUrlList.length
// }
// })
// }
// val.recordUrlList = val.recordUrlList.slice(0, maxUploadNum)
// await this.recorder.save(val)
// this.getRecordNum()
// await this.getPreRecordFail()
// },
async submitRecord (val) { async submitRecord (val) {
this.flag = false this.flag = false
delete val.duration const {duration,startTime,...record} = val
delete val.startTime await this.recorder.saveInternal(record)
const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
if (val.recordUrlList.length > maxUploadNum) {
const userInfo = uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = val || {}
const { name } = userInfo || {}
uni.$logger.error({
msg: `员工: ${name}, 客户: ${customerName}`,
extra: {
'手机号: ': phoneNumber,
'姓名: ': customerName,
'销售: ': salesName,
'车型: ': carModel,
'原因: ': '录音文件过长,数量' + val.recordUrlList.length
}
})
}
val.recordUrlList = val.recordUrlList.slice(0, maxUploadNum)
await this.recorder.save(val)
this.getRecordNum()
await this.getPreRecordFail() await this.getPreRecordFail()
}, },
searchReceptionList ({ item }, name) { searchReceptionList ({ item }, name) {
...@@ -400,8 +424,27 @@ export default { ...@@ -400,8 +424,27 @@ export default {
this[name] = item.value this[name] = item.value
this.resetData() this.resetData()
this.getReceptionList() this.getReceptionList()
} },
async handleDelete(item) {
uni.showModal({
title: '提示',
content: '确定要删除这条待提交记录吗?删除后将无法恢复。',
success: async (res) => {
if (res.confirm) {
try {
// 从数据库中删除记录
await this.recorder.deleteRecord(item)
// 刷新列表
await this.getPreRecordFail()
uni.showToast({ title: '删除成功', icon: 'success' })
} catch (error) {
uni.$logger.local.error('删除待提交记录失败:'+ error.message)
uni.showToast({ title: '删除失败', icon: 'none' })
}
}
}
})
},
} }
} }
</script> </script>
......
...@@ -23,7 +23,74 @@ export default { ...@@ -23,7 +23,74 @@ export default {
methods: { methods: {
async getList () { async getList () {
const params = this.params const params = this.params
const data = [{ name: '正常订单', value: '1' }, { name: '打折策略', value: '2' }, { name: '买赠策略', value: '3' }, { name: '冲量活动', value: '4' }, { name: '组合付款', value: '5' }] let flag = null
let hasStorage = !!(uni && uni.$storage && uni.$storage.get)
// 默认支持所有订单类型
let data = [
{ name: '正常订单', value: '1' },
{ name: '打折策略', value: '2' },
{ name: '买赠策略', value: '3' },
{ name: '冲量活动', value: '4' },
{ name: '组合付款', value: '5' }
]
// 基于门店配置控制是否只允许“正常订单”
try {
// 1)优先从本地缓存读取(CreateOrder / EquityCreateOrder 入口会写入)
if (hasStorage) {
const rawFlag = uni.$storage.get('createAllGoodsFlag')
if (rawFlag !== undefined && rawFlag !== null) {
flag = String(rawFlag)
}
}
// 2)本地没有时,实时调轻改/权益配置接口兜底一次(避免先打开弹窗再拿到配置的竞态)
if (flag === null) {
const userInfo = hasStorage ? uni.$storage.get('userInfo') : null
// merchantId 来源:userInfo > 父组件传入的 data(如 orderObj).merchantId > params.merchantId
const merchantId =
(userInfo && (userInfo.shopMerchantId || userInfo.merchantId)) ||
(this.data && this.data.merchantId) ||
(params && params.merchantId)
if (merchantId) {
// 轻改接口
if (uni?.$api?.boutiqueApi?.getShopMerchantPointConfig) {
try {
const res = await uni.$api.boutiqueApi.getShopMerchantPointConfig({ merchantId })
if (res && res.createAllGoodsFlag !== undefined && res.createAllGoodsFlag !== null) {
flag = String(res.createAllGoodsFlag)
uni.$storage.set('createAllGoodsFlag', res.createAllGoodsFlag)
}
} catch (err) {
console.warn('fetch createAllGoodsFlag failed in OrderTypePopup (boutique)', err)
}
}
// 若轻改未返回 createAllGoodsFlag,再试权益接口(同一弹窗可能用于权益页)
if (flag === null && uni?.$api?.equityApi?.getShopMerchantPointConfig) {
try {
const res = await uni.$api.equityApi.getShopMerchantPointConfig({ merchantId })
if (res && res.createAllGoodsFlag !== undefined && res.createAllGoodsFlag !== null) {
flag = String(res.createAllGoodsFlag)
uni.$storage.set('createAllGoodsFlag', res.createAllGoodsFlag)
}
} catch (err) {
console.warn('fetch createAllGoodsFlag failed in OrderTypePopup (equity)', err)
}
}
}
}
// 3)有 flag 且不为 1 时,只允许“正常订单”
if (flag !== null && flag !== '1') {
data = [{ name: '正常订单', value: '1' }]
}
} catch (e) {
// 读取失败时不影响默认行为
console.warn('read createAllGoodsFlag failed', e)
}
// 打开弹窗时输出:当前 createAllGoodsFlag 值、本次展示的订单类型
console.log('[OrderTypePopup] createAllGoodsFlag:', flag, '| 订单类型:', (data || []).map(i => i.name).join('、'))
this.updateParams(params, data || []) this.updateParams(params, data || [])
}, },
initData (list) { initData (list) {
......
...@@ -129,13 +129,24 @@ export default { ...@@ -129,13 +129,24 @@ export default {
border-radius: toRpx(16); border-radius: toRpx(16);
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
transition: all 0.05s;
overflow: hidden; overflow: hidden;
opacity: 0;
position: relative; position: relative;
background: rgba(255, 255, 255, 0.6); background: rgba(255, 255, 255, 0.95); // 增加不透明度,提升质感
visibility: hidden; backdrop-filter: blur(10px); // 添加毛玻璃效果,更高级
height: 0;
// 初始状态
max-height: 0;
opacity: 0;
transform: translateY(-20rpx) scale(0.95); // 稍微上移并缩小,制造弹出感
transform-origin: top center;
// 优化动画曲线:更干脆利落 (cubic-bezier)
// 缩短时间:0.4s -> 0.3s,更跟手不拖沓
transition:
max-height 0.3s cubic-bezier(0.215, 0.61, 0.355, 1),
opacity 0.2s linear,
transform 0.3s cubic-bezier(0.215, 0.61, 0.355, 1);
&::after { &::after {
position: absolute; position: absolute;
content: ''; content: '';
...@@ -144,9 +155,10 @@ export default { ...@@ -144,9 +155,10 @@ export default {
left: 0; left: 0;
right: 0; right: 0;
bottom: 0; bottom: 0;
filter: blur(toRpx(8)); // filter: blur(toRpx(8)); // 移除原来的模糊,改用 backdrop-filter
z-index: -1; z-index: -1;
} }
// ... 其他原有样式保持不变
.title { .title {
width: toRpx(120); width: toRpx(120);
height: toRpx(56); height: toRpx(56);
...@@ -161,6 +173,7 @@ export default { ...@@ -161,6 +173,7 @@ export default {
max-height: 60vh; max-height: 60vh;
overflow-y: auto; overflow-y: auto;
} }
// ... item 样式
.item { .item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
...@@ -183,21 +196,17 @@ export default { ...@@ -183,21 +196,17 @@ export default {
} }
.showList { .showList {
display: flex; display: flex;
// 展开状态:给予足够大的max-height
max-height: toRpx(1000); // 预估一个足够大的值,或者使用 100vh
opacity: 1; opacity: 1;
transform: translateY(0) scale(1); // 恢复原位原大小
padding-bottom: toRpx(16); padding-bottom: toRpx(16);
animation: scale-up-top-right 0.4s; // 移除之前的 animation
visibility: visible; // animation: scale-up-top-right 0.4s;
height: auto; // visibility: visible; // 不需要 visibility,因为 height 0 已经隐藏了内容
} // height: auto; // 使用 max-height 做动画
@keyframes scale-up-top-right {
0% {
transform: scale(0.5);
transform-origin: top right;
}
100% {
transform: scale(1);
transform-origin: top right;
}
} }
// 移除之前的 keyframes
// @keyframes scale-up-top-right { ... }
} }
</style> </style>
\ No newline at end of file \ No newline at end of file
...@@ -39,7 +39,7 @@ const secretKey = { ...@@ -39,7 +39,7 @@ const secretKey = {
const domain = { const domain = {
// ip: 'http://192.168.2.94:8558', // ip: 'http://192.168.2.94:8558',
// ip: 'http://192.168.2.3:8315', // ip: 'http://192.168.2.3:8315',
ip: 'http://192.168.1.122:8292', ip: 'http://192.168.1.76:8292',
/**登录: 192.168.2.3:8315 /**登录: 192.168.2.3:8315
商城: 192.168.2.3:8558 */ 商城: 192.168.2.3:8558 */
dev: 'https://scrm.dev.glsx.com.cn', dev: 'https://scrm.dev.glsx.com.cn',
...@@ -50,7 +50,7 @@ const domain = { ...@@ -50,7 +50,7 @@ const domain = {
const djDomain = { const djDomain = {
// ip: 'http://dj.dev.glsx.com.cn', // ip: 'http://dj.dev.glsx.com.cn',
ip: 'http://192.168.1.122:8292', ip: 'http://192.168.1.76:8292',
dev: 'http://dj.dev.glsx.com.cn', dev: 'http://dj.dev.glsx.com.cn',
beta: 'https://dj.beta.glsx.com.cn', //预发布 appid: wx9f91c1ec493eb425 beta: 'https://dj.beta.glsx.com.cn', //预发布 appid: wx9f91c1ec493eb425
uat: 'https://dj.test.glsx.com.cn', //测试 appid: wxe10067a63c1856ac uat: 'https://dj.test.glsx.com.cn', //测试 appid: wxe10067a63c1856ac
...@@ -164,6 +164,7 @@ const pathEnum = { ...@@ -164,6 +164,7 @@ const pathEnum = {
staffMiniprogram: '/rop-dj-staff-miniprogram/' staffMiniprogram: '/rop-dj-staff-miniprogram/'
} }
const CONFIG_ENV_MAP = { const CONFIG_ENV_MAP = {
0: 'ip',
1: 'develop', 1: 'develop',
2: 'test', 2: 'test',
3: 'production', 3: 'production',
......
...@@ -47,6 +47,14 @@ ...@@ -47,6 +47,14 @@
<script src="js/OSSUpLoader.js"></script> <script src="js/OSSUpLoader.js"></script>
<script> <script>
// document.addEventListener('UniAppJSBridgeReady', function(){ // document.addEventListener('UniAppJSBridgeReady', function(){
document.addEventListener('UniAppJSBridgeReady', function() {
// 主动告知宿主环境,Webview 已准备就绪
uni.postMessage({
data: {
action: 'webview_ready'
}
});
});
/** /**
* 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息 * 该函数用于接收来自 UniApp 的消息,它包含了文件上传所需的所有信息
* @param {string} accessKeyId - OSS 访问密钥 ID * @param {string} accessKeyId - OSS 访问密钥 ID
......
...@@ -122,17 +122,20 @@ class OSSUpLoader { ...@@ -122,17 +122,20 @@ class OSSUpLoader {
* @throws {Error} 如果文件路径转换失败,将抛出错误 * @throws {Error} 如果文件路径转换失败,将抛出错误
*/ */
_upload(fileName, file, callback) { _upload(fileName, file, callback) {
const partSize = this._getOptimalPartSize(file.size)
this.client this.client
.multipartUpload(this.ossFolder + fileName, file, { .multipartUpload(this.ossFolder + fileName, file, {
// 获取分片上传进度、断点和返回值。 // 获取分片上传进度、断点和返回值。
progress: (p, checkpoint, res) => { progress: (p, checkpoint, res) => {
this.currentCheckpoint = checkpoint
console.log(p) console.log(p)
this.currentCheckpoint = checkpoint
}, },
// 设置并发上传的分片数量。 // 设置并发上传的分片数量。
parallel: this.parallel, parallel: this.parallel,
//分片大小(kb) 最小为100kb 默认500kb //分片大小(kb) 最小为100kb 默认500kb
partSize: 1024 * this.partSize, // partSize: 1024 * this.partSize,
// 分片大小(bytes)
partSize: partSize,
timeout: this.timeout, timeout: this.timeout,
mime: this.mime mime: this.mime
}) })
...@@ -180,6 +183,41 @@ class OSSUpLoader { ...@@ -180,6 +183,41 @@ class OSSUpLoader {
}) })
} }
/**
* 根据文件大小计算最优分片大小
* 策略:文件越大,分片越大,以减少分片数量和请求开销
* @param {number} fileSize - 文件大小 (bytes)
* @returns {number} 分片大小 (bytes)
*/
_getOptimalPartSize(fileSize) {
const MB = 1024 * 1024
// 定义分片策略阶梯 (阈值 -> 分片大小)
// 注意:顺序从大到小排列,匹配即止
const strategies = [
// 优化后的分片策略 (平衡网络开销与失败重试成本)
// 1GB+: 10MB 分片 (约100+个请求,并发效率高)
{ threshold: 1 * 1024 * MB, size: 10 * MB },
// 100MB+: 5MB 分片 (20-200个请求,适中)
{ threshold: 100 * MB, size: 5 * MB },
// 50MB+: 2MB 分片 (25-50个请求)
{ threshold: 50 * MB, size: 2 * MB },
// 10MB+: 1MB 分片 (10-50个请求)
// 避免小文件分片过小导致 HTTP 握手开销占比过高
{ threshold: 10 * MB, size: 1 * MB }
// <10MB: 使用默认 partSize (通常 1MB)
]
for (const { threshold, size } of strategies) {
if (fileSize > threshold) {
return size
}
}
// 默认回退到配置的基础大小
return this.partSize * 1024
}
/** /**
* 将文件路径转换为可下载的文件对象 * 将文件路径转换为可下载的文件对象
* *
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* @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: 2026-02-10 11:04:43
* @FilePath: \gl_tape\init.js * @FilePath: \gl_tape\init.js
*/ */
import { DBRecord } from './utils/recordManager/index' import { DBRecord } from './utils/recordManager/index'
...@@ -30,8 +30,8 @@ uni.$throttle = utils.throttle ...@@ -30,8 +30,8 @@ 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 DBRecord()
uni.$dbManager = new DBManager() // uni.$dbManager = new DBManager()
uni.$track = new Track() uni.$track = new Track()
console.log('init.js', HOST['eva']) console.log('init.js', HOST['eva'])
uni.signHttpConfig = { uni.signHttpConfig = {
...@@ -44,6 +44,10 @@ uni.signHttpConfig = { ...@@ -44,6 +44,10 @@ uni.signHttpConfig = {
sessionParamName: 'sessionId', sessionParamName: 'sessionId',
sessionId: _ => uni.$storage?.get('sessionId') sessionId: _ => uni.$storage?.get('sessionId')
}, },
sentry: {
enable: true, // 是否启用Sentry错误上报
dsn: 'https://cce6491788ff4b8899d8f912e6982a96@sentry.glsx.com.cn/42'
},
response: { response: {
code_key: 'code', code_key: 'code',
code_success_value: '0', code_success_value: '0',
...@@ -92,7 +96,24 @@ uni.signHttpConfig = { ...@@ -92,7 +96,24 @@ uni.signHttpConfig = {
} }
} }
!(async _ => { // !(async _ => {
await uni.$dbManager.init() // await uni.$dbManager.init()
await uni.$dbTempRecord.init() // await uni.$dbTempRecord.init()
})() // })()
if (!uni.$dbRecord) {
uni.$dbRecord = new DBRecord()
}
// 导出数据库初始化 Promise,供其他模块等待
if (!uni.$dbReady) {
uni.$dbReady = (async _ => {
try {
await uni.$dbRecord.init()
// await uni.$dbTempRecord.init() // 已废弃
uni.$logger.local.info('数据库初始化完成')
return true
} catch (e) {
uni.$logger.local.error('数据库初始化失败: ' + e.message)
return false
}
})()
}
import TaskQueue from '../utils/TaskQueue'
import { PathUtils } from '../utils/recordManager/index'
class SQLite { class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
constructor(name, version, description, size) { constructor(name, version, description, size) {
this.name = name this.name = name
this.version = version || '1.0' this.version = version || '1.0'
this.description = description || 'SQLite DB' this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null this.db = null
//注意:
this.dbPath = null // 存储数据库的完整路径
// 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
}
} }
init() { _enqueue(task) {
return new Promise((resolve, reject) => { // 使用共享的队列实例
plus.sqlite.openDatabase({ const queueInstance = SQLite._queues[this.name]
name: this.name, // 数据库名称 return queueInstance.enqueue(task)
path: `_doc/${this.name}.db`, // 数据库地址
success: resolve, // 直接使用 resolve
fail: reject // 直接使用 reject
})
})
} }
selectSql(sql) { async init() {
// 如果已经有路径,直接使用
if (this.dbPath) {
uni.$logger?.local?.info(`[SQLite] 使用已有路径: ${this.dbPath}`)
return this.openDatabase()
}
// 获取当前文档目录路径
const rootPath = await PathUtils.getFilePath()
this.dbPath = `${rootPath}${this.name}.db`
uni.$logger?.local?.info(`[SQLite] 数据库路径已确定: ${this.dbPath}`)
return this.openDatabase()
}
/**
* 打开数据库
*/
openDatabase() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.$logger.local.info(`执行SQL语句: ${sql}`) uni.$logger?.local?.info(`[SQLite] 尝试打开数据库: path=${this.dbPath}`)
plus.sqlite.selectSql({ const isOpen = this.isOpen()
if (isOpen) {
uni.$logger?.local?.info(`[SQLite] 数据库已打开,跳过重复打开`)
resolve(true)
return
}
plus.sqlite.openDatabase({
name: this.name, name: this.name,
sql, path: this.dbPath,
success: result => { success: e => {
// 处理查询结果,尝试还原数组或对象字符串 uni.$logger?.local?.info(`[SQLite] ✅ 数据库打开成功`)
const processedRows = result.map(row => resolve(e)
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
try {
// 尝试将字符串解析为对象或数组
return [key, JSON.parse(value)]
} catch {
// 如果解析失败,保留原始值
return [key, value]
}
})
)
)
resolve(processedRows)
}, },
fail: reject fail: e => {
// 处理 -1402 错误 (Same Name Already Open),视为成功
if (e.code === -1402) {
uni.$logger?.local?.warn(`[SQLite] ⚠️ 数据库已打开 (Code -1402), 视为成功: ${this.name}`)
resolve(e)
return
}
uni.$logger?.local?.error(`[SQLite] ❌ 数据库打开失败: ${JSON.stringify(e)}`)
reject(e)
}
}) })
}) })
} }
selectSql(sql) {
return this._enqueue(
() =>
new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({
name: this.name,
sql,
success: result => {
// 处理查询结果,尝试还原数组或对象字符串
const processedRows = result.map(row =>
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
// 优化:仅当 value 是字符串且以 { 或 [ 开头时才尝试解析
// 避免将普通数字字符串(如 "123")误解析为 Number 导致精度丢失
if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
try {
return [key, JSON.parse(value)]
} catch {
return [key, value]
}
}
return [key, value]
})
)
)
resolve(processedRows)
},
fail: reject
})
})
)
}
executeSql(sql) { executeSql(sql) {
return new Promise((resolve, reject) => { return this._enqueue(
uni.$logger.local.info(`执行SQL语句: ${sql}`) () =>
plus.sqlite.executeSql({ new Promise((resolve, reject) => {
name: this.name, uni.$logger.local.warn(`执行SQL语句: ${sql}`)
sql, plus.sqlite.executeSql({
success: resolve, name: this.name,
fail: reject sql,
}) success: resolve,
}) fail: reject
})
})
)
} }
async isTableExists(tableName) { async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'` const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
...@@ -141,7 +201,7 @@ class SQLite { ...@@ -141,7 +201,7 @@ class SQLite {
isOpen() { isOpen() {
let isopen = plus.sqlite.isOpenDatabase({ let isopen = plus.sqlite.isOpenDatabase({
name: this.name, name: this.name,
path: `_doc/${this.name}.db` path: this.dbPath
}) })
return isopen return isopen
} }
...@@ -153,13 +213,20 @@ class SQLite { ...@@ -153,13 +213,20 @@ class SQLite {
} }
} }
drop(tabName) { drop(tabName) {
const sql = `DROP TABLE ${tabName}` const sql = `DROP TABLE IF EXISTS ${tabName}`
return this.executeSql(sql) return this.executeSql(sql)
} }
formatValue(value) { formatValue(value) {
return typeof value === 'object' && value !== null ? `'${JSON.stringify(value)}'` : `'${value}'` let strVal = ''
if (typeof value === 'object' && value !== null) {
strVal = JSON.stringify(value)
} else {
strVal = String(value)
}
// SQL 中转义单引号的方法是将 ' 替换为 ''
return `'${strVal.replace(/'/g, "''")}'`
} }
/** /**
* 检查指定字段是否存在于表中 * 检查指定字段是否存在于表中
* @param {string} tableName - 表名 * @param {string} tableName - 表名
...@@ -175,7 +242,7 @@ class SQLite { ...@@ -175,7 +242,7 @@ class SQLite {
throw new Error(error.message) throw new Error(error.message)
} }
} }
/** /**
* 批量添加字段到表中 * 批量添加字段到表中
* @param {string} tableName - 表名 * @param {string} tableName - 表名
......
{ {
"name": "展业助手", "name" : "展业助手",
"appid": "__UNI__D3BD3DF", "appid" : "__UNI__D3BD3DF",
"description": "", "description" : "",
"versionName": "2.21.2", "versionName" : "2.22.1",
"versionCode": 2212, "versionCode" : 2221,
"transformPx": false, "transformPx" : false,
"sassImplementationName": "node-sass", "sassImplementationName" : "node-sass",
/* 5+App特有相关 */ /* 5+App特有相关 */
"app-plus": { "app-plus" : {
"cache": false, "cache" : false,
"bounce": "none", "bounce" : "none",
"usingComponents": true, "usingComponents" : true,
"nvueStyleCompiler": "uni-app", "nvueStyleCompiler" : "uni-app",
"compilerVersion": 3, "compilerVersion" : 3,
"compatible": { "compatible" : {
"ignoreVersion": true "ignoreVersion" : true
},
"screenOrientation" : "landscape",
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
},
/* 模块配置 */
"modules" : {
"Camera" : {},
"Record" : {},
"VideoPlayer" : {},
"AudioPlayer" : {},
"SQLite" : {},
"Maps" : {},
"Geolocation" : {}
},
/* 应用发布信息 */
"distribute" : {
/* android打包配置 */
"android" : {
"permissions" : [
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.INTERNET\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>"
],
"abiFilters" : [ "armeabi-v7a", "arm64-v8a", "x86" ],
"targetSdkVersion" : 30,
"minSdkVersion" : 21,
"excludePermissions" : [
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>"
]
},
/* ios打包配置 */
"ios" : {
"dSYMs" : false,
"UIBackgroundModes" : "audio"
},
/* SDK配置 */
"sdkConfigs" : {
"ad" : {},
"speech" : {},
"geolocation" : {
"baidu" : {
"__platform__" : [ "android" ],
"appkey_ios" : "",
"appkey_android" : "rfN7u5gCi0KyCGIWWBYGXlmKrVQsKH8z"
}
},
"maps" : {}
},
"icons" : {
"android" : {
"hdpi" : "static/72.png",
"xhdpi" : "static/96.png",
"xxhdpi" : "static/144.png"
}
}
},
"nativePlugins" : {
"Ba-KeepAliveSuit" : {
"__plugin_info__" : {
"name" : "安卓保活套装(通用、常驻通知、电池优化、自启管理、后台运行等)",
"description" : "在Ba-KeepAlive的基础上,新增了忽略电池优化、自启管理、常驻通知。为定位、推送、websocket、定时任务、蓝牙、聊天等保驾护航(**注意:**不保证支持所有机型和场景,建议先试用再购买)",
"platforms" : "Android",
"url" : "https://ext.dcloud.net.cn/plugin?id=11765",
"android_package_name" : "uni.gltap",
"ios_bundle_id" : "",
"isCloud" : true,
"bought" : 1,
"pid" : "11765",
"parameters" : {}
}
}
}
},
/* 快应用特有相关 */
"quickapp" : {},
/* 小程序特有相关 */
"mp-weixin" : {
"appid" : "wx79d1ff39bee3d047",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true
}, },
"screenOrientation": "landscape", "mp-alipay" : {
"splashscreen": { "usingComponents" : true
"alwaysShowBeforeRender": true,
"waiting": true,
"autoclose": true,
"delay": 0
}, },
/* 模块配置 */ "mp-baidu" : {
"modules": { "usingComponents" : true
"Camera": {},
"Record": {},
"VideoPlayer": {},
"AudioPlayer": {},
"SQLite": {},
"Maps": {},
"Geolocation": {}
}, },
/* 应用发布信息 */ "mp-toutiao" : {
"distribute": { "usingComponents" : true
/* android打包配置 */
"android": {
"permissions": [
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.INTERNET\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.RECORD_AUDIO\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>"
],
"abiFilters": ["armeabi-v7a", "arm64-v8a", "x86"],
"targetSdkVersion": 30,
"minSdkVersion": 21,
"excludePermissions": ["<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>"]
},
/* ios打包配置 */
"ios": {
"dSYMs": false,
"UIBackgroundModes": "audio"
},
/* SDK配置 */
"sdkConfigs": {
"ad": {},
"speech": {},
"geolocation": {
"baidu": {
"__platform__": ["android"],
"appkey_ios": "",
"appkey_android": "rfN7u5gCi0KyCGIWWBYGXlmKrVQsKH8z"
}
},
"maps": {}
},
"icons": {
"android": {
"hdpi": "static/72.png",
"xhdpi": "static/96.png",
"xxhdpi": "static/144.png"
}
}
}, },
"nativePlugins": { "uniStatistics" : {
"Ba-KeepAliveSuit": { "enable" : false
"__plugin_info__": {
"name": "安卓保活套装(通用、常驻通知、电池优化、自启管理、后台运行等)",
"description": "在Ba-KeepAlive的基础上,新增了忽略电池优化、自启管理、常驻通知。为定位、推送、websocket、定时任务、蓝牙、聊天等保驾护航(**注意:**不保证支持所有机型和场景,建议先试用再购买)",
"platforms": "Android",
"url": "https://ext.dcloud.net.cn/plugin?id=11765",
"android_package_name": "uni.gltap",
"ios_bundle_id": "",
"isCloud": true,
"bought": 1,
"pid": "11765",
"parameters": {}
}
}
}
},
/* 快应用特有相关 */
"quickapp": {},
/* 小程序特有相关 */
"mp-weixin": {
"appid": "wx79d1ff39bee3d047",
"setting": {
"urlCheck": false
}, },
"usingComponents": true "vueVersion" : "2",
}, "h5" : {
"mp-alipay": { "devServer" : {
"usingComponents": true "port" : 8080,
}, "https" : false
"mp-baidu": { }
"usingComponents": true
},
"mp-toutiao": {
"usingComponents": true
},
"uniStatistics": {
"enable": false
},
"vueVersion": "2",
"h5": {
"devServer": {
"port": 8080,
"https": false
} }
}
} }
...@@ -51,10 +51,10 @@ export default { ...@@ -51,10 +51,10 @@ export default {
cancelColor: '#292D33', cancelColor: '#292D33',
confirmText: modalInfo.confirmText, confirmText: modalInfo.confirmText,
confirmColor: '#347BFF', confirmColor: '#347BFF',
success: function (res) { success: (res) => {
// wx.__HAS_SHOW_MODAL = false; // wx.__HAS_SHOW_MODAL = false;
// if (res.cancel) _this.showNextModal(); // if (res.cancel) _this.showNextModal();
if (res.cancel) showNextModal() if (res.cancel) this.showNextModal()
modalInfo.eventCallback(res) modalInfo.eventCallback(res)
} }
}) })
......
...@@ -8,7 +8,8 @@ export default { ...@@ -8,7 +8,8 @@ export default {
let { useCarConfig, moduleList, media } = this, let { useCarConfig, moduleList, media } = this,
array = useCarConfig ? moduleList : media array = useCarConfig ? moduleList : media
let item = array.find(e => e.id == key), let item = array.find(e => e.id == key),
value = this.receptionTrack[key] // value = this.receptionTrack[key]
value = this.receptionTrack[key] ? { ...this.receptionTrack[key] } : null
if (value) { if (value) {
value.openCount += 1 value.openCount += 1
value.entryTime = Date.now() value.entryTime = Date.now()
...@@ -37,9 +38,14 @@ export default { ...@@ -37,9 +38,14 @@ export default {
receptionTrackLeave (keyName = 'id') { receptionTrackLeave (keyName = 'id') {
if (this.type == 'preview') return if (this.type == 'preview') return
let key = this[keyName], let key = this[keyName],
value = this.receptionTrack[key] // value = this.receptionTrack[key]
value.stayDuration += Number(Date.now() - value.entryTime) // value.stayDuration += Number(Date.now() - value.entryTime)
this.$store.dispatch("setReceptionTrack", { key, value }) // this.$store.dispatch("setReceptionTrack", { key, value })
value = this.receptionTrack[key] ? { ...this.receptionTrack[key] } : null
if (value) {
value.stayDuration += Number(Date.now() - value.entryTime)
this.$store.dispatch("setReceptionTrack", { key, value })
}
if (keyName == 'id' && key == 1) { //轻改才会触发 if (keyName == 'id' && key == 1) { //轻改才会触发
let [receptionRef] = this.$refs.media1 let [receptionRef] = this.$refs.media1
receptionRef.previewLeave && receptionRef.previewLeave(receptionRef.currentItem) receptionRef.previewLeave && receptionRef.previewLeave(receptionRef.currentItem)
......
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54
* @LastEditors: limin
* @LastEditTime: 2025-08-12 10:32:25
* @FilePath: \gl_tape\mixin\record\recorder.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { AudioManager, TempRecord, RecordDto, helpler } from '../../utils/recordManager/index'
import { mapMutations, mapState, mapGetters } from 'vuex'
import utils from '@/utils/utils.js'
import { storageApi } from '@/utils/cache'
import permision from '@/js_sdk/wa-permission/permission.js'
export default {
provide() {
return {
getRecorder: () => this.record
}
},
async mounted() {
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onError)
this.initDto()
this.record = new TempRecord(this.tempRecord, this.triggleTempNumber)
this.triggleTempNumber()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
// customerInfo: {
// handler(val) {
// this.handler(val, this.updateCustomerInfo)
// },
// deep: true
// },
customerKey: {
handler() {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
deep: true
},
booksList: {
handler(val) {
this.handler(val, this.updateBookList)
}
},
receptionStatus: {
handler(val) {
this.handler(val, this.updateReceptionStatus)
}
},
receptionKey: {
handler(val) {
this.handler(this.receptionTrack, this.updateMaterialPointList)
}
}
},
computed: {
...mapState(['user.customerInfo']),
...mapGetters(['customerInfo', 'receptionStatus', 'booksList', 'receptionTrack', 'receptionKey', 'customerKey'])
},
methods: {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setPerRecordNumber']),
...mapMutations(['clearCustomerInfo']),
//开始录音
startAudio: utils.throttle(async function (isInitData = true) {
const isPermission = await this.checkBeforeStart()
if (!isPermission) return
uni.$logger.local.info('〖接待管理Recorder〗 == 开始接待 ')
isInitData && this.initReception()
this.initTime()
this.audioManager.start()
}, 300),
initReception() {
this.setBooks([])
this.clearCustomerInfo()
this.setReceptionStatus('')
},
async onAudioStart() {
if (this.audioManager.counter === 0) {
await this.record.add()
} else {
this.record.addAudio()
}
},
async onAudioStop() {
if (this.audioManager.isRecording) {
uni.$logger.local.info('〖接待管理Recorder〗 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.info('〖接待管理Recorder〗 == 断开录音! ')
}
},
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
},
/**
* 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void}
*/
async stopAudio(isNotSave = false) {
uni.$logger.local.info('〖接待管理Recorder〗 == 结束接待! ')
this.stop()
await this.saveAndClearRecord(isNotSave)
},
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
uni.$logger.local.info('〖接待管理Recorder〗 == 不保存记录! ')
this.record.clearSavedFiles()
this.record.clearLocalRecord()
return
}
this.record.setReceptionEndTime() //设置接待结束时间
//如果不需要保存记录
await this.record.save()
},
stop() {
this.endWatchClick()
this.record.clearLoopTimer()
if (this.audioManager.isRecording) {
this.audioManager.stop()
}
},
handler(params, fn) {
if (this.audioManager.isRecording || this.record?.currentRecord?.endReasonType == 1) {
fn.call(this, params)
}
},
reset() {
this.audioManager = null
this.record = null
this.tempRecord = null
},
initDto() {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo()
const { deviceId: appCode } = uni.getDeviceInfo()
const dto = new RecordDto({
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
endReasonType: 0, //原因 1.异常 0.正常
loginPhone: phone,
appCode,
merchantId: shopMerchantId,
merchantName,
bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType: channelType || 1 //1问界 2 比亚迪 3 其他
})
this.sceneType = sceneType
this.tempRecord = dto
},
updateCustomerInfo(customerInfo = {}) {
const { customerName, phoneNumber, salesUuid, carModel, staffName: salesName, carBrand, carBrandId, oneCarBrand, oneCarBrandId } = customerInfo
this.record.updatePreRecords({
customerName,
phoneNumber,
carModel,
salesUuid,
salesName,
carBrand,
carBrandId,
oneCarBrand,
oneCarBrandId
})
},
updateBookList(booksList) {
const receptionCustomerPaySourceList = booksList.map(item => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl
}
})
this.record.updatePreRecords({ receptionCustomerPaySourceList })
},
updateMaterialPointList(receptionTrack) {
const { merchantId, staffUuid, staffName } = this.tempRecord
let receptionCustomerMaterialPointList = []
Object.keys(receptionTrack).map(key => {
receptionCustomerMaterialPointList.push({
...receptionTrack[key],
merchantId,
staffUuid,
staffName,
businessScene: this.sceneType
})
})
this.record.updatePreRecords({ receptionCustomerMaterialPointList })
},
updateReceptionStatus(status) {
this.record.updatePreRecords({ receptionStatus: status })
},
getRecorder() {
return this.record
},
async triggleTempNumber() {
const _records = await this.record.getRecords()
this.setPerRecordNumber(_records.length)
},
async isPermission(hintText = '为了记录语音通话,请打开录音权限') {
const result = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
await helpler.sleep(0)
if (result !== 1) {
uni.showToast({
title: hintText,
icon: 'none'
})
}
return result === 1
},
async checkBeforeStart() {
const isPermission = await this.isPermission()
const isRecording = this.audioManager.isRecording
return isPermission && !isRecording
}
},
beforeDestroy() {
this.stop()
this.reset()
}
}
...@@ -2,224 +2,44 @@ ...@@ -2,224 +2,44 @@
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-12-26 10:03:54 * @Date: 2024-12-26 10:03:54
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-08-12 10:32:25 * @LastEditTime: 2026-01-21 19:07:13
* @FilePath: \gl_tape\mixin\record\recorder.js * @FilePath: \gl_tape\mixin\record\recorder.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
*/ */
import { AudioManager, TempRecord, RecordDto, helpler } from '../../utils/recordManager/index' import RecordService from '../../utils/recordManager/RecordService'
import { mapMutations, mapState, mapGetters } from 'vuex' import { mapMutations, mapState, mapGetters } from 'vuex'
import utils from '@/utils/utils.js'
import { storageApi } from '@/utils/cache'
import permision from '@/js_sdk/wa-permission/permission.js'
export default { export default {
provide() { provide() {
return { return {
getRecorder: () => this.record getRecorder: () => this.recordService?.getRecorder()
} }
}, },
async mounted() { data() {
this.audioManager = new AudioManager(this.onAudioStart, this.onAudioStop, this.onError) return {
this.initDto() recordService: null
this.record = new TempRecord(this.tempRecord, this.triggleTempNumber)
this.triggleTempNumber()
},
watch: {
/**
* 监听客户信息是否发生变化
* @param {object} val 监听客户信息
*/
// customerInfo: {
// handler(val) {
// this.handler(val, this.updateCustomerInfo)
// },
// deep: true
// },
customerKey: {
handler() {
this.handler(this.customerInfo, this.updateCustomerInfo)
},
deep: true
},
booksList: {
handler(val) {
this.handler(val, this.updateBookList)
}
},
receptionStatus: {
handler(val) {
this.handler(val, this.updateReceptionStatus)
}
},
receptionKey: {
handler(val) {
this.handler(this.receptionTrack, this.updateMaterialPointList)
}
} }
}, },
computed: { async mounted() {
...mapState(['user.customerInfo']), // 获取 RecordService 单例 (已在构造函数中自动初始化)
...mapGetters(['customerInfo', 'receptionStatus', 'booksList', 'receptionTrack', 'receptionKey', 'customerKey']) this.recordService = RecordService.getInstance()
}, },
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus', 'setBooks', 'setPerRecordNumber']), ...mapMutations('audio', ['setReceptionStatus', 'setBooks']),
...mapMutations(['clearCustomerInfo']),
//开始录音 //开始录音
startAudio: utils.throttle(async function (isInitData = true) { async startAudio(isInitData = true) {
const isPermission = await this.checkBeforeStart() return this.recordService.startAudio(isInitData)
if (!isPermission) return
uni.$logger.local.info('〖接待管理Recorder〗 == 开始接待 ')
isInitData && this.initReception()
this.initTime()
this.audioManager.start()
}, 300),
initReception() {
this.setBooks([])
this.clearCustomerInfo()
this.setReceptionStatus('')
},
async onAudioStart() {
if (this.audioManager.counter === 0) {
await this.record.add()
} else {
this.record.addAudio()
}
}, },
async onAudioStop() {
if (this.audioManager.isRecording) { //结束接待
uni.$logger.local.info('〖接待管理Recorder〗 == 接待中,再次开启录音! ')
this.audioManager.start()
} else {
uni.$logger.local.info('〖接待管理Recorder〗 == 断开录音! ')
}
},
onAudioError(error) {
const message = error.message
this.reportError(`录音异常: error: ${message}`, message)
},
/**
* 结束接待
* @params {boolean} status true 不保存记录/AUDIO_STATUS.ABNORMAL 只要断开录音
* @returns {void}
*/
async stopAudio(isNotSave = false) { async stopAudio(isNotSave = false) {
uni.$logger.local.info('〖接待管理Recorder〗 == 结束接待! ') return this.recordService.stopAudio(isNotSave)
this.stop()
await this.saveAndClearRecord(isNotSave)
},
async saveAndClearRecord(isNotSave = false) {
if (isNotSave) {
uni.$logger.local.info('〖接待管理Recorder〗 == 不保存记录! ')
this.record.clearSavedFiles()
this.record.clearLocalRecord()
return
}
this.record.setReceptionEndTime() //设置接待结束时间
//如果不需要保存记录
await this.record.save()
}, },
stop() { stop() {
this.endWatchClick() this.recordService.stop()
this.record.clearLoopTimer()
if (this.audioManager.isRecording) {
this.audioManager.stop()
}
},
handler(params, fn) {
if (this.audioManager.isRecording || this.record?.currentRecord?.endReasonType == 1) {
fn.call(this, params)
}
},
reset() {
this.audioManager = null
this.record = null
this.tempRecord = null
},
initDto() {
const { shopMerchantId, phone, sceneType, uuid, name, merchantId, channelType, merchantName } = storageApi.getUserInfo()
const { deviceId: appCode } = uni.getDeviceInfo()
const dto = new RecordDto({
staffUuid: uuid,
staffName: name,
serviceMerchantId: merchantId,
endReasonType: 0, //原因 1.异常 0.正常
loginPhone: phone,
appCode,
merchantId: shopMerchantId,
merchantName,
bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType: channelType || 1 //1问界 2 比亚迪 3 其他
})
this.sceneType = sceneType
this.tempRecord = dto
},
updateCustomerInfo(customerInfo = {}) {
const { customerName, phoneNumber, salesUuid, carModel, staffName: salesName, carBrand, carBrandId, oneCarBrand, oneCarBrandId } = customerInfo
this.record.updatePreRecords({
customerName,
phoneNumber,
carModel,
salesUuid,
salesName,
carBrand,
carBrandId,
oneCarBrand,
oneCarBrandId
})
},
updateBookList(booksList) {
const receptionCustomerPaySourceList = booksList.map(item => {
return {
id: item.id,
sourceType: item.id,
sourceUrl: item.imgUrl
}
})
this.record.updatePreRecords({ receptionCustomerPaySourceList })
}, },
updateMaterialPointList(receptionTrack) { // 代理权限检查
const { merchantId, staffUuid, staffName } = this.tempRecord async isPermission(hintText) {
let receptionCustomerMaterialPointList = [] return await this.recordService.isPermission(hintText)
Object.keys(receptionTrack).map(key => {
receptionCustomerMaterialPointList.push({
...receptionTrack[key],
merchantId,
staffUuid,
staffName,
businessScene: this.sceneType
})
})
this.record.updatePreRecords({ receptionCustomerMaterialPointList })
},
updateReceptionStatus(status) {
this.record.updatePreRecords({ receptionStatus: status })
},
getRecorder() {
return this.record
},
async triggleTempNumber() {
const _records = await this.record.getRecords()
this.setPerRecordNumber(_records.length)
},
async isPermission(hintText = '为了记录语音通话,请打开录音权限') {
const result = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
await helpler.sleep(0)
if (result !== 1) {
uni.showToast({
title: hintText,
icon: 'none'
})
}
return result === 1
},
async checkBeforeStart() {
const isPermission = await this.isPermission()
const isRecording = this.audioManager.isRecording
return isPermission && !isRecording
} }
},
beforeDestroy() {
this.stop()
this.reset()
} }
} }
/* /*
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 11:28:48 * @Date: 2024-04-08 11:28:48
* @LastEditors: yangming@didihu.com.cn yangming@didihu.com.cn * @LastEditors: limin
* @LastEditTime: 2025-05-21 15:17:55 * @LastEditTime: 2026-01-21 15:56:43
* @FilePath: \gl_tape\mixin\timeout.js * @FilePath: \gl_tape\mixin\timeout.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
const TIMER_DURATION = 40 * 60 * 1000 //40分钟 const TIMEOUT = 40 // 40分钟
const TIMER_INTERVAL = 1 * 60 * 1000 //1分钟检一次 const Miniute = 60 * 1000
const TIMER_TIMEOUT = TIMER_DURATION / TIMER_INTERVAL const TIMER_DURATION = TIMEOUT * Miniute
const CHECK_INTERVAL = 1 * Miniute // 1分钟检查一次
import utils from '@/utils/utils'
export default { export default {
data() {
return {
__timerId: null,
_lastActiveTime: 0
}
},
methods: { methods: {
//结束提示 // 结束提示
stopRecorder() { async stopRecorder() {
this.setReceptionStatus(0) this.setReceptionStatus(0)
this.record.withError() await this.recordService.getRecorder().withError()
this.stop() await this.stop()
uni.$logger.local.info('== 长时间未触碰平板断开录音 ==')
}, },
//监听点击事件 // 初始化或启动监听
initTime() { initTime() {
uni.$logger.local.info('== 触碰平板开始计时 ==') // 1. 无论是否已启动,先更新活跃时间
this.endWatchClick() this._lastActiveTime = Date.now()
this.__timer = setInterval(() => { // 2. 如果定时器已在运行,直接返回,避免重复创建
if (this.__counter >= TIMER_TIMEOUT) { // 这是相比原方案最大的优化:全周期只有一个 setInterval 实例
//关闭录音 if (this.__timerId) return
uni.$logger.local.info('== 长时间未触碰平板 == __timer:' + this.__timer + '__counter:' + this.__counter + '分钟') // 3. 启动周期性检查
this.endWatchClick() this.__watchStart()
this.stopRecorder() },
return
__watchStart() {
this.__timerId = setInterval(async () => {
const now = Date.now()
// 直接计算时间差,比维护 counter 计数器更准确、更简单
if (now - this._lastActiveTime >= TIMER_DURATION) {
await this.__watchStop()
if (!this.__timerId) uni.$logger.local.info(`== 检测到${ TIMEOUT }分钟闲置未操作,自动停止录音 ==`)
} }
this.__counter++ }, CHECK_INTERVAL)
uni.$logger.local.info('== 未触碰平板计时 ==' + this.__counter + '分钟' + '== __timer:' + this.__timer) if (this.__timerId) uni.$logger.local.info('== 开启闲置检测 ==')
}, TIMER_INTERVAL) },
async __watchStop() {
await this.stopRecorder()
this.endWatchClick()
}, },
// 停止监听
endWatchClick() { endWatchClick() {
if (this.__timer) { if (this.__timerId) {
clearInterval(this.__timer) clearInterval(this.__timerId)
this.__timer = null this.__timerId = null
this.__counter = 0
uni.$logger.local.info('== 停止监听未触碰平板事件 == __timer:' + this.__timer + ' __counter:' + this.__counter)
} }
this._lastActiveTime = null
uni.$logger.local.info('== 停止闲置检测 ==')
}, },
handleTouchStart() {
if (this.__counter > 0) { // 响应触摸事件
uni.$logger.local.info(`== ${this.__counter}分钟后触碰平板,重置计数器 == __timer:${this.__timer}`) // 使用 debounce 包装:在连续触摸过程中(如滑动屏幕)不更新,
} // 只有用户停止操作 1秒后,才更新一次时间戳
this.__counter = 0 handleTouchStart: utils.debounce(function() {
} this._lastActiveTime = Date.now()
}, 1500),
},
created() {
uni.$on('reset_timeout', this.handleTouchStart)
}, },
beforeDestroy() { beforeDestroy() {
if (this.__timer) { uni.$off('reset_timeout', this.handleTouchStart)
clearInterval(this.__timer) this.endWatchClick()
}
} }
} }
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<view :class="['popup-body', { 'has-ai': AIUrl }]"> <view :class="['popup-body', { 'has-ai': AIUrl }]">
<video ref="videoPlayer" :src="detailUrl" controls v-if="sourceType == 2"></video> <video ref="videoPlayer" :src="detailUrl" controls v-if="sourceType == 2"></video>
<view class="img-detail" v-else> <view class="img-detail" v-else>
<image @click="back" :src="detailUrl" mode="heightFix" /> <image @click="back" :src="imagePreviewUrl" mode="heightFix" />
</view> </view>
</view> </view>
<view class="AI-window" v-if="AIUrl"> <view class="AI-window" v-if="AIUrl">
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
</template> </template>
<script type="text/ecmascript-6"> <script type="text/ecmascript-6">
import { aiUrlMixin, report } from '@/mixin/index.js' import { aiUrlMixin, report } from '@/mixin/index.js'
import { getImageDisplayUrl } from '@/utils/ossImageProcess.js'
export default { export default {
mixins: [report, aiUrlMixin], mixins: [report, aiUrlMixin],
...@@ -53,6 +54,10 @@ export default { ...@@ -53,6 +54,10 @@ export default {
if (this.isComponents) status = this.show if (this.isComponents) status = this.show
return status return status
}, },
imagePreviewUrl () {
// 仅图片回显拼接 OSS 参数展示,视频保持原始 URL
return getImageDisplayUrl(this.detailUrl)
}
}, },
onLoad (options) { onLoad (options) {
this.init(options) this.init(options)
......
...@@ -286,32 +286,30 @@ export default { ...@@ -286,32 +286,30 @@ export default {
let warrantyCardList = [] let warrantyCardList = []
for (var i = 0; i < data?.subOrderList?.length; i++) { for (var i = 0; i < data?.subOrderList?.length; i++) {
let e = data?.subOrderList[i] let e = data?.subOrderList[i]
total_price += e.finalPrice total_price += Number(e.finalPrice) || 0
// 根据订单类型决定使用哪个价格: // 根据订单类型决定使用哪个价格:
// - 正常订单(1)和冲量活动(4):使用 totalPrice(原价) // - 正常订单(1)和冲量活动(4):使用 totalPrice(原价)
// - 打折策略(2)、买赠策略(3)、组合付款(5):使用 finalPrice(优惠后价格) // - 打折策略(2)、买赠策略(3)、组合付款(5):使用 finalPrice(优惠后价格)
const orderType = e.djOrderType || data.djOrderType const orderType = e.djOrderType || data.djOrderType
if (orderType === 1 || orderType === 4) { if (orderType === 1 || orderType === 4) {
// 正常订单或冲量活动,使用原价 // 正常订单或冲量活动,使用原价(向上取整保留2位小数)
if (e.totalPrice !== undefined && e.totalPrice !== null) { if (e.totalPrice !== undefined && e.totalPrice !== null) {
e.price = Number( e.price = utils.ceilDecimal(Number(e.totalPrice) / Number(e.number || 1)).toFixed(2)
utils.decimal(Number(e.totalPrice) / Number(e.number || 1), 2)
).toFixed(2)
} else if (e.finalPrice !== undefined && e.finalPrice !== null) { } else if (e.finalPrice !== undefined && e.finalPrice !== null) {
e.price = Number( e.price = utils.ceilDecimal(Number(e.finalPrice) / Number(e.number || 1)).toFixed(2)
utils.decimal(Number(e.finalPrice) / Number(e.number || 1), 2) } else {
).toFixed(2) // 当总价/单价为 0 或缺失时,显式展示为 0.00,避免前端显示为空
e.price = '0.00'
} }
} else { } else {
// 优惠类型订单,使用优惠后价格 // 优惠类型订单,使用优惠后价格(向上取整保留2位小数)
if (e.finalPrice !== undefined && e.finalPrice !== null) { if (e.finalPrice !== undefined && e.finalPrice !== null) {
e.price = Number( e.price = utils.ceilDecimal(Number(e.finalPrice) / Number(e.number || 1)).toFixed(2)
utils.decimal(Number(e.finalPrice) / Number(e.number || 1), 2)
).toFixed(2)
} else if (e.totalPrice !== undefined && e.totalPrice !== null) { } else if (e.totalPrice !== undefined && e.totalPrice !== null) {
e.price = Number( e.price = utils.ceilDecimal(Number(e.totalPrice) / Number(e.number || 1)).toFixed(2)
utils.decimal(Number(e.totalPrice) / Number(e.number || 1), 2) } else {
).toFixed(2) // 当总价/单价为 0 或缺失时,显式展示为 0.00,避免前端显示为空
e.price = '0.00'
} }
} }
e.positionStr = this.positionTypeList.filter(v => v.positionValue == e.upgradeGoodsPosition)[0]?.positionName || '' e.positionStr = this.positionTypeList.filter(v => v.positionValue == e.upgradeGoodsPosition)[0]?.positionName || ''
...@@ -326,51 +324,56 @@ export default { ...@@ -326,51 +324,56 @@ export default {
// 获取订单类型(优先使用套餐内商品的订单类型,否则使用订单级别的) // 获取订单类型(优先使用套餐内商品的订单类型,否则使用订单级别的)
const orderType = item.packageGoodsOrderList?.[0]?.djOrderType || data.djOrderType const orderType = item.packageGoodsOrderList?.[0]?.djOrderType || data.djOrderType
item.packageGoodsOrderList.forEach(g => { item.packageGoodsOrderList.forEach(g => {
// 根据订单类型决定使用哪个价格 // 根据订单类型决定使用哪个价格,并对商品单价向上取整保留两位小数
if (orderType === 1 || orderType === 4) { if (orderType === 1 || orderType === 4) {
// 正常订单或冲量活动,使用原价 // 正常订单或冲量活动,使用原价
if (g.totalPrice !== undefined && g.totalPrice !== null) { if (g.totalPrice !== undefined && g.totalPrice !== null) {
g.price = Number(g.totalPrice) / Number(g.number || 1) g.price = utils.ceilDecimal(Number(g.totalPrice) / Number(g.number || 1)).toFixed(2)
} else if (g.finalPrice !== undefined && g.finalPrice !== null) { } else if (g.finalPrice !== undefined && g.finalPrice !== null) {
g.price = Number(g.finalPrice) / Number(g.number || 1) g.price = utils.ceilDecimal(Number(g.finalPrice) / Number(g.number || 1)).toFixed(2)
} else { } else {
g.price = g.upgradePrice || 0 g.price = utils.ceilDecimal(g.upgradePrice || 0).toFixed(2)
} }
} else { } else {
// 优惠类型订单,使用优惠后价格 // 优惠类型订单,使用优惠后价格
if (g.finalPrice !== undefined && g.finalPrice !== null) { if (g.finalPrice !== undefined && g.finalPrice !== null) {
g.price = Number(g.finalPrice) / Number(g.number || 1) g.price = utils.ceilDecimal(Number(g.finalPrice) / Number(g.number || 1)).toFixed(2)
} else if (g.totalPrice !== undefined && g.totalPrice !== null) { } else if (g.totalPrice !== undefined && g.totalPrice !== null) {
g.price = Number(g.totalPrice) / Number(g.number || 1) g.price = utils.ceilDecimal(Number(g.totalPrice) / Number(g.number || 1)).toFixed(2)
} else { } else {
g.price = g.upgradePrice || 0 g.price = utils.ceilDecimal(g.upgradePrice || 0).toFixed(2)
} }
} }
}) })
item.goodsList = item.packageGoodsOrderList item.goodsList = item.packageGoodsOrderList
// 套餐价格根据订单类型计算 // 套餐价格根据订单类型计算(按单价先保留两位小数再汇总,避免浮点误差)
item.price = item.goodsList.reduce((prev, cur) => { item.price = item.goodsList.reduce((prev, cur) => {
// 根据订单类型决定使用哪个价格 // 根据订单类型决定使用哪个价格
const unitPrice = (orderType === 1 || orderType === 4) const unitPriceRaw =
? (cur.totalPrice !== undefined && cur.totalPrice !== null orderType === 1 || orderType === 4
? Number(cur.totalPrice) / Number(cur.number || 1) ? cur.totalPrice !== undefined && cur.totalPrice !== null
: (cur.finalPrice !== undefined && cur.finalPrice !== null
? Number(cur.finalPrice) / Number(cur.number || 1)
: cur.price || 0))
: (cur.finalPrice !== undefined && cur.finalPrice !== null
? Number(cur.finalPrice) / Number(cur.number || 1)
: (cur.totalPrice !== undefined && cur.totalPrice !== null
? Number(cur.totalPrice) / Number(cur.number || 1) ? Number(cur.totalPrice) / Number(cur.number || 1)
: cur.price || 0)) : cur.finalPrice !== undefined && cur.finalPrice !== null
? Number(cur.finalPrice) / Number(cur.number || 1)
: cur.price || 0
: cur.finalPrice !== undefined && cur.finalPrice !== null
? Number(cur.finalPrice) / Number(cur.number || 1)
: cur.totalPrice !== undefined && cur.totalPrice !== null
? Number(cur.totalPrice) / Number(cur.number || 1)
: cur.price || 0
const unitPrice = utils.decimal(unitPriceRaw, 2)
return prev + unitPrice return prev + unitPrice
}, 0) }, 0)
// 套餐单价本身也保留两位
item.price = Number(utils.decimal(item.price, 2)).toFixed(2)
item.count = item.goodsList.length ? item.goodsList[0].number : 1 item.count = item.goodsList.length ? item.goodsList[0].number : 1
let total = item.price * item.count const total = Number(item.price) * Number(item.count || 1)
item.finalPrice = utils.decimal(total, 2) // 套餐总价 / 最终价格统一保留两位小数
item.finalPrice = Number(utils.decimal(total, 2)).toFixed(2)
item.packageGoodsOrderList.forEach(g => { item.packageGoodsOrderList.forEach(g => {
g.positionStr = this.positionTypeList.filter(v => v.positionValue == g.upgradeGoodsPosition)[0]?.positionName || '' g.positionStr = this.positionTypeList.filter(v => v.positionValue == g.upgradeGoodsPosition)[0]?.positionName || ''
}) })
total_price += item.finalPrice total_price += Number(item.finalPrice) || 0
}) })
data = { data = {
...@@ -584,7 +587,7 @@ export default { ...@@ -584,7 +587,7 @@ export default {
if (data) { if (data) {
console.log(`类型为:${selectPayType}`) console.log(`类型为:${selectPayType}`)
console.log(this.orderInfo) console.log(this.orderInfo)
console.log(data,'data') console.log(data, 'data')
if (selectPayType == 3 || selectPayType == 1) { if (selectPayType == 3 || selectPayType == 1) {
// 确保 orderInfo 和 payOrder 对象存在,避免空指针错误 // 确保 orderInfo 和 payOrder 对象存在,避免空指针错误
if (!this.orderInfo) { if (!this.orderInfo) {
......
...@@ -345,7 +345,8 @@ export default { ...@@ -345,7 +345,8 @@ export default {
required: true, required: true,
min: 0, min: 0,
max: 100, max: 100,
inputPlaceholder: '' inputPlaceholder: '',
blurFun: 'handleIssueCouponCountBlur'
}, },
{ {
label: '本月待邀约', label: '本月待邀约',
...@@ -566,6 +567,9 @@ export default { ...@@ -566,6 +567,9 @@ export default {
brandType, brandType,
tabName tabName
} }
if (item.firstBrandId == -1) {
item.issueCouponCount = item.issueCouponCount != null ? item.issueCouponCount : item.recordIssueCouponCount || 0
}
} else { } else {
hwOhterObjArray.forEach(e => { hwOhterObjArray.forEach(e => {
item[e.key] = null item[e.key] = null
...@@ -582,7 +586,7 @@ export default { ...@@ -582,7 +586,7 @@ export default {
this.orderObj = { this.orderObj = {
...orderObj, ...orderObj,
reportDate: currentDate, reportDate: currentDate,
isDateWithin7Days:editableDay ? !disabledReport : diffDay < 7, isDateWithin7Days: editableDay ? !disabledReport : diffDay < 7,
remark, remark,
lastStaffName: data.lastStaffName, lastStaffName: data.lastStaffName,
lastStaffUuid: data.lastStaffUuid, lastStaffUuid: data.lastStaffUuid,
...@@ -658,7 +662,17 @@ export default { ...@@ -658,7 +662,17 @@ export default {
item[key] = '' item[key] = ''
this.dateKey[`${key}_${index}`] = Date.now() this.dateKey[`${key}_${index}`] = Date.now()
} }
console.log(item[key]) if (i.blurFun) this[i.blurFun](item, index)
},
handleIssueCouponCountBlur (item) {
if (item.issueCouponCount < item.recordIssueCouponCount) {
uni.showToast({
title: `填写的今日店端实际发券数不能小于实际发券数!当前实际发券数=${item.recordIssueCouponCount}`,
icon: 'none'
})
return true
}
return false
}, },
async submit () { async submit () {
uni.showLoading({ uni.showLoading({
...@@ -669,24 +683,29 @@ export default { ...@@ -669,24 +683,29 @@ export default {
eventCode: 'app_submit_daily_report' eventCode: 'app_submit_daily_report'
}) //提交驻店日报埋点 }) //提交驻店日报埋点
try { try {
let { orderObj, carBandList, hwOhterObjArray, defaultObjArray } = this let { orderObj, carBandList, hwOhterObjArray, defaultObjArray } = this,
couponFlag = false
orderObj.isAdmin = false orderObj.isAdmin = false
orderObj.oprBy = orderObj.staffUuid orderObj.oprBy = orderObj.staffUuid
orderObj.sceneType = 1 orderObj.sceneType = 1
orderObj.brandDataList = carBandList orderObj.brandDataList = carBandList
if (couponFlag) return
if (orderObj.pickerValue == 0) { if (orderObj.pickerValue == 0) {
if (['', null].includes(orderObj.staffCount)) throw { if (['', null].includes(orderObj.staffCount)) throw {
message: '今日驻店人数(按店)', message: '今日驻店人数(按店)',
refId: 'staffCount' refId: 'staffCount'
} }
carBandList.map((item, index) => { carBandList.map((item, index) => {
if (item.firstBrandId == -1) defaultObjArray.map(el => { if (item.firstBrandId == -1) {
if (el.required && ['', null].includes(item[el.key])) throw { defaultObjArray.map(el => {
message: `${item.tabName}${el.label}`, if (el.required && ['', null].includes(item[el.key])) throw {
refId: `${el.refId}_${index}`, message: `${item.tabName}${el.label}`,
tabIndex: index refId: `${el.refId}_${index}`,
} tabIndex: index
}) }
})
couponFlag = this.handleIssueCouponCountBlur(item)
}
else hwOhterObjArray.map(el => { else hwOhterObjArray.map(el => {
if (el.required && ['', null].includes(item[el.key])) throw { if (el.required && ['', null].includes(item[el.key])) throw {
message: `${item.tabName}${el.label}`, message: `${item.tabName}${el.label}`,
...@@ -696,6 +715,7 @@ export default { ...@@ -696,6 +715,7 @@ export default {
}) })
}) })
} }
if (couponFlag) return
if (orderObj.onBreak == 'Y') { if (orderObj.onBreak == 'Y') {
orderObj.brandDataList.forEach(item => { orderObj.brandDataList.forEach(item => {
item.notDeliveryCount = item.notDeliveryCount || 0 item.notDeliveryCount = item.notDeliveryCount || 0
......
...@@ -58,6 +58,7 @@ ...@@ -58,6 +58,7 @@
</template> </template>
<script> <script>
import utils from '@/utils/utils'
export default { export default {
name: 'OrderStrategy', name: 'OrderStrategy',
props: { props: {
...@@ -127,17 +128,17 @@ export default { ...@@ -127,17 +128,17 @@ export default {
// 折扣比例:0.1-10,表示 0.1 折到 10 折(即 0.01 到 1.0) // 折扣比例:0.1-10,表示 0.1 折到 10 折(即 0.01 到 1.0)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
const finalPrice = basePrice * (ratio / 10) const finalPrice = basePrice * (ratio / 10)
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} else if (this.localState.mode === 'amount' && this.localState.discountAmount) { } else if (this.localState.mode === 'amount' && this.localState.discountAmount) {
const discountAmount = parseFloat(this.localState.discountAmount) const discountAmount = parseFloat(this.localState.discountAmount)
// 折扣金额:0.01 到不能大于基础价格 // 折扣金额:0.01 到不能大于基础价格
if (discountAmount >= 0.01 && discountAmount <= basePrice) { if (discountAmount >= 0.01 && discountAmount <= basePrice) {
const finalPrice = basePrice - discountAmount const finalPrice = basePrice - discountAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
// 买赠策略 // 买赠策略
...@@ -145,7 +146,7 @@ export default { ...@@ -145,7 +146,7 @@ export default {
if (this.localState.isGift === '1') { if (this.localState.isGift === '1') {
return '¥0.00' return '¥0.00'
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
// 组合付款 // 组合付款
...@@ -155,13 +156,13 @@ export default { ...@@ -155,13 +156,13 @@ export default {
// 抵扣金额:0.01 到不能大于基础价格 // 抵扣金额:0.01 到不能大于基础价格
if (deductAmount >= 0.01 && deductAmount <= basePrice) { if (deductAmount >= 0.01 && deductAmount <= basePrice) {
const finalPrice = basePrice - deductAmount const finalPrice = basePrice - deductAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
}, },
watch: { watch: {
...@@ -254,15 +255,15 @@ export default { ...@@ -254,15 +255,15 @@ export default {
if (this.localState.mode === 'ratio' && this.localState.discountRatio) { if (this.localState.mode === 'ratio' && this.localState.discountRatio) {
const ratio = parseFloat(this.localState.discountRatio) const ratio = parseFloat(this.localState.discountRatio)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
return Math.round(bp * (ratio / 10) * 100) / 100 return utils.ceilDecimal(bp * (ratio / 10))
} }
} else if (this.localState.mode === 'amount' && this.localState.discountAmount) { } else if (this.localState.mode === 'amount' && this.localState.discountAmount) {
const discountAmount = parseFloat(this.localState.discountAmount) const discountAmount = parseFloat(this.localState.discountAmount)
if (discountAmount >= 0.01 && discountAmount <= bp) { if (discountAmount >= 0.01 && discountAmount <= bp) {
return Math.round((bp - discountAmount) * 100) / 100 return utils.ceilDecimal(bp - discountAmount)
} }
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
} }
// 买赠策略 // 买赠策略
...@@ -270,7 +271,7 @@ export default { ...@@ -270,7 +271,7 @@ export default {
if (this.localState.isGift === '1') { if (this.localState.isGift === '1') {
return 0 return 0
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
} }
// 组合付款 // 组合付款
...@@ -278,13 +279,13 @@ export default { ...@@ -278,13 +279,13 @@ export default {
if (this.localState.mode === 'deduct' && this.localState.deductAmount) { if (this.localState.mode === 'deduct' && this.localState.deductAmount) {
const deductAmount = parseFloat(this.localState.deductAmount) const deductAmount = parseFloat(this.localState.deductAmount)
if (deductAmount >= 0.01 && deductAmount <= bp) { if (deductAmount >= 0.01 && deductAmount <= bp) {
return Math.round((bp - deductAmount) * 100) / 100 return utils.ceilDecimal(bp - deductAmount)
} }
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
}, },
// 失去焦点时格式化(跟价格输入框一样的逻辑) // 失去焦点时格式化(跟价格输入框一样的逻辑)
onBlur(key) { onBlur(key) {
......
...@@ -34,6 +34,7 @@ ...@@ -34,6 +34,7 @@
</view> </view>
</template> </template>
<script> <script>
import utils from '@/utils/utils'
import OrderStrategy from './OrderStrategy.vue' import OrderStrategy from './OrderStrategy.vue'
export default { export default {
...@@ -256,12 +257,12 @@ export default { ...@@ -256,12 +257,12 @@ export default {
if (strategyConfig.mode === 'ratio' && strategyConfig.discountRatio) { if (strategyConfig.mode === 'ratio' && strategyConfig.discountRatio) {
const ratio = parseFloat(strategyConfig.discountRatio) const ratio = parseFloat(strategyConfig.discountRatio)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
finalPricePerUnit = Math.round(sellPrice * (ratio / 10) * 100) / 100 finalPricePerUnit = utils.ceilDecimal(sellPrice * (ratio / 10))
} }
} else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) { } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
const discountAmount = parseFloat(strategyConfig.discountAmount) const discountAmount = parseFloat(strategyConfig.discountAmount)
if (discountAmount >= 0.01 && discountAmount <= sellPrice) { if (discountAmount >= 0.01 && discountAmount <= sellPrice) {
finalPricePerUnit = Math.round((sellPrice - discountAmount) * 100) / 100 finalPricePerUnit = utils.ceilDecimal(sellPrice - discountAmount)
} }
} }
} }
...@@ -278,7 +279,7 @@ export default { ...@@ -278,7 +279,7 @@ export default {
if (strategyConfig.mode === 'deduct' && strategyConfig.deductAmount) { if (strategyConfig.mode === 'deduct' && strategyConfig.deductAmount) {
const deductAmount = parseFloat(strategyConfig.deductAmount) const deductAmount = parseFloat(strategyConfig.deductAmount)
if (deductAmount >= 0.01 && deductAmount <= sellPrice) { if (deductAmount >= 0.01 && deductAmount <= sellPrice) {
finalPricePerUnit = Math.round((sellPrice - deductAmount) * 100) / 100 finalPricePerUnit = utils.ceilDecimal(sellPrice - deductAmount)
} }
} }
} }
...@@ -316,7 +317,7 @@ export default { ...@@ -316,7 +317,7 @@ export default {
if (!goods) return 0 if (!goods) return 0
const sellPrice = parseFloat(goods.sellPrice || 0) const sellPrice = parseFloat(goods.sellPrice || 0)
// 四舍五入保留两位小数 // 四舍五入保留两位小数
return Math.round(sellPrice * 100) / 100 return utils.ceilDecimal(sellPrice)
}, },
// 计算最终显示价格 // 计算最终显示价格
getDisplayPrice(goods, item) { getDisplayPrice(goods, item) {
...@@ -332,13 +333,13 @@ export default { ...@@ -332,13 +333,13 @@ export default {
const ratio = parseFloat(strategyConfig.discountRatio) const ratio = parseFloat(strategyConfig.discountRatio)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
const finalPrice = basePrice * (ratio / 10) const finalPrice = basePrice * (ratio / 10)
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) { } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
const discountAmount = parseFloat(strategyConfig.discountAmount) const discountAmount = parseFloat(strategyConfig.discountAmount)
if (discountAmount >= 0.01 && discountAmount <= basePrice) { if (discountAmount >= 0.01 && discountAmount <= basePrice) {
const finalPrice = basePrice - discountAmount const finalPrice = basePrice - discountAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + basePrice.toFixed(2)
...@@ -358,7 +359,7 @@ export default { ...@@ -358,7 +359,7 @@ export default {
const deductAmount = parseFloat(strategyConfig.deductAmount) const deductAmount = parseFloat(strategyConfig.deductAmount)
if (deductAmount >= 0.01 && deductAmount <= basePrice) { if (deductAmount >= 0.01 && deductAmount <= basePrice) {
const finalPrice = basePrice - deductAmount const finalPrice = basePrice - deductAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + basePrice.toFixed(2)
...@@ -372,7 +373,7 @@ export default { ...@@ -372,7 +373,7 @@ export default {
const packageItem = this.list.find(pkg => pkg.packageGoods.goodsList.includes(goods)) const packageItem = this.list.find(pkg => pkg.packageGoods.goodsList.includes(goods))
if (packageItem) { if (packageItem) {
const number = parseInt(packageItem.packageGoods.number || 1) const number = parseInt(packageItem.packageGoods.number || 1)
const totalFinalPrice = Math.round(finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(finalPricePerUnit * number)
// 存储总价和单价优惠后的价格 // 存储总价和单价优惠后的价格
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
this.$set(goods, 'finalPricePerUnit', finalPricePerUnit) this.$set(goods, 'finalPricePerUnit', finalPricePerUnit)
...@@ -403,7 +404,7 @@ export default { ...@@ -403,7 +404,7 @@ export default {
// 按当前单价和套餐数量,重新计算无优惠时的 finalPrice // 按当前单价和套餐数量,重新计算无优惠时的 finalPrice
const unitPrice = parseFloat(goods.sellPrice || 0) const unitPrice = parseFloat(goods.sellPrice || 0)
const number = parseInt(item?.packageGoods?.number || 1) const number = parseInt(item?.packageGoods?.number || 1)
const totalFinalPrice = Math.round(unitPrice * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(unitPrice * number)
this.$set(goods, 'finalPricePerUnit', unitPrice) this.$set(goods, 'finalPricePerUnit', unitPrice)
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
}, },
...@@ -413,7 +414,7 @@ export default { ...@@ -413,7 +414,7 @@ export default {
if (item.packageGoods && item.packageGoods.goodsList) { if (item.packageGoods && item.packageGoods.goodsList) {
item.packageGoods.goodsList.forEach(goods => { item.packageGoods.goodsList.forEach(goods => {
if (goods.strategyConfig && goods.finalPricePerUnit !== undefined) { if (goods.strategyConfig && goods.finalPricePerUnit !== undefined) {
const totalFinalPrice = Math.round(goods.finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(goods.finalPricePerUnit * number)
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
} }
}) })
......
...@@ -33,6 +33,7 @@ ...@@ -33,6 +33,7 @@
</template> </template>
<script> <script>
import utils from '@/utils/utils'
import OrderStrategy from './OrderStrategy.vue' import OrderStrategy from './OrderStrategy.vue'
export default { export default {
...@@ -109,7 +110,7 @@ export default { ...@@ -109,7 +110,7 @@ export default {
if (!item || !item.goods) return 0 if (!item || !item.goods) return 0
const sellPrice = parseFloat(item.goods.sellPrice || 0) const sellPrice = parseFloat(item.goods.sellPrice || 0)
// 四舍五入保留两位小数 // 四舍五入保留两位小数
return Math.round(sellPrice * 100) / 100 return utils.ceilDecimal(sellPrice)
}, },
// 计算最终显示价格 // 计算最终显示价格
getDisplayPrice(item) { getDisplayPrice(item) {
...@@ -126,14 +127,14 @@ export default { ...@@ -126,14 +127,14 @@ export default {
const ratio = parseFloat(strategyConfig.discountRatio) const ratio = parseFloat(strategyConfig.discountRatio)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
const finalPrice = basePrice * (ratio / 10) const finalPrice = basePrice * (ratio / 10)
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) { } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
// 折扣金额:0.01 到不能大于基础价格 // 折扣金额:0.01 到不能大于基础价格
const discountAmount = parseFloat(strategyConfig.discountAmount) const discountAmount = parseFloat(strategyConfig.discountAmount)
if (discountAmount >= 0.01 && discountAmount <= basePrice) { if (discountAmount >= 0.01 && discountAmount <= basePrice) {
const finalPrice = basePrice - discountAmount const finalPrice = basePrice - discountAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + basePrice.toFixed(2)
...@@ -154,7 +155,7 @@ export default { ...@@ -154,7 +155,7 @@ export default {
const deductAmount = parseFloat(strategyConfig.deductAmount) const deductAmount = parseFloat(strategyConfig.deductAmount)
if (deductAmount >= 0.01 && deductAmount <= basePrice) { if (deductAmount >= 0.01 && deductAmount <= basePrice) {
const finalPrice = basePrice - deductAmount const finalPrice = basePrice - deductAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + basePrice.toFixed(2)
...@@ -166,7 +167,7 @@ export default { ...@@ -166,7 +167,7 @@ export default {
onPriceChange(item, finalPricePerUnit) { onPriceChange(item, finalPricePerUnit) {
// 计算总价:单件优惠价 * 数量 // 计算总价:单件优惠价 * 数量
const number = parseInt(item.goods.number || 1) const number = parseInt(item.goods.number || 1)
const totalFinalPrice = Math.round(finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(finalPricePerUnit * number)
// 存储总价 // 存储总价
this.$set(item.goods, 'finalPrice', totalFinalPrice) this.$set(item.goods, 'finalPrice', totalFinalPrice)
// 同时存储单价优惠后的价格,用于数量改变时重新计算 // 同时存储单价优惠后的价格,用于数量改变时重新计算
...@@ -178,7 +179,7 @@ export default { ...@@ -178,7 +179,7 @@ export default {
// 如果有优惠策略配置 // 如果有优惠策略配置
if (item.goods.strategyConfig && item.goods.finalPricePerUnit !== undefined) { if (item.goods.strategyConfig && item.goods.finalPricePerUnit !== undefined) {
const number = parseInt(item.goods.number || 1) const number = parseInt(item.goods.number || 1)
const totalFinalPrice = Math.round(item.goods.finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(item.goods.finalPricePerUnit * number)
this.$set(item.goods, 'finalPrice', totalFinalPrice) this.$set(item.goods, 'finalPrice', totalFinalPrice)
} }
}, },
...@@ -353,7 +354,7 @@ export default { ...@@ -353,7 +354,7 @@ export default {
// 按当前单价和数量,重新计算无优惠时的 finalPrice // 按当前单价和数量,重新计算无优惠时的 finalPrice
const unitPrice = parseFloat(goods.sellPrice || 0) const unitPrice = parseFloat(goods.sellPrice || 0)
const number = parseInt(goods.number || 1) const number = parseInt(goods.number || 1)
const totalFinalPrice = Math.round(unitPrice * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(unitPrice * number)
this.$set(goods, 'finalPricePerUnit', unitPrice) this.$set(goods, 'finalPricePerUnit', unitPrice)
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
}, },
......
...@@ -60,6 +60,7 @@ ...@@ -60,6 +60,7 @@
</template> </template>
<script> <script>
import utils from '@/utils/utils'
import OrderStrategy from './OrderStrategy.vue' import OrderStrategy from './OrderStrategy.vue'
export default { export default {
...@@ -359,7 +360,7 @@ export default { ...@@ -359,7 +360,7 @@ export default {
} else if (item.goods && item.goods.number) { } else if (item.goods && item.goods.number) {
number = parseInt(item.goods.number || 1) number = parseInt(item.goods.number || 1)
} }
const totalFinalPrice = Math.round(unitPrice * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(unitPrice * number)
this.$set(goods, 'finalPricePerUnit', unitPrice) this.$set(goods, 'finalPricePerUnit', unitPrice)
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
}, },
...@@ -409,8 +410,8 @@ export default { ...@@ -409,8 +410,8 @@ export default {
sellPrice = parseFloat(item.goods.sellPrice || 0) sellPrice = parseFloat(item.goods.sellPrice || 0)
} }
// 四舍五入保留两位小数 // 向上取整保留两位小数
return Math.round(sellPrice * 100) / 100 return utils.ceilDecimal(sellPrice)
}, },
// 计算最终显示价格 // 计算最终显示价格
getDisplayPrice(item) { getDisplayPrice(item) {
...@@ -426,16 +427,16 @@ export default { ...@@ -426,16 +427,16 @@ export default {
const ratio = parseFloat(strategyConfig.discountRatio) const ratio = parseFloat(strategyConfig.discountRatio)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
const finalPrice = basePrice * (ratio / 10) const finalPrice = basePrice * (ratio / 10)
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) { } else if (strategyConfig.mode === 'amount' && strategyConfig.discountAmount) {
const discountAmount = parseFloat(strategyConfig.discountAmount) const discountAmount = parseFloat(strategyConfig.discountAmount)
if (discountAmount >= 0.01 && discountAmount <= basePrice) { if (discountAmount >= 0.01 && discountAmount <= basePrice) {
const finalPrice = basePrice - discountAmount const finalPrice = basePrice - discountAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
// '3' 买赠策略 // '3' 买赠策略
...@@ -443,7 +444,7 @@ export default { ...@@ -443,7 +444,7 @@ export default {
if (strategyConfig.isGift === '1') { if (strategyConfig.isGift === '1') {
return '¥0.00' return '¥0.00'
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
// '5' 组合付款 // '5' 组合付款
...@@ -452,13 +453,13 @@ export default { ...@@ -452,13 +453,13 @@ export default {
const deductAmount = parseFloat(strategyConfig.deductAmount) const deductAmount = parseFloat(strategyConfig.deductAmount)
if (deductAmount >= 0.01 && deductAmount <= basePrice) { if (deductAmount >= 0.01 && deductAmount <= basePrice) {
const finalPrice = basePrice - deductAmount const finalPrice = basePrice - deductAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
}, },
// 价格变化回调(finalPrice 是单件商品优惠后的价格,需要乘以数量得到总价) // 价格变化回调(finalPrice 是单件商品优惠后的价格,需要乘以数量得到总价)
onPriceChange(item, finalPricePerUnit) { onPriceChange(item, finalPricePerUnit) {
...@@ -466,12 +467,12 @@ export default { ...@@ -466,12 +467,12 @@ export default {
if (item.multipleSpecificationsGoods && item.multipleSpecificationsGoods.goods) { if (item.multipleSpecificationsGoods && item.multipleSpecificationsGoods.goods) {
number = parseInt(item.multipleSpecificationsGoods.number || 1) number = parseInt(item.multipleSpecificationsGoods.number || 1)
const totalFinalPrice = Math.round(finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(finalPricePerUnit * number)
this.$set(item.multipleSpecificationsGoods.goods, 'finalPrice', totalFinalPrice) this.$set(item.multipleSpecificationsGoods.goods, 'finalPrice', totalFinalPrice)
this.$set(item.multipleSpecificationsGoods.goods, 'finalPricePerUnit', finalPricePerUnit) this.$set(item.multipleSpecificationsGoods.goods, 'finalPricePerUnit', finalPricePerUnit)
} else if (item.goods) { } else if (item.goods) {
number = parseInt(item.goods.number || 1) number = parseInt(item.goods.number || 1)
const totalFinalPrice = Math.round(finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(finalPricePerUnit * number)
this.$set(item.goods, 'finalPrice', totalFinalPrice) this.$set(item.goods, 'finalPrice', totalFinalPrice)
this.$set(item.goods, 'finalPricePerUnit', finalPricePerUnit) this.$set(item.goods, 'finalPricePerUnit', finalPricePerUnit)
} }
...@@ -490,7 +491,7 @@ export default { ...@@ -490,7 +491,7 @@ export default {
} }
if (goods && goods.strategyConfig && goods.finalPricePerUnit !== undefined) { if (goods && goods.strategyConfig && goods.finalPricePerUnit !== undefined) {
const totalFinalPrice = Math.round(goods.finalPricePerUnit * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(goods.finalPricePerUnit * number)
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
} }
}, },
......
<template> <template>
<view class="detail-box"> <view class="detail-box">
<view class="nav-bar"> <view class="nav-bar">
<view <view class="back" @click="backPage">
class="back" <uni-icons type="left" :size="20" color="#000"></uni-icons>
@click="backPage"
>
<uni-icons
type="left"
:size="20"
color="#000"
></uni-icons>
</view> </view>
<view class="title">展业工具</view> <view class="title">展业工具</view>
</view> </view>
...@@ -17,23 +10,9 @@ ...@@ -17,23 +10,9 @@
<view class="detail-left"> <view class="detail-left">
<view class="common-title">展业</view> <view class="common-title">展业</view>
<view class="content"> <view class="content">
<image <image class="banner" src="../../../assets/images/common/tool_banner.png" mode="scaleToFill" />
class="banner"
src="../../../assets/images/common/tool_banner.png"
mode="scaleToFill"
/>
<template v-if="toolComponentName === 'DailyReport'"> <template v-if="toolComponentName === 'DailyReport'">
<uni-calendar <uni-calendar ref="calendar" :clearDate="false" :endDate="endDate" :showMonth="false" @monthSwitch="currentMonth = `${$event.year}-${$event.month}`" @change="currentDate = $event.fulldate" backgroundColor="transparent" :selected="selectedDays" :date="currentDate" />
ref="calendar"
:clearDate="false"
:endDate="endDate"
:showMonth="false"
@monthSwitch="currentMonth = `${$event.year}-${$event.month}`"
@change="currentDate = $event.fulldate"
backgroundColor="transparent"
:selected="selectedDays"
:date="currentDate"
/>
</template> </template>
<template v-else-if="toolComponentName === 'WageAppeal'"> <template v-else-if="toolComponentName === 'WageAppeal'">
<MonthCalendar @confirm="confirmMonth"></MonthCalendar> <MonthCalendar @confirm="confirmMonth"></MonthCalendar>
...@@ -44,49 +23,24 @@ ...@@ -44,49 +23,24 @@
</view> </view>
</view> </view>
<view class="detail-right"> <view class="detail-right">
<component <component :is="toolComponentName" @jump="jump" :transmission-of-data="transmissionOfData" :currentDate="currentDate" :currentMonth="currentMonth" :lastMonth="lastMonth" @setCalendarSelected="selectedDays = $event" :enterType="enterType" />
:is="toolComponentName"
@jump="jump"
:transmission-of-data="transmissionOfData"
:currentDate="currentDate"
:currentMonth="currentMonth"
:lastMonth="lastMonth"
@setCalendarSelected="selectedDays = $event"
:enterType="enterType"
/>
</view> </view>
</view> </view>
<NoticePopup <NoticePopup ref="notice" title="重要提示" text="当前页面暂未保存,是否确认退出" type="warning"></NoticePopup>
ref="notice"
title="重要提示"
text="当前页面暂未保存,是否确认退出"
type="warning"
></NoticePopup>
<!-- 学习中心权限弹窗 --> <!-- 学习中心权限弹窗 -->
<StudyPopup :show.sync="showStudyPermissionPopup" title="" :width="848" :height="870" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248" style="overflow: hidden"> <StudyPopup :show.sync="showStudyPermissionPopup" title="" :width="848" :height="870" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248" style="overflow: hidden">
<StudyCenterPermissionPopup :lockReason="lockReason" @confirm="handleStudyPermissionConfirm" /> <StudyCenterPermissionPopup :lockReason="lockReason" @confirm="handleStudyPermissionConfirm" />
</StudyPopup> </StudyPopup>
<!-- 异常订单锁单弹窗,样式与车险工具页保持一致 --> <!-- 异常订单锁单弹窗,样式与车险工具页保持一致 -->
<ErrorOrderPopup <ErrorOrderPopup :show.sync="showErrorOrderPopup" title="" :width="848" :height="870" :topImage="require('@/assets/images/common/warning-notice.png')" :topImageWidth="848" :topImageHeight="248" style="overflow: hidden">
:show.sync="showErrorOrderPopup"
title=""
:width="848"
:height="870"
:topImage="require('@/assets/images/common/warning-notice.png')"
:topImageWidth="848"
:topImageHeight="248"
style="overflow: hidden"
>
<view> <view>
<view class="error-order-title">异常订单提醒</view> <view class="error-order-title">异常订单提醒</view>
<view class="error-order-content">存在{{ abnormalOrderCount }} 条异常订单未处理,请尽快处理!</view> <view class="error-order-content">存在{{ abnormalOrderCount }} 条异常订单未处理,请尽快处理!</view>
</view> </view>
<template #footer> <template #footer>
<view class="flex justify-between error-order-footer"> <view class="flex justify-between error-order-footer">
<view class="footer-btn sure flex-1" @click="showErrorOrderPopup = false"> <view class="footer-btn sure flex-1" @click="showErrorOrderPopup = false">好的</view>
好的
</view>
</view> </view>
</template> </template>
</ErrorOrderPopup> </ErrorOrderPopup>
...@@ -129,7 +83,7 @@ export default { ...@@ -129,7 +83,7 @@ export default {
MonthCalendar, MonthCalendar,
ErrorOrderPopup ErrorOrderPopup
}, },
data () { data() {
return { return {
toolComponentName: '', toolComponentName: '',
transmissionOfData: null, transmissionOfData: null,
...@@ -143,10 +97,10 @@ export default { ...@@ -143,10 +97,10 @@ export default {
// 异常订单锁单弹窗 // 异常订单锁单弹窗
showErrorOrderPopup: false, showErrorOrderPopup: false,
abnormalOrderCount: 0, abnormalOrderCount: 0,
enterType: '', enterType: ''
} }
}, },
onLoad (options) { onLoad(options) {
if (options.componentName) this.toolComponentName = options.componentName if (options.componentName) this.toolComponentName = options.componentName
if (options.currentDate) this.setCurrentDate(options.currentDate) if (options.currentDate) this.setCurrentDate(options.currentDate)
if (options.enterType) this.enterType = options.enterType if (options.enterType) this.enterType = options.enterType
...@@ -167,20 +121,20 @@ export default { ...@@ -167,20 +121,20 @@ export default {
} }
}) })
}, },
onUnload () { onUnload() {
uni.$off('showErrorOrderPopup') uni.$off('showErrorOrderPopup')
}, },
methods: { methods: {
setCurrentDate (currentDate) { setCurrentDate(currentDate) {
this.currentDate = currentDate this.currentDate = currentDate
this.currentMonth = dayjs(currentDate).format('YYYY-MM') this.currentMonth = dayjs(currentDate).format('YYYY-MM')
}, },
async entranceClick (item) { async entranceClick(item) {
if(this.toolComponentName == item.name) return if (this.toolComponentName == item.name) return
const noInterceptPage = ['DailyReport'] const noInterceptPage = ['DailyReport']
// 原禁止提单inspectionOfProhibitionBill方法被替换getLimitRecord // 原禁止提单inspectionOfProhibitionBill方法被替换getLimitRecord
// if (!noInterceptPage.includes(item.name) && ((await this.checkDailyReport()) || (await this.inspectionOfProhibitionBill()))) return // if (!noInterceptPage.includes(item.name) && ((await this.checkDailyReport()) || (await this.inspectionOfProhibitionBill()))) return
if (!noInterceptPage.includes(item.name) && ((await this.checkDailyReport()))) return if (!noInterceptPage.includes(item.name) && (await this.checkDailyReport())) return
// 提示去学习中心弹窗 // 提示去学习中心弹窗
const res = await this.getLimitRecord() const res = await this.getLimitRecord()
if (res.lockOrder) { if (res.lockOrder) {
...@@ -229,11 +183,11 @@ export default { ...@@ -229,11 +183,11 @@ export default {
// 打开弹窗 // 打开弹窗
this.$refs.notice.open() this.$refs.notice.open()
}, },
backPage () { backPage() {
uni.navigateBack() uni.navigateBack()
}, },
// name:跳转组件名,val:跳转参数 // name:跳转组件名,val:跳转参数
jump (name, val) { jump(name, val) {
this.toolComponentName = name this.toolComponentName = name
console.log(this.toolComponentName, val) console.log(this.toolComponentName, val)
if (val) { if (val) {
...@@ -254,7 +208,7 @@ export default { ...@@ -254,7 +208,7 @@ export default {
// 确认选择的月份 // 确认选择的月份
confirmMonth(month) { confirmMonth(month) {
this.lastMonth = month this.lastMonth = month
}, }
} }
} }
</script> </script>
...@@ -305,8 +259,8 @@ export default { ...@@ -305,8 +259,8 @@ export default {
.error-order-title { .error-order-title {
text-align: center; text-align: center;
color: #333333; color: #333333;
font-size: toRpx(40); font-size: toRpx(40);
font-weight: 500; font-weight: 500;
} }
.error-order-content { .error-order-content {
text-align: center; text-align: center;
...@@ -319,7 +273,7 @@ export default { ...@@ -319,7 +273,7 @@ export default {
margin-top: toRpx(64); margin-top: toRpx(64);
margin-bottom: toRpx(48); margin-bottom: toRpx(48);
width: 100%; width: 100%;
.cancel{ .cancel {
height: toRpx(88); height: toRpx(88);
border-radius: toRpx(64); border-radius: toRpx(64);
opacity: 1; opacity: 1;
...@@ -331,7 +285,7 @@ export default { ...@@ -331,7 +285,7 @@ export default {
font-size: toRpx(32); font-size: toRpx(32);
font-weight: 400; font-weight: 400;
} }
.sure{ .sure {
height: toRpx(88); height: toRpx(88);
border-radius: toRpx(64); border-radius: toRpx(64);
opacity: 1; opacity: 1;
......
...@@ -61,6 +61,10 @@ const EQUITY_ORDER_COUNT_FIELDS = [ ...@@ -61,6 +61,10 @@ const EQUITY_ORDER_COUNT_FIELDS = [
prop: 'safePackageMaxAchieveCount' prop: 'safePackageMaxAchieveCount'
}, },
{ {
label: '安心包Lite',
prop: 'safePackageLiteAchieveCount'
},
{
label: '安心包', label: '安心包',
prop: 'safePackageAchieveCount' prop: 'safePackageAchieveCount'
}, },
......
This diff could not be displayed because it is too large.
...@@ -97,13 +97,13 @@ ...@@ -97,13 +97,13 @@
:tabIndex.sync="tabIndex" :tabIndex.sync="tabIndex"
nameKey="tabName" nameKey="tabName"
></type-tab-component> ></type-tab-component>
<view class="car-band-form-box"> <view :class="['car-band-form-box',{'car-band-form-box-type-2': orderObj.templateType == 2}]">
<template v-for="(item,index) in carBandList"> <template v-for="(item,index) in carBandList">
<view <view
:class="['box',{show:index == tabIndex}]" :class="['box',{show:index == tabIndex}]"
:key="index" :key="index"
> >
<template v-for="(i,ind) in hwOhterObjArray"> <template v-for="(i,ind) in templateList">
<view <view
:class="['form-item flex',{name:i.name}]" :class="['form-item flex',{name:i.name}]"
:key="`${index}_${ind}`" :key="`${index}_${ind}`"
...@@ -353,16 +353,16 @@ export default { ...@@ -353,16 +353,16 @@ export default {
}, },
{ {
label: '实际售前触客数', label: '实际售前触客数',
key: 'equityToShopCount', key: 'extendedWarrantyToShopCount',
type: 'number', type: 'number',
required: true, required: true,
min: 0, min: 0,
max: 100, max: 100,
refId: 'equityToShopCount', refId: 'extendedWarrantyToShopCount',
}, },
{ {
label: '实际售后触客数', label: '实际售后触客数',
key: 'afterSaleEquityToShopCount', key: 'afterSaleExtendedWarrantyToShopCount',
type: 'number', type: 'number',
required: false, required: false,
min: 0, min: 0,
...@@ -427,6 +427,11 @@ export default { ...@@ -427,6 +427,11 @@ export default {
hide: NotAitoAndTemplateType3 hide: NotAitoAndTemplateType3
}, },
{ {
label: '安心包Lite成交数',
key: 'axPackageLiteCount',
hide: NotAitoAndTemplateType3
},
{
label: '安心包Pro成交数', label: '安心包Pro成交数',
key: 'axPackageProCount', key: 'axPackageProCount',
hide: NotAitoAndTemplateType3 hide: NotAitoAndTemplateType3
...@@ -480,7 +485,34 @@ export default { ...@@ -480,7 +485,34 @@ export default {
} }
] ]
return personalArray.filter(item => !item.hide) return personalArray.filter(item => !item.hide)
} },
templateList () {
const { hwOhterObjArray, orderObj: { templateType } } = this
const changeKeys = ['extendedWarrantyToShopCount', 'afterSaleExtendedWarrantyToShopCount']
const isType12 = templateType == 1 || templateType == 2
let base = hwOhterObjArray.map(item => {
const obj = { ...item }
if (isType12 && changeKeys.includes(obj.key)) {
obj.label = `延保${obj.label}`
} else if (!isType12 && changeKeys.includes(obj.key)) {
obj.label = `权益${obj.label}`
obj.key = obj.key === 'extendedWarrantyToShopCount' ? 'realEquityToShopCount' : 'afterSaleRealEquityToShopCount'
if (obj.refId) obj.refId = obj.key
}
return obj
})
if (templateType == 2) {
const afterIndex = base.findIndex(item => item.key == 'afterSaleExtendedWarrantyToShopCount')
if (afterIndex !== -1) {
const inserts = [
{ label: '权益实际售前触客数', key: 'realEquityToShopCount', type: 'number', required: true, min: 0, max: 100, refId: 'realEquityToShopCount' },
{ label: '权益实际售后触客数', key: 'afterSaleRealEquityToShopCount', type: 'number', required: false, min: 0, max: 100 }
]
base = [...base.slice(0, afterIndex + 1), ...inserts, ...base.slice(afterIndex + 1)]
}
}
return base
},
}, },
watch: { watch: {
currentMonth: { currentMonth: {
...@@ -495,7 +527,7 @@ export default { ...@@ -495,7 +527,7 @@ export default {
if (this.carBandList.length) this.getStaffDailyReportDetail() if (this.carBandList.length) this.getStaffDailyReportDetail()
}, },
deep: true, deep: true,
} },
}, },
mounted () { mounted () {
uni.$track.add({ uni.$track.add({
...@@ -621,10 +653,12 @@ export default { ...@@ -621,10 +653,12 @@ export default {
let { brandDataList, remark } = data let { brandDataList, remark } = data
if (brandDataList && brandDataList.length) { if (brandDataList && brandDataList.length) {
carBandList = carBandList.map((item, index) => { carBandList = carBandList.map((item, index) => {
this.dateKey[`deliveryCount_${index}`] = Date.now() let dataKeyList = ['deliveryCount', 'notDeliveryCount',
this.dateKey[`notDeliveryCount_${index}`] = Date.now() 'extendedWarrantyToShopCount', 'afterSaleExtendedWarrantyToShopCount',
this.dateKey[`equityToShopCount_${index}`] = Date.now() 'realEquityToShopCount', 'afterSaleRealEquityToShopCount']
this.dateKey[`afterSaleEquityToShopCount_${index}`] = Date.now() dataKeyList.map(key => {
this.dateKey[`${key}_${index}`] = Date.now()
})
let carBand = brandDataList.find(ele => { let carBand = brandDataList.find(ele => {
if ([0, 1, 3, 4, 5, 6].includes(ele.brandType)) { if ([0, 1, 3, 4, 5, 6].includes(ele.brandType)) {
return ele.brandType == item.brandType return ele.brandType == item.brandType
...@@ -668,7 +702,7 @@ export default { ...@@ -668,7 +702,7 @@ export default {
this.orderObj = { this.orderObj = {
...orderObj, ...orderObj,
reportDate: currentDate, reportDate: currentDate,
isDateWithin7Days:editableDay ? !disabledReport : diffDay < 7, isDateWithin7Days: editableDay ? !disabledReport : diffDay < 7,
remark, remark,
lastStaffName: data.lastStaffName, lastStaffName: data.lastStaffName,
lastStaffUuid: data.lastStaffUuid, lastStaffUuid: data.lastStaffUuid,
...@@ -680,7 +714,7 @@ export default { ...@@ -680,7 +714,7 @@ export default {
cancelOrderMoney: data.cancelOrderMoney, cancelOrderMoney: data.cancelOrderMoney,
templateType: isHmStore ? 1 : data.templateType || 1, templateType: isHmStore ? 1 : data.templateType || 1,
staffCount: data.staffCount, staffCount: data.staffCount,
onBreak: data.onBreak ? data.onBreak : diffDay < 7 ? data.onBreak || 'N' : '', onBreak: data.onBreak ? data.onBreak : diffDay < 7 ? data.onBreak || 'N' : 'N',
pickerValue: data.onBreak == 'Y' ? 1 : 0, pickerValue: data.onBreak == 'Y' ? 1 : 0,
staffCountError: false, staffCountError: false,
} }
...@@ -778,7 +812,7 @@ export default { ...@@ -778,7 +812,7 @@ export default {
eventCode: 'app_submit_daily_report' eventCode: 'app_submit_daily_report'
}) //提交驻店日报埋点 }) //提交驻店日报埋点
try { try {
let { orderObj, carBandList, hwOhterObjArray, userInfo } = this let { orderObj, carBandList, templateList, userInfo, orderObj:{templateType} } = this
orderObj.isAdmin = false orderObj.isAdmin = false
orderObj.oprBy = orderObj.staffUuid orderObj.oprBy = orderObj.staffUuid
orderObj.sceneType = 0 orderObj.sceneType = 0
...@@ -789,8 +823,8 @@ export default { ...@@ -789,8 +823,8 @@ export default {
refId: 'staffCount' refId: 'staffCount'
} }
carBandList.map((item, index) => { carBandList.map((item, index) => {
hwOhterObjArray.map(el => { templateList.map(el => {
if (el.required && ['', null].includes(item[el.key])) throw { if (el.required && ['', null, undefined].includes(item[el.key])) throw {
message: `${item.tabName}${el.label}`, message: `${item.tabName}${el.label}`,
refId: `${el.refId}_${index}`, refId: `${el.refId}_${index}`,
tabIndex: index tabIndex: index
...@@ -800,8 +834,11 @@ export default { ...@@ -800,8 +834,11 @@ export default {
} }
if (orderObj.onBreak == 'Y') { if (orderObj.onBreak == 'Y') {
orderObj.brandDataList.forEach(item => { orderObj.brandDataList.forEach(item => {
// 如果是调休,店端总未触客数&实际售前触客数默认值为空默认赋值为0
item.notDeliveryCount = item.notDeliveryCount || 0 item.notDeliveryCount = item.notDeliveryCount || 0
item.equityToShopCount = item.equityToShopCount || 0 if(templateType == 1 || templateType == 2) item.extendedWarrantyToShopCount = item.extendedWarrantyToShopCount || 0
if(templateType == 3 || templateType == 2) item.realEquityToShopCount = item.realEquityToShopCount || 0
}) })
} }
// 非调休 日报填报前参数校验 // 非调休 日报填报前参数校验
...@@ -865,6 +902,41 @@ export default { ...@@ -865,6 +902,41 @@ export default {
this.orderObj[i.submitValue] = value this.orderObj[i.submitValue] = value
}, },
handleTemplagePickerChange ({ item }) { handleTemplagePickerChange ({ item }) {
// const oldTemplateType = this.orderObj.templateType;
// const newTemplateType = item.value;
// // 更新模板类型
// this.orderObj.templateType = newTemplateType;
// // 如果模板类型发生变化,清空 carBandList 中受模板影响的字段
// if (oldTemplateType !== newTemplateType) {
// this.carBandList = this.carBandList.map(carBand => {
// const resetFields = {};
// // 所有模板共用的字段保留,但以下字段可能因模板而异,需重置
// const fieldsToReset = [
// 'extendedWarrantyToShopCount',
// 'afterSaleExtendedWarrantyToShopCount',
// 'realEquityToShopCount',
// 'afterSaleRealEquityToShopCount'
// ];
// fieldsToReset.forEach(key => {
// resetFields[key] = null;
// });
// // 可选:如果新模板是“广联权益”(3),也清空延保相关字段(如个人退单等,但这些在 orderObj,非 carBand)
// return { ...carBand, ...resetFields };
// });
// // 同步更新 dateKey,触发 input 重新渲染(避免缓存问题)
// this.carBandList.forEach((_, index) => {
// ['extendedWarrantyToShopCount', 'afterSaleExtendedWarrantyToShopCount', 'realEquityToShopCount', 'afterSaleRealEquityToShopCount']
// .forEach(key => {
// this.dateKey[`${key}_${index}`] = Date.now();
// });
// });
// }
this.orderObj.templateType = item.value this.orderObj.templateType = item.value
}, },
cancel () { cancel () {
...@@ -1050,6 +1122,9 @@ export default { ...@@ -1050,6 +1122,9 @@ export default {
visibility: visible; visibility: visible;
} }
} }
.car-band-form-box-type-2 {
height: toRpx(672);
}
.box { .box {
margin: 0; margin: 0;
border-radius: 0 0 toRpx(32); border-radius: 0 0 toRpx(32);
......
...@@ -282,7 +282,7 @@ export default { ...@@ -282,7 +282,7 @@ export default {
// 待上传协议状态也支持撤销 // 待上传协议状态也支持撤销
if (order.payType == 1) { if (order.payType == 1) {
// 线上支付显示"错误工单" // 线上支付显示"错误工单"
config.secondaryButtons.push({ text: '错误工单', type: 'secondary', dataType: 'error' }) // config.secondaryButtons.push({ text: '错误工单', type: 'secondary', dataType: 'error' })
} else { } else {
// 非线上支付显示"撤销工单" // 非线上支付显示"撤销工单"
config.secondaryButtons.push({ text: '撤销工单', type: 'secondary', dataType: 'revoke' }) config.secondaryButtons.push({ text: '撤销工单', type: 'secondary', dataType: 'revoke' })
...@@ -366,7 +366,7 @@ export default { ...@@ -366,7 +366,7 @@ export default {
else if (order.orderStatus == 3 || order.orderStatus == 5) { else if (order.orderStatus == 3 || order.orderStatus == 5) {
if (order.payType == 1) { if (order.payType == 1) {
// 线上支付显示"错误工单" // 线上支付显示"错误工单"
config.secondaryButtons.push({ text: '错误工单', type: 'secondary', dataType: 'error' }) // config.secondaryButtons.push({ text: '错误工单', type: 'secondary', dataType: 'error' })
} else { } else {
// 非线上支付显示"撤销工单" // 非线上支付显示"撤销工单"
config.secondaryButtons.push({ text: '撤销工单', type: 'secondary', dataType: 'revoke' }) config.secondaryButtons.push({ text: '撤销工单', type: 'secondary', dataType: 'revoke' })
...@@ -375,7 +375,7 @@ export default { ...@@ -375,7 +375,7 @@ export default {
// 其他状态,支持撤销 // 其他状态,支持撤销
else { else {
if (order.payType == 1) { if (order.payType == 1) {
config.secondaryButtons.push({ text: '错误工单', type: 'secondary', dataType: 'error' }) // config.secondaryButtons.push({ text: '错误工单', type: 'secondary', dataType: 'error' })
} else { } else {
config.secondaryButtons.push({ text: '撤销工单', type: 'secondary', dataType: 'revoke' }) config.secondaryButtons.push({ text: '撤销工单', type: 'secondary', dataType: 'revoke' })
} }
......
...@@ -58,6 +58,7 @@ ...@@ -58,6 +58,7 @@
</template> </template>
<script> <script>
import utils from '@/utils/utils'
export default { export default {
name: 'OrderStrategy', name: 'OrderStrategy',
props: { props: {
...@@ -127,17 +128,17 @@ export default { ...@@ -127,17 +128,17 @@ export default {
// 折扣比例:0.1-10,表示 0.1 折到 10 折(即 0.01 到 1.0) // 折扣比例:0.1-10,表示 0.1 折到 10 折(即 0.01 到 1.0)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
const finalPrice = basePrice * (ratio / 10) const finalPrice = basePrice * (ratio / 10)
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} else if (this.localState.mode === 'amount' && this.localState.discountAmount) { } else if (this.localState.mode === 'amount' && this.localState.discountAmount) {
const discountAmount = parseFloat(this.localState.discountAmount) const discountAmount = parseFloat(this.localState.discountAmount)
// 折扣金额:0.01 到不能大于基础价格 // 折扣金额:0.01 到不能大于基础价格
if (discountAmount >= 0.01 && discountAmount <= basePrice) { if (discountAmount >= 0.01 && discountAmount <= basePrice) {
const finalPrice = basePrice - discountAmount const finalPrice = basePrice - discountAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
// 买赠策略 // 买赠策略
...@@ -145,7 +146,7 @@ export default { ...@@ -145,7 +146,7 @@ export default {
if (this.localState.isGift === '1') { if (this.localState.isGift === '1') {
return '¥0.00' return '¥0.00'
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
// 组合付款 // 组合付款
...@@ -155,13 +156,13 @@ export default { ...@@ -155,13 +156,13 @@ export default {
// 抵扣金额:0.01 到不能大于基础价格 // 抵扣金额:0.01 到不能大于基础价格
if (deductAmount >= 0.01 && deductAmount <= basePrice) { if (deductAmount >= 0.01 && deductAmount <= basePrice) {
const finalPrice = basePrice - deductAmount const finalPrice = basePrice - deductAmount
return '¥' + (Math.round(finalPrice * 100) / 100).toFixed(2) return '¥' + utils.ceilDecimal(finalPrice).toFixed(2)
} }
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
return '¥' + basePrice.toFixed(2) return '¥' + utils.ceilDecimal(basePrice).toFixed(2)
} }
}, },
watch: { watch: {
...@@ -254,15 +255,15 @@ export default { ...@@ -254,15 +255,15 @@ export default {
if (this.localState.mode === 'ratio' && this.localState.discountRatio) { if (this.localState.mode === 'ratio' && this.localState.discountRatio) {
const ratio = parseFloat(this.localState.discountRatio) const ratio = parseFloat(this.localState.discountRatio)
if (ratio >= 0.1 && ratio <= 10) { if (ratio >= 0.1 && ratio <= 10) {
return Math.round(bp * (ratio / 10) * 100) / 100 return utils.ceilDecimal(bp * (ratio / 10))
} }
} else if (this.localState.mode === 'amount' && this.localState.discountAmount) { } else if (this.localState.mode === 'amount' && this.localState.discountAmount) {
const discountAmount = parseFloat(this.localState.discountAmount) const discountAmount = parseFloat(this.localState.discountAmount)
if (discountAmount >= 0.01 && discountAmount <= bp) { if (discountAmount >= 0.01 && discountAmount <= bp) {
return Math.round((bp - discountAmount) * 100) / 100 return utils.ceilDecimal(bp - discountAmount)
} }
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
} }
// 买赠策略 // 买赠策略
...@@ -270,7 +271,7 @@ export default { ...@@ -270,7 +271,7 @@ export default {
if (this.localState.isGift === '1') { if (this.localState.isGift === '1') {
return 0 return 0
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
} }
// 组合付款 // 组合付款
...@@ -278,13 +279,13 @@ export default { ...@@ -278,13 +279,13 @@ export default {
if (this.localState.mode === 'deduct' && this.localState.deductAmount) { if (this.localState.mode === 'deduct' && this.localState.deductAmount) {
const deductAmount = parseFloat(this.localState.deductAmount) const deductAmount = parseFloat(this.localState.deductAmount)
if (deductAmount >= 0.01 && deductAmount <= bp) { if (deductAmount >= 0.01 && deductAmount <= bp) {
return Math.round((bp - deductAmount) * 100) / 100 return utils.ceilDecimal(bp - deductAmount)
} }
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
} }
return Math.round(bp * 100) / 100 return utils.ceilDecimal(bp)
}, },
// 失去焦点时格式化(跟价格输入框一样的逻辑) // 失去焦点时格式化(跟价格输入框一样的逻辑)
onBlur(key) { onBlur(key) {
......
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
</view> </view>
</template> </template>
<script> <script>
import utils from '@/utils/utils'
export default { export default {
name: 'Package', name: 'Package',
props: { props: {
...@@ -199,7 +200,7 @@ export default { ...@@ -199,7 +200,7 @@ export default {
// 按当前单价和套餐数量,重新计算无优惠时的 finalPrice // 按当前单价和套餐数量,重新计算无优惠时的 finalPrice
const unitPrice = parseFloat(goods.sellPrice || 0) const unitPrice = parseFloat(goods.sellPrice || 0)
const number = parseInt(item?.packageGoods?.number || 1) const number = parseInt(item?.packageGoods?.number || 1)
const totalFinalPrice = Math.round(unitPrice * number * 100) / 100 const totalFinalPrice = utils.ceilDecimal(unitPrice * number)
this.$set(goods, 'finalPricePerUnit', unitPrice) this.$set(goods, 'finalPricePerUnit', unitPrice)
this.$set(goods, 'finalPrice', totalFinalPrice) this.$set(goods, 'finalPrice', totalFinalPrice)
} }
......
...@@ -147,7 +147,6 @@ import OrderPopup from '@/components/OrderPopup/index.vue' ...@@ -147,7 +147,6 @@ import OrderPopup from '@/components/OrderPopup/index.vue'
import SelectCar from './components/SelectCar.vue' import SelectCar from './components/SelectCar.vue'
import FormCell from './components/FormCell.vue' import FormCell from './components/FormCell.vue'
import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js' import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js'
import { appendImageOssProcess } from '@/utils/ossImageProcess.js'
import SelectCity from './components/SelectCity.vue' import SelectCity from './components/SelectCity.vue'
import UploadMedia from './components/uploadMedia.vue' import UploadMedia from './components/uploadMedia.vue'
import NoticePopup from '@/components/NoticePopup.vue' import NoticePopup from '@/components/NoticePopup.vue'
...@@ -1236,7 +1235,6 @@ export default { ...@@ -1236,7 +1235,6 @@ export default {
// 上传所有选择的图片 // 上传所有选择的图片
for (const tempFilePath of res.tempFilePaths) { for (const tempFilePath of res.tempFilePaths) {
let url = await uploadFile(tempFilePath) let url = await uploadFile(tempFilePath)
url = appendImageOssProcess(url)
console.log('上传图片成功', url) console.log('上传图片成功', url)
this[type](url) this[type](url)
} }
...@@ -1265,7 +1263,6 @@ export default { ...@@ -1265,7 +1263,6 @@ export default {
// 上传所有选择的图片 // 上传所有选择的图片
for (const tempFilePath of res.tempFilePaths) { for (const tempFilePath of res.tempFilePaths) {
let url = await uploadFile(tempFilePath) let url = await uploadFile(tempFilePath)
url = appendImageOssProcess(url)
console.log('上传图片成功', url) console.log('上传图片成功', url)
this[type](url) this[type](url)
} }
......
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
<script> <script>
// import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js' // import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js'
import { uploadFile } from '@/utils/ossUpload.js' import { uploadFile } from '@/utils/ossUpload.js'
import { appendImageOssProcess, getImageDisplayUrl } from '@/utils/ossImageProcess.js' import { getImageDisplayUrl } from '@/utils/ossImageProcess.js'
import permision from '@/js_sdk/wa-permission/permission.js' import permision from '@/js_sdk/wa-permission/permission.js'
export default { export default {
...@@ -156,7 +156,6 @@ export default { ...@@ -156,7 +156,6 @@ export default {
// 上传所有选择的图片 // 上传所有选择的图片
for (let i = 0; i < res.tempFilePaths.length; i++) { for (let i = 0; i < res.tempFilePaths.length; i++) {
let url = await uploadFile(res.tempFiles[i], res.tempFilePaths[i]) let url = await uploadFile(res.tempFiles[i], res.tempFilePaths[i])
url = appendImageOssProcess(url)
uni.hideLoading() uni.hideLoading()
...@@ -198,7 +197,6 @@ export default { ...@@ -198,7 +197,6 @@ export default {
// 上传所有选择的图片 // 上传所有选择的图片
for (let i = 0; i < res.tempFilePaths.length; i++) { for (let i = 0; i < res.tempFilePaths.length; i++) {
let url = await uploadFile(res.tempFiles[i], res.tempFilePaths[i]) let url = await uploadFile(res.tempFiles[i], res.tempFilePaths[i])
url = appendImageOssProcess(url)
console.log('上传图片成功', url) console.log('上传图片成功', url)
uni.hideLoading() uni.hideLoading()
// const fileExtension = res.tempFiles[0]?.name ? res.tempFiles[0]?.name.split('.').pop().toLowerCase() : res.tempFiles[0]?.path.split('.').pop().toLowerCase() // const fileExtension = res.tempFiles[0]?.name ? res.tempFiles[0]?.name.split('.').pop().toLowerCase() : res.tempFiles[0]?.path.split('.').pop().toLowerCase()
......
...@@ -119,7 +119,7 @@ ...@@ -119,7 +119,7 @@
<script> <script>
// import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js' // import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js'
import { uploadFile } from '@/utils/ossUpload.js' import { uploadFile } from '@/utils/ossUpload.js'
import { appendImageOssProcess, getImageDisplayUrl } from '@/utils/ossImageProcess.js' import { getImageDisplayUrl } from '@/utils/ossImageProcess.js'
import FormCell from './components/FormCell.vue' import FormCell from './components/FormCell.vue'
import GeneralPopup from './components/GeneralPopup.vue' import GeneralPopup from './components/GeneralPopup.vue'
import OrderPopup from '@/components/OrderPopup/index.vue' import OrderPopup from '@/components/OrderPopup/index.vue'
...@@ -671,8 +671,8 @@ export default { ...@@ -671,8 +671,8 @@ export default {
}, },
// 添加图片到对应的数组中(确保响应式更新) // 添加图片到对应的数组中(确保响应式更新)
addImage(field, url) { addImage(field, url) {
// 图片追加 OSS 处理参数,视频不处理 // 上传完成后保持原始 URL;仅在回显/预览时拼接 OSS 处理参数展示
const finalUrl = url.includes(this.videoProcess) ? url : appendImageOssProcess(url) const finalUrl = url
// 添加新图片 // 添加新图片
if (!Array.isArray(this.uploadedImages[field.key])) { if (!Array.isArray(this.uploadedImages[field.key])) {
this.$set(this.uploadedImages, field.key, []) this.$set(this.uploadedImages, field.key, [])
......
...@@ -373,7 +373,7 @@ import FormCell from './components/FormCell.vue' ...@@ -373,7 +373,7 @@ import FormCell from './components/FormCell.vue'
import GeneralPopup from './components/GeneralPopup.vue' import GeneralPopup from './components/GeneralPopup.vue'
// import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js' // import { uploadFile } from '@/utils/ossUploadFile/uploadFile.js'
import { uploadFile } from '@/utils/ossUpload.js' import { uploadFile } from '@/utils/ossUpload.js'
import { appendImageOssProcess, getImageDisplayUrl } from '@/utils/ossImageProcess.js' import { getImageDisplayUrl } from '@/utils/ossImageProcess.js'
import OrderPopup from '@/components/OrderPopup/index.vue' import OrderPopup from '@/components/OrderPopup/index.vue'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import NoticePopup from '@/components/NoticePopup.vue' import NoticePopup from '@/components/NoticePopup.vue'
...@@ -1416,8 +1416,8 @@ export default { ...@@ -1416,8 +1416,8 @@ export default {
}) })
}, },
addMedia(field, media) { addMedia(field, media) {
const url = media.type === 'image' ? appendImageOssProcess(media.url) : media.url // 上传完成后保持原始 URL;仅在回显/预览时拼接 OSS 处理参数展示
this.$set(this.formData, field, url) this.$set(this.formData, field, media.url)
}, },
removeMedia(field) { removeMedia(field) {
// 显示确认对话框 // 显示确认对话框
......
...@@ -13,14 +13,17 @@ ...@@ -13,14 +13,17 @@
{{ imgList.length }}/10 {{ imgList.length }}/10
</view> </view>
</template> </template>
<template v-for="(i, index) in imgList"> <view
<view class="img-item" :key="index"> class="img-item"
<image :src="i" class="img" mode="aspectFill" @click="previewMedia(i, 1)" /> v-for="(i, index) in imgList"
<view class="del flex"> :key="index"
<uni-icons type="closeempty" :size="10" color="#fff" @click="delImage(index)"></uni-icons> >
</view> <!-- 缩略图展示时为图片拼接 OSS 预览参数,存储与提交依然使用原始 URL -->
<image :src="getImageDisplayUrl(i)" class="img" mode="aspectFill" @click="previewMedia(i, 1)" />
<view class="del flex">
<uni-icons type="closeempty" :size="10" color="#fff" @click="delImage(index)"></uni-icons>
</view> </view>
</template> </view>
</view> </view>
<view class="img-tips">单个文件不超过10M,最多可上传10张。</view> <view class="img-tips">单个文件不超过10M,最多可上传10张。</view>
</view> </view>
...@@ -46,6 +49,7 @@ ...@@ -46,6 +49,7 @@
<script type="text/ecmascript-6"> <script type="text/ecmascript-6">
import { uploadFile } from '@/utils/ossUpload.js' import { uploadFile } from '@/utils/ossUpload.js'
import permision from '@/js_sdk/wa-permission/permission.js' import permision from '@/js_sdk/wa-permission/permission.js'
import { getImageDisplayUrl as rawGetImageDisplayUrl } from '@/utils/ossImageProcess.js'
const MAX_IMAGE_SIZE = 10 * 1024 * 1024, // 图片最大10MB const MAX_IMAGE_SIZE = 10 * 1024 * 1024, // 图片最大10MB
MAX_IMG_COUNT = 10 // 最大图片数量 MAX_IMG_COUNT = 10 // 最大图片数量
export default { export default {
...@@ -68,6 +72,9 @@ export default { ...@@ -68,6 +72,9 @@ export default {
mounted() { mounted() {
}, },
methods: { methods: {
getImageDisplayUrl(url) {
return rawGetImageDisplayUrl(url)
},
delImage(index) { delImage(index) {
this.imgList.splice(index, 1) this.imgList.splice(index, 1)
}, },
......
<template> <template>
<view class="step-3"> <view class="step-3">
<view class="upload-box box"> <view class="upload-box box">
<view class="title"> <view class="title">交付照片</view>
交付照片
</view>
<view class="img-list flex"> <view class="img-list flex">
<template v-for="(i, index) in detail.imgList"> <template v-for="(i, index) in detail.imgList">
<view <view class="img-item" :key="index">
class="img-item" <image :src="getImageDisplayUrl(i)" class="img" mode="aspectFill" @click="previewMedia(i, 1)" />
:key="index"
>
<image
:src="i"
class="img"
mode="aspectFill"
@click="previewMedia(i, 1)"
/>
</view> </view>
</template> </template>
</view> </view>
...@@ -30,7 +20,7 @@ ...@@ -30,7 +20,7 @@
<view class="sprite-icon icon-delivery-step-2"></view> <view class="sprite-icon icon-delivery-step-2"></view>
<view class="info"> <view class="info">
客户提车确认 客户提车确认
<view class="des">提车时间:{{detail.pickUpTime}}</view> <view class="des">提车时间:{{ detail.pickUpTime }}</view>
</view> </view>
<view class="btn flex">已提车</view> <view class="btn flex">已提车</view>
</view> </view>
...@@ -38,6 +28,7 @@ ...@@ -38,6 +28,7 @@
</template> </template>
<script type="text/ecmascript-6"> <script type="text/ecmascript-6">
import { getImageDisplayUrl as rawGetImageDisplayUrl } from '@/utils/ossImageProcess.js'
export default { export default {
name: '', name: '',
props: { props: {
...@@ -56,6 +47,9 @@ export default { ...@@ -56,6 +47,9 @@ export default {
mounted () { mounted () {
}, },
methods: { methods: {
getImageDisplayUrl (url) {
return rawGetImageDisplayUrl(url)
},
previewMedia (media, type) { previewMedia (media, type) {
const url = `/pages/boutique/preview?tabName=预览&sourceType=${type}&detailUrl=${media}` const url = `/pages/boutique/preview?tabName=预览&sourceType=${type}&detailUrl=${media}`
uni.navigateTo({ uni.navigateTo({
......
...@@ -48,12 +48,14 @@ export default { ...@@ -48,12 +48,14 @@ export default {
}) })
return return
} }
this.$refs.home.updateApp() // this.$refs.home.updateApp()
this.$refs.home?.updateApp()
this.init() this.init()
}, },
methods: { methods: {
init () { init () {
this.$refs.home.$refs.leftBox.getMessageInfo() // this.$refs.home.$refs.leftBox.getMessageInfo()
this.$refs.home?.$refs?.leftBox?.getMessageInfo()
}, },
} }
} }
......
...@@ -15,6 +15,7 @@ import update from './modules/update' ...@@ -15,6 +15,7 @@ import update from './modules/update'
import sys from './modules/sys' import sys from './modules/sys'
import point from './modules/point' import point from './modules/point'
import boutique from './modules/boutique' import boutique from './modules/boutique'
import createActivityTracker from './plugins/activityTracker'
Vue.use(Vuex) Vue.use(Vuex)
const store = new Vuex.Store({ const store = new Vuex.Store({
...@@ -26,7 +27,15 @@ const store = new Vuex.Store({ ...@@ -26,7 +27,15 @@ const store = new Vuex.Store({
point, point,
boutique boutique
}, },
getters getters,
plugins: [
createActivityTracker([
// 'setCustomerInfo',
'setReceptionTrack',
// 'setPaymentType',
// 'setCurrentCarInfo'
])
]
}) })
// Vue.prototype.$store = store; // Vue.prototype.$store = store;
......
...@@ -51,6 +51,26 @@ export default { ...@@ -51,6 +51,26 @@ export default {
state.customerInfo = data state.customerInfo = data
state.customerKey = Date.now() state.customerKey = Date.now()
}, },
setReceptionTrack (state, { key, value }) {
state.receptionTrack[key] = value
state.receptionKey = Date.now()
},
clearReceptionTrack (state) {
state.receptionTrack = {}
state.receptionKey = Date.now()
},
updateViewKey (state) {
state.viewKey = Date.now();
},
setPaymentType (state, value) {
state.paymentType = value;
},
setCarBrandsList (state, value) {
state.carBrands = value;
},
setEmployeeList (state, value) {
state.employeeList = value;
},
setCurrentCarInfo (state, data = {}) { setCurrentCarInfo (state, data = {}) {
state.currentCarInfo = data; state.currentCarInfo = data;
}, },
...@@ -80,7 +100,7 @@ export default { ...@@ -80,7 +100,7 @@ export default {
return state.customerInfo; return state.customerInfo;
}, },
setCustomerInfo ({ commit }, value) { setCustomerInfo ({ commit }, value) {
uni.$logger.local.info(`当前接待客户信息: ${JSON.stringify(value)}`) // uni.$logger.local.info(`当前接待客户信息: ${JSON.stringify(value)}`)
commit("setCustomerInfo", value); commit("setCustomerInfo", value);
}, },
clearCustomerInfo ({ commit }) { clearCustomerInfo ({ commit }) {
...@@ -89,26 +109,23 @@ export default { ...@@ -89,26 +109,23 @@ export default {
clearHistory ({ state }) { clearHistory ({ state }) {
state.historyStatus = Date.now(); state.historyStatus = Date.now();
}, },
setPaymentType ({ state }, value) { setPaymentType ({ commit }, value) {
state.paymentType = value; commit('setPaymentType', value)
}, },
setCarBrandsList ({ state }, value) { setCarBrandsList ({ commit }, value) {
state.carBrands = value; commit('setCarBrandsList', value)
}, },
setEmployeeList ({ state }, value) { setEmployeeList ({ commit }, value) {
state.employeeList = value; commit('setEmployeeList', value)
}, },
setReceptionTrack ({ state }, { key, value }) { setReceptionTrack ({ commit }, { key, value }) {
state.receptionTrack[key] = value commit('setReceptionTrack', { key, value })
state.receptionKey = Date.now()
}, },
clearReceptionTrack ({ state }) { clearReceptionTrack ({ commit }) {
state.receptionTrack = {} commit('clearReceptionTrack')
state.receptionKey = Date.now()
}, },
updateViewKey ({ state }) { updateViewKey ({ commit }) {
state.viewKey = Date.now(); commit('updateViewKey')
}, },
setCurrentCarInfo ({ commit }, value) { setCurrentCarInfo ({ commit }, value) {
commit("setCurrentCarInfo", value); commit("setCurrentCarInfo", value);
......
// store/plugins/activityTracker.js
import utils from '@/utils/utils'
/**
* 自动监听用户活跃状态的 Vuex 插件
* 当指定的 mutation 发生时,触发 reset_timeout 事件
*/
export default function createActivityTracker(mutationsToWatch = []) {
// 使用 utils.throttle 限制触发频率,避免高频 mutation 导致过多 emit
const notifyActivity = utils.throttle(() => {
uni.$emit('reset_timeout')
}, 1000)
return store => {
store.subscribe((mutation, state) => {
// 如果 mutation 在监控列表中,则触发活跃通知
if (mutationsToWatch.includes(mutation.type)) {
notifyActivity()
}
})
}
}
/*
* @Descripttion: 通用任务队列类实现了串行执行、超时控制、异常隔离等功能
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-14 12:03:27
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:45:20
* @FilePath: \gl_tape\utils\TaskQueue.js
*/
export default class TaskQueue {
constructor(name = 'TaskQueue') {
this.name = name
this.queue = Promise.resolve()
}
/**
* 将任务加入队列
* @param {Function} task - 返回 Promise 的任务函数
* @param {number} timeout - 超时时间(ms),默认 20000
* @returns {Promise}
*/
enqueue(task, timeout = 20000) {
const taskWithTimeout = () => this._withTimeout(task, timeout)
// 将任务追加到队列末尾
const next = this.queue.then(taskWithTimeout).catch(err => {
// 队列自身的错误不应中断后续任务,但这里的 err 已经被 taskWithTimeout 内部捕获并处理了
// 这里再次抛出是为了让调用者能捕获到错误
throw err
})
// 更新队列指针,确保队列始终指向最新的 Promise,且永远是 resolved 状态(catch 了错误)
// 这样后续任务不会因为前一个任务失败而无法执行
this.queue = next.catch(() => {})
return next
}
/**
* 带超时控制的任务执行器
* @private
*/
_withTimeout(task, timeout) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
const error = new Error(`${this.name}操作超时(${timeout}ms)`)
uni.$logger.local.error(error.message)
reject(error)
}, timeout)
// 使用 Promise.resolve().then(task) 确保即使 task() 同步抛错也能被捕获并进入 finally
Promise.resolve().then(task)
.then(resolve)
.catch(reject)
.finally(() => clearTimeout(timeoutId))
})
}
}
\ No newline at end of file \ No newline at end of file
...@@ -44,5 +44,6 @@ export const STORAGE_OBJECTKEY = { ...@@ -44,5 +44,6 @@ export const STORAGE_OBJECTKEY = {
studyCenterPermission: 'studyCenterPermission', studyCenterPermission: 'studyCenterPermission',
caseInfo: 'caseInfo', caseInfo: 'caseInfo',
boutique_YQorderSetting: 'boutique_YQorderSetting', boutique_YQorderSetting: 'boutique_YQorderSetting',
sessionId:'sessionId' sessionId: 'sessionId',
createAllGoodsFlag: 'createAllGoodsFlag'
} }
...@@ -3,20 +3,35 @@ import { LogLevel } from './constants' ...@@ -3,20 +3,35 @@ import { LogLevel } from './constants'
import { getTime, withinSpliter, daysBetween } from './util' import { getTime, withinSpliter, daysBetween } from './util'
class LocalLog { class LocalLog {
logger = null logger = null
logListener = null
constructor() { constructor() {
this.logger = new LogCat() this.logger = new LogCat()
this.removeOverDays(90)
}
setLogListener(listener) {
this.logListener = listener
}
_write(level, msg) {
this.logger.writeLog(level, msg)
if (this.logListener) {
try {
this.logListener(level, msg)
} catch (e) {
console.error('LocalLog listener error', e)
}
}
} }
debug(msg) { debug(msg) {
this.logger.writeLog(LogLevel.DEBUG, msg) this._write(LogLevel.DEBUG, msg)
} }
info(msg) { info(msg) {
this.logger.writeLog(LogLevel.INFO, msg) this._write(LogLevel.INFO, msg)
} }
warn(msg) { warn(msg) {
this.logger.writeLog(LogLevel.WARN, msg) this._write(LogLevel.WARN, msg)
} }
error(msg) { error(msg) {
this.logger.writeLog(LogLevel.ERROR, msg) this._write(LogLevel.ERROR, msg)
} }
getFiles(beginDate, endDate) { getFiles(beginDate, endDate) {
const logFiles = this.logger.getLogFileList() const logFiles = this.logger.getLogFileList()
...@@ -36,15 +51,16 @@ class LocalLog { ...@@ -36,15 +51,16 @@ class LocalLog {
return fileList return fileList
} }
removeOverDays(day = 7) { removeOverDays(day = 7) {
const logFiles = this.logger.getLogFileList() this.logger._cleanOldLogs(day)
if (!logFiles.length) return // const logFiles = this.logger.getLogFileList()
const today = getTime('YYYY-MM-DD') // if (!logFiles.length) return
logFiles.forEach(({ name, path }) => { // const today = getTime('YYYY-MM-DD')
const fileDate = name.split('.').shift() // logFiles.forEach(({ name, path }) => {
if (daysBetween(fileDate, today) > day) { // const fileDate = name.split('.').shift()
this.logger.removeLogFile(path) // if (daysBetween(fileDate, today) > day) {
} // this.logger.removeLogFile(path)
}) // }
// })
} }
} }
export default LocalLog export default LocalLog
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-09-03 14:22:52
* @LastEditors: limin
* @LastEditTime: 2026-01-22 16:21:17
* @FilePath: \gl_tape\utils\logger\RemoteLog.js
*/
import sentryInit from '@/utils/sentryConfig/sentryInit' import sentryInit from '@/utils/sentryConfig/sentryInit'
import { LogLevel , RemoteExtraDataKey} from './constants' import { LogLevel , RemoteExtraDataKey} from './constants'
class RemoteLog { class RemoteLog {
...@@ -20,10 +29,43 @@ class RemoteLog { ...@@ -20,10 +29,43 @@ class RemoteLog {
} }
send(level, { extra = {}, msg, tag = { key: '', value: '' } }) { send(level, { extra = {}, msg, tag = { key: '', value: '' } }) {
this.sentry.withScope(scope => { this.sentry.withScope(scope => {
scope.setTags(tag.key, tag.value) // 1. 设置 Tag
scope.setExtra(RemoteExtraDataKey, extra) if (tag && tag.key) {
scope.setTag(tag.key, tag.value)
}
// 2. 自动补充环境信息到 Extra
const systemInfo = uni.getSystemInfoSync()
const enhancedExtra = {
...extra,
device_brand: systemInfo.brand,
device_model: systemInfo.model,
os_name: systemInfo.osName, // uni-app x 支持,或用 platform
os_version: systemInfo.osVersion,
uni_platform: systemInfo.uniPlatform,
app_version: systemInfo.appVersion,
network_type: 'unknown' // 可选:尝试获取网络状态
}
// 尝试获取网络状态(如果允许异步)
// uni.getNetworkType({ success: (res) => enhancedExtra.network_type = res.networkType })
scope.setExtra(RemoteExtraDataKey, enhancedExtra)
// 3. 设置级别
scope.setLevel(level) scope.setLevel(level)
this.sentry.captureException(new Error(msg))
// 4. 上报 (区分 Error 对象和普通消息)
// 如果 msg 本身就是 Error 对象,直接上报以保留堆栈信息
// 如果是字符串,则包装成 Error
if (msg instanceof Error) {
this.sentry.captureException(msg)
} else {
// 将字符串消息作为 Error 的 message,这样在 Sentry 面板中更直观
const error = new Error(String(msg))
// 可以手动尝试附加调用栈(虽然 new Error 已经有了)
this.sentry.captureException(error)
}
}) })
} }
} }
......
...@@ -8,6 +8,7 @@ class Logger { ...@@ -8,6 +8,7 @@ class Logger {
remote = null remote = null
local = null local = null
fields = [] fields = []
logListener = null
constructor(fields = []) { constructor(fields = []) {
this.fields = fields this.fields = fields
this.init() this.init()
...@@ -17,6 +18,12 @@ class Logger { ...@@ -17,6 +18,12 @@ class Logger {
this.remote = new RemoteLog(user) this.remote = new RemoteLog(user)
this.local = new LocalLog() this.local = new LocalLog()
} }
setLogListener(listener) {
this.logListener = listener
if (this.local) {
this.local.setLogListener(listener)
}
}
debug(info) { debug(info) {
this.write(LogLevel.DEBUG, info) this.write(LogLevel.DEBUG, info)
} }
...@@ -32,6 +39,14 @@ class Logger { ...@@ -32,6 +39,14 @@ class Logger {
write(level, info) { write(level, info) {
this.remote[level](info) this.remote[level](info)
this.local[level](info) this.local[level](info)
// console.log("🚀 ~ Logger ~ write ~ level:", this.logListener)
// if (this.logListener) {
// try {
// this.logListener(level, info)
// } catch (e) {
// console.error('Log listener error', e)
// }
// }
} }
getUserInfo() { getUserInfo() {
const userInfo = storageApi.getUserInfo() const userInfo = storageApi.getUserInfo()
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* OSS 图片处理参数 * OSS 图片处理参数
* 用于上传图片返回地址及详情/编辑回显时的图片展示 * 用于上传图片返回地址及详情/编辑回显时的图片展示
*/ */
export const IMAGE_OSS_PROCESS = 'x-oss-process=image/format,jpg/quality,q_100' const IMAGE_OSS_PROCESS = 'x-oss-process=image/format,jpg/quality,q_100'
const VIDEO_EXTENSIONS = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.m4v', '.3gp', '.mkv', '.webm'] const VIDEO_EXTENSIONS = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.m4v', '.3gp', '.mkv', '.webm']
const VIDEO_OSS_SNAPSHOT = 'x-oss-process=video/snapshot' const VIDEO_OSS_SNAPSHOT = 'x-oss-process=video/snapshot'
...@@ -12,7 +12,7 @@ const VIDEO_OSS_SNAPSHOT = 'x-oss-process=video/snapshot' ...@@ -12,7 +12,7 @@ const VIDEO_OSS_SNAPSHOT = 'x-oss-process=video/snapshot'
* @param {string} url - 媒体 URL * @param {string} url - 媒体 URL
* @returns {boolean} * @returns {boolean}
*/ */
export function isVideoUrl(url) { function isVideoUrl(url) {
if (!url || typeof url !== 'string') return false if (!url || typeof url !== 'string') return false
if (url.includes(VIDEO_OSS_SNAPSHOT)) return true if (url.includes(VIDEO_OSS_SNAPSHOT)) return true
const urlLower = url.toLowerCase() const urlLower = url.toLowerCase()
...@@ -25,7 +25,7 @@ export function isVideoUrl(url) { ...@@ -25,7 +25,7 @@ export function isVideoUrl(url) {
* @param {string} url - 原始 URL * @param {string} url - 原始 URL
* @returns {string} 带处理参数的 URL * @returns {string} 带处理参数的 URL
*/ */
export function appendImageOssProcess(url) { function appendImageOssProcess(url) {
if (!url || typeof url !== 'string') return url || '' if (!url || typeof url !== 'string') return url || ''
if (isVideoUrl(url)) return url if (isVideoUrl(url)) return url
if (url.includes(IMAGE_OSS_PROCESS)) return url if (url.includes(IMAGE_OSS_PROCESS)) return url
...@@ -40,9 +40,16 @@ export function appendImageOssProcess(url) { ...@@ -40,9 +40,16 @@ export function appendImageOssProcess(url) {
* @param {boolean} [isImageType] - 已知为图片类型时可传 true,跳过视频判断 * @param {boolean} [isImageType] - 已知为图片类型时可传 true,跳过视频判断
* @returns {string} * @returns {string}
*/ */
export function getImageDisplayUrl(url, isImageType = false) { function getImageDisplayUrl(url, isImageType = false) {
if (!url || typeof url !== 'string') return url || '' if (!url || typeof url !== 'string') return url || ''
if (isImageType) return appendImageOssProcess(url) if (isImageType) return appendImageOssProcess(url)
if (isVideoUrl(url)) return url if (isVideoUrl(url)) return url
return appendImageOssProcess(url) return appendImageOssProcess(url)
} }
module.exports = {
IMAGE_OSS_PROCESS,
isVideoUrl,
appendImageOssProcess,
getImageDisplayUrl
}
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-12-04 18:17:23
* @LastEditors: limin
* @LastEditTime: 2025-01-06 18:50:33
* @FilePath: \gl_tape\utils\recordManager\AudioManager.js
*/
class AudioManager {
startOptions = {
duration: 10 * 60 * 1000, //默认10分钟
sampleRate: 16000,
numberOfChannels: 1
}
__isRecording = false
__counter = 0
events = {}
/**
* AudioManager类的构造函数
* 负责初始化音频管理器实例,包括音频录制的开始、停止和错误处理
* @param {Function} onStart - 音频录制开始时的回调函数
* @param {Function} onStop - 音频录制停止时的回调函数
* @param {Function} onError - 音频录制遇到错误时的回调函数
*/
constructor(onStart, onStop, onError) {
this.on()
this.events = {
onStart,
onStop,
onError
}
}
on() {
this.recorderManager = uni.getRecorderManager()
this.recorderManager.onStart(this.onStart.bind(this))
this.recorderManager.onStop(this.onStop.bind(this))
this.recorderManager.onError(this.onError.bind(this))
}
/**
* 启动录音管理器开始录音
* 此方法用于初始化录音过程,它将配置参数应用到录音管理器,并开始录音
*/
start() {
uni.$logger.local.info('〖录音管理Audio〗 == 开启录音 ')
this.recorderManager.start(this.startOptions)
}
/**
* 异步处理录音开始时的回调函数
*
* 此函数在录音开始时被调用,主要用于执行一些初始化操作和状态更新
* 它首先记录了一条信息到日志,然后执行事件的onStart方法,
* 并且更新内部计数器和录音状态标志
*/
async onStart() {
// 记录录音开始的信息到日志
uni.$logger.local.info('〖录音管理Audio〗 == 开启录音回调 ')
// 等待事件的onStart方法执行完成
await this.events.onStart()
// 内部计数器增加,用于跟踪录音开始的次数
this.__counter++
// 设置录音状态标志为true,表示当前正在录音
this.__isRecording = true
}
/**
* 停止录音功能
*
* 此方法用于停止当前正在进行的录音操作它首先记录了停止录音的信息,
* 然后重置了当前的录音状态,最后通过调用RecorderManager的stop方法来停止录音
*/
stop() {
// 记录停止录音的信息
uni.$logger.local.info('〖录音管理Audio〗 == 停止录音 ')
// 重置录音状态
this.reset()
// 调用RecorderManager的stop方法来停止录音
this.recorderManager.stop()
}
/**
* 异步处理停止录音的回调函数
* @param {Object} res - 停止录音的回调结果对象
*
* 此函数用于在录音停止时执行相应的逻辑它接收一个回调结果对象作为参数,
* 该对象包含有关停止录音的信息它首先记录了一条信息表示录音已停止,
* 然后调用events对象上的onStop方法处理具体的停止录音逻辑
*/
async onStop(res) {
uni.$logger.local.info('〖录音管理Audio〗 == 停止录音回调 ')
await this.events.onStop(res)
}
/**
* 异步处理错误的方法
*
* 当遇到错误时,此方法会被调用,它将等待错误事件处理完成
* 主要作用是将错误传递给注册在this.events上的错误事件处理器
*
* @param {Error} err - 发生的错误对象
*/
async onError(err) {
await this.events.onError(err)
}
/**
* 获取当前是否正在录音的状态
*
* 此方法用于获取实例当前的录音状态它返回一个布尔值,表示是否正在录音
* 该方法没有参数
*
* @returns {boolean} 当前是否正在录音true表示正在录音,false表示未在录音
*/
get isRecording() {
return this.__isRecording
}
/**
* 获取当前计数器的值
*
* 此方法作为属性访问器,用于获取内部私有属性 __counter 的值
* 它没有参数
* 返回值为当前计数器的值
*/
get counter() {
return this.__counter
}
onError(err) {}
/**
* 重置录音状态
*
* 此方法用于将录音管理器的状态重置为初始状态,即不是正在录音,且计数器清零
* 它主要用于准备开始新的录音过程或取消当前录音过程时,清理所有录音相关状态
*/
reset() {
// 记录重置录音状态的日志信息
uni.$logger.local.info('〖录音管理Audio〗 == 重置录音状态 ')
// 设置__isRecording属性为false,表示当前不处于录音状态
this.__isRecording = false
// 将__counter计数器重置为0,此计数器可能用于记录录音过程中的某些度量,如录音时间
this.__counter = 0
}
}
export default AudioManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 14:48:44
* @LastEditors: limin
* @LastEditTime: 2025-01-06 09:35:40
* @FilePath: \gl_tape\utils\recordManager\RecordDto.js
*/
export default class RecordDto {
staffUuid = ''
staffName = ''
serviceMerchantId = ''
carModel = ''
endReasonType = 1 //原因 1.异常 0.正常
customerName = ''
phoneNumber = ''
appCode = ''
loginPhone = ''
salesName = ''
salesUuid = ''
receptionStatus = '' //接待结果 1.成交 0.战败
receptionStartTime = ''
receptionEndTime = ''
receptionCustomerPaySourceList = [] //1.付款凭证文件路径 2.客户购车发票文件路径 3.客户延保合同文件路径
merchantId = ''
merchantName = ''
bussinessType = 0 // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
channelType = 1 //1问界 2 比亚迪 3 其他
receptionCustomerMaterialPointList = []
carBrand = ''
carBrandId = ''
oneCarBrand = ''
oneCarBrandId = ''
constructor(options) {
Object.assign(this, options)
}
}
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2025-08-12 10:23:15
* @FilePath: \gl_tape\utils\recordManager\TempRecord.js
*/
import utils from '../utils'
import helpler from './helpler'
import { FileStatus } from '../common/constants'
class TempRecord {
timer = null
timer_interval = 30 * 1000
record = null
path = ''
newRecord = null
onTempRecordNumberChanged = null
constructor(record, onTempRecordNumberChanged) {
this.newRecord = record
this.recordManager = uni.$dbTempRecord
this.dbManager = uni.$dbManager
this.onTempRecordNumberChanged = onTempRecordNumberChanged
}
getRecords() {
return this.recordManager.getRecords()
}
getRecord(id) {
return this.recordManager.getRecordById(id)
}
async addRecord(record = this.record) {
await this.recordManager.addRecord(record)
this.triggleRecordNumChanged()
}
updateRecord(item, where) {
return this.recordManager.updateRecord(item, where)
}
async removeRecord(id) {
await this.recordManager.removeRecord(id)
this.triggleRecordNumChanged()
}
async __update(key, value) {
if (this.record[key] === value) return
this.record[key] = value
return this.updateRecord({ [key]: value }, { id: this.record.id })
}
async getFilePath() {
if (!this.path) {
this.path = await utils.getFileSaveFolderOnClient()
}
return this.path
}
async save(record = this.record) {
try {
if (!record) throw new Error('记录对象为空')
uni.$logger.local.info('〖接待记录Record〗 == 开始持久化记录 ==' + JSON.stringify(record))
this.clearLoopTimer()
await this.saveTempFile(record)
const { recordUrlList, tempFilePath, ...__record } = record
const recordLongList = await this.__analysisUrlList(recordUrlList)
const { maxUploadNum = 10 } = uni.$storage.get('mock_data')
if (recordLongList.length > maxUploadNum) {
const userInfo = uni.$storage.get('userInfo')
const { customerName, phoneNumber, carModel, salesName } = record || {}
const { name } = userInfo || {}
uni.$logger.error({
msg: `员工: ${name}, 客户: ${customerName}`,
extra: {
'手机号: ': phoneNumber,
'姓名: ': customerName,
'销售: ': salesName,
'车型: ': carModel,
'原因: ': '录音文件过长,数量' + recordLongList.length
}
})
}
__record.recordUrlList = recordLongList.slice(0, maxUploadNum)
uni.$logger.local.info('〖接待记录Record〗 == 更新文件,保存记录!')
await this.dbManager.addRecord(__record)
await this.clearLocalRecord(record)
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 保存记录异常' + error.message)
}
}
async clearLocalRecord(record = this.record) {
const { id, tempFilePath } = record
uni.$logger.local.info('〖接待记录Record〗 == 删除临时文件' + tempFilePath)
await this.removeFile(tempFilePath)
await this.removeRecord(id)
record = null
uni.$logger.local.info('〖接待记录Record〗 == 置空接待记录')
}
/**
* 清除已保存的录音文件
* @param {Object} options - 配置参数
* @param {Array} options.recordUrlList - 录音文件列表,默认为当前记录的recordUrlList
*/
clearSavedFiles({ recordUrlList = [] } = this.record) {
// 遍历录音文件列表并删除每个文件
recordUrlList.forEach(item => {
this.removeFile(item.file)
})
}
async __analysisUrlList(recordUrlList) {
if (!recordUrlList?.length) return []
try {
const __path = await this.getFilePath()
const __list = recordUrlList.reduce((arr, item) => {
if (item?.file) {
arr.push({
status: FileStatus.Waiting,
file: __path + item.file.replace(/.+\/(\d+\.mp3)/, '$1')
})
} else {
uni.$logger.local.warn('〖接待记录Record〗 == 有文件为空路径,舍弃!! ==')
}
return arr
}, [])
return __list
} catch (error) {
uni.$logger.local.info('〖接待记录Record〗 == 解析接待文件列表异常' + error.message)
throw new Error(error.message)
}
}
/**
* 添加新的接待记录
*/
async add() {
// 创建一个新的记录对象
this.record = this.__createNewRecord()
// 异步添加新创建的记录对象
await this.addRecord(this.record)
// 添加音频资源
this.addAudio()
}
__createNewRecord() {
return {
id: utils.uuid(),
...this.newRecord,
receptionStartTime: this.getTimeNow(),
receptionEndTime: '',
recordUrlList: []
}
}
/**
* 添加音频
* @param {Object} isUpdate - 是否更新音频
* @returns {void}
*/
// Update the record with the new information
async addAudio() {
this.clearLoopTimer()
uni.$logger.local.info('〖接待记录Record〗 == 保存上一个临时文件!')
//保存上一个临时文件
await this.saveLastAudio()
//删除上一个临时文件
await this.removeOldTempAudio()
//等待1秒
await helpler.sleep(1000)
//新增一个录音
await this.addNewAudio()
//更新临时录音文件
await this.updatePath()
//开启轮询保存临时录音文件
this.startSaveAudioLoop()
}
async addNewAudio() {
const lastAudio = await helpler.getLatestAudioFilePath()
uni.$logger.local.info('〖接待记录Record〗 == 添加一个新的录音' + lastAudio)
this.record.tempFilePath = lastAudio
const __path = await this.saveFilePath(lastAudio)
this.record.recordUrlList.push({ file: __path })
}
removeOldTempAudio() {
const { tempFilePath } = this.record
uni.$logger.local.info('〖接待记录Record〗 == 删除上一个临时文件 -> ' + tempFilePath)
return this.removeFile(tempFilePath)
}
updatePath() {
const { id, tempFilePath, recordUrlList } = this.record
return this.updateRecord({ tempFilePath, recordUrlList }, { id })
}
/**
* 保存文件
* @param {Object} record - 接待记录对象
* @returns - 返回保存后的文件路径
*/
async saveTempFile(record = this.record) {
const { tempFilePath, recordUrlList } = record
const lastIndex = recordUrlList.length - 1
if (lastIndex < 0 || !tempFilePath) return
const { file } = recordUrlList[lastIndex]
const saveResultPath = await this.saveFilePath(tempFilePath)
if (saveResultPath) {
uni.$logger.local.info('〖接待记录Record〗 == 删除上一次保存的文件 ' + file)
await this.removeFile(file)
record.recordUrlList[lastIndex].file = saveResultPath
}
return saveResultPath
}
async saveFilePath(tempFilePath) {
uni.$logger.local.info('〖接待记录Record〗 == 开始保存临时录音 tempFilePath-> ' + tempFilePath)
if (!tempFilePath) return
const saveResult = await uni.saveFile({
tempFilePath
})
let saveResultPath = saveResult[1]?.savedFilePath
uni.$logger.local.info('〖接待记录Record〗 == 保存后的文件路径 saveResultPath ->' + saveResultPath)
return saveResultPath
}
removeFile(filePath) {
if (!filePath) return
return new Promise(resolve => {
uni.removeSavedFile({
filePath,
complete: resolve
})
})
}
async saveLastAudio() {
const __path = await this.saveTempFile()
__path && this.updateUrlList()
}
updateUrlList() {
const { id, recordUrlList } = this.record
return this.updateRecord({ recordUrlList }, { id })
}
startSaveAudioLoop() {
this.clearLoopTimer()
this.timer = setInterval(this.saveLastAudio.bind(this), this.timer_interval)
}
clearLoopTimer() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}
get currentRecord() {
return this.record
}
setReceptionEndTime() {
return this.__update('receptionEndTime', this.getTimeNow())
}
getTimeNow() {
return utils.convertDateTimeFormat(new Date(), '/')
}
withError() {
return this.__update('endReasonType', 1)
}
async updatePreRecords(items) {
if (items) {
Object.keys(items).forEach(async key => await this.__update(key, items[key]))
}
return this.record
}
async triggleRecordNumChanged() {
if (this.onTempRecordNumberChanged) {
this.onTempRecordNumberChanged()
}
}
}
export default TempRecord
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:34:39
* @LastEditors: limin
* @LastEditTime: 2025-01-06 09:36:04
* @FilePath: \gl_tape\utils\recordManager\dbRecord.js
*/
import DBManager from '../DBManager.js'
class DBRecord {
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',
'tempFilePath TEXT',
'carBrand TEXT',
'carBrandId INTEGER',
'oneCarBrand TEXT',
'oneCarBrandId INTEGER'
]
table_name = 'temp_records'
constructor() {
this.db = new DBManager(this.table_name, this.table_columns)
return this.db
}
}
export default DBRecord
import utils from '../utils'
/**
* 内部方法,用于获取完整的音频文件路径
*
* 此函数调用 `getAudioPathName` 获取文件名,并通过 `getAudioPath` 获取完整路径。
*/
async function getLatestAudioFilePath() {
const pathName = await __getAudioPathName()
return __getAudioPath(pathName)
}
/**
* 异步获取音频文件路径名称
*
* 此函数用于查找特定目录中所有以 'uniapp_temp' 开头的文件,并返回修改时间最晚的文件名。
* 如果没有找到符合条件的文件,则返回一个空字符串或抛出错误。
*/
async function __getAudioPathName() {
const path = await utils.getAudioFilePath()
return __getLatestFileName(path, 'uniapp_temp')
}
/**
* 异步获取指定名称的音频文件路径
*
* 此函数用于根据给定的文件名查找其完整路径,并返回修改时间最晚的文件路径。
* 如果没有找到符合条件的文件,则返回一个空字符串或抛出错误。
* @param {string} name - 文件名(不包含扩展名)
*/
async function __getAudioPath(name) {
const path = await utils.getAudioFilePath(name + '/recorder')
return __getLatestFilePath(path)
}
/**
* 获取指定目录中修改时间最晚的文件名
*
* @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选)
* @returns {Promise<string>} - 修改时间最晚的文件名
*/
async function __getLatestFileName(directoryPath, prefix = '') {
const latestFile = await __getLatestFile(directoryPath, prefix)
return latestFile ? latestFile.name : ''
}
/**
* 获取指定目录中修改时间最晚的文件路径
*
* @param {string} directoryPath - 目录路径
* @returns {Promise<string>} - 修改时间最晚的文件路径
*/
async function __getLatestFilePath(directoryPath) {
const latestFile = await __getLatestFile(directoryPath)
return latestFile ? directoryPath + '/' + latestFile.name : ''
}
/**
* 获取指定目录中修改时间最晚的文件
*
* @param {string} directoryPath - 目录路径
* @param {string} prefix - 文件名前缀(可选)
* @returns {Promise<object|null>} - 修改时间最晚的文件对象或 null
*/
async function __getLatestFile(directoryPath, prefix = '') {
return new Promise((resolve, reject) => {
plus.io.resolveLocalFileSystemURL(
directoryPath,
e => {
const dirR = e.createReader()
dirR.readEntries(
async entries => {
const files = entries.filter(item => (prefix ? item.name.startsWith(prefix) : true))
const filePromises = files.map(item => __getFileMetadata(item))
const results = await Promise.all(filePromises)
const latest = results.reduce((acc, current) => (current.modificationTime > acc.modificationTime ? current : acc), { modificationTime: 0 })
resolve(latest.name ? latest : null)
},
err => reject(err)
)
},
err => reject(err)
)
})
}
/**
* 获取文件的元数据
*
* @param {object} fileEntry - 文件条目
* @returns {Promise<object>} - 文件元数据
*/
async function __getFileMetadata(fileEntry) {
return new Promise((resolve, reject) => {
fileEntry.getMetadata(
metadata => {
resolve({
name: fileEntry.name,
modificationTime: new Date(metadata.modificationTime).getTime()
})
},
err => reject(err)
)
})
}
async function sleep(time){
return new Promise(resolve => setTimeout(resolve, time))
}
export default {
getLatestAudioFilePath,
sleep
}
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-06-28 17:12:39
* @LastEditors: limin
* @LastEditTime: 2025-03-11 18:07:04
* @FilePath: \gl_tape\utils\recordManager\index.js
*/
// import { singleton } from '../utils.js'
import AudioManager from './AudioManager.js'
import DBRecord from './dbRecord.js'
// import Record from './Record.js'
import RecordDto from './RecordDto.js'
import TempRecord from './TempRecord.js'
import helpler from './helpler.js'
// const SingleDBTempRecord = singleton(TempRecord)
module.exports = { AudioManager, DBRecord, RecordDto, TempRecord, helpler }
...@@ -4,9 +4,11 @@ ...@@ -4,9 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2024-12-04 18:17:23 * @Date: 2024-12-04 18:17:23
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-01-06 18:50:33 * @LastEditTime: 2026-01-20 09:23:27
* @FilePath: \gl_tape\utils\recordManager\AudioManager.js * @FilePath: \gl_tape\utils\recordManager\AudioManager.js
*/ */
import StrategyFactory from './strategies'
class AudioManager { class AudioManager {
startOptions = { startOptions = {
duration: 10 * 60 * 1000, //默认10分钟 duration: 10 * 60 * 1000, //默认10分钟
...@@ -33,7 +35,12 @@ class AudioManager { ...@@ -33,7 +35,12 @@ class AudioManager {
} }
} }
on() { on() {
this.recorderManager = uni.getRecorderManager() // 使用策略工厂获取录音管理器实例
this.recorderManager = StrategyFactory.getRecorderStrategy()
// 统一日志输出,利用多态特性,不再需要 if 判断
uni.$logger.local.info(`AudioManager: Using ${this.recorderManager.name}`)
this.recorderManager.onStart(this.onStart.bind(this)) this.recorderManager.onStart(this.onStart.bind(this))
this.recorderManager.onStop(this.onStop.bind(this)) this.recorderManager.onStop(this.onStop.bind(this))
this.recorderManager.onError(this.onError.bind(this)) this.recorderManager.onError(this.onError.bind(this))
...@@ -53,11 +60,11 @@ class AudioManager { ...@@ -53,11 +60,11 @@ class AudioManager {
* 它首先记录了一条信息到日志,然后执行事件的onStart方法, * 它首先记录了一条信息到日志,然后执行事件的onStart方法,
* 并且更新内部计数器和录音状态标志 * 并且更新内部计数器和录音状态标志
*/ */
async onStart() { async onStart(res) {
// 记录录音开始的信息到日志 // 记录录音开始的信息到日志
uni.$logger.local.info('〖录音管理Audio〗 == 开启录音回调 ') uni.$logger.local.info('〖录音管理Audio〗 == 开启录音回调 '+JSON.stringify(res))
// 等待事件的onStart方法执行完成 // 等待事件的onStart方法执行完成
await this.events.onStart() await this.events.onStart(res)
// 内部计数器增加,用于跟踪录音开始的次数 // 内部计数器增加,用于跟踪录音开始的次数
this.__counter++ this.__counter++
// 设置录音状态标志为true,表示当前正在录音 // 设置录音状态标志为true,表示当前正在录音
...@@ -121,7 +128,10 @@ class AudioManager { ...@@ -121,7 +128,10 @@ class AudioManager {
get counter() { get counter() {
return this.__counter return this.__counter
} }
onError(err) {}
setCounter(val) {
this.__counter = val
}
/** /**
* 重置录音状态 * 重置录音状态
......
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-11-22 08:18:23
* @LastEditors: limin
* @LastEditTime: 2026-01-13 19:02:14
* @FilePath: \gl_tape\utils\recordManager\DBManager.js
*/
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
sqlite = null
isTableExists = false
constructor(table_name, table_columns) {
this.table_name = table_name || this.db_table_name
this.table_columns = 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)
uni.$logger.warn(`数据库是否存在isTableExists: ${isTableExists}`)
if (!isTableExists) {
await this.db.createTable(this.table_name, this.table_columns)
}
// else { //如果存在 判断需要新增的字段是否存在 不存在则添加
// const isColumnExists = await this.db.isColumnExists(this.table_name, 'carBrand')
// console.log(isColumnExists, 'isColumnExists')
// uni.$logger.info(`字段是否存在isColumnExists: ${isColumnExists}`)
// if (!isColumnExists) {
// await this.db.addColumns(this.table_name, [
// { name: 'carBrand', definition: 'TEXT DEFAULT ""' },
// { name: 'carBrandId', definition: 'INTEGER DEFAULT 0' },
// { name: 'oneCarBrand', definition: 'TEXT DEFAULT ""' },
// { name: 'oneCarBrandId', definition: 'INTEGER DEFAULT 0' }
// ])
// }
// }
return true
} catch (error) {
uni.$logger.error(`初始化数据库失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
async openDB() {}
/**
* 将一条新记录添加到当前对象的记录列表中
*
* @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record) {
await this.db.insert(this.table_name, record)
}
/**
* 移除一个ID对应的记录
*
* @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表
*/
async removeRecord(id) {
return this.db.delete(this.table_name, { id })
}
/**
* 根据给定的 ID 获取一条记录
*
* @param {number} id - 要获取的记录的 ID
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
*
*/
async getRecordById(id) {
const records = await this.db.select(this.table_name, { id })
return Array.isArray(records) ? records[0] : records // sqlite 返回数组
}
/**
* 根据条件获取记录列表
* @param {Object} where - 查询条件
* @returns {Array} - 记录列表
*/
async getRecordsByWhere(where) {
return this.db.select(this.table_name, where)
}
/**
* 获取记录列表
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
async getRecords() {
return this.db.select(this.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.table_name, record, where)
}
async isOpen() {
return this.db.isOpen()
}
async isTableExists() {
return this.db.isTableExists(this.table_name)
}
/**
* 清除所有记录
*
* @returns {void} - 此函数不返回任何值
*/
async clearRecords() {
this.db.delete(this.table_name)
}
async drop() {
this.db.drop(this.table_name)
}
}
export default DBManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2025-01-02 18:49:17
* @LastEditors: limin
* @LastEditTime: 2026-01-21 10:52:09
*/
import TempRecord from './TempRecord'
class NativeSave extends TempRecord {
constructor(record, onTempRecordNumberChanged, attributesProvider) {
super(record, onTempRecordNumberChanged, attributesProvider)
}
/**
* 添加新的接待记录
* - 创建内存中的记录对象
* - 同步写入临时记录数据库
* - 启动音频处理流程
* @returns {Promise<void>}
*/
async add(audio) {
uni.$logger.local.info('〖NativeSave〗 == add called with: ' + audio?.fileName)
// 创建一个新的记录对象
const recordUrlList = audio && audio.fileName ? [{ file: audio.fileName }] : []
// 调用基类通用流程
await super.add(recordUrlList)
}
}
export default NativeSave
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-16 14:48:27
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:47:12
* @FilePath: \gl_tape\utils\recordManager\PathUtils.js
*/
/**
* 路径处理工具类
*/
class PathUtils {
static _basePath = null
// 默认保存文件夹名称
static SAVE_DIR_NAME = 'uniapp_save'
// 默认文件保存路径 (相对于 _doc/)
static DEFAULT_SAVE_PATH = `_doc/${this.SAVE_DIR_NAME}/`
static CACHED_ROOT_PATH = null
// 本地缓存键名
static ROOT_PATH_CACHE_KEY = 'sqlite_root_path_cache'
/**
* 路径拼接工具
* @param {...string} args 路径片段
* @returns {string}
*/
static join(...args) {
if (args.length === 0) return ''
const parts = args.map((part, index) => {
if (!part) return ''
let str = String(part)
if (index !== 0) {
str = str.replace(/^\/+/, '') // 去除开头的斜杠
}
if (index !== args.length - 1) {
str = str.replace(/\/+$/, '') // 去除结尾的斜杠
}
return str
}).filter(p => p.length > 0)
return parts.join('/')
}
/**
* 获取基础保存路径 (带缓存)
*/
static async getBasePath() {
if (this._basePath) return this._basePath
this._basePath = await this.getFileSaveFolderOnClient()
return this._basePath
}
/**
* 获取文件系统根目录的完整路径
* @returns {Promise<string>}
*/
static getFilePath() {
// 1. 优先使用内存缓存,性能最高
if (this.CACHED_ROOT_PATH) {
uni.$logger?.local?.info(`[PathUtils] 命中内存缓存,根路径: ${this.CACHED_ROOT_PATH}`);
return Promise.resolve(this.CACHED_ROOT_PATH);
}
// 2. 尝试读取持久化缓存
const storageCache = uni.getStorageSync(this.ROOT_PATH_CACHE_KEY);
if (storageCache) {
uni.$logger?.local?.info(`[PathUtils] 命中本地缓存,根路径: ${storageCache}`);
// 同步到内存缓存
this.CACHED_ROOT_PATH = storageCache;
return Promise.resolve(this.CACHED_ROOT_PATH);
}
// 3. 无缓存,请求原生文件系统API
return new Promise((resolve, reject) => {
if (!plus) {
reject(new Error('plus runtime 未初始化'));
return;
}
plus.io.requestFileSystem(
plus.io.PRIVATE_DOC,
(fs) => {
const fullPath = fs.root.fullPath;
uni.$logger?.local?.info(`[PathUtils] 请求原生API获取根路径: ${fullPath}`);
// 写入两级缓存
this.CACHED_ROOT_PATH = fullPath;
uni.setStorageSync(this.ROOT_PATH_CACHE_KEY, fullPath);
resolve(fullPath);
},
(error) => {
reject(new Error(`[PathUtils] 获取文件系统失败: ${JSON.stringify(error)}`));
}
);
});
}
/**
* 获取客户端文件保存基础路径
*/
static async getFileSaveFolderOnClient() {
const rootPath = await this.getFilePath()
const path = this.join(rootPath, this.SAVE_DIR_NAME)
return `file://${path}/`
}
/**
* 获取音频文件基础路径
*/
static async getAudioFilePath(path = '') {
const rootPath = await this.getFilePath()
const fullPath = this.join(rootPath, path)
return `file://${fullPath}`
}
/**
* 获取绝对路径
* @param {string} relativePath 相对路径或文件名
*/
static async getAbsolutePath(relativePath) {
if (!relativePath) return ''
if (relativePath.startsWith('file://') || relativePath.startsWith('/')) {
return relativePath
}
const base = await this.getBasePath()
// 避免重复斜杠
if (base.endsWith('/') && relativePath.startsWith('/')) {
return base + relativePath.substring(1)
}
if (!base.endsWith('/') && !relativePath.startsWith('/')) {
return base + '/' + relativePath
}
return base + relativePath
}
/**
* 确保目录存在 (递归创建)
* @param {string} dirPath 目录路径
*/
static ensureDir(dirPath) {
return new Promise((resolve, reject) => {
// #ifdef APP-PLUS
plus.io.resolveLocalFileSystemURL(dirPath, entry => {
resolve(entry.fullPath)
}, () => {
// 目录不存在,尝试创建
// NativeRecorder 传的是 "_doc/uniapp_save/"
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, fs => {
const root = fs.root
let path = dirPath
if (path.startsWith('_doc/')) path = path.substring(5)
const createDir = (entry, folders) => {
if (folders.length === 0) {
resolve(entry.fullPath)
return
}
entry.getDirectory(folders[0], { create: true }, dirEntry => {
createDir(dirEntry, folders.slice(1))
}, err => {
reject(new Error('创建目录失败: ' + err.message))
})
}
createDir(root, path.split('/').filter(p => p))
}, err => reject(err))
})
// #endif
// #ifndef APP-PLUS
resolve(dirPath)
// #endif
})
}
}
export default PathUtils
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-14 14:30:10
* @LastEditors: limin
* @LastEditTime: 2026-01-22 15:47:06
* @FilePath: \gl_tape\utils\recordManager\RecordCacheManager.js
*/
/**
* 缓存配置表
* 用于定义哪些字段需要走 LocalStorage 暂存策略
*/
const CACHE_CONFIG = {
MATERIAL_POINTS: {
keyPrefix: 'MATERIAL_POINTS_', // Storage Key 前缀
targetField: 'receptionCustomerMaterialPointList' // 对应的 Record 字段名
}
}
/**
* 记录缓存管理器
* 统一管理大字段的暂存、合并与清理
*/
const RecordCacheManager = {
/**
* 暂存数据
* @param {string} recordId - 记录ID
* @param {string} type - 缓存类型 (key of CACHE_CONFIG)
* @param {any} data - 数据
*/
set(recordId, type, data) {
if (!recordId || !CACHE_CONFIG[type]) return
try {
const config = CACHE_CONFIG[type]
uni.setStorageSync(config.keyPrefix + recordId, data)
} catch (e) {
uni.$logger.local.error(`RecordCacheManager: Set ${type} failed: ${e.message}`)
}
},
/**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
* @param {Object} record - 记录对象 (仅用于获取ID)
* @returns {Object} 从缓存恢复的数据对象
*/
consumeAll(record) {
if (!record || !record.id) return {}
const restoredData = {}
Object.values(CACHE_CONFIG).forEach(config => {
try {
const key = config.keyPrefix + record.id
const data = uni.getStorageSync(key)
if (data) {
restoredData[config.targetField] = data
uni.removeStorageSync(key) // 消费即焚
}
} catch (e) {
uni.$logger.local.warn(`RecordCacheManager: Consume ${config.keyPrefix} failed: ${e.message}`)
}
})
return restoredData
},
/**
* 清理指定记录的所有缓存
* @param {string} recordId
*/
clearAll(recordId) {
if (!recordId) return
Object.values(CACHE_CONFIG).forEach(config => {
try {
uni.removeStorageSync(config.keyPrefix + recordId)
} catch (e) {}
})
}
}
export default RecordCacheManager
/*
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2024-12-06 10:13:02
* @LastEditors: limin
* @LastEditTime: 2026-01-23 19:37:59
* @FilePath: \gl_tape\utils\recordManager\TimeoutService.js
*/
class TimeoutService {
TIMEOUT = 720000// 40分钟
Miniute = 60 * 1000
TIMER_DURATION = this.TIMEOUT * this.Miniute
CHECK_INTERVAL = 1 * this.Miniute // 1分钟检查一次
onStop = null
__timerId = null
_lastActiveTime = 0
constructor(onStop) {
this.onStop = onStop
}
start() {
uni.$on('reset_timeout', this.handleTouchStart)
this.watch()
}
async stopRecorder() {
return this.onStop()
}
// 初始化或启动监听
watch() {
// 1. 无论是否已启动,先更新活跃时间
this._lastActiveTime = Date.now()
// 2. 如果定时器已在运行,直接返回,避免重复创建
// 这是相比原方案最大的优化:全周期只有一个 setInterval 实例
if (this.__timerId) return
// 3. 启动周期性检查
this.__watchStart()
}
__watchStart() {
this.__timerId = setInterval(async () => {
const now = Date.now()
// 直接计算时间差,比维护 counter 计数器更准确、更简单
if (now - this._lastActiveTime >= this.TIMER_DURATION) {
await this.__watchStop()
if (!this.__timerId) uni.$logger.local.info(`== 检测到${this.TIMEOUT}分钟闲置未操作,自动停止录音 ==`)
}
}, this.CHECK_INTERVAL)
if (this.__timerId) uni.$logger.local.info('== 开启闲置检测 ==')
}
async __watchStop() {
await this.stopRecorder()
this.endWatchClick()
}
endWatchClick() {
if (this.__timerId) {
clearInterval(this.__timerId)
this.__timerId = null
}
this._lastActiveTime = null
uni.$logger.local.info('== 停止闲置检测 ==')
}
handleTouchStart() {
//实现防抖
if (this._debounceTimer) clearTimeout(this._debounceTimer)
this._debounceTimer = setTimeout(() => {
this._lastActiveTime = Date.now()
}, 1000)
}
stop() {
uni.$off('reset_timeout', this.handleTouchStart)
this.endWatchClick()
}
}
export default TimeoutService
/* /*
* @Descripttion: * @Descripttion:
* @version: 1.0.0 * @version: 1.0.0
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:34:39 * @Date: 2025-01-02 18:34:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-01-06 09:36:04 * @LastEditTime: 2026-01-22 15:58:34
* @FilePath: \gl_tape\utils\recordManager\dbRecord.js * @FilePath: \gl_tape\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`,
`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',
'tempFilePath TEXT',
'carBrand TEXT',
'carBrandId INTEGER',
'oneCarBrand TEXT',
'oneCarBrandId INTEGER'
]
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`,
`staffUuid TEXT`,
`staffName TEXT`,
`serviceMerchantId INTEGER`,
'carModel TEXT',
'endReasonType INTEGER',
'customerName TEXT',
'phoneNumber TEXT',
'appCode TEXT',
'loginPhone TEXT',
'salesName TEXT',
'salesUuid TEXT',
'receptionStatus INTEGER',
'receptionStartTime TEXT',
'receptionEndTime TEXT',
'receptionCustomerPaySourceList TEXT',
'merchantId INTEGER',
'merchantName TEXT',
'bussinessType INTEGER',
'channelType INTEGER',
'receptionCustomerMaterialPointList TEXT',
'recordUrlList TEXT',
'carBrand TEXT',
'carBrandId INTEGER',
'oneCarBrand TEXT',
'oneCarBrandId INTEGER',
'tempFilePath TEXT',
'recordStatus INTEGER DEFAULT 1' // 0: recording, 1: completed
]
super(table_name, table_columns)
this._initPromise = null
}
async init() {
if (this._initPromise) return this._initPromise
this._initPromise = (async () => {
try {
await super.init()
await this.ensureColumns()
await this.migrateTempRecords()
return true
} catch (e) {
uni.$logger.local.error('DBRecord: init failed ' + e.message)
throw e
}
})()
return this._initPromise
}
/**
* 确保表字段存在(用于版本升级)
*/
async ensureColumns() {
try {
// 优化:只查询一次表结构
const columnInfo = await this.db.selectSql(`PRAGMA table_info(${this.table_name})`)
const existingColumns = columnInfo.map(col => col.name)
const columnsToAdd = this.table_columns.reduce((acc, colDef) => {
const [name, ...def] = colDef.trim().split(/\s+/)
if (name && !existingColumns.includes(name)) {
acc.push({ name, definition: def.join(' ') })
}
return acc
}, [])
if (columnsToAdd.length > 0) {
await this.db.addColumns(this.table_name, columnsToAdd)
uni.$logger.local.info(`DBRecord: Added columns ${columnsToAdd.map(c => c.name).join(', ')}`)
}
} catch (e) {
uni.$logger.local.error('DBRecord: ensureColumns failed ' + e.message)
}
}
/**
* 将旧的临时表数据迁移到正式表
*/
async migrateTempRecords() {
const tempTableName = 'temp_records'
try {
const exists = await this.db.isTableExists(tempTableName)
if (!exists) return
uni.$logger.local.warn('DBRecord: Found temp_records table, starting migration...')
// 获取所有临时记录
const tempRecords = await this.db.selectSql(`SELECT * FROM ${tempTableName}`)
if (tempRecords && tempRecords.length > 0) {
for (const record of tempRecords) {
if (!record.id) continue
// 标记为进行中
record.recordStatus = 0
// 检查是否已存在
const existing = await this.getRecordById(record.id)
if (existing) {
// 如果存在,说明正式表已有记录,temp_records 中的是残留数据,直接跳过
uni.$logger.local.warn(`DBRecord: Temp record ${record.id} already exists in records, skipping migration.`)
} else {
// 如果不存在,插入它
await this.addRecord(record)
uni.$logger.local.info(`DBRecord: Migrated temp record ${record.id}`)
}
}
}
// 迁移完成后删除旧表
await this.db.drop(tempTableName)
uni.$logger.local.warn('DBRecord: Migration completed, temp_records table dropped.')
} catch (e) {
uni.$logger.local.error('DBRecord: Migration failed ' + e.message)
}
}
/**
* 获取已完成的接待记录 (recordStatus = 1)
*/
async getCompletedRecords() {
return this.getRecordsByWhere({ recordStatus: 1 })
}
/**
* 获取进行中/临时的接待记录 (recordStatus = 0)
*/
async getTempRecords() {
return this.getRecordsByWhere({ recordStatus: 0 })
} }
} }
export default DBRecord export default DBRecord
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!