Commit a191a53d by liimin

feat(store): 添加全局状态管理模块并集成录音服务监听器

- 新增 store 模块,包含 reception 状态管理及 commit 方法
- 在 RecordService 中集成 store 监听器,实现接待状态、客户信息等数据同步
- 新增 replaceAll 工具函数用于字符串替换
- 完善 RecordSave 服务的上传逻辑,增加文件状态处理和 API 调用
- 添加测试文件用于验证 store 和监听器功能
- 修复 SQLite 查询中的类型错误和常量定义
1 parent 22119ae0
...@@ -107,7 +107,7 @@ ...@@ -107,7 +107,7 @@
"files.insertFinalNewline": true, "files.insertFinalNewline": true,
"files.simpleDialog.enable": true, "files.simpleDialog.enable": true,
"files.associations": { "files.associations": {
"*.uts": "typescript", "*.uts": "uts",
"*.ejs": "html", "*.ejs": "html",
"*.art": "html", "*.art": "html",
"**/tsconfig.json": "jsonc", "**/tsconfig.json": "jsonc",
......
...@@ -9,11 +9,11 @@ export default { ...@@ -9,11 +9,11 @@ export default {
setTimeout(() => { setTimeout(() => {
//模拟接待开始 //模拟接待开始
console.log("Simulating reception start..."); console.log("Simulating reception start...");
RecordService.getInstance().startAudio(); // RecordService.getInstance().startAudio();
//模拟接待结束 //模拟接待结束
console.log("Simulating reception end..."); console.log("Simulating reception end...");
setTimeout(() => { setTimeout(() => {
RecordService.getInstance().stopAudio(); // RecordService.getInstance().stopAudio();
}, 10000); }, 10000);
}, 1000); }, 1000);
}, },
......
...@@ -2,10 +2,28 @@ import http from '@/api/request/http.uts' ...@@ -2,10 +2,28 @@ import http from '@/api/request/http.uts'
import type { OssTokenData } from '../composables/uploader/types/oss.uts' import type { OssTokenData } from '../composables/uploader/types/oss.uts'
export async function getToken(params: UTSJSONObject): Promise<UTSJSONObject> { export async function getToken(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = { const data: UTSJSONObject = {
projectName: 'boutique', projectName: 'boutique',
...params ...params
} }
const d = http.fetch('dj.api.smartcarlife.recepiton.customer.oss.getToken', data,false, 'dj') const d = http.fetch('dj.api.smartcarlife.recepiton.customer.oss.getToken', data,false, 'dj')
// console.log("🚀 ~ getToken ~ d:", d) // console.log("🚀 ~ getToken ~ d:", d)
return d return d
}
export async function saveRecCustomer(params: UTSJSONObject): Promise<UTSJSONObject> {
const data: UTSJSONObject = {
projectName: 'boutique',
...params
}
const d = http.fetch('dj.api.smartcarlife.recepiton.customer.saveRecCustomer', data,false, 'dj')
// console.log("🚀 ~ getToken ~ d:", d)
return d
}
export async function searchRecordingEndTime(params: UTSJSONObject): Promise<string> {
const data: UTSJSONObject = {
projectName: 'boutique',
...params
}
const d = http.fetch('dj.api.smartcarlife.recepiton.customer.searchRecordingEndTime', data,false, 'dj')
// console.log("🚀 ~ getToken ~ d:", d)
return d as Promise<string>
} }
import { import {
openDatabase, openDatabase,
closeDatabase, closeDatabase,
executeSql, executeSql,
selectSql, selectSql,
transaction, transaction,
isOpenDatabase, isOpenDatabase,
DatabaseOptions, DatabaseOptions,
SqlOperationOptions, SqlOperationOptions,
SqlTransactionOptions, SqlTransactionOptions,
SqliteFail, SqliteFail,
SQLiteSuccess SQLiteSuccess
} from '@/uni_modules/lime-sqlite' } from '@/uni_modules/lime-sqlite'
import TaskQueue from '../../utils/task-queue.uts' import TaskQueue from '../../utils/task-queue.uts'
import { PathUtils } from '../../utils/path-utils.uts' import { PathUtils } from '../../utils/path-utils.uts'
...@@ -29,7 +29,7 @@ export default class SQLite { ...@@ -29,7 +29,7 @@ export default class SQLite {
this.version = version this.version = version
this.description = description this.description = description
this.size = size this.size = size
// 初始化该数据库的队列(如果不存在) // 初始化该数据库的队列(如果不存在)
if (!SQLite._queues.has(name)) { if (!SQLite._queues.has(name)) {
SQLite._queues.set(name, new TaskQueue(`SQLite:${name}`)) SQLite._queues.set(name, new TaskQueue(`SQLite:${name}`))
...@@ -95,7 +95,7 @@ export default class SQLite { ...@@ -95,7 +95,7 @@ export default class SQLite {
} }
} }
} as DatabaseOptions } as DatabaseOptions
openDatabase(options) openDatabase(options)
}) })
} }
...@@ -108,7 +108,7 @@ export default class SQLite { ...@@ -108,7 +108,7 @@ export default class SQLite {
// lime-sqlite 使用 executeSql 执行所有 SQL,包括查询 // lime-sqlite 使用 executeSql 执行所有 SQL,包括查询
// 如果是查询,需要确保 executeSql 返回数据 // 如果是查询,需要确保 executeSql 返回数据
// 某些版本 lime-sqlite 可能将 select 语句也视为执行,返回 boolean // 某些版本 lime-sqlite 可能将 select 语句也视为执行,返回 boolean
// 尝试使用 selectSql 替代 executeSql ? // 尝试使用 selectSql 替代 executeSql ?
// 经检查 interface.uts,只有 executeSql. // 经检查 interface.uts,只有 executeSql.
// 错误 9010007 Boolean cannot be cast to UTSJSONObject 可能意味着 // 错误 9010007 Boolean cannot be cast to UTSJSONObject 可能意味着
// executeSql 的 success 回调接收到了 Boolean (true),但 interface 定义或 cast 逻辑期望 JSONObject // executeSql 的 success 回调接收到了 Boolean (true),但 interface 定义或 cast 逻辑期望 JSONObject
...@@ -117,19 +117,19 @@ export default class SQLite { ...@@ -117,19 +117,19 @@ export default class SQLite {
sql: [sql], sql: [sql],
success: (res: any) => { success: (res: any) => {
// console.log("🚀 ~ SQLite ~ selectSql ~ res:", res,sql) // console.log("🚀 ~ SQLite ~ selectSql ~ res:", res,sql)
// 检查 res 类型 // 检查 res 类型
if (typeof res === 'boolean') { if (typeof res === 'boolean') {
resolve([] as any[]) resolve([] as any[])
return return
} }
try { try {
const result = res as SQLiteSuccess const result = res as SQLiteSuccess
// 优先使用 result 字段,因为它在接口定义中是 UTSJSONObject[] // 优先使用 result 字段,因为它在接口定义中是 UTSJSONObject[]
// 如果 result 为空,再降级使用 data // 如果 result 为空,再降级使用 data
const rows = result.result ?? result.data const rows = result.result ?? result.data
if (rows == null) { if (rows == null) {
resolve([] as any[]) resolve([] as any[])
return return
...@@ -143,7 +143,7 @@ export default class SQLite { ...@@ -143,7 +143,7 @@ export default class SQLite {
if (row instanceof UTSJSONObject) { if (row instanceof UTSJSONObject) {
const rowObj = row as UTSJSONObject const rowObj = row as UTSJSONObject
const newRow = {} const newRow = {}
const map = rowObj.toMap() const map = rowObj.toMap()
map.forEach((value, key) => { map.forEach((value, key) => {
// 类型安全检查,防止 ClassCastException (如 Integer -> String) // 类型安全检查,防止 ClassCastException (如 Integer -> String)
...@@ -191,7 +191,7 @@ export default class SQLite { ...@@ -191,7 +191,7 @@ export default class SQLite {
} }
} }
} as SqlOperationOptions } as SqlOperationOptions
// 尝试调用 selectSql 接口(如果存在),或者直接使用 executeSql // 尝试调用 selectSql 接口(如果存在),或者直接使用 executeSql
// 检查 lime-sqlite 是否有 selectSql 导出 // 检查 lime-sqlite 是否有 selectSql 导出
// 如果 interface.uts 没有 selectSql,那么我们只能用 executeSql // 如果 interface.uts 没有 selectSql,那么我们只能用 executeSql
...@@ -223,7 +223,7 @@ export default class SQLite { ...@@ -223,7 +223,7 @@ export default class SQLite {
} }
} }
} as SqlOperationOptions } as SqlOperationOptions
executeSql(options) executeSql(options)
}) })
) )
...@@ -269,7 +269,7 @@ export default class SQLite { ...@@ -269,7 +269,7 @@ export default class SQLite {
} }
if (order != null) { if (order != null) {
const orderMap = order.toMap() const orderMap = order.toMap()
const orderKeys: string[] = [] const orderKeys: UTSArray<string> = []
orderMap.forEach((value, key) => { orderMap.forEach((value, key) => {
orderKeys.push(key) orderKeys.push(key)
}) })
...@@ -279,20 +279,20 @@ export default class SQLite { ...@@ -279,20 +279,20 @@ export default class SQLite {
sql += ` ORDER BY ${orderKey} ${orderType}` sql += ` ORDER BY ${orderKey} ${orderType}`
} }
} }
return selectSql(sql) return this.selectSql(sql)
} }
// 插入示例 // 插入示例
insert(tabName: string, keyValues: UTSJSONObject): Promise<any | null> { insert(tabName: string, keyValues: UTSJSONObject): Promise<any | null> {
const map = keyValues.toMap() const map = keyValues.toMap()
const valStr: string[] = [] const valStr: UTSArray<string> = []
const keyList: string[] = [] const keyList: UTSArray<string> = []
map.forEach((value, key) => { map.forEach((value, key) => {
keyList.push(key) keyList.push(key)
valStr.push(`${this.formatValue(value)}`) valStr.push(`${this.formatValue(value)}`)
}) })
const keyStr = keyList.join(', ') const keyStr = keyList.join(', ')
const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr.join(', ')})` const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr.join(', ')})`
return this.executeSql(sql) return this.executeSql(sql)
...@@ -301,14 +301,14 @@ export default class SQLite { ...@@ -301,14 +301,14 @@ export default class SQLite {
// 更新示例 // 更新示例
update(tabName: string, setData: UTSJSONObject, where: UTSJSONObject): Promise<any | null> { update(tabName: string, setData: UTSJSONObject, where: UTSJSONObject): Promise<any | null> {
const setMap = setData.toMap() const setMap = setData.toMap()
const setList: string[] = [] const setList: UTSArray<string> = []
setMap.forEach((value, key) => { setMap.forEach((value, key) => {
setList.push(`${key} = ${this.formatValue(value)}`) setList.push(`${key} = ${this.formatValue(value)}`)
}) })
const setStr = setList.join(', ') const setStr = setList.join(', ')
const whereMap = where.toMap() const whereMap = where.toMap()
const whereList: string[] = [] const whereList: UTSArray<string> = []
whereMap.forEach((value, key) => { whereMap.forEach((value, key) => {
whereList.push(`${key} = ${this.formatValue(value)}`) whereList.push(`${key} = ${this.formatValue(value)}`)
}) })
...@@ -321,7 +321,7 @@ export default class SQLite { ...@@ -321,7 +321,7 @@ export default class SQLite {
// 删除示例 // 删除示例
delete(tabName: string, where: UTSJSONObject): Promise<any | null> { delete(tabName: string, where: UTSJSONObject): Promise<any | null> {
const whereMap = where.toMap() const whereMap = where.toMap()
const whereList: string[] = [] const whereList: UTSArray<string> = []
whereMap.forEach((value, key) => { whereMap.forEach((value, key) => {
whereList.push(`${key} = ${this.formatValue(value)}`) whereList.push(`${key} = ${this.formatValue(value)}`)
}) })
...@@ -331,7 +331,7 @@ export default class SQLite { ...@@ -331,7 +331,7 @@ export default class SQLite {
} }
isOpen(): boolean { isOpen(): boolean {
// lime-sqlite 提供了 isOpenDatabase 异步方法? // lime-sqlite 提供了 isOpenDatabase 异步方法?
// 文档里是 isOpenDatabase({ ... }) // 文档里是 isOpenDatabase({ ... })
// interface 里没写返回值类型,但通常是 void (async callback) // interface 里没写返回值类型,但通常是 void (async callback)
// 但 plus.sqlite.isOpenDatabase 是同步的 // 但 plus.sqlite.isOpenDatabase 是同步的
...@@ -346,10 +346,10 @@ export default class SQLite { ...@@ -346,10 +346,10 @@ export default class SQLite {
// 在 openDatabase 实现里,我们调用了 this.isOpen()。 // 在 openDatabase 实现里,我们调用了 this.isOpen()。
// 现在的策略:移除同步 isOpen 检查,直接调用 openDatabase,并在 fail 回调里处理 "already open" 的情况。 // 现在的策略:移除同步 isOpen 检查,直接调用 openDatabase,并在 fail 回调里处理 "already open" 的情况。
// 或者,我们可以维护一个本地状态 `this.isOpened`。 // 或者,我们可以维护一个本地状态 `this.isOpened`。
return false // 无法同步检查,返回 false 让它去尝试打开 return false // 无法同步检查,返回 false 让它去尝试打开
} }
// 新增 asyncIsOpen 以备不时之需 // 新增 asyncIsOpen 以备不时之需
asyncIsOpen(): Promise<boolean> { asyncIsOpen(): Promise<boolean> {
return new Promise((resolve) => { return new Promise((resolve) => {
...@@ -379,9 +379,6 @@ export default class SQLite { ...@@ -379,9 +379,6 @@ export default class SQLite {
drop(tabName: string): Promise<any | null> { drop(tabName: string): Promise<any | null> {
const sql = `DROP TABLE IF EXISTS ${tabName}` const sql = `DROP TABLE IF EXISTS ${tabName}`
console.log("🚀 ~ SQLite ~ createTable ~ sql:", sql)
console.log("🚀 ~ SQLite ~ createTable ~ sql:", sql)
console.log("🚀 ~ SQLite ~ createTable ~ sql:", sql)
return this.executeSql(sql) return this.executeSql(sql)
} }
...@@ -425,7 +422,7 @@ export default class SQLite { ...@@ -425,7 +422,7 @@ export default class SQLite {
// 确保 definition 存在 // 确保 definition 存在
const definition = column['definition'] const definition = column['definition']
const defStr = (definition != null && definition != "") ? definition : 'TEXT' const defStr = (definition != null && definition != "") ? definition : 'TEXT'
// 尝试执行添加列 // 尝试执行添加列
if (name != null) { if (name != null) {
try { try {
......
...@@ -3,7 +3,7 @@ import AudioManager from './AudioManager.uts' ...@@ -3,7 +3,7 @@ import AudioManager from './AudioManager.uts'
import TempRecord from './TempRecord.uts' import TempRecord from './TempRecord.uts'
// import TimeoutService from './TimeoutService.uts' // import TimeoutService from './TimeoutService.uts'
import { logger } from '../logger/index.uts' import { logger } from '../logger/index.uts'
// import store, { state as storeState, mutations } from '@/store/index.uts' import { state as storeState, commit } from '@/store/index.uts'
import { checkPermission, requestPermissions } from '@/uni_modules/permission-handler-plus' import { checkPermission, requestPermissions } from '@/uni_modules/permission-handler-plus'
import { watch } from 'vue' import { watch } from 'vue'
import { storage } from '../../utils/storage.uts' import { storage } from '../../utils/storage.uts'
...@@ -22,15 +22,15 @@ type DebounceTimer = { ...@@ -22,15 +22,15 @@ type DebounceTimer = {
}; };
class RecordService { class RecordService {
static sInstance: RecordService | null = null static sInstance: RecordService | null = null
audioManager: AudioManager | null = null audioManager: AudioManager | null = null
record: TempRecord | null = null record: TempRecord | null = null
tempRecordDto: RecordData | null = null tempRecordDto: RecordData | null = null
debounceTimers: Map<string, DebounceTimer> = new Map() debounceTimers: Map<string, DebounceTimer> = new Map()
_startAudioPromise: Promise<boolean> | null = null _startAudioPromise: Promise<boolean> | null = null
// timeoutService: TimeoutService | null = null // timeoutService: TimeoutService | null = null
// Watchers unsubscription // Watchers unsubscription
unwatchCustomer: (() => void) | null = null unwatchCustomer: (() => void) | null = null
unwatchStatus: (() => void) | null = null unwatchStatus: (() => void) | null = null
...@@ -52,19 +52,19 @@ class RecordService { ...@@ -52,19 +52,19 @@ class RecordService {
try { try {
logger.info('【录音服务RecordService】 == 初始化', "RecordService") logger.info('【录音服务RecordService】 == 初始化', "RecordService")
this.audioManager = new AudioManager( this.audioManager = new AudioManager(
(res:StartRecordSuccess) => { this.onAudioStart(res) }, (res:StartRecordSuccess) => { this.onAudioStart(res) },
(res) => { this.onAudioStop(res) }, (res) => { this.onAudioStop(res) },
(err) => { this.onAudioError(err) } (err) => { this.onAudioError(err) }
) )
this.initDto() this.initDto()
this.record = new TempRecord( this.record = new TempRecord(
this.tempRecordDto, this.tempRecordDto,
() => { this.triggleTempNumber() }, () => { this.triggleTempNumber() },
() => { return this.attributesProvider() } () => { return this.attributesProvider() }
) )
// this.timeoutService = new TimeoutService(() => { return this.onTimeOut() }) // this.timeoutService = new TimeoutService(() => { return this.onTimeOut() })
this.triggleTempNumber() this.triggleTempNumber()
...@@ -86,54 +86,52 @@ class RecordService { ...@@ -86,54 +86,52 @@ class RecordService {
initWatchers() { initWatchers() {
// 监听 customerKey // 监听 customerKey
/*
this.unwatchCustomer = watch( this.unwatchCustomer = watch(
() => storeState.customerKey, (): string => storeState.customerKey,
() => { (val: string) => {
const customerInfo = storeState.customerInfo const customerInfo = storeState.customerInfo
this.handler('updateCustomerInfo', customerInfo, (val) => { this.updateCustomerInfo(val) }, 1000) this.handler('updateCustomerInfo', customerInfo, (val: UTSJSONObject | null) => { this.updateCustomerInfo(val) }, 1000)
}, },
{ immediate: true } { immediate: true }
) )
// 监听 receptionStatus // 监听 receptionStatus
this.unwatchStatus = watch( this.unwatchStatus = watch(
() => storeState.receptionStatus, (): string => storeState.receptionStatus,
(val) => { (val: string) => {
this.handler('updateReceptionStatus', val, (v) => { this.updateReceptionStatus(v) }, 200) this.handler('updateReceptionStatus', val, (v: any) => { this.updateReceptionStatus(v as string) }, 200)
}, },
{ immediate: true } { immediate: true }
) )
this.unwatchBookList = watch( this.unwatchBookList = watch(
() => storeState.booksList, (): UTSJSONObject[] => storeState.booksList,
(val) => { (val: UTSJSONObject[]) => {
this.handler('updateBookList', val, (v) => { this.updateBookList(v as any[]) }, 1500) this.handler('updateBookList', val, (v: UTSJSONObject[]) => { this.updateBookList(v) }, 1500)
}, },
{ immediate: true } { immediate: true }
) )
this.unwatchReceptionKey = watch( this.unwatchReceptionKey = watch(
() => storeState.receptionKey, (): string => storeState.receptionKey,
() => { (val: string) => {
const receptionTrack = storeState.receptionTrack const receptionTrack = storeState.receptionTrack
this.handler('updateMaterialPointList', receptionTrack, (v) => { this.updateMaterialPointList(v) }, 1000) this.handler('updateMaterialPointList', receptionTrack, (v: UTSJSONObject[]) => { this.updateMaterialPointList(v) }, 1000)
}, },
{ immediate: true } { immediate: true }
) )
*/
} }
// --- 业务逻辑 --- // --- 业务逻辑 ---
async startAudio(isInitData: boolean = true): Promise<boolean> { async startAudio(isInitData: boolean = true): Promise<boolean> {
if (this._startAudioPromise != null) return this._startAudioPromise! if (this._startAudioPromise != null) return this._startAudioPromise!
this._startAudioPromise = (async (): Promise<boolean> => { this._startAudioPromise = (async (): Promise<boolean> => {
try { try {
const isPermission = await this.checkBeforeStart() const isPermission = await this.checkBeforeStart()
if (!isPermission) return false if (!isPermission) return false
logger.info('【录音服务RecordService】 == 开始接待 ', "RecordService") logger.info('【录音服务RecordService】 == 开始接待 ', "RecordService")
if (isInitData) { if (isInitData) {
this.initReception() this.initReception()
...@@ -161,7 +159,7 @@ class RecordService { ...@@ -161,7 +159,7 @@ class RecordService {
const obj:UTSJSONObject = userInfo!='' ? JSON.parse(userInfo) as UTSJSONObject : {} const obj:UTSJSONObject = userInfo!='' ? JSON.parse(userInfo) as UTSJSONObject : {}
const sceneType = obj.get('sceneType') const sceneType = obj.get('sceneType')
const dynamicAttrs = { const dynamicAttrs = {
bussinessType: this.getBussinessType(sceneType) bussinessType: this.getBussinessType(sceneType)
} }
return dynamicAttrs return dynamicAttrs
} catch (e) { } catch (e) {
...@@ -171,9 +169,9 @@ class RecordService { ...@@ -171,9 +169,9 @@ class RecordService {
} }
initReception() { initReception() {
// store.commit('audio/setBooks', []) commit('updateBookList', [] as UTSJSONObject[])
// store.commit('clearCustomerInfo') commit('updateCustomerInfo', null as UTSJSONObject | null)
// store.commit('audio/setReceptionStatus', '') commit('updateReceptionStatus', '')
} }
async onAudioStart(res: StartRecordSuccess) { async onAudioStart(res: StartRecordSuccess) {
...@@ -279,19 +277,19 @@ class RecordService { ...@@ -279,19 +277,19 @@ class RecordService {
this.record?.clearLoopTimer() this.record?.clearLoopTimer()
this.stopAudioRecord() this.stopAudioRecord()
} }
async onTimeOut() { async onTimeOut() {
// store.commit('audio/setReceptionStatus', 0) commit('updateReceptionStatus', '0')
await this.record!.withError() await this.record!.withError()
this.stopAudioRecord() this.stopAudioRecord()
} }
stopAudioRecord() { stopAudioRecord() {
this.audioManager?.stop() this.audioManager?.stop()
// this.timeoutService?.stop() // this.timeoutService?.stop()
} }
handler(key: string, params: any, fn: (arg: any) => void, delay: number = 0) { handler<T>(key: string, params: T, fn: (arg: T) => void, delay: number = 0) {
if (this.isReceptioning()) { if (this.isReceptioning()) {
if (delay > 0) { if (delay > 0) {
this.debounce(key, () => fn(params), delay) this.debounce(key, () => fn(params), delay)
...@@ -324,10 +322,10 @@ class RecordService { ...@@ -324,10 +322,10 @@ class RecordService {
fn() fn()
this.debounceTimers.delete(key) this.debounceTimers.delete(key)
}, delay) }, delay)
this.debounceTimers.set(key, { fn, timer }) this.debounceTimers.set(key, { fn, timer })
} }
flushAllDebounceTimers() { flushAllDebounceTimers() {
this.debounceTimers.forEach((item, key) => { this.debounceTimers.forEach((item, key) => {
clearTimeout(item.timer) clearTimeout(item.timer)
...@@ -341,10 +339,10 @@ class RecordService { ...@@ -341,10 +339,10 @@ class RecordService {
this.debounceTimers.clear() this.debounceTimers.clear()
} }
updateCustomerInfo(customerInfo: any) { updateCustomerInfo(customerInfo: UTSJSONObject | null) {
const info = customerInfo as UTSJSONObject const info = customerInfo
if (info == null) return if (info == null) return
const customerName = info['customerName'] const customerName = info['customerName']
const phoneNumber = info['phoneNumber'] const phoneNumber = info['phoneNumber']
const salesUuid = info['salesUuid'] const salesUuid = info['salesUuid']
...@@ -354,7 +352,7 @@ class RecordService { ...@@ -354,7 +352,7 @@ class RecordService {
const carBrandId = info['carBrandId'] const carBrandId = info['carBrandId']
const oneCarBrand = info['oneCarBrand'] const oneCarBrand = info['oneCarBrand']
const oneCarBrandId = info['oneCarBrandId'] const oneCarBrandId = info['oneCarBrandId']
this.record!.updatePreRecords({ this.record!.updatePreRecords({
customerName, customerName,
phoneNumber, phoneNumber,
...@@ -368,7 +366,7 @@ class RecordService { ...@@ -368,7 +366,7 @@ class RecordService {
}) })
} }
updateBookList(booksList: any[]) { updateBookList(booksList: UTSJSONObject[]) {
const receptionCustomerPaySourceList: UTSJSONObject[] = [] const receptionCustomerPaySourceList: UTSJSONObject[] = []
booksList.forEach((item: any) => { booksList.forEach((item: any) => {
const book = item as UTSJSONObject const book = item as UTSJSONObject
...@@ -378,25 +376,25 @@ class RecordService { ...@@ -378,25 +376,25 @@ class RecordService {
sourceUrl: book['imgUrl'] sourceUrl: book['imgUrl']
}) })
}) })
this.record!.updatePreRecords({ receptionCustomerPaySourceList }) this.record!.updatePreRecords({ receptionCustomerPaySourceList })
} }
updateMaterialPointList(receptionTrack: any) { updateMaterialPointList(receptionTrack: UTSJSONObject[]) {
const track = receptionTrack as UTSJSONObject const track = receptionTrack
if (track == null) return if (track == null) return
const merchantId = this.tempRecordDto?.merchantId const merchantId = this.tempRecordDto?.merchantId
const staffUuid = this.tempRecordDto?.staffUuid const staffUuid = this.tempRecordDto?.staffUuid
const staffName = this.tempRecordDto?.staffName const staffName = this.tempRecordDto?.staffName
const userInfo = storage.get('userInfo') as UTSJSONObject | null const userInfo = storage.get('userInfo') as string
const sceneType = userInfo?.getNumber('sceneType') const userInfoObj:UTSJSONObject = userInfo!='' ? JSON.parse(userInfo) as UTSJSONObject : {}
const sceneType = userInfoObj.getNumber('sceneType')
const receptionCustomerMaterialPointList: any[] = []
const receptionCustomerMaterialPointList: UTSJSONObject[] = []
const map = track.toMap()
map.forEach((v, k) => { track.forEach((v: any) => {
const point = v as UTSJSONObject const point = v as UTSJSONObject
// Convert to JSON object to allow dynamic property assignment // Convert to JSON object to allow dynamic property assignment
const newPoint = { const newPoint = {
...@@ -451,7 +449,7 @@ class RecordService { ...@@ -451,7 +449,7 @@ class RecordService {
granted = true granted = true
} }
}) })
if (granted) { if (granted) {
resolve(true) resolve(true)
} else { } else {
......
...@@ -315,8 +315,8 @@ class TempRecord { ...@@ -315,8 +315,8 @@ class TempRecord {
* 缓存物料点数据 * 缓存物料点数据
* @param {Array} list * @param {Array} list
*/ */
cacheMaterialPoints(list: any[]) { cacheMaterialPoints(list: UTSJSONObject[]) {
if (this.record != null && this.record!.id != null) { if (this.record != null && this.record!.id != "") {
RecordCache.set(this.record!.id, 'MATERIAL_POINTS', list) RecordCache.set(this.record!.id, 'MATERIAL_POINTS', list)
} }
} }
......
...@@ -14,7 +14,8 @@ const FileStatus = { ...@@ -14,7 +14,8 @@ const FileStatus = {
Uploading:3, Uploading:3,
NotExist:4, NotExist:4,
Uploaded:5, Uploaded:5,
Completed:6 //状态4 的 完成状态 Completed:6, //状态4 的 完成状态
HasFile:999 // 有文件的记录
} }
export { export {
WsTyps, WsTyps,
......
import { reactive } from 'vue'
import {
ReceptionState,
receptionState,
setCustomerKey,
setCustomerInfo,
setReceptionStatus,
setBookList,
setReceptionKey,
setReceptionTrack
} from './modules/reception.uts'
/**
* 全局状态管理
* 支持模块化拆分,同时兼容 Vuex 风格 API
*/
// 1. 定义全局 State 结构
export type RootState = {
// 扁平化映射 (为了兼容旧代码)
customerKey: string
customerInfo: UTSJSONObject | null
receptionStatus: string
booksList: UTSJSONObject[]
receptionKey: string
receptionTrack: UTSJSONObject[]
// 模块化结构 (推荐新代码使用)
// reception: ReceptionState
}
// 2. 组合 State
// 使用 Class + Getter 实现扁平化访问和模块化
export class GlobalState {
get customerKey(): string { return receptionState.customerKey }
get customerInfo(): UTSJSONObject | null { return receptionState.customerInfo }
get receptionStatus(): string { return receptionState.receptionStatus }
get booksList(): UTSJSONObject[] { return receptionState.booksList }
get receptionKey(): string { return receptionState.receptionKey }
get receptionTrack(): UTSJSONObject[] { return receptionState.receptionTrack }
// 模块化访问入口
get reception(): ReceptionState { return receptionState }
}
export const state = new GlobalState()
// 3. 统一 Commit 分发
export const commit = (type: string, payload: any | null) => {
switch (type) {
// --- Reception Module ---
case 'updateCustomerKey':
setCustomerKey(payload as string)
break
case 'updateCustomerInfo':
setCustomerInfo(payload as UTSJSONObject | null)
break
case 'updateReceptionStatus':
setReceptionStatus(payload as string)
break
case 'updateBookList':
setBookList(payload as UTSJSONObject[])
break
case 'updateReceptionKey':
setReceptionKey(payload as string)
break
case 'updateReceptionTrack':
setReceptionTrack(payload as UTSJSONObject[])
break
default:
console.warn(`[Store] Unknown mutation type: ${type}`)
}
}
// 4. 导出 Store 对象
export default {
state,
commit
}
import { reactive } from 'vue'
export type ReceptionState = {
customerKey: string
customerInfo: UTSJSONObject | null
receptionStatus: string
booksList: UTSJSONObject[]
receptionKey: string
receptionTrack: UTSJSONObject[]
}
// 模块状态
export const receptionState = reactive({
customerKey: '',
customerInfo: null,
receptionStatus: '',
booksList: [],
receptionKey: '',
receptionTrack: []
} as ReceptionState)
// 模块变更方法 (Mutations)
export const setCustomerKey = (payload: string) => {
receptionState.customerKey = payload
}
export const setCustomerInfo = (payload: UTSJSONObject | null) => {
receptionState.customerInfo = payload
}
export const setReceptionStatus = (payload: string) => {
receptionState.receptionStatus = payload
}
export const setBookList = (payload: UTSJSONObject[]) => {
receptionState.booksList = payload
}
export const setReceptionKey = (payload: string) => {
receptionState.receptionKey = payload
}
export const setReceptionTrack = (payload: UTSJSONObject[]) => {
receptionState.receptionTrack = payload
}
import { RecordService } from '@/composables/recorder/index.uts'
import TempRecord from '@/composables/recorder/TempRecord.uts'
import { RecordData } from '@/composables/recorder/types/index.uts'
import { state as storeState, commit } from '@/store/index.uts'
/**
* 测试 RecordService 的监听器功能
*
* 使用方法:
* 在 App.uvue 或任意页面的 onReady/onLoad 中调用此函数即可在控制台查看测试结果
* import { testRecordWatchers } from '@/test/test_record_watchers.uts'
* testRecordWatchers()
*/
export function testRecordWatchers() {
console.log('=== 开始测试 RecordService 监听器 ===')
const service = RecordService.getInstance()
// 1. 模拟 isReceptioning 为 true,使 handler 能执行回调
// 只有在接待中 (isReceptioning() == true) 才会响应状态变化
// 我们通过设置一个 endReasonType=1 (异常结束/暂存状态?) 的伪造记录来模拟此条件
// 或者更直接地,我们可以临时覆盖 isReceptioning 方法(如果 UTS 允许)
// 方案 A: 构造伪造数据让 isReceptioning 返回 true
// isReceptioning() => (audioManager?.isRecording) || (record?.currentRecord?.endReasonType == 1)
const mockRecordData = {
id: 'mock_test_id',
endReasonType: 1
} as RecordData
// 创建 TempRecord 实例并注入
// 注意:TempRecord 构造函数可能依赖 uni.$dbRecord,但在测试环境下可能未初始化
// 如果报错,可能需要 Mock DBRecord.getInstance()
try {
const mockTempRecord = new TempRecord(mockRecordData, null, null)
service.record = mockTempRecord
console.log(`[Test] 注入 Mock Record, isReceptioning 当前状态: ${service.isReceptioning()}`)
} catch (e) {
console.error('[Test] 注入 Mock Record 失败:', e)
return
}
// 2. Mock 目标方法以验证调用
// 使用 any 类型绕过类型检查进行方法覆写 (Monkey Patching)
const serviceAny = service as any
// 备份原方法,以便测试后恢复
const originalUpdateCustomerInfo = serviceAny.updateCustomerInfo
const originalUpdateReceptionStatus = serviceAny.updateReceptionStatus
const originalUpdateBookList = serviceAny.updateBookList
const originalUpdateMaterialPointList = serviceAny.updateMaterialPointList
// 计数器
let customerInfoCount = 0
let receptionStatusCount = 0
let bookListCount = 0
let materialPointListCount = 0
// 覆写方法 (Spy)
serviceAny.updateCustomerInfo = (val: any) => {
console.log(`[Test] updateCustomerInfo 被调用,参数: ${JSON.stringify(val)}`)
customerInfoCount++
}
serviceAny.updateReceptionStatus = (val: any) => {
console.log(`[Test] updateReceptionStatus 被调用,参数: ${val}`)
receptionStatusCount++
}
serviceAny.updateBookList = (val: any) => {
console.log(`[Test] updateBookList 被调用`)
bookListCount++
}
serviceAny.updateMaterialPointList = (val: any) => {
console.log(`[Test] updateMaterialPointList 被调用`)
materialPointListCount++
}
// 3. 触发 Store 变化
console.log('[Test] 正在触发 Store 变化...')
// --- 测试 updateCustomerInfo (debounce 1000ms) ---
// 监听的是 customerKey 变化,回调中使用 customerInfo
const testCustomerInfo = { customerName: '测试客户', phoneNumber: '13800000000' }
commit('updateCustomerInfo', testCustomerInfo)
// 触发 watcher
commit('updateCustomerKey', 'KEY_' + Date.now())
// --- 测试 updateReceptionStatus (debounce 200ms) ---
commit('updateReceptionStatus', '1') // 状态变更
// --- 测试 updateBookList (debounce 1500ms) ---
const testBookList = [{ id: 'book1', imgUrl: 'url1' }]
commit('updateBookList', testBookList) // 数组变更可能不触发 watcher?
// 注意:监听的是 storeState.booksList 引用变化。commit 会替换数组,应该能触发。
// --- 测试 updateMaterialPointList (debounce 1000ms) ---
// 监听 receptionKey,回调中使用 receptionTrack
const testTrack = [{ id: 'point1', x: 10, y: 20 }]
commit('updateReceptionTrack', testTrack)
// 触发 watcher
commit('updateReceptionKey', 'REC_KEY_' + Date.now())
// 4. 等待 Debounce 结束
// 最长 delay 是 1500ms,我们等待 2000ms
console.log('[Test] 等待防抖结束 (2000ms)...')
setTimeout(() => {
console.log('=== 测试结果报告 ===')
const check = (name: string, count: number) => {
const pass = count >= 1
console.log(`${name}: ${pass ? 'PASS ✅' : 'FAIL ❌'} (调用次数: ${count})`)
}
check('updateCustomerInfo', customerInfoCount)
check('updateReceptionStatus', receptionStatusCount)
check('updateBookList', bookListCount)
check('updateMaterialPointList', materialPointListCount)
// 5. 恢复环境
serviceAny.updateCustomerInfo = originalUpdateCustomerInfo
serviceAny.updateReceptionStatus = originalUpdateReceptionStatus
serviceAny.updateBookList = originalUpdateBookList
serviceAny.updateMaterialPointList = originalUpdateMaterialPointList
service.record = null // 重置 record
console.log('=== 测试结束,环境已恢复 ===')
}, 2000)
}
import store from '@/store/index.uts'
import { watch } from 'vue'
export function testStore() {
console.log("=== 开始 Store 测试 ===")
// 1. 初始状态检查
const initVal = store.state.customerKey
console.log(`初始 customerKey: '${initVal}'`)
// 2. 设置监听器 (模拟 RecordService)
const stopWatch = watch(
() => store.state.customerKey,
(newVal, oldVal) => {
console.log(`[Watch] customerKey 发生变化: '${oldVal}' -> '${newVal}'`)
},
{ immediate: false }
)
// 3. 执行 Commit
console.log("执行 commit('updateCustomerKey', 'TEST_KEY_123')...")
store.commit('updateCustomerKey', 'TEST_KEY_123')
// 4. 验证状态
// 验证扁平化访问
const flatState = store.state.customerKey
const flatPass = flatState === 'TEST_KEY_123'
console.log(`验证扁平化访问: ${flatPass ? 'PASS' : 'FAIL'} (期望: 'TEST_KEY_123', 实际: '${flatState}')`)
// 验证模块化访问
const moduleState = store.state.reception.customerKey
const modulePass = moduleState === 'TEST_KEY_123'
console.log(`验证模块化访问: ${modulePass ? 'PASS' : 'FAIL'} (期望: 'TEST_KEY_123', 实际: '${moduleState}')`)
// 5. 清理
stopWatch()
// 恢复状态 (可选)
// store.commit('updateCustomerKey', initVal)
console.log("=== Store 测试结束 ===")
}
...@@ -4,69 +4,49 @@ ...@@ -4,69 +4,49 @@
"compiler_version": "4.87" "compiler_version": "4.87"
}, },
"files": { "files": {
"pages/demo/gl-tape-demo/index.kt": { "pages/demo/record/index.kt": {
"md5": "0aae13f9001ec4f53db18f232da3b9816d12d620", "class": "GenPagesDemoRecordIndex",
"class": "GenPagesDemoGlTapeDemoIndex" "md5": "46db702d44876c630d91abbce66cfca7cf3b20e9"
},
"pages/demo/permission/index.kt": {
"class": "GenPagesDemoPermissionIndex",
"md5": "18cb329597e3254e8c67cefdc1f196e3a1260273"
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-load-more.kt": {
"md5": "1e3f265be090ef72c9841a36e09d19bb3abc1a93",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoadMore"
}, },
"pages/demo/echarts/index.kt": { "uni_modules/z-paging-x/components/z-paging-x-empty/z-paging-x-empty.kt": {
"md5": "e9c323efac81c50aa4eca12e75586263bacd95fb", "class": "GenUniModulesZPagingXComponentsZPagingXEmptyZPagingXEmpty",
"class": "GenPagesDemoEchartsIndex" "md5": "e8fa2621d20e3d4183965c604b60282e40ce5932"
}, },
"pages/demo/tailwindcss/index.kt": { "components/evaluationForm/TypeTabComponent.kt": {
"md5": "c427026081cb75ed3d462c5ebf8a3ac0750bfa34", "class": "GenComponentsEvaluationFormTypeTabComponent",
"class": "GenPagesDemoTailwindcssIndex" "md5": "0c65870c54770c8dfebb843dc83b547ef7d25a50"
}, },
"pages/common/components/AccountList.kt": { "pages/common/components/AccountList.kt": {
"class": "GenPagesCommonComponentsAccountList", "class": "GenPagesCommonComponentsAccountList",
"md5": "d78e30a9fd29b1bd3fc6451b74a39845095f79ee" "md5": "d78e30a9fd29b1bd3fc6451b74a39845095f79ee"
}, },
"pages/demo/record/index.kt": {
"md5": "46db702d44876c630d91abbce66cfca7cf3b20e9",
"class": "GenPagesDemoRecordIndex"
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-refresher.kt": { "uni_modules/z-paging-x/components/z-paging-x/components/z-paging-refresher.kt": {
"md5": "fc38688c293b8de58280ea7094b45716e5c5d262", "class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingRefresher",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingRefresher" "md5": "fc38688c293b8de58280ea7094b45716e5c5d262"
}, },
"uni_modules/z-paging-x/components/z-paging-x/z-paging-x.kt": { "uni_modules/z-paging-x/components/z-paging-x/components/z-paging-load-more.kt": {
"md5": "790b2fe11f0d1a339b2a255af60a133b90113a36", "class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoadMore",
"class": "GenUniModulesZPagingXComponentsZPagingXZPagingX" "md5": "1e3f265be090ef72c9841a36e09d19bb3abc1a93"
},
"pages/demo/old/index.kt": {
"class": "GenPagesDemoOldIndex",
"md5": "8b8d4a1b49e2ef7592d4e2f958b222392cf46fe8"
},
"pages/common/login/index.kt": {
"md5": "165659590e28e0663c371d8606710e0c7fd36859",
"class": "GenPagesCommonLoginIndex"
},
"pages/common/components/NoData.kt": {
"class": "GenPagesCommonComponentsNoData",
"md5": "0608111022dbb7da0f7c3e452b7409d1ec7f5735"
}, },
"index.kt": { "index.kt": {
"md5": "eea29e723be30ffc425911e50ea2a80ea6bfbf75", "md5": "59fce655dd1f091f92da134100f07e53b94e39b1",
"class": "" "class": ""
}, },
"components/evaluationForm/TypeTabComponent.kt": { "pages/common/components/NoData.kt": {
"md5": "0c65870c54770c8dfebb843dc83b547ef7d25a50", "md5": "0608111022dbb7da0f7c3e452b7409d1ec7f5735",
"class": "GenComponentsEvaluationFormTypeTabComponent" "class": "GenPagesCommonComponentsNoData"
}, },
"pages/demo/media/index.kt": { "pages/demo/media/index.kt": {
"md5": "d76917918ad2397c0cd8429328b52ab77a83ff4f", "class": "GenPagesDemoMediaIndex",
"class": "GenPagesDemoMediaIndex" "md5": "d76917918ad2397c0cd8429328b52ab77a83ff4f"
}, },
"uni_modules/z-paging-x/components/z-paging-x-empty/z-paging-x-empty.kt": { "pages/demo/tailwindcss/index.kt": {
"md5": "e8fa2621d20e3d4183965c604b60282e40ce5932", "class": "GenPagesDemoTailwindcssIndex",
"class": "GenUniModulesZPagingXComponentsZPagingXEmptyZPagingXEmpty" "md5": "c427026081cb75ed3d462c5ebf8a3ac0750bfa34"
},
"uni_modules/lime-echart/components/l-echart/l-echart.kt": {
"md5": "23c5a52d57071d3771477b55f910fbe9ccac83fc",
"class": "GenUniModulesLimeEchartComponentsLEchartLEchart"
}, },
"pages/demo/local-store/index.kt": { "pages/demo/local-store/index.kt": {
"class": "GenPagesDemoLocalStoreIndex", "class": "GenPagesDemoLocalStoreIndex",
...@@ -76,25 +56,45 @@ ...@@ -76,25 +56,45 @@
"md5": "d8d028fdb9eab322150af58a90c2361ddfea3f18", "md5": "d8d028fdb9eab322150af58a90c2361ddfea3f18",
"class": "GenPagesIndexIndex" "class": "GenPagesIndexIndex"
}, },
"pages/common/login/index.kt": {
"md5": "165659590e28e0663c371d8606710e0c7fd36859",
"class": "GenPagesCommonLoginIndex"
},
"pages/demo/echarts/index.kt": {
"md5": "e9c323efac81c50aa4eca12e75586263bacd95fb",
"class": "GenPagesDemoEchartsIndex"
},
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-loading.kt": {
"md5": "bc2c0931a10ad4eea405d60556ee5e702cc28f62",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoading"
},
"components/PublishPopup.kt": {
"class": "GenComponentsPublishPopup",
"md5": "b0c3be2d9836f013bc4b67bbf5fe08a456f6ce18"
},
"pages/common/accountItems/index.kt": { "pages/common/accountItems/index.kt": {
"md5": "ce7b7aebc25c812bc76446384be7b4ae423373da", "md5": "ce7b7aebc25c812bc76446384be7b4ae423373da",
"class": "GenPagesCommonAccountItemsIndex" "class": "GenPagesCommonAccountItemsIndex"
}, },
"pages/demo/gl-tape-demo/index.kt": {
"md5": "0aae13f9001ec4f53db18f232da3b9816d12d620",
"class": "GenPagesDemoGlTapeDemoIndex"
},
"pages/demo/old/index.kt": {
"class": "GenPagesDemoOldIndex",
"md5": "8b8d4a1b49e2ef7592d4e2f958b222392cf46fe8"
},
"uni_modules/uni-icons/components/uni-icons/uni-icons.kt": { "uni_modules/uni-icons/components/uni-icons/uni-icons.kt": {
"class": "GenUniModulesUniIconsComponentsUniIconsUniIcons", "class": "GenUniModulesUniIconsComponentsUniIconsUniIcons",
"md5": "95aae1ef2b0e8906a602ca5d24eea964329fab31" "md5": "95aae1ef2b0e8906a602ca5d24eea964329fab31"
}, },
"uni_modules/z-paging-x/components/z-paging-x/components/z-paging-loading.kt": { "pages/demo/permission/index.kt": {
"md5": "bc2c0931a10ad4eea405d60556ee5e702cc28f62", "class": "GenPagesDemoPermissionIndex",
"class": "GenUniModulesZPagingXComponentsZPagingXComponentsZPagingLoading" "md5": "18cb329597e3254e8c67cefdc1f196e3a1260273"
},
"uni_modules/lime-echart/components/l-echart/l-echart.kt": {
"md5": "23c5a52d57071d3771477b55f910fbe9ccac83fc",
"class": "GenUniModulesLimeEchartComponentsLEchartLEchart"
}, },
"components/PublishPopup.kt": { "uni_modules/z-paging-x/components/z-paging-x/z-paging-x.kt": {
"md5": "b0c3be2d9836f013bc4b67bbf5fe08a456f6ce18", "class": "GenUniModulesZPagingXComponentsZPagingXZPagingX",
"class": "GenComponentsPublishPopup" "md5": "790b2fe11f0d1a339b2a255af60a133b90113a36"
} }
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -620,3 +620,26 @@ export function isEqual(a: any, b: any): boolean { ...@@ -620,3 +620,26 @@ export function isEqual(a: any, b: any): boolean {
return a == b; return a == b;
} }
/**
* 替换字符串中的所有匹配项
* @param text 原始字符串
* @param find 要查找的字符串
* @param replace 替换后的字符串
* @returns 替换后的字符串
*/
export function replaceAll(text: string, find: string, replace: string): string {
if (text.indexOf(find) == -1) {
return text
}
const parts = text.split(find)
let res = ""
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
res = res + part
if (i < parts.length - 1) {
res = res + replace
}
}
return res
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!