Commit 3db5cb82 by liimin

feat(recorder): 添加业务数据获取功能并重构策略设计

- 新增 getAllBusinessData、getBusinessData、getBusinessDataFromRecord 和 getMaterialPoints 方法
- 实现配置驱动的策略模式,支持 book、customer、material、status 四种业务类型
- 移除旧的 RecordCache 管理器,优化缓存和数据合并逻辑
- 更新 README 文档,添加业务数据获取的使用示例和说明
- 统一权限处理逻辑,简化异步操作流程
- 重构 TempRecord 数据更新逻辑,提高代码可维护性
1 parent d47d9aa2
...@@ -172,9 +172,9 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -172,9 +172,9 @@ class DBRecord extends DBBase implements IDBRecord {
*/ */
private parseRecords(records: any[]): RecordData[] { private parseRecords(records: any[]): RecordData[] {
const res: RecordData[] = []; const res: RecordData[] = [];
// 基础 JSON 字段 // 基础 JSON 字段(所有策略共有)
const baseJsonFields = ["recordUrlList"]; const baseJsonFields = ["recordUrlList"];
// 业务策略定义的 JSON 字段 // 业务策略特有的 JSON 字段
const strategyJsonFields = this.strategy.getJsonFields(); const strategyJsonFields = this.strategy.getJsonFields();
// 合并字段列表 // 合并字段列表
const listFields = [...baseJsonFields, ...strategyJsonFields]; const listFields = [...baseJsonFields, ...strategyJsonFields];
......
...@@ -44,7 +44,7 @@ const customerInfo = { ...@@ -44,7 +44,7 @@ const customerInfo = {
carModel: 'Model Y' carModel: 'Model Y'
} }
// updateBusinessData(类型, 数据, 防抖时间ms) // updateBusinessData(类型,数据,防抖时间 ms)
recordService.updateBusinessData( recordService.updateBusinessData(
BusinessDataType.CUSTOMER, BusinessDataType.CUSTOMER,
customerInfo, customerInfo,
...@@ -74,7 +74,43 @@ recordService.updateBusinessData( ...@@ -74,7 +74,43 @@ recordService.updateBusinessData(
) )
``` ```
## 3. 自定义业务策略 ## 3. 获取业务数据
### 获取本地缓存的物料轨迹点
```typescript
// 异步获取存储在本地缓存中的物料轨迹点数据
const materialPoints = await recordService.getMaterialPoints()
console.log('物料轨迹点:', materialPoints)
// 或者使用通用方法
const materialData = await recordService.getBusinessData('MATERIAL_POINTS')
console.log('物料数据:', materialData?.receptionCustomerMaterialPointList)
```
### 获取数据库中存储的业务数据
```typescript
// 从当前临时记录中获取客户信息(存储在数据库中)
const customerInfo = recordService.getBusinessDataFromRecord('CUSTOMER')
console.log('客户姓名:', customerInfo.customerName)
console.log('电话号码:', customerInfo.phoneNumber)
// 获取书籍/资源列表
const bookList = recordService.getBusinessDataFromRecord('BOOK')
console.log('资源列表:', bookList)
// 获取接待状态
const status = recordService.getBusinessDataFromRecord('STATUS')
console.log('接待状态:', status)
```
### 注意事项
- **MATERIAL_POINTS** (物料轨迹点) 存储在本地缓存,需要使用 `await` 异步获取
- **BOOK、CUSTOMER、STATUS** 等其他类型存储在临时记录数据库中,可以直接同步获取
## 4. 自定义业务策略
如果您需要切换业务场景(例如从“汽车销售”切换到“房产销售”),可以通过实现 `IRecorderStrategy` 接口来定义新的策略。 如果您需要切换业务场景(例如从“汽车销售”切换到“房产销售”),可以通过实现 `IRecorderStrategy` 接口来定义新的策略。
......
import { commit } from "@/store/index.uts"; import { commit } from "@/store/index.uts";
import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus"; // import { checkPermission, requestPermissions } from "@/uni_modules/permission-handler-plus";
import { handleError } from "../../utils/error.uts"; import { handleError } from "../../utils/error.uts";
// import TimeoutService from './TimeoutService.uts' // import TimeoutService from './TimeoutService.uts'
import { ensurePermission } from "../../utils/permission.uts"; // 不再使用,已改为 uni-app 原生 API
import { logger } from "../logger/index.uts"; import { logger } from "../logger/index.uts";
// import { sleep } from './helper.uts' // 文件不存在,先注释掉 // import { sleep } from './helper.uts' // 文件不存在,先注释掉
import AudioManager from "./AudioManager.uts"; import AudioManager from "./AudioManager.uts";
...@@ -40,6 +41,53 @@ export class RecordService { ...@@ -40,6 +41,53 @@ export class RecordService {
this.stop(); this.stop();
this.reset(); this.reset();
} }
/**
* 获取所有业务数据
* @returns 包含所有业务数据的对象
*/
async getAllBusinessData(): Promise<UTSJSONObject> {
const recordId = this.record?.currentRecord?.id ?? "";
const currentRecord = this.record?.currentRecord as any | null;
return await this.businessHandler.getBusinessData(recordId, currentRecord);
}
/**
* 获取指定类型的业务数据
* @param type 业务数据类型标识 (如 'customer', 'book', 'status', 'material')
* @returns 业务数据,如果不存在则返回 null
*/
async getBusinessData(type: string): Promise<any> {
const recordId = this.record?.currentRecord?.id ?? "";
const currentRecord = this.record?.currentRecord as any | null;
return await this.businessHandler.getBusinessDataByType(recordId, currentRecord, type);
}
/**
* 从当前记录中获取业务数据(存储在数据库中的字段)
* @param type 业务数据类型标识
* @returns 业务数据对象
*/
getBusinessDataFromRecord(type: string): any {
const currentRecord = this.record?.currentRecord;
if (currentRecord === null) return {} as UTSJSONObject;
// 将 RecordData 转换为 UTSJSONObject 以便动态访问属性
const recordObj = currentRecord as UTSJSONObject;
return this.businessHandler.getBusinessDataByType("", recordObj, type);
}
/**
* 便捷方法:获取物料轨迹点数据
* @returns 物料轨迹点列表
*/
async getMaterialPoints(): Promise<any | null> {
const recordId = this.record?.currentRecord?.id ?? "";
// 直接调用策略的 getBusinessDataByType 方法获取 material 类型数据
const result = await this.businessHandler.getBusinessDataByType(recordId, null, "material");
if (result === null) return null;
const obj = result as UTSJSONObject;
return obj.receptionCustomerMaterialPointList ?? null;
}
getRecorder(): null | TempRecord { getRecorder(): null | TempRecord {
return this.record; return this.record;
} }
...@@ -66,10 +114,6 @@ export class RecordService { ...@@ -66,10 +114,6 @@ export class RecordService {
handleError(error, "RecordService", "【录音服务RecordService】 == 初始化异常:"); handleError(error, "RecordService", "【录音服务RecordService】 == 初始化异常:");
} }
} }
initDto() {
// initialize as RecordData or null
this.tempRecordDto = null;
}
// initReception() { // initReception() {
// commit("updateBookList", [] as UTSJSONObject[]); // commit("updateBookList", [] as UTSJSONObject[]);
// commit("updateCustomerInfo", null as null | UTSJSONObject); // commit("updateCustomerInfo", null as null | UTSJSONObject);
...@@ -77,42 +121,13 @@ export class RecordService { ...@@ -77,42 +121,13 @@ export class RecordService {
// } // }
// initWatchers() {} // initWatchers() {}
async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> { initDto() {
return new Promise((resolve) => { // initialize as RecordData or null
checkPermission("Microphone", (result) => { this.tempRecordDto = null;
if (result === "granted") {
resolve(true);
} else {
requestPermissions({
names: ["Microphone"],
success: (res) => {
let granted = false;
// res is string[]
const resList = res as string[];
resList.forEach((v: string) => {
if (v == "granted") {
granted = true;
}
});
if (granted) {
resolve(true);
} else {
uni.showToast({
title: hintText,
icon: "none"
});
resolve(false);
}
},
fail: (err) => {
handleError(err, "RecordService", "【录音服务RecordService】 == 请求录音权限失败:");
resolve(false);
}
});
} }
});
}); async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> {
return await ensurePermission("Microphone", hintText);
} }
isReceptioning(): boolean { isReceptioning(): boolean {
...@@ -146,6 +161,7 @@ export class RecordService { ...@@ -146,6 +161,7 @@ export class RecordService {
await this.record.addAudio(recordFile); await this.record.addAudio(recordFile);
} }
} catch (error) { } catch (error) {
console.log("🚀 ~ RecordService ~ onAudioStart ~ error:", error);
handleError(error, "RecordService", "〖RecordService〗 == onAudioStart error:"); handleError(error, "RecordService", "〖RecordService〗 == onAudioStart error:");
} }
} }
...@@ -165,14 +181,14 @@ export class RecordService { ...@@ -165,14 +181,14 @@ export class RecordService {
this.stopAudioRecord(); this.stopAudioRecord();
} }
// --- 外部调用接口 ---
reset() { reset() {
// this.flushAllDebounceTimers(); // this.flushAllDebounceTimers();
this.audioManager = null; this.audioManager = null;
this.record = null; this.record = null;
} }
// --- 外部调用接口 ---
async saveAndClearRecord(isNotSave: boolean = false) { async saveAndClearRecord(isNotSave: boolean = false) {
if (this.record === null) return; if (this.record === null) return;
if (isNotSave) { if (isNotSave) {
...@@ -274,6 +290,7 @@ export class RecordService { ...@@ -274,6 +290,7 @@ export class RecordService {
// 如果策略返回了数据对象,则交由 Service 进行预记录持久化 (updatePreRecords) // 如果策略返回了数据对象,则交由 Service 进行预记录持久化 (updatePreRecords)
this.record?.updatePreRecords(result); this.record?.updatePreRecords(result);
} }
} }
export const recordService = RecordService.getInstance(); export const recordService = RecordService.getInstance();
export default recordService; export default recordService;
import { convertDateTimeFormat, deepClone, getUUID, isEqual, nullValues } from "../../utils/index.uts"; import { convertDateTimeFormat, deepClone, getUUID } from "../../utils/index.uts";
import { PathUtils } from "../../utils/path-utils.uts"; import { PathUtils } from "../../utils/path-utils.uts";
import { logger } from "../logger/index.uts"; import { logger } from "../logger/index.uts";
import { FileStatus } from "./common/constants.uts"; import { FileStatus } from "./common/constants.uts";
import DBRecord from "./DBRecord.uts"; import DBRecord from "./DBRecord.uts";
import RecordCache from "./RecordCache.uts";
import RecordSave from "./RecordSave.uts"; import RecordSave from "./RecordSave.uts";
import { RecordData, RecordFile } from "./types"; import { RecordData, RecordFile } from "./types";
...@@ -89,31 +88,18 @@ class TempRecord { ...@@ -89,31 +88,18 @@ class TempRecord {
// 这里我们通过 DBRecord 获取 (DBRecord 应该知道当前策略) // 这里我们通过 DBRecord 获取 (DBRecord 应该知道当前策略)
const strategy = this.db.getStrategy(); const strategy = this.db.getStrategy();
// 1. 恢复缓存并合并数据 // 1. 处理录音文件列表
const mergedRecord = await strategy.consumeBusinessCache(record.id, recObj);
// 2. 处理录音文件列表 (这是核心通用逻辑,保留在这里)
const recordLongList = await this.analysisUrlList(recordUrlList); const recordLongList = await this.analysisUrlList(recordUrlList);
// 3. 准备最终更新数据 // 2. 准备核心更新数据
const updateData = toUpdateData; const updateData = toUpdateData;
updateData.recordStatus = 1; updateData.recordStatus = 1;
updateData.recordUrlList = recordLongList; updateData.recordUrlList = recordLongList;
// 4. 将策略合并后的业务数据(除了核心字段外)同步到 updateData // 3. 委托给策略合并所有业务数据
// 排除 updateData 已有的核心字段,避免覆盖 const finalRecord = await strategy.mergeBeforeSave(record.id, recObj, updateData);
const mergedMap = mergedRecord.toMap();
mergedMap.forEach((value, key) => {
// 仅合并不存在的字段,或者策略明确要求覆盖的字段
// 简单起见,我们将策略返回的所有非核心字段都合并进去
// 修复 updateData.has 报错: updateData 是 UTSJSONObject,使用 has 方法可能存在兼容性问题
// 使用 get(key) !== null 来判断
if (updateData.get(key) === null && key !== "recordUrlList" && key !== "recordStatus") {
updateData.set(key, value);
}
});
await this.__saveData(updateData, record); await this.__saveData(finalRecord, record);
} catch (error) { } catch (error) {
logger.info(`〖接待记录Record〗 == 保存记录异常${ error}`, "TempRecord"); logger.info(`〖接待记录Record〗 == 保存记录异常${ error}`, "TempRecord");
} }
...@@ -145,57 +131,12 @@ class TempRecord { ...@@ -145,57 +131,12 @@ class TempRecord {
async __update(items: null | UTSJSONObject): Promise<void> { async __update(items: null | UTSJSONObject): Promise<void> {
const record = this.record; const record = this.record;
if (record === null || items === null) return; if (record === null || items === null) return;
// Convert to UTSJSONObject for dynamic property access // 直接应用所有更新
const currentRecordJson = deepClone<UTSJSONObject>(record); Object.assign(record, items);
if (currentRecordJson === null) return; this.record = record;
const updates = {} as UTSJSONObject; // 持久化到数据库
const itemMap = items.toMap();
// filter changed values
let hasUpdates = false;
itemMap.forEach((v, k) => {
const key = k as string;
const currentVal = currentRecordJson.get(key);
// Explicitly cast to Any to satisfy isEqual signature if inferred as Any?
const isNotEqual = !isEqual(currentVal as any, v as any);
// Handle nullValues check safely
// nullValues is string?[] or (string|null)[]
// v is Any?
let isNotNullValue = true;
if (v === null) {
isNotNullValue = false;
} else {
// nullValues check manually
for (const nv of nullValues) {
if (nv === v) {
isNotNullValue = false;
break;
}
}
}
if (isNotNullValue && isNotEqual) {
updates.set(key, v);
hasUpdates = true;
}
});
if (hasUpdates) {
// Apply updates to the JSON object
updates.toMap().forEach((v, k) => {
currentRecordJson.set(k, v);
});
// Update this.record by converting back
const updatedRecord = deepClone<RecordData>(currentRecordJson);
if (updatedRecord !== null) {
this.record = updatedRecord;
}
const id = record.id; const id = record.id;
await this.updateRecord(updates, { id }); await this.updateRecord(items, { id });
}
} }
/** /**
...@@ -292,24 +233,6 @@ class TempRecord { ...@@ -292,24 +233,6 @@ class TempRecord {
} }
} }
/**
* 保存前的钩子函数 (子类可覆盖)
* @param {object} record
* @returns {Promise<void>}
*/
// async beforeSave(record: RecordData) {
// // 默认不做任何事
// }
/**
* 缓存物料点数据
* @param {Array} list
*/
cacheMaterialPoints(list: UTSJSONObject[]) {
if (this.record !== null && this.record.id !== "") {
RecordCache.set(this.record.id, "MATERIAL_POINTS", list);
}
}
async clearLocalRecord(record: null | RecordData = null, removeDbRecord = true) { async clearLocalRecord(record: null | RecordData = null, removeDbRecord = true) {
const rec = record ?? this.record; const rec = record ?? this.record;
if (rec === null) return; if (rec === null) return;
......
/* import { logger } from "../../logger/index.uts";
* @Descripttion:
* @version: 1.0.0
* @Author: limin
* @Date: 2026-01-14 14:30:10
* @LastEditors: limin
* @LastEditTime: 2026-03-06 15:04:58
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordCache.uts
*/
import { logger } from "../logger/index.uts";
/** /**
* 记录缓存管理器
* 统一管理大字段的暂存、合并与清理
*/
export default class RecordCache {
/**
* 清理指定记录的所有缓存
* @param {string} recordId
* @param {string[]} keys - 需要清理的缓存 key 列表
*/
static clearAll(recordId: string, keys: string[]) {
if (recordId === "") return;
keys.forEach(keyPrefix => {
try {
uni.removeStorage({
key: keyPrefix + recordId,
fail: () => {}
});
} catch {}
});
}
/**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存 * 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
* @param {string} recordId - 记录 ID
* @param {Map<string, string>} cacheConfig - 缓存配置 Map<KeyPrefix, TargetField>
* @returns {object} 从缓存恢复的数据对象
*/ */
static async consumeAll(recordId: string, cacheConfig: Map<string, string>): Promise<UTSJSONObject> { export async function consumeAll(recordId: string, cacheConfig: Map<string, string>): Promise<UTSJSONObject> {
if (recordId === "") return {}; if (recordId === "") return {};
const restoredData: UTSJSONObject = {}; const restoredData: UTSJSONObject = {};
// 遍历配置 // 遍历配置
const keyList: string[] = []; const keyList: string[] = [];
// UTS Map iteration workaround: manually iterate using forEach on the map itself
cacheConfig.forEach((_, key) => { cacheConfig.forEach((_, key) => {
keyList.push(key); keyList.push(key);
}); });
...@@ -75,22 +39,53 @@ export default class RecordCache { ...@@ -75,22 +39,53 @@ export default class RecordCache {
fail: (res) => { fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${storageKey} failed: ${res.errMsg}`, "RecordCache"); logger.warn(`RecordCacheManager: Remove ${storageKey} failed: ${res.errMsg}`, "RecordCache");
} }
}); // 消费即焚 });
} }
} catch (error) { } catch (error) {
logger.warn(`RecordCacheManager: Consume ${keyPrefix} failed: ${error}`, "RecordCache"); logger.warn(`RecordCacheManager: Consume ${keyPrefix} failed: ${error}`, "RecordCache");
} }
} }
return restoredData; return restoredData;
}
/**
* 清理指定记录的所有缓存
*/
export function clearAll(recordId: string, keys: string[]) {
if (recordId === "") return;
keys.forEach(keyPrefix => {
try {
uni.removeStorage({
key: keyPrefix + recordId,
fail: () => {}
});
} catch {}
});
}
/**
* 从存储加载数据
*/
export async function load(key: string): Promise<any | null> {
try {
return await new Promise<any | null>((resolve) => {
uni.getStorage({
key,
success: (res) => resolve(res.data),
fail: () => resolve(null)
});
});
} catch (error) {
console.error(`[RecordCacheManager] Load from storage failed:`, error);
return null;
} }
}
/** /**
* 暂存数据 * 暂存数据
* @param {string} recordId - 记录ID
* @param {string} keyPrefix - 缓存 Key 前缀
* @param {any} data - 数据
*/ */
static set(recordId: string, keyPrefix: string, data: any) { export function set(recordId: string, keyPrefix: string, data: any) {
if (recordId === "" || keyPrefix === "") return; if (recordId === "" || keyPrefix === "") return;
try { try {
uni.setStorage({ uni.setStorage({
...@@ -103,5 +98,4 @@ export default class RecordCache { ...@@ -103,5 +98,4 @@ export default class RecordCache {
} catch (error) { } catch (error) {
logger.error(`RecordCacheManager: Set ${keyPrefix} failed: ${error}`, "RecordCache"); logger.error(`RecordCacheManager: Set ${keyPrefix} failed: ${error}`, "RecordCache");
} }
}
} }
import * as RecordCacheManager from "./RecordCacheManager.uts";
/**
* 策略工具函数集合
* 用于提取各策略中的通用逻辑
*/
/**
* 缓存业务数据
*/
export function cacheBusinessData(
cacheConfig: Map<string, string>,
recordId: string,
type: string,
data: any
): void {
const keyPrefix = cacheConfig.get(type);
if (keyPrefix !== null) {
RecordCacheManager.set(recordId, keyPrefix, data);
}
}
/**
* 消费业务缓存
*/
export async function consumeBusinessCache(
cacheConfig: Map<string, string>,
currentRecord: UTSJSONObject
): Promise<UTSJSONObject> {
const restored = await RecordCacheManager.consumeAll("", cacheConfig);
return Object.assign({}, currentRecord, restored);
}
/**
* 清理业务缓存
*/
export function clearBusinessCache(
cacheConfig: Map<string, string>,
recordId: string
): void {
const keyList: string[] = [];
cacheConfig.forEach((entry) => {
keyList.push(entry.value);
});
RecordCacheManager.clearAll(recordId, keyList);
}
/**
* 从存储加载数据(便捷函数)
*/
export async function loadFromStorage(key: string): Promise<any | null> {
return await RecordCacheManager.load(key);
}
...@@ -13,6 +13,8 @@ export enum BusinessDataType { ...@@ -13,6 +13,8 @@ export enum BusinessDataType {
STATUS = "status" STATUS = "status"
} }
export type BusiType = "book" | "customer" | "material" | "status";
/** /**
* 通用业务数据处理器接口 * 通用业务数据处理器接口
* 用于将业务层数据转换为数据库存储所需的格式 * 用于将业务层数据转换为数据库存储所需的格式
......
...@@ -50,7 +50,33 @@ export interface IRecorderStrategy extends IBusinessDataHandler { ...@@ -50,7 +50,33 @@ export interface IRecorderStrategy extends IBusinessDataHandler {
/** /**
* 清理该记录的所有业务缓存 * 清理该记录的所有业务缓存
* @param recordId 记录ID * @param recordId 记录 ID
*/ */
clearBusinessCache(recordId: string): void clearBusinessCache(recordId: string): void
/**
* 获取指定类型的业务数据
* @param recordId 记录 ID(用于从缓存获取)
* @param currentRecord 当前记录对象(用于从数据库字段获取)
* @param type 业务数据类型标识
* @returns 业务数据,如果不存在则返回 null
*/
getBusinessDataByType(recordId: string, currentRecord: any | null, type: string): Promise<any>
/**
* 获取所有业务数据
* @param recordId 记录 ID(用于从缓存获取)
* @param currentRecord 当前记录对象(用于从数据库字段获取)
* @returns 所有业务数据
*/
getBusinessData(recordId: string, currentRecord: any | null): Promise<UTSJSONObject>
/**
* 保存前数据处理:将业务数据与核心记录数据合并(可选实现)
* @param recordId 记录 ID
* @param baseRecord 基础记录数据
* @param updateData 待更新的数据
* @returns 合并后的完整记录对象
*/
mergeBeforeSave(recordId: string, baseRecord: UTSJSONObject, updateData: UTSJSONObject): Promise<UTSJSONObject>
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!