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 {
......
/* /*
* @Descripttion: * @Descripttion:
* @version: 1.0.0 * @version: 1.0.0
* @Author: limin * @Author: limin
* @Date: 2026-01-28 20:57:12 * @Date: 2026-01-28 20:57:12
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-03-01 18:34:16 * @LastEditTime: 2026-03-04 19:31:33
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\RecordSave.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\RecordSave.uts
*/ */
import Queue from '../../utils/Queue.uts' import Queue from '../../utils/Queue.uts'
import { FileStatus } from './common/constants.uts' import { FileStatus } from './common/constants.uts'
// import dayjs from 'dayjs' // import dayjs from 'dayjs'
import { convertDateTimeFormat } from '../../utils/index.uts' import { convertDateTimeFormat, replaceAll } from '../../utils/index.uts'
// import store from '@/store' // UTS 中 store 使用方式可能不同,暂时注释或模拟 // import store from '@/store' // UTS 中 store 使用方式可能不同,暂时注释或模拟
import FileUploadService from '../uploader/FileUploadService.uts' import FileUploadService from '../uploader/FileUploadService.uts'
import { logger } from '../logger/index.uts' import { logger } from '../logger/index.uts'
import DBRecord from './DBRecord.uts' import DBRecord from './DBRecord.uts'
import type { RecordData } from './types' import type { RecordData } from './types'
import { saveRecCustomer, searchRecordingEndTime } from '@/api/receiption.uts'
// 模拟 utils // 模拟 utils
function deepClone(obj: any | null): any | null { function deepClone(obj: any | null): any | null {
if (obj == null) return null if (obj == null) return null
...@@ -32,13 +34,13 @@ const UPLOAD_INTERVAL = 0.5 * 60 * 1000 ...@@ -32,13 +34,13 @@ const UPLOAD_INTERVAL = 0.5 * 60 * 1000
/** /**
* 接待记录保存服务 * 接待记录保存服务
* *
* 职责: * 职责:
* 1. 管理接待记录的上传队列 * 1. 管理接待记录的上传队列
* 2. 处理文件上传结果 * 2. 处理文件上传结果
* 3. 保存接待记录到服务器 * 3. 保存接待记录到服务器
* 4. 清理本地文件和记录 * 4. 清理本地文件和记录
* *
* 特点: * 特点:
* - 使用 FileUploadManager 处理文件上传 * - 使用 FileUploadManager 处理文件上传
* - 自动轮询上传队列 * - 自动轮询上传队列
...@@ -61,7 +63,7 @@ class RecordSave { ...@@ -61,7 +63,7 @@ class RecordSave {
private constructor() { private constructor() {
this.interval = UPLOAD_INTERVAL this.interval = UPLOAD_INTERVAL
// Bind methods not needed in UTS class methods // Bind methods not needed in UTS class methods
} }
...@@ -93,7 +95,7 @@ class RecordSave { ...@@ -93,7 +95,7 @@ class RecordSave {
} }
} }
uni.onNetworkStatusChange(this._networkHandler!) uni.onNetworkStatusChange(this._networkHandler!)
logger.info('【接待记录保存服务】初始化成功', "RecordSave") logger.info('【接待记录保存服务】初始化成功', "RecordSave")
} catch (error) { } catch (error) {
logger.error(`【接待记录保存服务】初始化失败 error:${error}`, "RecordSave") logger.error(`【接待记录保存服务】初始化失败 error:${error}`, "RecordSave")
...@@ -123,11 +125,11 @@ class RecordSave { ...@@ -123,11 +125,11 @@ class RecordSave {
try { try {
const fileInfo = this.parseFileInfo(data) const fileInfo = this.parseFileInfo(data)
const error = fileInfo['error'] as string | null const error = fileInfo['error'] as string | null
if (error != null) { if (error != null) {
throw new Error(`上传文件信息解析异常: ${error}`) throw new Error(`上传文件信息解析异常: ${error}`)
} }
const recordId = fileInfo['recordId'] as string const recordId = fileInfo['recordId'] as string
const fileName = fileInfo['fileName'] as string const fileName = fileInfo['fileName'] as string
const status = fileInfo['status'] as number const status = fileInfo['status'] as number
...@@ -142,7 +144,7 @@ class RecordSave { ...@@ -142,7 +144,7 @@ class RecordSave {
} }
const dbRecord = await this.getDbRecord() const dbRecord = await this.getDbRecord()
const record = await dbRecord.getRecordById(recordId) const record = await dbRecord.getRecordById(recordId)
if (record == null) { if (record == null) {
throw new Error(`未找到记录: ${recordId}`) throw new Error(`未找到记录: ${recordId}`)
...@@ -189,7 +191,7 @@ class RecordSave { ...@@ -189,7 +191,7 @@ class RecordSave {
if (data != null && (status == FileStatus.NoFile || status == FileStatus.NotExist)) { if (data != null && (status == FileStatus.NoFile || status == FileStatus.NotExist)) {
return this._parseNoFileStatus(data) return this._parseNoFileStatus(data)
} }
const filePath = (data['filePath'] as string ?? '') + (data['fileName'] as string ?? '') const filePath = (data['filePath'] as string ?? '') + (data['fileName'] as string ?? '')
return { error: '【接待记录保存服务】 == 未知文件状态', data: data, filePath: filePath } return { error: '【接待记录保存服务】 == 未知文件状态', data: data, filePath: filePath }
} }
...@@ -199,7 +201,7 @@ class RecordSave { ...@@ -199,7 +201,7 @@ class RecordSave {
const fileName = data['fileName'] const fileName = data['fileName']
const filePath = data['filePath'] const filePath = data['filePath']
const status = data['status'] const status = data['status']
const clientPath = (filePath as string ?? '') + (fileName as string ?? '') const clientPath = (filePath as string ?? '') + (fileName as string ?? '')
if (recordId == null) { if (recordId == null) {
return { error: '【接待记录保存服务】 == 缺少记录ID', data: data, filePath: clientPath } return { error: '【接待记录保存服务】 == 缺少记录ID', data: data, filePath: clientPath }
...@@ -219,16 +221,16 @@ class RecordSave { ...@@ -219,16 +221,16 @@ class RecordSave {
const detail = data['detail'] as UTSJSONObject const detail = data['detail'] as UTSJSONObject
const dataList = detail['data'] as UTSJSONObject[] const dataList = detail['data'] as UTSJSONObject[]
const payload = dataList[0] const payload = dataList[0]
const recordId = payload['recordId'] const recordId = payload['recordId']
const fileName = payload['fileName'] const fileName = payload['fileName']
const filePath = payload['filePath'] const filePath = payload['filePath']
const clientPath = (filePath as string ?? '') + (fileName as string ?? '') const clientPath = (filePath as string ?? '') + (fileName as string ?? '')
if (recordId == null) { if (recordId == null) {
return { error: '文件上传回调,缺少recordId', data: data, filePath: clientPath } return { error: '文件上传回调,缺少recordId', data: data, filePath: clientPath }
} }
const code = payload['code'] const code = payload['code']
const message = payload['message'] const message = payload['message']
const fileData = payload['data'] as UTSJSONObject const fileData = payload['data'] as UTSJSONObject
...@@ -236,7 +238,7 @@ class RecordSave { ...@@ -236,7 +238,7 @@ class RecordSave {
const res = oss['res'] as UTSJSONObject const res = oss['res'] as UTSJSONObject
const requestUrls = res['requestUrls'] as string[] const requestUrls = res['requestUrls'] as string[]
const serverUrl = requestUrls[0] const serverUrl = requestUrls[0]
if (code != 0 || serverUrl == null) { if (code != 0 || serverUrl == null) {
return { error: `解析异常: code->${code} message->${message}`, data: data, recordId: recordId, filePath: clientPath } return { error: `解析异常: code->${code} message->${message}`, data: data, recordId: recordId, filePath: clientPath }
} }
...@@ -257,6 +259,7 @@ class RecordSave { ...@@ -257,6 +259,7 @@ class RecordSave {
_changeFilePathToServer(record: UTSJSONObject, fileInfo: UTSJSONObject): UTSJSONObject { _changeFilePathToServer(record: UTSJSONObject, fileInfo: UTSJSONObject): UTSJSONObject {
const _record = deepClone(record) as UTSJSONObject const _record = deepClone(record) as UTSJSONObject
console.log("🚀 ~ RecordSave ~ _changeFilePathToServer ~ _record:", _record)
logger.info(`【接待记录保存服务】 == 开始更新文件路径, recordId: ${_record['id']}`, "RecordSave") logger.info(`【接待记录保存服务】 == 开始更新文件路径, recordId: ${_record['id']}`, "RecordSave")
const status = fileInfo['status'] as number const status = fileInfo['status'] as number
...@@ -268,10 +271,10 @@ class RecordSave { ...@@ -268,10 +271,10 @@ class RecordSave {
logger.info(`【接待记录保存服务】 == 记录被标记为无文件状态`, "RecordSave") logger.info(`【接待记录保存服务】 == 记录被标记为无文件状态`, "RecordSave")
return _record return _record
} }
_record['status'] = FileStatus.HasFile
const recordUrlList = this.urlListFilter(_record['recordUrlList'] as UTSJSONObject[]) const recordUrlList = this.urlListFilter(_record['recordUrlList'] as UTSJSONObject[])
_record['recordUrlList'] = recordUrlList _record['recordUrlList'] = recordUrlList
// find target file // find target file
let targetFile: UTSJSONObject | null = null let targetFile: UTSJSONObject | null = null
for (const item of recordUrlList) { for (const item of recordUrlList) {
...@@ -293,12 +296,14 @@ class RecordSave { ...@@ -293,12 +296,14 @@ class RecordSave {
const fileName = fileInfo['fileName'] as string const fileName = fileInfo['fileName'] as string
const clientPath = fileInfo['clientPath'] as string const clientPath = fileInfo['clientPath'] as string
const itemFile = (item['file'] ?? item['filePath']) as string const itemFile = (item['file'] ?? item['filePath']) as string
if (!this.isLegalFile(fileName)) return !this.isLegalFile(itemFile) if (!this.isLegalFile(fileName)) return !this.isLegalFile(itemFile)
return itemFile == clientPath || itemFile.endsWith(fileName) return itemFile == clientPath || itemFile.endsWith(fileName)
} }
_updateFileStatus(targetFile: UTSJSONObject, fileInfo: UTSJSONObject) { _updateFileStatus(targetFile: UTSJSONObject, fileInfo: UTSJSONObject) {
console.log("🚀 ~ RecordSave ~ _updateFileStatus ~ targetFile:", targetFile)
console.log("🚀 ~ RecordSave ~ _updateFileStatus ~ fileInfo:", fileInfo)
const status = fileInfo['status'] as number const status = fileInfo['status'] as number
targetFile['status'] = status targetFile['status'] = status
if (status == FileStatus.Uploaded) { if (status == FileStatus.Uploaded) {
...@@ -313,16 +318,16 @@ class RecordSave { ...@@ -313,16 +318,16 @@ class RecordSave {
// const dbRecord = await this.getDbRecord() // const dbRecord = await this.getDbRecord()
// const record = recordId != null ? await dbRecord.getRecordById(recordId) : {} // const record = recordId != null ? await dbRecord.getRecordById(recordId) : {}
// const userInfo = (uni.getStorageSync('userInfo') as UTSJSONObject | null) ?? {} // const userInfo = (uni.getStorageSync('userInfo') as UTSJSONObject | null) ?? {}
// const customerName = record != null ? record['customerName'] : '' // const customerName = record != null ? record['customerName'] : ''
// const customerPhone = record != null ? record['customerPhone'] : '' // 假设字段名 // const customerPhone = record != null ? record['customerPhone'] : '' // 假设字段名
// const carType = record != null ? record['carType'] : '' // 假设字段名 // const carType = record != null ? record['carType'] : '' // 假设字段名
// const user = (userInfo['user'] as UTSJSONObject | null) ?? {} // const user = (userInfo['user'] as UTSJSONObject | null) ?? {}
// const userName = user['userName'] // const userName = user['userName']
// const now = convertDateTimeFormat(new Date(), "-") // const now = convertDateTimeFormat(new Date(), "-")
logger.error(`${1}-${message},员工: ${1}, 客户: ${1}`, "RecordSave") logger.error(`${1}-${message},员工: ${1}, 客户: ${1}`, "RecordSave")
// extra info logged via msg for now // extra info logged via msg for now
} catch (error) { } catch (error) {
...@@ -349,7 +354,7 @@ class RecordSave { ...@@ -349,7 +354,7 @@ class RecordSave {
const dbRecord = await this.getDbRecord() const dbRecord = await this.getDbRecord()
let _records: RecordData[] = await dbRecord.getCompletedRecords() let _records: RecordData[] = await dbRecord.getCompletedRecords()
return await this.flattenData(_records ?? []) return await this.flattenData(_records ?? [])
} }
/** /**
* 上传文件记录 * 上传文件记录
...@@ -357,11 +362,11 @@ class RecordSave { ...@@ -357,11 +362,11 @@ class RecordSave {
*/ */
async uploadRecord(record: UTSJSONObject) { async uploadRecord(record: UTSJSONObject) {
logger.info(`【接待记录保存服务】 == 开始上传文件!! record: ${JSON.stringify(record)}`, "RecordSave") logger.info(`【接待记录保存服务】 == 开始上传文件!! record: ${JSON.stringify(record)}`, "RecordSave")
const recordId = record.getString('recordId') const recordId = record.getString('recordId')
const fileName = record.getString('fileName') const fileName = record.getString('fileName')
const filePath = record.getString('filePath') const filePath = record.getString('filePath')
try { try {
const status = record.getNumber('status') const status = record.getNumber('status')
if (status == FileStatus.NoFile || status == FileStatus.NotExist) { if (status == FileStatus.NoFile || status == FileStatus.NotExist) {
...@@ -393,10 +398,10 @@ class RecordSave { ...@@ -393,10 +398,10 @@ class RecordSave {
bucketName: null, // 可选:覆盖默认 bucket bucketName: null, // 可选:覆盖默认 bucket
region: null // 可选:覆盖默认 region region: null // 可选:覆盖默认 region
} }
// 使用 FileUploadService 上传 // 使用 FileUploadService 上传
const res = await FileUploadService.upload(options) const res = await FileUploadService.upload(options)
// 构造成功结果 // 构造成功结果
const result = { const result = {
status: FileStatus.Uploaded, status: FileStatus.Uploaded,
...@@ -424,7 +429,7 @@ class RecordSave { ...@@ -424,7 +429,7 @@ class RecordSave {
} catch (error) { } catch (error) {
logger.error(`【接待记录保存服务】 == 上传失败: ${error}`, "RecordSave") logger.error(`【接待记录保存服务】 == 上传失败: ${error}`, "RecordSave")
const errorMsg = typeof error === 'string' ? error : `${error}` const errorMsg = typeof error === 'string' ? error : `${error}`
const errorResult = { const errorResult = {
detail: { detail: {
...@@ -437,7 +442,7 @@ class RecordSave { ...@@ -437,7 +442,7 @@ class RecordSave {
}] }]
} }
} }
this.handleUploadResult(errorResult) this.handleUploadResult(errorResult)
} }
} }
...@@ -462,17 +467,16 @@ class RecordSave { ...@@ -462,17 +467,16 @@ class RecordSave {
} }
async _saveOrUpdate(data: UTSJSONObject) { async _saveOrUpdate(data: UTSJSONObject) {
console.log("🚀 ~ RecordSave ~ _saveOrUpdate ~ data:", data)
logger.info(`【接待记录保存服务】 == 开始保存或更新接待记录!!`, "RecordSave") logger.info(`【接待记录保存服务】 == 开始保存或更新接待记录!!`, "RecordSave")
const status = data['status'] as number const status = data['status'] as number // 没有文件的记录,status 为 NoFile 有文件的记录没有此状态
const record = deepClone(data) as UTSJSONObject const record = deepClone(data) as UTSJSONObject
// remove status, tempFilePath, receptionStatus from record if needed
// In UTS, we can't easily destructure-remove. We just ignore them when saving if API doesn't care.
const recordUrlList = record['recordUrlList'] as UTSJSONObject[] const recordUrlList = record['recordUrlList'] as UTSJSONObject[]
const fileList = Array.isArray(recordUrlList) ? recordUrlList : [] const fileList = Array.isArray(recordUrlList) ? recordUrlList : []
const isAllCompleted = status == FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i['status'] as number)) const isAllCompleted = status == FileStatus.NoFile || fileList.every(i => [FileStatus.Uploaded, FileStatus.Completed].includes(i['status'] as number))
if (isAllCompleted) { if (isAllCompleted) {
await this._handleCompletedRecord(record, fileList) await this._handleCompletedRecord(record, fileList)
} else { } else {
...@@ -487,25 +491,24 @@ class RecordSave { ...@@ -487,25 +491,24 @@ class RecordSave {
const localPaths = uploadedFiles.map(i => i['filePathOnClient'] as string) const localPaths = uploadedFiles.map(i => i['filePathOnClient'] as string)
logger.warn(`【接待记录保存服务】 == 本条接待所有文件已经上传和处理完毕!!`, "RecordSave") logger.warn(`【接待记录保存服务】 == 本条接待所有文件已经上传和处理完毕!!`, "RecordSave")
// 2. 准备提交参数 // 2. 准备提交参数
const params = deepClone(record) as UTSJSONObject const params = deepClone(record) as UTSJSONObject
params['recordUrlList'] = serverPaths // replace with string array params['recordUrlList'] = serverPaths // replace with string array
if (params['receptionEndTime'] == null || params['receptionEndTime'] == "") { if (params['receptionEndTime'] == null || params['receptionEndTime'] == "") {
params['receptionEndTime'] = await this._requestReceptionEndTime(serverPaths, params['receptionStartTime'] as string) params['receptionEndTime'] = await this._requestReceptionEndTime(serverPaths, params['receptionStartTime'] as string)
} }
// 3. 提交到服务器 // 3. 提交到服务器
logger.info(`【接待记录保存服务】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`, "RecordSave") logger.info(`【接待记录保存服务】 == 开始向服务器保存接待记录!!参数: ${JSON.stringify(params)}`, "RecordSave")
// 模拟 api 调用 // 模拟 api 调用
// const res = await uni.$api.commonApi.saveRecCustomer(params) const res = await saveRecCustomer(params)
const res = true // mock
logger.warn(`【接待记录保存服务】 == 服务器返回结果: ${JSON.stringify(res)}`, "RecordSave") logger.warn(`【接待记录保存服务】 == 服务器返回结果: ${JSON.stringify(res)}`, "RecordSave")
// 4. 清理本地数据 // 4. 清理本地数据
if (res) { if (res != null) {
logger.info(`【上传服务】 == 开始删除客户端的文件!!`, "RecordSave") logger.info(`【上传服务】 == 开始删除客户端的文件!!`, "RecordSave")
await this._removeRecordFiles(localPaths) await this._removeRecordFiles(localPaths)
await this._removeRecordById(record['id'] as string) await this._removeRecordById(record['id'] as string)
...@@ -517,15 +520,18 @@ class RecordSave { ...@@ -517,15 +520,18 @@ class RecordSave {
*/ */
async _requestReceptionEndTime(recordUrlList: string[], receptionStartTime: string): Promise<string> { async _requestReceptionEndTime(recordUrlList: string[], receptionStartTime: string): Promise<string> {
if (recordUrlList.length === 0) return receptionStartTime if (recordUrlList.length === 0) return receptionStartTime
logger.info(`【上传服务】 == 向服务器获取结束接待时间: recordUrlList ->${serializeIfObject(recordUrlList)} receptionStartTime: -> ${receptionStartTime}`, "RecordSave") logger.info(`【上传服务】 == 向服务器获取结束接待时间: recordUrlList ->${serializeIfObject(recordUrlList)} receptionStartTime: -> ${receptionStartTime}`, "RecordSave")
// mock api // mock api
// const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTime.replace(/\//g, '-') }) // const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTime.replace(/\//g, '-') })
const endTime = receptionStartTime // mock const receptionStartTimeStr = replaceAll(receptionStartTime, '/', '-')
const endTime = await searchRecordingEndTime({ recordUrlList, receptionStartTime: receptionStartTimeStr })
logger.info(`【上传服务】 == 服务器返回结束接待时间: endTime ->${endTime}`, "RecordSave") logger.info(`【上传服务】 == 服务器返回结束接待时间: endTime ->${endTime}`, "RecordSave")
return endTime.replace(/-/g, '/') if(endTime.includes('-')){
return replaceAll(endTime, '-', '/')
}
return endTime
} }
async _handleIncompleteRecord(record: UTSJSONObject) { async _handleIncompleteRecord(record: UTSJSONObject) {
...@@ -584,7 +590,7 @@ class RecordSave { ...@@ -584,7 +590,7 @@ class RecordSave {
const recordUrlListRaw = cur.recordUrlList ?? [] const recordUrlListRaw = cur.recordUrlList ?? []
// Filter RecordFile[] // Filter RecordFile[]
const recordUrlList = recordUrlListRaw.filter(item => (item.file != null && item.file !== "") || (item.filePath !== "")) const recordUrlList = recordUrlListRaw.filter(item => (item.file != null && item.file !== "") || (item.filePath !== ""))
// 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题) // 1. 记录级别的黑名单检查 (针对空文件等整条记录的问题)
const recordId = cur.id const recordId = cur.id
if (this._isInBlackList(recordId)) { if (this._isInBlackList(recordId)) {
...@@ -599,17 +605,17 @@ class RecordSave { ...@@ -599,17 +605,17 @@ class RecordSave {
try { try {
const fileStatus = file.status ?? 0 const fileStatus = file.status ?? 0
if (fileStatus === FileStatus.Uploaded || fileStatus === FileStatus.Completed) continue if (fileStatus === FileStatus.Uploaded || fileStatus === FileStatus.Completed) continue
const fileUrl = (file.file ?? file.filePath) const fileUrl = (file.file ?? file.filePath)
const aFullPath = fileUrl.split('/') const aFullPath = fileUrl.split('/')
const fileName = aFullPath.pop()! const fileName = aFullPath.pop()!
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
const file2Up = deepClone(file) as UTSJSONObject const file2Up = deepClone(file) as UTSJSONObject
file2Up['recordId'] = recordId file2Up['recordId'] = recordId
file2Up['fileName'] = fileName file2Up['fileName'] = fileName
file2Up['filePath'] = filePath file2Up['filePath'] = filePath
const fileExists = await this.checkFileExists(fileUrl) const fileExists = await this.checkFileExists(fileUrl)
if (!fileExists) { if (!fileExists) {
logger.error(`【接待记录保存服务】 == 记录中有语音文件地址,但是文件不存在, recordId: ${recordId}, fileUrl: ${fileUrl}`, "RecordSave") logger.error(`【接待记录保存服务】 == 记录中有语音文件地址,但是文件不存在, recordId: ${recordId}, fileUrl: ${fileUrl}`, "RecordSave")
...@@ -679,12 +685,12 @@ class RecordSave { ...@@ -679,12 +685,12 @@ class RecordSave {
resolve() resolve()
} }
this._taskStartTime = Date.now() this._taskStartTime = Date.now()
const recordId = record['recordId'] as string const recordId = record['recordId'] as string
const fileName = record['fileName'] as string const fileName = record['fileName'] as string
this._currentKey = this._getTaskKey(recordId, fileName) this._currentKey = this._getTaskKey(recordId, fileName)
const execute = async () => { const execute = async () => {
try { try {
if (this._isInBlackList(recordId)) { if (this._isInBlackList(recordId)) {
...@@ -696,7 +702,7 @@ class RecordSave { ...@@ -696,7 +702,7 @@ class RecordSave {
} catch (error) { } catch (error) {
const errorMsg = typeof error === 'string' ? error : `${error}` const errorMsg = typeof error === 'string' ? error : `${error}`
this._addToBlackList(recordId, `上传文件时发生异常(uploadRecord): ${errorMsg}`) this._addToBlackList(recordId, `上传文件时发生异常(uploadRecord): ${errorMsg}`)
logger.error(`上传文件时发生异常(uploadRecord): ${errorMsg}, recordId: ${recordId}`, "RecordSave") logger.error(`上传文件时发生异常(uploadRecord): ${errorMsg}, recordId: ${recordId}`, "RecordSave")
this.endTask() this.endTask()
} }
} }
...@@ -742,7 +748,7 @@ class RecordSave { ...@@ -742,7 +748,7 @@ class RecordSave {
async startPolling(isForce: boolean = false) { async startPolling(isForce: boolean = false) {
// await uni.$dbReady (now managed by singleton init) // await uni.$dbReady (now managed by singleton init)
await DBRecord.getInstance().init() await DBRecord.getInstance().init()
await this._ensureInitialized() await this._ensureInitialized()
this._blackList.clear() this._blackList.clear()
if (this._pumpRunning || this.updateResolve != null) { if (this._pumpRunning || this.updateResolve != null) {
...@@ -790,7 +796,7 @@ class RecordSave { ...@@ -790,7 +796,7 @@ class RecordSave {
// 从队列取出任务 // 从队列取出任务
record = this.snapshot!.dequeue() record = this.snapshot!.dequeue()
// 执行任务 // 执行任务
if (record != null) { if (record != null) {
await this.beginTask(record) await this.beginTask(record)
......
...@@ -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
...@@ -549,6 +549,7 @@ val FileStatus: UTSJSONObject = object : UTSJSONObject(UTSSourceMapPosition("Fil ...@@ -549,6 +549,7 @@ val FileStatus: UTSJSONObject = object : UTSJSONObject(UTSSourceMapPosition("Fil
var NotExist: Number = 4 var NotExist: Number = 4
var Uploaded: Number = 5 var Uploaded: Number = 5
var Completed: Number = 6 var Completed: Number = 6
var HasFile: Number = 999
} }
open class PathUtils : IUTSSourceMap { open class PathUtils : IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? { override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
...@@ -842,6 +843,25 @@ fun isEqual(a: Any, b: Any): Boolean { ...@@ -842,6 +843,25 @@ fun isEqual(a: Any, b: Any): Boolean {
} }
return a == b return a == b
} }
fun replaceAll(text: String, find: String, replace: String): String {
if (text.indexOf(find) == -1) {
return text
}
val parts = text.split(find)
var res = ""
run {
var i: Number = 0
while(i < parts.length){
val part = parts[i]
res = res + part
if (i < parts.length - 1) {
res = res + replace
}
i++
}
}
return res
}
inline fun <reified T> parse(data: Any): T? { inline fun <reified T> parse(data: Any): T? {
return (data as UTSJSONObject).parse<T>() return (data as UTSJSONObject).parse<T>()
} }
...@@ -1467,6 +1487,24 @@ fun getToken(params: UTSJSONObject): UTSPromise<UTSJSONObject> { ...@@ -1467,6 +1487,24 @@ fun getToken(params: UTSJSONObject): UTSPromise<UTSJSONObject> {
return@w d return@w d
}) })
} }
fun saveRecCustomer(params: UTSJSONObject): UTSPromise<UTSJSONObject> {
return wrapUTSPromise(suspend w@{
val data: UTSJSONObject = UTSJSONObject.assign(object : UTSJSONObject(UTSSourceMapPosition("data", "api/receiption.uts", 13, 11)) {
var projectName = "boutique"
}, params)
val d = http.fetch("dj.api.smartcarlife.recepiton.customer.saveRecCustomer", data, false, "dj")
return@w d
})
}
fun searchRecordingEndTime(params: UTSJSONObject): UTSPromise<String> {
return wrapUTSPromise(suspend w@{
val data: UTSJSONObject = UTSJSONObject.assign(object : UTSJSONObject(UTSSourceMapPosition("data", "api/receiption.uts", 22, 11)) {
var projectName = "boutique"
}, params)
val d = http.fetch("dj.api.smartcarlife.recepiton.customer.searchRecordingEndTime", data, false, "dj")
return@w d as UTSPromise<String>
})
}
abstract class AliOSSBaseStrategy : IUploadStrategy, IUTSSourceMap { abstract class AliOSSBaseStrategy : IUploadStrategy, IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? { override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("AliOSSBaseStrategy", "composables/uploader/AliOSSBaseStrategy.uts", 9, 23) return UTSSourceMapPosition("AliOSSBaseStrategy", "composables/uploader/AliOSSBaseStrategy.uts", 9, 23)
...@@ -2265,7 +2303,7 @@ open class SQLite { ...@@ -2265,7 +2303,7 @@ open class SQLite {
sql += " ORDER BY " + orderKey + " " + orderType sql += " ORDER BY " + orderKey + " " + orderType
} }
} }
return selectSql(sql) return this.selectSql(sql)
} }
open fun insert(tabName: String, keyValues: UTSJSONObject): UTSPromise<Any?> { open fun insert(tabName: String, keyValues: UTSJSONObject): UTSPromise<Any?> {
val map = keyValues.toMap() val map = keyValues.toMap()
...@@ -2337,9 +2375,6 @@ open class SQLite { ...@@ -2337,9 +2375,6 @@ open class SQLite {
} }
open fun drop(tabName: String): UTSPromise<Any?> { open fun drop(tabName: String): UTSPromise<Any?> {
val sql = "DROP TABLE IF EXISTS " + tabName val sql = "DROP TABLE IF EXISTS " + tabName
console.log("🚀 ~ SQLite ~ createTable ~ sql:", sql, " at composables/db/sqlite.uts:382")
console.log("🚀 ~ SQLite ~ createTable ~ sql:", sql, " at composables/db/sqlite.uts:383")
console.log("🚀 ~ SQLite ~ createTable ~ sql:", sql, " at composables/db/sqlite.uts:384")
return this.executeSql(sql) return this.executeSql(sql)
} }
open fun formatValue(value: Any?): String { open fun formatValue(value: Any?): String {
...@@ -2386,7 +2421,7 @@ open class SQLite { ...@@ -2386,7 +2421,7 @@ open class SQLite {
await(this.executeSql("ALTER TABLE " + tableName + " ADD COLUMN " + name + " " + defStr)) await(this.executeSql("ALTER TABLE " + tableName + " ADD COLUMN " + name + " " + defStr))
} }
catch (e: Throwable) { catch (e: Throwable) {
console.log("Add column " + name + " failed (maybe exists): " + e, " at composables/db/sqlite.uts:436") console.log("Add column " + name + " failed (maybe exists): " + e, " at composables/db/sqlite.uts:433")
} }
} }
i++ i++
...@@ -2720,7 +2755,7 @@ fun deepClone(obj: Any?): Any? { ...@@ -2720,7 +2755,7 @@ fun deepClone(obj: Any?): Any? {
if (obj == null) { if (obj == null) {
return null return null
} }
return UTSAndroid.consoleDebugError(JSON.parse(JSON.stringify(obj)), " at composables/recorder/RecordSave.uts:23") return UTSAndroid.consoleDebugError(JSON.parse(JSON.stringify(obj)), " at composables/recorder/RecordSave.uts:24")
} }
fun serializeIfObject(obj: Any): String { fun serializeIfObject(obj: Any): String {
if (UTSAndroid.`typeof`(obj) === "object" && obj != null) { if (UTSAndroid.`typeof`(obj) === "object" && obj != null) {
...@@ -2731,7 +2766,7 @@ fun serializeIfObject(obj: Any): String { ...@@ -2731,7 +2766,7 @@ fun serializeIfObject(obj: Any): String {
val UPLOAD_INTERVAL: Number = 30000 val UPLOAD_INTERVAL: Number = 30000
open class RecordSave : IUTSSourceMap { open class RecordSave : IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? { override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("RecordSave", "composables/recorder/RecordSave.uts", 47, 7) return UTSSourceMapPosition("RecordSave", "composables/recorder/RecordSave.uts", 48, 7)
} }
open lateinit var interval: Number open lateinit var interval: Number
open var _pumpTimer: Number? = null open var _pumpTimer: Number? = null
...@@ -2886,6 +2921,7 @@ open class RecordSave : IUTSSourceMap { ...@@ -2886,6 +2921,7 @@ open class RecordSave : IUTSSourceMap {
} }
open fun _changeFilePathToServer(record: UTSJSONObject, fileInfo: UTSJSONObject): UTSJSONObject { open fun _changeFilePathToServer(record: UTSJSONObject, fileInfo: UTSJSONObject): UTSJSONObject {
val _record = deepClone(record) as UTSJSONObject val _record = deepClone(record) as UTSJSONObject
console.log("🚀 ~ RecordSave ~ _changeFilePathToServer ~ _record:", _record, " at composables/recorder/RecordSave.uts:262")
logger__1.info("【接待记录保存服务】 == 开始更新文件路径, recordId: " + _record["id"], "RecordSave") logger__1.info("【接待记录保存服务】 == 开始更新文件路径, recordId: " + _record["id"], "RecordSave")
val status = fileInfo["status"] as Number val status = fileInfo["status"] as Number
if (status == FileStatus["NoFile"]) { if (status == FileStatus["NoFile"]) {
...@@ -2895,6 +2931,7 @@ open class RecordSave : IUTSSourceMap { ...@@ -2895,6 +2931,7 @@ open class RecordSave : IUTSSourceMap {
logger__1.info("【接待记录保存服务】 == 记录被标记为无文件状态", "RecordSave") logger__1.info("【接待记录保存服务】 == 记录被标记为无文件状态", "RecordSave")
return _record return _record
} }
_record["status"] = FileStatus["HasFile"]
val recordUrlList = this.urlListFilter(_record["recordUrlList"] as UTSArray<UTSJSONObject>) val recordUrlList = this.urlListFilter(_record["recordUrlList"] as UTSArray<UTSJSONObject>)
_record["recordUrlList"] = recordUrlList _record["recordUrlList"] = recordUrlList
var targetFile: UTSJSONObject? = null var targetFile: UTSJSONObject? = null
...@@ -2921,6 +2958,8 @@ open class RecordSave : IUTSSourceMap { ...@@ -2921,6 +2958,8 @@ open class RecordSave : IUTSSourceMap {
return itemFile == clientPath || itemFile.endsWith(fileName) return itemFile == clientPath || itemFile.endsWith(fileName)
} }
open fun _updateFileStatus(targetFile: UTSJSONObject, fileInfo: UTSJSONObject) { open fun _updateFileStatus(targetFile: UTSJSONObject, fileInfo: UTSJSONObject) {
console.log("🚀 ~ RecordSave ~ _updateFileStatus ~ targetFile:", targetFile, " at composables/recorder/RecordSave.uts:305")
console.log("🚀 ~ RecordSave ~ _updateFileStatus ~ fileInfo:", fileInfo, " at composables/recorder/RecordSave.uts:306")
val status = fileInfo["status"] as Number val status = fileInfo["status"] as Number
targetFile["status"] = status targetFile["status"] = status
if (status == FileStatus["Uploaded"]) { if (status == FileStatus["Uploaded"]) {
...@@ -2975,7 +3014,7 @@ open class RecordSave : IUTSSourceMap { ...@@ -2975,7 +3014,7 @@ open class RecordSave : IUTSSourceMap {
try { try {
val status = record.getNumber("status") val status = record.getNumber("status")
if (status == FileStatus["NoFile"] || status == FileStatus["NotExist"]) { if (status == FileStatus["NoFile"] || status == FileStatus["NotExist"]) {
val result: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("result", "composables/recorder/RecordSave.uts", 323, 23), "status" to status, "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "detail" to object : UTSJSONObject() { val result: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("result", "composables/recorder/RecordSave.uts", 328, 23), "status" to status, "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "detail" to object : UTSJSONObject() {
var data = _uA( var data = _uA(
_uO("code" to 0, "message" to "no file", "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "status" to status) _uO("code" to 0, "message" to "no file", "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "status" to status)
) )
...@@ -2984,9 +3023,9 @@ open class RecordSave : IUTSSourceMap { ...@@ -2984,9 +3023,9 @@ open class RecordSave : IUTSSourceMap {
return@w return@w
} }
val objectKey = "records/" + recordId + "/" + fileName val objectKey = "records/" + recordId + "/" + fileName
val options: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("options", "composables/recorder/RecordSave.uts", 344, 19), "filePath" to ((filePath ?: "") + (fileName ?: "")), "objectKey" to objectKey, "bucketName" to null, "region" to null) val options: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("options", "composables/recorder/RecordSave.uts", 349, 19), "filePath" to ((filePath ?: "") + (fileName ?: "")), "objectKey" to objectKey, "bucketName" to null, "region" to null)
val res = await(`default`.upload(options)) val res = await(`default`.upload(options))
val result: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("result", "composables/recorder/RecordSave.uts", 353, 19), "status" to FileStatus["Uploaded"], "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "detail" to object : UTSJSONObject() { val result: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("result", "composables/recorder/RecordSave.uts", 358, 19), "status" to FileStatus["Uploaded"], "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "detail" to object : UTSJSONObject() {
var data = _uA( var data = _uA(
_uO("code" to 0, "message" to "success", "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "data" to object : UTSJSONObject() { _uO("code" to 0, "message" to "success", "recordId" to recordId, "fileName" to fileName, "filePath" to filePath, "data" to object : UTSJSONObject() {
var oss = object : UTSJSONObject() { var oss = object : UTSJSONObject() {
...@@ -3008,7 +3047,7 @@ open class RecordSave : IUTSSourceMap { ...@@ -3008,7 +3047,7 @@ open class RecordSave : IUTSSourceMap {
} else { } else {
"" + error "" + error
} }
val errorResult: UTSJSONObject = object : UTSJSONObject(UTSSourceMapPosition("errorResult", "composables/recorder/RecordSave.uts", 380, 19)) { val errorResult: UTSJSONObject = object : UTSJSONObject(UTSSourceMapPosition("errorResult", "composables/recorder/RecordSave.uts", 385, 19)) {
var detail = object : UTSJSONObject() { var detail = object : UTSJSONObject() {
var data = _uA( var data = _uA(
_uO("code" to -1, "message" to errorMsg, "recordId" to recordId, "fileName" to fileName, "filePath" to filePath) _uO("code" to -1, "message" to errorMsg, "recordId" to recordId, "fileName" to fileName, "filePath" to filePath)
...@@ -3038,6 +3077,7 @@ open class RecordSave : IUTSSourceMap { ...@@ -3038,6 +3077,7 @@ open class RecordSave : IUTSSourceMap {
} }
open fun _saveOrUpdate(data: UTSJSONObject): UTSPromise<Unit> { open fun _saveOrUpdate(data: UTSJSONObject): UTSPromise<Unit> {
return wrapUTSPromise(suspend { return wrapUTSPromise(suspend {
console.log("🚀 ~ RecordSave ~ _saveOrUpdate ~ data:", data, " at composables/recorder/RecordSave.uts:470")
logger__1.info("【接待记录保存服务】 == 开始保存或更新接待记录!!", "RecordSave") logger__1.info("【接待记录保存服务】 == 开始保存或更新接待记录!!", "RecordSave")
val status = data["status"] as Number val status = data["status"] as Number
val record = deepClone(data) as UTSJSONObject val record = deepClone(data) as UTSJSONObject
...@@ -3082,9 +3122,9 @@ open class RecordSave : IUTSSourceMap { ...@@ -3082,9 +3122,9 @@ open class RecordSave : IUTSSourceMap {
params["receptionEndTime"] = await(this._requestReceptionEndTime(serverPaths, params["receptionStartTime"] as String)) params["receptionEndTime"] = await(this._requestReceptionEndTime(serverPaths, params["receptionStartTime"] as String))
} }
logger__1.info("【接待记录保存服务】 == 开始向服务器保存接待记录!!参数: " + JSON.stringify(params), "RecordSave") logger__1.info("【接待记录保存服务】 == 开始向服务器保存接待记录!!参数: " + JSON.stringify(params), "RecordSave")
val res = true val res = await(saveRecCustomer(params))
logger__1.warn("【接待记录保存服务】 == 服务器返回结果: " + JSON.stringify(res), "RecordSave") logger__1.warn("【接待记录保存服务】 == 服务器返回结果: " + JSON.stringify(res), "RecordSave")
if (res) { if (res != null) {
logger__1.info("【上传服务】 == 开始删除客户端的文件!!", "RecordSave") logger__1.info("【上传服务】 == 开始删除客户端的文件!!", "RecordSave")
await(this._removeRecordFiles(localPaths)) await(this._removeRecordFiles(localPaths))
await(this._removeRecordById(record["id"] as String)) await(this._removeRecordById(record["id"] as String))
...@@ -3097,9 +3137,13 @@ open class RecordSave : IUTSSourceMap { ...@@ -3097,9 +3137,13 @@ open class RecordSave : IUTSSourceMap {
return@w receptionStartTime return@w receptionStartTime
} }
logger__1.info("【上传服务】 == 向服务器获取结束接待时间: recordUrlList ->" + serializeIfObject(recordUrlList) + " receptionStartTime: -> " + receptionStartTime, "RecordSave") logger__1.info("【上传服务】 == 向服务器获取结束接待时间: recordUrlList ->" + serializeIfObject(recordUrlList) + " receptionStartTime: -> " + receptionStartTime, "RecordSave")
val endTime = receptionStartTime val receptionStartTimeStr = replaceAll(receptionStartTime, "/", "-")
val endTime = await(searchRecordingEndTime(_uO("recordUrlList" to recordUrlList, "receptionStartTime" to receptionStartTimeStr)))
logger__1.info("【上传服务】 == 服务器返回结束接待时间: endTime ->" + endTime, "RecordSave") logger__1.info("【上传服务】 == 服务器返回结束接待时间: endTime ->" + endTime, "RecordSave")
return@w endTime.replace(UTSRegExp("-", "g"), "/") if (endTime.includes("-")) {
return@w replaceAll(endTime, "-", "/")
}
return@w endTime
}) })
} }
open fun _handleIncompleteRecord(record: UTSJSONObject): UTSPromise<Unit> { open fun _handleIncompleteRecord(record: UTSJSONObject): UTSPromise<Unit> {
...@@ -3222,7 +3266,7 @@ open class RecordSave : IUTSSourceMap { ...@@ -3222,7 +3266,7 @@ open class RecordSave : IUTSSourceMap {
}) })
} }
open fun urlListFilter(urlList: UTSArray<UTSJSONObject>): UTSArray<UTSJSONObject> { open fun urlListFilter(urlList: UTSArray<UTSJSONObject>): UTSArray<UTSJSONObject> {
console.log("🚀 ~ RecordSave ~ urlListFilter ~ urlList:", urlList, " at composables/recorder/RecordSave.uts:635") console.log("🚀 ~ RecordSave ~ urlListFilter ~ urlList:", urlList, " at composables/recorder/RecordSave.uts:641")
if (!UTSArray.isArray(urlList)) { if (!UTSArray.isArray(urlList)) {
return _uA() return _uA()
} }
...@@ -3707,8 +3751,8 @@ open class TempRecord : IUTSSourceMap { ...@@ -3707,8 +3751,8 @@ open class TempRecord : IUTSSourceMap {
} }
}) })
} }
open fun cacheMaterialPoints(list: UTSArray<Any>) { open fun cacheMaterialPoints(list: UTSArray<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)
} }
} }
...@@ -3844,6 +3888,184 @@ open class TempRecord : IUTSSourceMap { ...@@ -3844,6 +3888,184 @@ open class TempRecord : IUTSSourceMap {
}) })
} }
} }
open class ReceptionState (
@JsonNotNull
open var customerKey: String,
open var customerInfo: UTSJSONObject? = null,
@JsonNotNull
open var receptionStatus: String,
@JsonNotNull
open var booksList: UTSArray<UTSJSONObject>,
@JsonNotNull
open var receptionKey: String,
@JsonNotNull
open var receptionTrack: UTSArray<UTSJSONObject>,
) : UTSReactiveObject(), IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("ReceptionState", "store/modules/reception.uts", 2, 13)
}
override fun __v_create(__v_isReadonly: Boolean, __v_isShallow: Boolean, __v_skip: Boolean): UTSReactiveObject {
return ReceptionStateReactiveObject(this, __v_isReadonly, __v_isShallow, __v_skip)
}
}
class ReceptionStateReactiveObject : ReceptionState, IUTSReactive<ReceptionState> {
override var __v_raw: ReceptionState
override var __v_isReadonly: Boolean
override var __v_isShallow: Boolean
override var __v_skip: Boolean
constructor(__v_raw: ReceptionState, __v_isReadonly: Boolean, __v_isShallow: Boolean, __v_skip: Boolean) : super(customerKey = __v_raw.customerKey, customerInfo = __v_raw.customerInfo, receptionStatus = __v_raw.receptionStatus, booksList = __v_raw.booksList, receptionKey = __v_raw.receptionKey, receptionTrack = __v_raw.receptionTrack) {
this.__v_raw = __v_raw
this.__v_isReadonly = __v_isReadonly
this.__v_isShallow = __v_isShallow
this.__v_skip = __v_skip
}
override fun __v_clone(__v_isReadonly: Boolean, __v_isShallow: Boolean, __v_skip: Boolean): ReceptionStateReactiveObject {
return ReceptionStateReactiveObject(this.__v_raw, __v_isReadonly, __v_isShallow, __v_skip)
}
override var customerKey: String
get() {
return _tRG(__v_raw, "customerKey", __v_raw.customerKey, __v_isReadonly, __v_isShallow)
}
set(value) {
if (!__v_canSet("customerKey")) {
return
}
val oldValue = __v_raw.customerKey
__v_raw.customerKey = value
_tRS(__v_raw, "customerKey", oldValue, value)
}
override var customerInfo: UTSJSONObject?
get() {
return _tRG(__v_raw, "customerInfo", __v_raw.customerInfo, __v_isReadonly, __v_isShallow)
}
set(value) {
if (!__v_canSet("customerInfo")) {
return
}
val oldValue = __v_raw.customerInfo
__v_raw.customerInfo = value
_tRS(__v_raw, "customerInfo", oldValue, value)
}
override var receptionStatus: String
get() {
return _tRG(__v_raw, "receptionStatus", __v_raw.receptionStatus, __v_isReadonly, __v_isShallow)
}
set(value) {
if (!__v_canSet("receptionStatus")) {
return
}
val oldValue = __v_raw.receptionStatus
__v_raw.receptionStatus = value
_tRS(__v_raw, "receptionStatus", oldValue, value)
}
override var booksList: UTSArray<UTSJSONObject>
get() {
return _tRG(__v_raw, "booksList", __v_raw.booksList, __v_isReadonly, __v_isShallow)
}
set(value) {
if (!__v_canSet("booksList")) {
return
}
val oldValue = __v_raw.booksList
__v_raw.booksList = value
_tRS(__v_raw, "booksList", oldValue, value)
}
override var receptionKey: String
get() {
return _tRG(__v_raw, "receptionKey", __v_raw.receptionKey, __v_isReadonly, __v_isShallow)
}
set(value) {
if (!__v_canSet("receptionKey")) {
return
}
val oldValue = __v_raw.receptionKey
__v_raw.receptionKey = value
_tRS(__v_raw, "receptionKey", oldValue, value)
}
override var receptionTrack: UTSArray<UTSJSONObject>
get() {
return _tRG(__v_raw, "receptionTrack", __v_raw.receptionTrack, __v_isReadonly, __v_isShallow)
}
set(value) {
if (!__v_canSet("receptionTrack")) {
return
}
val oldValue = __v_raw.receptionTrack
__v_raw.receptionTrack = value
_tRS(__v_raw, "receptionTrack", oldValue, value)
}
}
val receptionState = reactive(ReceptionState(customerKey = "", customerInfo = null, receptionStatus = "", booksList = _uA(), receptionKey = "", receptionTrack = _uA()))
val setCustomerKey = fun(payload: String){
receptionState.customerKey = payload
}
val setCustomerInfo = fun(payload: UTSJSONObject?){
receptionState.customerInfo = payload
}
val setReceptionStatus = fun(payload: String){
receptionState.receptionStatus = payload
}
val setBookList = fun(payload: UTSArray<UTSJSONObject>){
receptionState.booksList = payload
}
val setReceptionKey = fun(payload: String){
receptionState.receptionKey = payload
}
val setReceptionTrack = fun(payload: UTSArray<UTSJSONObject>){
receptionState.receptionTrack = payload
}
open class GlobalState : IUTSSourceMap {
override fun `__$getOriginalPosition`(): UTSSourceMapPosition? {
return UTSSourceMapPosition("GlobalState", "store/index.uts", 19, 14)
}
open val customerKey: String
get(): String {
return receptionState.customerKey
}
open val customerInfo: UTSJSONObject?
get(): UTSJSONObject? {
return receptionState.customerInfo
}
open val receptionStatus: String
get(): String {
return receptionState.receptionStatus
}
open val booksList: UTSArray<UTSJSONObject>
get(): UTSArray<UTSJSONObject> {
return receptionState.booksList
}
open val receptionKey: String
get(): String {
return receptionState.receptionKey
}
open val receptionTrack: UTSArray<UTSJSONObject>
get(): UTSArray<UTSJSONObject> {
return receptionState.receptionTrack
}
open val reception: ReceptionState
get(): ReceptionState {
return receptionState
}
}
val state = GlobalState()
val commit = fun(type: String, payload: Any?){
when (type) {
"updateCustomerKey" ->
setCustomerKey(payload as String)
"updateCustomerInfo" ->
setCustomerInfo(payload as UTSJSONObject?)
"updateReceptionStatus" ->
setReceptionStatus(payload as String)
"updateBookList" ->
setBookList(payload as UTSArray<UTSJSONObject>)
"updateReceptionKey" ->
setReceptionKey(payload as String)
"updateReceptionTrack" ->
setReceptionTrack(payload as UTSArray<UTSJSONObject>)
else ->
console.warn("[Store] Unknown mutation type: " + type, " at store/index.uts:71")
}
}
open class DebounceTimer ( open class DebounceTimer (
open var fn: () -> Unit, open var fn: () -> Unit,
@JsonNotNull @JsonNotNull
...@@ -3908,7 +4130,50 @@ open class RecordService : IUTSSourceMap { ...@@ -3908,7 +4130,50 @@ open class RecordService : IUTSSourceMap {
}, "RecordService") }, "RecordService")
} }
} }
open fun initWatchers() {} open fun initWatchers() {
this.unwatchCustomer = watch(fun(): String {
return state.customerKey
}
, fun(kVal: String){
val customerInfo = state.customerInfo
this.handler("updateCustomerInfo", customerInfo, fun(kVal: UTSJSONObject?){
this.updateCustomerInfo(kVal)
}
, 1000)
}
, WatchOptions(immediate = true))
this.unwatchStatus = watch(fun(): String {
return state.receptionStatus
}
, fun(kVal: String){
this.handler("updateReceptionStatus", kVal, fun(v: Any){
this.updateReceptionStatus(v as String)
}
, 200)
}
, WatchOptions(immediate = true))
this.unwatchBookList = watch(fun(): UTSArray<UTSJSONObject> {
return state.booksList
}
, fun(kVal: UTSArray<UTSJSONObject>){
this.handler("updateBookList", kVal, fun(v: UTSArray<UTSJSONObject>){
this.updateBookList(v)
}
, 1500)
}
, WatchOptions(immediate = true))
this.unwatchReceptionKey = watch(fun(): String {
return state.receptionKey
}
, fun(kVal: String){
val receptionTrack = state.receptionTrack
this.handler("updateMaterialPointList", receptionTrack, fun(v: UTSArray<UTSJSONObject>){
this.updateMaterialPointList(v)
}
, 1000)
}
, WatchOptions(immediate = true))
}
open fun startAudio(isInitData: Boolean = true): UTSPromise<Boolean> { open fun startAudio(isInitData: Boolean = true): UTSPromise<Boolean> {
return wrapUTSPromise(suspend w@{ return wrapUTSPromise(suspend w@{
if (this._startAudioPromise != null) { if (this._startAudioPromise != null) {
...@@ -3954,12 +4219,12 @@ open class RecordService : IUTSSourceMap { ...@@ -3954,12 +4219,12 @@ open class RecordService : IUTSSourceMap {
try { try {
val userInfo = storage.get("userInfo") as String val userInfo = storage.get("userInfo") as String
val obj: UTSJSONObject = if (userInfo != "") { val obj: UTSJSONObject = if (userInfo != "") {
UTSAndroid.consoleDebugError(JSON.parse(userInfo), " at composables/recorder/RecordService.uts:144") as UTSJSONObject UTSAndroid.consoleDebugError(JSON.parse(userInfo), " at composables/recorder/RecordService.uts:123") as UTSJSONObject
} else { } else {
UTSJSONObject() UTSJSONObject()
} }
val sceneType = obj.get("sceneType") val sceneType = obj.get("sceneType")
val dynamicAttrs: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("dynamicAttrs", "composables/recorder/RecordService.uts", 146, 19), "bussinessType" to this.getBussinessType(sceneType)) val dynamicAttrs: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("dynamicAttrs", "composables/recorder/RecordService.uts", 125, 19), "bussinessType" to this.getBussinessType(sceneType))
return dynamicAttrs return dynamicAttrs
} }
catch (e: Throwable) { catch (e: Throwable) {
...@@ -3969,7 +4234,11 @@ open class RecordService : IUTSSourceMap { ...@@ -3969,7 +4234,11 @@ open class RecordService : IUTSSourceMap {
return UTSJSONObject() return UTSJSONObject()
} }
} }
open fun initReception() {} open fun initReception() {
commit("updateBookList", _uA<UTSJSONObject>())
commit("updateCustomerInfo", null as UTSJSONObject?)
commit("updateReceptionStatus", "")
}
open fun onAudioStart(res: StartRecordSuccess): UTSPromise<Unit> { open fun onAudioStart(res: StartRecordSuccess): UTSPromise<Unit> {
return wrapUTSPromise(suspend w@{ return wrapUTSPromise(suspend w@{
try { try {
...@@ -4081,6 +4350,7 @@ open class RecordService : IUTSSourceMap { ...@@ -4081,6 +4350,7 @@ open class RecordService : IUTSSourceMap {
} }
open fun onTimeOut(): UTSPromise<Unit> { open fun onTimeOut(): UTSPromise<Unit> {
return wrapUTSPromise(suspend { return wrapUTSPromise(suspend {
commit("updateReceptionStatus", "0")
await(this.record!!.withError()) await(this.record!!.withError())
this.stopAudioRecord() this.stopAudioRecord()
}) })
...@@ -4088,7 +4358,7 @@ open class RecordService : IUTSSourceMap { ...@@ -4088,7 +4358,7 @@ open class RecordService : IUTSSourceMap {
open fun stopAudioRecord() { open fun stopAudioRecord() {
this.audioManager?.stop() this.audioManager?.stop()
} }
open fun handler(key: String, params: Any, fn: (arg: Any) -> Unit, delay: Number = 0) { open fun <T> handler(key: String, params: T, fn: (arg: T) -> Unit, delay: Number = 0) {
if (this.isReceptioning()) { if (this.isReceptioning()) {
if (delay > 0) { if (delay > 0) {
this.debounce(key, fun(){ this.debounce(key, fun(){
...@@ -4137,8 +4407,8 @@ open class RecordService : IUTSSourceMap { ...@@ -4137,8 +4407,8 @@ open class RecordService : IUTSSourceMap {
) )
this.debounceTimers.clear() this.debounceTimers.clear()
} }
open fun updateCustomerInfo(customerInfo: Any) { open fun updateCustomerInfo(customerInfo: UTSJSONObject?) {
val info = customerInfo as UTSJSONObject val info = customerInfo
if (info == null) { if (info == null) {
return return
} }
...@@ -4153,7 +4423,7 @@ open class RecordService : IUTSSourceMap { ...@@ -4153,7 +4423,7 @@ open class RecordService : IUTSSourceMap {
val oneCarBrandId = info["oneCarBrandId"] val oneCarBrandId = info["oneCarBrandId"]
this.record!!.updatePreRecords(_uO("customerName" to customerName, "phoneNumber" to phoneNumber, "carModel" to carModel, "salesUuid" to salesUuid, "salesName" to salesName, "carBrand" to carBrand, "carBrandId" to carBrandId, "oneCarBrand" to oneCarBrand, "oneCarBrandId" to oneCarBrandId)) this.record!!.updatePreRecords(_uO("customerName" to customerName, "phoneNumber" to phoneNumber, "carModel" to carModel, "salesUuid" to salesUuid, "salesName" to salesName, "carBrand" to carBrand, "carBrandId" to carBrandId, "oneCarBrand" to oneCarBrand, "oneCarBrandId" to oneCarBrandId))
} }
open fun updateBookList(booksList: UTSArray<Any>) { open fun updateBookList(booksList: UTSArray<UTSJSONObject>) {
val receptionCustomerPaySourceList: UTSArray<UTSJSONObject> = _uA() val receptionCustomerPaySourceList: UTSArray<UTSJSONObject> = _uA()
booksList.forEach(fun(item: Any){ booksList.forEach(fun(item: Any){
val book = item as UTSJSONObject val book = item as UTSJSONObject
...@@ -4166,22 +4436,26 @@ open class RecordService : IUTSSourceMap { ...@@ -4166,22 +4436,26 @@ open class RecordService : IUTSSourceMap {
) )
this.record!!.updatePreRecords(_uO("receptionCustomerPaySourceList" to receptionCustomerPaySourceList)) this.record!!.updatePreRecords(_uO("receptionCustomerPaySourceList" to receptionCustomerPaySourceList))
} }
open fun updateMaterialPointList(receptionTrack: Any) { open fun updateMaterialPointList(receptionTrack: UTSArray<UTSJSONObject>) {
val track = receptionTrack as UTSJSONObject val track = receptionTrack
if (track == null) { if (track == null) {
return return
} }
val merchantId = this.tempRecordDto?.merchantId val merchantId = this.tempRecordDto?.merchantId
val staffUuid = this.tempRecordDto?.staffUuid val staffUuid = this.tempRecordDto?.staffUuid
val staffName = this.tempRecordDto?.staffName val staffName = this.tempRecordDto?.staffName
val userInfo = storage.get("userInfo") as UTSJSONObject? val userInfo = storage.get("userInfo") as String
val sceneType = userInfo?.getNumber("sceneType") val userInfoObj: UTSJSONObject = if (userInfo != "") {
val receptionCustomerMaterialPointList: UTSArray<Any> = _uA() UTSAndroid.consoleDebugError(JSON.parse(userInfo), " at composables/recorder/RecordService.uts:348") as UTSJSONObject
val map = track.toMap() } else {
map.forEach(fun(v, k){ UTSJSONObject()
}
val sceneType = userInfoObj.getNumber("sceneType")
val receptionCustomerMaterialPointList: UTSArray<UTSJSONObject> = _uA()
track.forEach(fun(v: Any){
val point = v as UTSJSONObject val point = v as UTSJSONObject
val newPoint: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("newPoint", "composables/recorder/RecordService.uts", 375, 19), "merchantId" to merchantId, "staffUuid" to staffUuid, "staffName" to staffName, "businessScene" to sceneType) val newPoint: UTSJSONObject = _uO("__\$originalPosition" to UTSSourceMapPosition("newPoint", "composables/recorder/RecordService.uts", 354, 19), "merchantId" to merchantId, "staffUuid" to staffUuid, "staffName" to staffName, "businessScene" to sceneType)
val newPointJson = UTSAndroid.consoleDebugError(JSON.parse(JSON.stringify(newPoint)), " at composables/recorder/RecordService.uts:381") as UTSJSONObject val newPointJson = UTSAndroid.consoleDebugError(JSON.parse(JSON.stringify(newPoint)), " at composables/recorder/RecordService.uts:360") as UTSJSONObject
val pMap = point.toMap() val pMap = point.toMap()
pMap.forEach(fun(pv, pk){ pMap.forEach(fun(pv, pk){
newPointJson[pk] = pv newPointJson[pk] = pv
...@@ -4288,12 +4562,8 @@ open class GenApp : BaseApp { ...@@ -4288,12 +4562,8 @@ open class GenApp : BaseApp {
console.log("App Launch", " at App.uvue:7") console.log("App Launch", " at App.uvue:7")
setTimeout(fun(){ setTimeout(fun(){
console.log("Simulating reception start...", " at App.uvue:11") console.log("Simulating reception start...", " at App.uvue:11")
RecordService.getInstance().startAudio()
console.log("Simulating reception end...", " at App.uvue:14") console.log("Simulating reception end...", " at App.uvue:14")
setTimeout(fun(){ setTimeout(fun(){}, 10000)
RecordService.getInstance().stopAudio()
}
, 10000)
} }
, 1000) , 1000)
} }
......
...@@ -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!