Commit 4aed59ed by 前端

Merge branch 'fix/record-upload-loop_from_v5.8.6' into 'master'

Fix/record upload loop from v5.8.6

See merge request !105
2 parents 9a187531 0e7aaa95
# 2026-10-12 工作日志
## 主题:录音上传死循环 + 路径归并兜底失效 修复
### 一、死循环根因与修复(utils/recordManager/RecordSaveService.js)
- **根因**:`_handleCompletedRecord` 里 `res=false` 不抛异常 → 黑名单写入点全在 catch/特定判定 → 不命中;`_scheduleNext(0)` 0ms 空转 + 快照重建 → 滚雪球爆日志。
- **最终落地改动(超人要求最小改动、不过度设计)**:
1. `_handleCompletedRecord`:`res` 失败 → `throw` → 复用 `save()` 的 catch 把该记录加入黑名单(断死循环主因)。
2. `save()` catch:错误日志第三参 `data?.recordId` → `failRecordId`(黑名单报错带正确客户名)。
3. `_handleCompletedRecord` 新增 `serverPaths.length === 0` guard:无语音文件直接本地黑名单跳过,省一次必返回 false 的网络往返(超人定:recordUrlList=[] 不请求后端)。
- **超人否决的过度设计(已删)**:`_isSaveSuccess` fail-safe 白名单、`this._minTaskGap=1000`、`this._reportedMissing` 去重机制——根因是死循环非重复上报,三者均非必需。
- **checkFileExists**:还原成原版 `uni.getFileInfo` 回调(`success`/`fail` 永远 resolve,try/catch+await 版等价且更绕,已回退)。
### 二、文件"丢失"根因
- 日志 6 条路径 100% 为 `/data/user/0/uni.gltap/apps/__UNI__D3BD3DF/doc/records/`(内部私有,录音)。
- DB 与录音同根(DB 可查证明当前根即此);targetSdk=30 下 `uni.getFileInfo` 读绝对路径必失败 → 误判"不存在"。文件大概率仍在磁盘。
- **兜底失效 4 断点**:A. init.js 合并调用被注释(最致命);B. 备用目录找 uniapp_save 而非 records(目录错配);C. 弱判定未接 Java File;D. markAlternateRootHandled 一次失败即永久标记。
- **结论**:① 升级(wgt)不删录音(只换 www,clearPrevFile 排除 apps/doc);② 合并对本批 6 条无效(同根 fileExists=true 跳过);③ 正常录音用裸 `/data/user/0` 路径 `uni.uploadFile` 能成功上传。
### 三、路径归并触发点迁移(超人定)
- `StoragePathMerge.js` 新增静态 `runDeferred()`(fire-and-forget + 内部 .catch 告警 + _completed 防重入)。
- 原在 init.js dbReady 段调用 → 超人担心阻塞 → 移到 `pages/common/loading.vue` 的 `mounted()` 首行(pages[0],全角色冷启动必经,物理隔离启动流程)。
- init.js 删除调用 + 删除随之失效的 `import StoragePathMerge`。
- FileUploadManager.js L230 的 `PathUtils.normalizeLocalFilePath` 补 file:// 改动已复原(删无用 import),因 6 条走 guard 不进上传。
### 四、git 翻车与恢复(重要教训)
- WorkBuddy 内置 shell 的 git 完全不可用:`tail`/`head`/`dirname`/`cd`/`cp`/`mkdir`/`ls` 全 `command not found`,git 多参数被篡改。
- 首次 `git switch -c fix/... && git add <7个文件> && commit` 被篡改成 **root-commit 进 1573 文件**(应为基于 SAAS+V5.8.6 的普通提交)。
- 超人确认远端**非**空仓库 → 此 root-commit 作废。超人在原生 Git Bash 从 master 拉新分支 fix/record-upload-loop_from_v5.8.6。
- **恢复**:用 node `fs.copyFileSync` 把 7 个文件从 `D:/tmp/fix_backup/` 精确复制回工作区(字节级一致已验证)。
- 备份/恢复均用 node(内置 shell 无 cp/mkdir)。
### 五、最终 7 个修复文件清单
init.js、pages/common/loading.vue、utils/recordManager/RecordSaveService.js、utils/storageMerge/StoragePathMerge.js、constants.js、docMediaMerge.js、recordMediaVerify.js
### 六、待办(未动,超人拍板)
- 提交时只 `git add` 这 7 个文件,绝不用 `git add -A`/`.`(否则带 2K)。
- `.workbuddy/` 加 `.gitignore`,不随业务提交。
- 提交后 GitLab 提 MR → origin/master(勿本地 master,落后 2619)。
# 2026-10-13 工作日志
## 诊断:checkFileExists 为何判定 /data/user/0/... 录音"不存在"
### 硬事实链(已读代码确认)
- `RecordSaveService.js:493` `file.file = PathUtils.normalizeLocalFilePath(file.file)` —— 把裸 `/data/user/0/.../x.mp3` 改成 `file:///data/user/0/.../x.mp3`(三斜杠:file:// + /data)。
- `PathUtils.js:110`:`startsWith('/') ? 'file://'+rawPath : rawPath`。
- `RecordSaveService.js:535-551` `checkFileExists` 用 `uni.getFileInfo({filePath})`,前置 `isLegalFile`(L554 仅查 endsWith('.mp3'),非元凶)。
- `uni.getFileInfo` 底层 `plus.io.getFileInfo`:targetSdk≥29 + scoped storage 下既不能按绝对路径访问内部私有目录,也不认 `file://` scheme → fail → resolve(false) → 误判"不存在"。
### 结论
- 判不存在根因:getFileInfo 读不了 `/data/user/0/...` 内部私有绝对路径(即超人第9-11轮确认的"文件丢失"根因本身)。
- L493 normalize 是**上次复原 FileUploadManager.js:230 时漏掉的同款有害改动**:给内部路径加 file:// 反而更读不到。
- "没问题的"那批:路径非裸 `/` 开头(外部存储 file:///storage/... 或 _doc 虚拟路径,getFileInfo 能解析)或已是 http URL 被 L527 标 Uploaded 后 L494 continue 跳过不查。
### 待超人拍板的修复选项(未动代码)
- A 删 L493 normalize(去有害转换,但裸路径 getFileInfo 仍可能 fail)
- B 让 checkFileExists 失败不阻断上传(uploadFile 能读字节成功,最治本、改动最小,倾向此)
- C 恢复 fileIo.fileExists Java 降级(超人之前因怕副作用否决过)
### 已确认(读 FileUploadManager.js:226)
- 上传传参 `const filePath = record.filePath + record.fileName`;`record.filePath` 来自 flattenData L497,由 L493 已污染的 `file.file`(file:///data/...) split 得出。
- 故 L493 同时污染**上传传参**(传 `//file:///data/.../x.mp3` 坏路径)与 checkFileExists。删 L493 一举修复两处。
- 但删 L493 后 checkFileExists 拿裸 /data/user/0/... 仍 getFileInfo fail → 仍标 NotExist → uploadRecord 对 NotExist 直接回调跳过上传(L195)。故还需 B:checkFileExists false 不阻断上传。
- **最小治本组合 = 删 L493 + 改 L500-503(false 时也尝试上传)**。
### 已落地改动(超人指令:删 L493 + 不做存在判断直接上传)
- 删 RecordSaveService.js:493 `file.file = PathUtils.normalizeLocalFilePath(file.file)` → 恢复裸 /data/user/0/... 路径
- 删 flattenData 内 checkFileExists 判断块(reportError + 标 NotExist)→ 不再做文件存在判定,直接进 result
- 删悬挂 import L17 `PathUtils`(仅 L493 用)
- 保留 checkFileExists/isLegalFile 方法(超人怕副作用,不动);checkFileExists 现无调用方(死方法)
- node --check 语法通过
### 完整上传链路(已读全代码确认)
录制结束/入队 → save(data)[L111] → enQueue[L294] → task[L566]
→ L581 await uploadRecord(record)[L317] → FileUploadManager.uploadRecord(record, cb)[L322]
├─ 上传成功: cb→handleUploadResult[L85]→save(data)[L87]→parseFileInfo[L113]→_changeFilePathToServer[L139]→_saveOrUpdate[L140]
│ → _handleCompletedRecord[L377](全 Uploaded)→ serverPaths 空?L387 黑名单✅ / saveRecCustomer[L399]失败throw→L149 黑名单✅
└─ 上传异常(reject): uploadRecord L326 catch→handleUploadResult(errorResult)[L344]→save→parseFileInfo L216 code≠0→error→L122抛→catch L149 黑名单✅
### 黑名单触发点(4处)
1. L387 serverPaths 空 → 黑名单
2. L149 save 异常(含上传失败 parseFileInfo 报错)→ 黑名单✅闭环完整
3. L583 task 层 uploadRecord reject → 死代码(L326 不 rethrow,永不触发)
4. L487/L507 flattenData 查询链黑名单
### 关键澄清(重要,已纠正此前错误结论)
- **flattenData 的 result 经 `enQueue`(L293)→`Queue(snapshot)`→`task` 出队→`uploadRecord(record)`(L317)→`FileUploadManager.uploadRecord` 实际喂给上传链**(不是纯查询链)。
- L493 污染 `file.file`(file:///...)→`aFullPath=file.file.split('/')`(L496)→`filePath=aFullPath.join('/')+'/'`(L498)→ result 的 filePath 带 file:// 前缀 → FileUploadManager L190 `fullPath=record.filePath+fileName` 拼成坏路径 → `uni.uploadFile` 失败。
- **删 L493 是修复上传传参的关键**,不是"只清理查询逻辑"。10-12 复原 FileUploadManager L230 只去掉"再包一层 file://",但 record.filePath 仍带 file://(源自 flattenData L493),故那轮未真正修复上传路径;本次删 L493 才根治。
- FileUploadManager L194 仍按 **DB 原始 record.status**(NoFile/NotExist) 跳过上传;删 checkFileExists 不碰 DB status,上传跳过逻辑不变。
- 那 6 条能否传出去仍取决于 **DB 里 file.status 是否被标 NotExist**(历史批次)。需查 DB 确认——若已是 NotExist,删 L493 也救不回,FileUploadManager L194 仍跳过;若非 NotExist,裸路径上传能成功(超人确认过)。
### 11:38 超人追问:两种路径上传能力 + 删 L493/去 checkFileExists 副作用
**两种绝对路径能否上传成功(底层 = UniAppStrategy.uploadFile → uni.uploadFile({filePath: file.path},L99;file.path=record.filePath+fileName 裸路径)):**
- `uni.uploadFile` 是原生 HTTP 上传,直接读文件字节流,不走 plus.io/ContentResolver。
- `/data/user/0/uni.gltap/...`(内部私有)与 `/storage/emulated/0/Android/data/uni.gltap/...`(外部私有)都是**应用自己目录**,原生 File 可读。
- **不加 file://、裸绝对路径:两种都能上传成功** ✓。相反加 `file:///` 三斜杠反而失败(uni.uploadFile 的 filePath 不认 file:// scheme,当不存在路径→fail)。
- 前提约束:上述两条都在 `uni.gltap` 应用目录内(项目现状)。若 `/storage/emulated/0/...` 指向**非应用私有**目录(如 DCIM/Download),targetSdk≥29 scoped storage 下无权限→失败。但项目录音只落 `/data/user/0/...`,日志落外部私有,均不涉及。
**副作用面(已查实):**
- 删 L493:纯正面,修复上传传参(坏 file:/// 路径→裸路径)。无负面副作用。
- 删 checkFileExists 判断块(不标 NotExist、不打"文件不存在"日志):
- 上传链不受影响:uploadRecord L194 按 **DB 原始 status** 跳过,flattenData result 的 status 已不再被改写。
- UI 零依赖:pages 目录 grep `NotExist|getRecordsSnapshotFlatten|snapshotFlatten|fileList` **No matches**→前端页面不依赖这些标记,无展示副作用。
- 日志:不再打"记录中有语音文件地址但文件不存在"reportError(减少噪声,正面)。
- 行为变化:文件真在盘→直接上传成功;真不在(包根切换旧路径)→`uni.uploadFile` fail→L149 黑名单。即"上传不成功进黑名单"闭环,且能救回被判丢失但实际在盘的文件。
- 是否引起别的问题:唯一变化是从"提前 check 拦截进黑名单"变"真实上传失败后进黑名单",多一次失败上传尝试,后果可控(进黑名单/告警/不卡死)。属超人要的效果。
- 残留待确认:DB 里那 6 条 file.status 是否被历史标成 NotExist——若是,删 L493 也救不回。建议本地查 DB。
### 加 `file.file = PathUtils.normalizeLocalFilePath(file.file)` 这行的目的 + 去掉是否影响前缀判断(超人 12:23 提问,已查清)
- **加这行的目的**:`normalizeLocalFilePath`(PathUtils.js:107-111)注释明确——把 `/` 开头的绝对路径补成 `file://` 形式,意图让底层 API(plus.io / getFileInfo / 上传策略)按 URL scheme 识别应用内部私有目录文件(scoped storage 下 plus.io 读不到绝对路径的"补丁"尝试)。但实测上传主链路 UniAppStrategy→`uni.uploadFile` **不认 file:// scheme**(要裸绝对路径),所以对本项目上传是**反向有害**:把本可上传的裸路径改成 `uni.uploadFile` 拒绝的坏路径。
- **DB 那 6 条 file.file 是裸 `/data/user/0/...`(无 file://)**:证据=超人上一轮贴的日志原文路径 `.../doc/records/1791431937899_fda81fcb.mp3`(无 scheme)。故 L493 对这 6 条确实做了"裸→file:/// 三斜杠"的加坏转换,删掉是正确修复(非 no-op)。
- **去掉后 `file.file` 前缀判断的影响面(逐项查实):**
1. flattenData 内部(L493-495):`file.file.split('/')` 拆目录+文件名。裸路径拆出正确 `/data/...`;file:// 版本拆出 `file:///data/...` 坏路径。去掉→修复上传传参,**无副作用**。
2. **UploadManager._registerStrategies()(L167-169)只注册 WebViewStrategy + UniAppStrategy,NativeStrategy 未注册** → `NativeStrategy.js:90 if(filePath.startsWith('file://'))` 是**死代码**,对录音频链永不执行,去掉 file:// 不影响策略选择。
3. **UniAppStrategy 上传链**:拿裸 `record.filePath + fileName`(RecordSaveService L494-495 split 产出),`uni.uploadFile` 原生 HTTP 读字节,能读 `/data/user/0/...`(内部私有)与 `/storage/emulated/0/...`(外部私有,均 app 目录内),两种都成功。
4. 其他 `file://` 前缀判断点:`RecordManager.js:169`、`TempRecord.js:244`、`fileIo.js:17`、`pathCache.js:8` —— 这些消费的是**录制时/存储归并阶段的路径**,**不消费 flattenData 改过的 file.file**;且 L493 只改 flattenData 内部循环变量、不动 DB。故完全不受影响。
5. 平行链:`UploadService.js`、`mixin/uploader.js` 也用 `file.file.split('/')` + `checkFileExists(file.file)`,但它们是独立上传类/UI 上传器,各自读 DB 原始 file.file,**不共享 RecordSaveService 的 file.file 状态**,不在本次改动范围。
- 结论:删 L493 是修复(裸路径→uni.uploadFile 能读),不引发前缀判断类副作用;真正读 file:// 的上传策略未注册,其余前缀判断点不碰本链数据。
# 项目长期记忆(gl_tape)
## 工程硬约束(已踩坑)
1. **git / 文件操作必须在原生 Git Bash,绝不用 WorkBuddy 内置终端**。
内置 shell 缺 `tail`/`head`/`dirname`/`cd`/`cp`/`mkdir`/`ls`,git 多参数被篡改会酿灾(曾把整个仓库误当 root-commit 提交 1573 文件)。
备份/恢复文件用 node:`fs.copyFileSync(src,dst)`(需先 `mkdirSync(dir,{recursive:true})`)。
2. 提交业务改动用 `git add <精确7个文件>`,禁用 `git add -A`/`.`——本项目工作区有大量本地新增未跟踪目录,误加即 2K 污染。
3. `.workbuddy/`(AI 记忆目录)加 `.gitignore`,不随业务提交。
## 项目结构要点
- 首页非统一 home:登录后按 `sceneType` 分流到 `pages/boutique/index`、`pages/equity/index`、`pages/usedCar/index`。**冷启动必经页是 `pages/common/loading.vue`(pages[0],全角色)**——后台异步任务触发点放这里最稳。
- 录音存内部私有 `/data/user/0/uni.gltap/apps/__UNI__D3BD3DF/doc/records/`;targetSdk=30 下 `uni.getFileInfo` 读绝对路径必失败,上传走 `uni.uploadFile` 裸路径可成功。
- 路径归并:`utils/storageMerge/StoragePathMerge.js` 静态 `runDeferred()`(fire-and-forget+内部catch),由 loading.vue mounted 触发,包根切换(/data/user/0↔/data/user/N)后旧录音兜底。
## 协作风格(超人)
- 明确"最小改动":删一切非必需代码(fail-safe 白名单/去重/间隔垫底都曾因"过度设计"被否)。
- 原文逐字保留,推断须有证据,结论与实测冲突即摆证据修正。
- 服务启停由他控制,不擅自常驻。
import http from '../request/http' import http from '../request/http'
import { env } from '../../env' import { env } from '../../env'
import materialCache from '../../utils/materialCache'
const ENV = env == 'ip' ? 'develop' : env, const ENV = env == 'ip' ? 'develop' : env,
serverConfig = { serverConfig = {
...@@ -133,7 +134,12 @@ const getImageVersion = async () => { ...@@ -133,7 +134,12 @@ const getImageVersion = async () => {
return accountInfo?.version || Date.now() return accountInfo?.version || Date.now()
} }
/**获取素材配置 */ /**获取素材配置 */
const sourceRequests = new Map()
const getSoureData = async (shopMerchantId, sceneType, params = {}) => { const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
const storageName = materialCache.getSourceKey(shopMerchantId, sceneType, params)
const requestId = (sourceRequests.get(storageName) || 0) + 1
sourceRequests.set(storageName, requestId)
const isCurrent = () => sourceRequests.get(storageName) === requestId
try { try {
const res = await getEquityMaterialId({ const res = await getEquityMaterialId({
merchantId: shopMerchantId, merchantId: shopMerchantId,
...@@ -144,11 +150,9 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => { ...@@ -144,11 +150,9 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
id: res.id id: res.id
}) })
if (data) { if (data) {
let { toolList, materialInfoList } = data, let { toolList = [], materialInfoList = [] } = data
storageName = `source_${sceneType}_${shopMerchantId}`
if (params.brandId && params.subBrandId) storageName += `_${params.brandId}_${params.subBrandId}`
let insurance = materialInfoList.find(e => e.componentName == 'insurance'), let insurance = materialInfoList.find(e => e.componentName == 'insurance'),
hasEquity = toolList.find(e => e.id == insurance.id) hasEquity = insurance && toolList.find(e => e.id == insurance.id)
if (insurance && hasEquity) { if (insurance && hasEquity) {
let configList let configList
try { try {
...@@ -157,6 +161,7 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => { ...@@ -157,6 +161,7 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
} catch (error) { } catch (error) {
configList = uni.$storage.get('findReceptionpriproConfigList') configList = uni.$storage.get('findReceptionpriproConfigList')
} }
configList = Array.isArray(configList) ? configList : []
const toolOtherList = configList.map(i => { const toolOtherList = configList.map(i => {
return { return {
id: hasEquity.id + 100 + i.id, id: hasEquity.id + 100 + i.id,
...@@ -181,14 +186,22 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => { ...@@ -181,14 +186,22 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
}) })
materialInfoList = materialInfoList.concat(moduleOtherList) materialInfoList = materialInfoList.concat(moduleOtherList)
} }
data.toolList = await imgTransformBase64(toolList, ['shortTitleUrl']) if (!isCurrent()) return
data.moduleList = await imgTransformBase64(materialInfoList, ['thumbnail', 'receptionSourceDetailList', 'screenList']) data = { ...data, id: res.id, toolList, moduleList: materialInfoList }
uni.setStorageSync(storageName, { let cacheSaved = false
moduleList: data.moduleList, try {
toolList: data.toolList, const base = await materialCache.saveSourceCache(storageName, data)
id: res.id data = { ...data, ...base }
}) cacheSaved = true
return Promise.resolve(data) } catch (error) {
console.warn('素材基础缓存写入失败', storageName)
}
if (!isCurrent()) return
// 首屏只等待基础数据;图片下载、转换和写入在后台进行。
setTimeout(() => {
if (cacheSaved && isCurrent()) materialCache.cacheMaterialImages(storageName, data).catch(() => {})
}, 0)
return data
} else throw false } else throw false
} else throw false } else throw false
} catch (error) { } catch (error) {
...@@ -201,64 +214,6 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => { ...@@ -201,64 +214,6 @@ const getSoureData = async (shopMerchantId, sceneType, params = {}) => {
}) })
} }
} }
/**批量图片转base64 */
const imgTransformBase64 = async (imgList = [], keyList = []) => {
return await Promise.all(
imgList?.map(async e => {
await Promise.all(
Object.keys(e).map(async key => {
if (keyList.includes(key)) {
let isArray = Array.isArray(e[key])
if (isArray) {
await Promise.all(
e[key].map(async i => {
await Promise.all(
Object.keys(i).map(async k => {
// i[`original_${k}`] = JSON.parse(JSON.stringify(i[k]))
if (k == 'detailUrl' && i[k]) i[k] = await getBase64(i[k])
})
)
})
)
} else {
if (typeof e[key] === 'string' && e[key]) {
// e[`original_${key}`] = JSON.parse(JSON.stringify(e[key]))
e[key] = await getBase64(e[key])
}
if (e[key] && typeof e[key] === 'object') {
await Promise.all(
Object.keys(e[key]).map(async k => {
// e[key][`original_${k}`] = JSON.parse(JSON.stringify(e[key][k]))
if (e[key][k]) e[key][k] = await getBase64(e[key][k])
})
)
}
}
}
})
)
return e
})
)
}
/**转base64 */
const getBase64 = async url => {
return new Promise((resolve, reject) => {
uni.request({
url,
method: 'GET',
responseType: 'arraybuffer',
success: res => {
const base64 = `data:image/png;base64,${uni.arrayBufferToBase64(res.data)}`
resolve(base64)
},
fail: err => {
resolve(url)
// reject(err)
}
})
})
}
module.exports = { module.exports = {
getImageVersion, getImageVersion,
getMockData, getMockData,
......
...@@ -53,7 +53,7 @@ class Request { ...@@ -53,7 +53,7 @@ class Request {
title: '网络异常', title: '网络异常',
icon: 'none' icon: 'none'
}) })
uni.$logger.locale.error('网络异常') uni.$logger.local.error('网络异常')
reject('网络异常') reject('网络异常')
return return
} }
......
...@@ -22,6 +22,8 @@ ...@@ -22,6 +22,8 @@
</template> </template>
<script type='text/ecmascript-6'> <script type='text/ecmascript-6'>
import materialCache from '@/utils/materialCache'
export default { export default {
name: 'CarBrands', name: 'CarBrands',
props: { props: {
...@@ -81,6 +83,9 @@ export default { ...@@ -81,6 +83,9 @@ export default {
}, },
mounted() { mounted() {
}, },
beforeDestroy() {
this.cancelPendingRequests()
},
methods: { methods: {
autoSelect() { autoSelect() {
const { carBrandList, boutiqueDefaultCarBrandId, defaultCarId } = this const { carBrandList, boutiqueDefaultCarBrandId, defaultCarId } = this
...@@ -89,26 +94,11 @@ export default { ...@@ -89,26 +94,11 @@ export default {
if (carIndex < 0) carIndex = 0 if (carIndex < 0) carIndex = 0
if (carBrandList.length) this.selectCar(carBrandList[carIndex], true, defaultCarId) if (carBrandList.length) this.selectCar(carBrandList[carIndex], true, defaultCarId)
}, },
open() { async open() {
const requestId = (this._brandRequestId || 0) + 1
this._brandRequestId = requestId
this.$store.dispatch('setCarBrandOpenStatus', true) this.$store.dispatch('setCarBrandOpenStatus', true)
const userInfo = uni.$storage.get("userInfo"), // 已有品牌先展示,离线时不再触发品牌接口。
{ shopMerchantId } = userInfo;
/**获取品牌车型 */
uni.$api.commonApi
.getMerchantCarBrandList([shopMerchantId])
.then(({ data }) => {
let list = data[0].carBrandList,
carBrandList = [];
list?.map((e) => {
e.childs.map((i) => {
i.brandName = e.name
i.brandId = e.id;
carBrandList.push(i);
});
});
this.$store.dispatch("setCarBrandsList", carBrandList);
uni.$storage.set("carBrandList", carBrandList);
})
const { carBrand } = this const { carBrand } = this
if (carBrand) { if (carBrand) {
const { carBrandList } = this, const { carBrandList } = this,
...@@ -118,12 +108,28 @@ export default { ...@@ -118,12 +108,28 @@ export default {
this.$refs.carBrandListVisible.open() this.$refs.carBrandListVisible.open()
this.carBrandListOff = true this.carBrandListOff = true
} }
return } else {
this.$refs.carBrandListVisible.open()
this.carBrandListOff = true
}
if (!await materialCache.getNetworkStatus() || this._brandRequestId !== requestId) return
try {
const { shopMerchantId } = uni.$storage.get('userInfo') || {}
const { data } = await uni.$api.commonApi.getMerchantCarBrandList([shopMerchantId])
if (this._brandRequestId !== requestId) return
const carBrandList = []
;(data?.[0]?.carBrandList || []).forEach(brand => {
;(brand.childs || []).forEach(child => {
carBrandList.push({ ...child, brandName: brand.name, brandId: brand.id })
})
})
this.$store.dispatch('setCarBrandsList', carBrandList)
uni.$storage.set('carBrandList', carBrandList)
} catch (error) {
// 刷新失败时保留当前可用的品牌列表。
} }
this.$refs.carBrandListVisible.open()
this.carBrandListOff = true
}, },
selectCar(e, auto = false, carId) { async selectCar(e, auto = false, carId) {
if (!e.brandId || !e.id) return uni.showToast({ if (!e.brandId || !e.id) return uni.showToast({
title: "车型ID或品牌ID为空", title: "车型ID或品牌ID为空",
icon: "none", icon: "none",
...@@ -132,6 +138,9 @@ export default { ...@@ -132,6 +138,9 @@ export default {
index = 0 index = 0
if (clickFlga) return if (clickFlga) return
this.clickFlga = true this.clickFlga = true
const requestId = (this._carRequestId || 0) + 1
this._carRequestId = requestId
const isCurrent = () => this._carRequestId === requestId
// 进入车系选择过程中保持弹层打开态,避免「查看长图」按钮冒出来 // 进入车系选择过程中保持弹层打开态,避免「查看长图」按钮冒出来
this.$store.dispatch('setCarBrandOpenStatus', true) this.$store.dispatch('setCarBrandOpenStatus', true)
this.selectItem = { this.selectItem = {
...@@ -140,8 +149,14 @@ export default { ...@@ -140,8 +149,14 @@ export default {
carChildsBrandName: e.name, carChildsBrandName: e.name,
carChildsBrandId: e.id carChildsBrandId: e.id
} }
const carList = uni.getStorageSync(`${e.id}_${e.brandId}_carlist`) const cacheKey = `${e.id}_${e.brandId}_carlist`
if (carList) { const refreshIds = this._carRefreshIds || (this._carRefreshIds = new Map())
const refreshId = (refreshIds.get(cacheKey) || 0) + 1
refreshIds.set(cacheKey, refreshId)
const isLatestRefresh = () => refreshIds.get(cacheKey) === refreshId
const carList = uni.getStorageSync(cacheKey)
const hasCache = Array.isArray(carList) && carList.length > 0
if (hasCache) {
this.clickFlga = false this.clickFlga = false
this.carlist = carList this.carlist = carList
if (auto && carList.length) { if (auto && carList.length) {
...@@ -151,39 +166,60 @@ export default { ...@@ -151,39 +166,60 @@ export default {
} }
else this.$refs.carBoxVisible.open() else this.$refs.carBoxVisible.open()
} else { } else {
this.carlist = []
if (!auto) uni.showLoading({ if (!auto) uni.showLoading({
mask: true mask: true
}) })
} }
uni.$api.commonApi.getCarBrandsList({ try {
brandId: e.brandId, const online = await materialCache.getNetworkStatus()
childBrandId: e.id // 缓存已自动选中时仍允许后台刷新,弹层状态只由当前选择更新。
}).then(res => { if (!isLatestRefresh() || (!isCurrent() && !hasCache)) return
uni.hideLoading() if (!online) {
this.carlist = res if (!hasCache) uni.showToast({ title: '该品牌车系尚未缓存,请联网后重试', icon: 'none' })
if (res) uni.setStorageSync(`${e.id}_${e.brandId}_carlist`, res) return
if (!carList) { }
if (auto && res.length) { const res = await uni.$api.commonApi.getCarBrandsList({
if (carId) index = res.findIndex(i => i.id == carId) brandId: e.brandId,
childBrandId: e.id
})
if (!isLatestRefresh()) return
if (Array.isArray(res)) uni.setStorageSync(cacheKey, res)
if (!isCurrent()) return
const nextList = Array.isArray(res) ? res : []
this.carlist = nextList
if (!hasCache) {
if (auto && nextList.length) {
if (carId) index = nextList.findIndex(i => i.id == carId)
if (index < 0) index = 0 if (index < 0) index = 0
this.handleSelect(res[index]) this.handleSelect(nextList[index])
} } else {
else {
this.$store.dispatch('setCarBrandOpenStatus', true) this.$store.dispatch('setCarBrandOpenStatus', true)
this.$refs.carBoxVisible.open() this.$refs.carBoxVisible.open()
} }
} }
this.clickFlga = false } catch (error) {
}).catch(err => { // 请求过程中断网时保留已展示的缓存。
this.clickFlga = false } finally {
uni.hideLoading() if (isCurrent()) {
}) this.clickFlga = false
uni.hideLoading()
}
}
},
cancelPendingRequests() {
this._brandRequestId = (this._brandRequestId || 0) + 1
this._carRequestId = (this._carRequestId || 0) + 1
if (this.clickFlga) uni.hideLoading()
this.clickFlga = false
}, },
handleSelect(item) { handleSelect(item) {
const customerInfo = this.$store.state.user.customerInfo, this.cancelPendingRequests()
const customerInfo = { ...this.$store.state.user.customerInfo },
{ selectItem, linkage } = this { selectItem, linkage } = this
Object.assign(customerInfo, { Object.assign(customerInfo, {
carModel: item.name,
carModelId: item.id,
carBrand: selectItem.carChildsBrandName, carBrand: selectItem.carChildsBrandName,
carBrandId: selectItem.carChildsBrandId, carBrandId: selectItem.carChildsBrandId,
oneCarBrand: selectItem.carBrand, oneCarBrand: selectItem.carBrand,
...@@ -198,8 +234,8 @@ export default { ...@@ -198,8 +234,8 @@ export default {
oneCarBrand:${customerInfo.oneCarBrand}, oneCarBrand:${customerInfo.oneCarBrand},
oneCarBrandId:${customerInfo.oneCarBrandId}`) oneCarBrandId:${customerInfo.oneCarBrandId}`)
this.$store.dispatch('setCustomerInfo', customerInfo) this.$store.dispatch('setCustomerInfo', customerInfo)
this.$store.dispatch('updateViewKey')
this.$store.dispatch('setCurrentCarInfo', selectItem) this.$store.dispatch('setCurrentCarInfo', selectItem)
this.$store.dispatch('updateViewKey')
} }
this.$refs.carBoxVisible?.close(); this.$refs.carBoxVisible?.close();
this.$refs.carBrandListVisible?.close(); this.$refs.carBrandListVisible?.close();
...@@ -211,6 +247,7 @@ export default { ...@@ -211,6 +247,7 @@ export default {
}) })
}, },
close() { close() {
this.cancelPendingRequests()
this.$refs?.carBoxVisible?.close(); this.$refs?.carBoxVisible?.close();
this.$refs?.carBrandListVisible?.close() this.$refs?.carBrandListVisible?.close()
this.carBrandListOff = false this.carBrandListOff = false
...@@ -218,6 +255,7 @@ export default { ...@@ -218,6 +255,7 @@ export default {
}, },
closeCarBoxVisible() { closeCarBoxVisible() {
this.cancelPendingRequests()
// 关车系弹窗:若还要从品牌列表回来,保持打开态;否则关闭 // 关车系弹窗:若还要从品牌列表回来,保持打开态;否则关闭
if (this.carBrandListOff) { if (this.carBrandListOff) {
this.$store.dispatch('setCarBrandOpenStatus', true) this.$store.dispatch('setCarBrandOpenStatus', true)
...@@ -227,6 +265,7 @@ export default { ...@@ -227,6 +265,7 @@ export default {
this.$emit('close') this.$emit('close')
}, },
clickClose() { clickClose() {
this.cancelPendingRequests()
this.carBrandListOff = false this.carBrandListOff = false
this.$store.dispatch('setCarBrandOpenStatus', false) this.$store.dispatch('setCarBrandOpenStatus', false)
this.$emit('close') this.$emit('close')
...@@ -260,4 +299,4 @@ export default { ...@@ -260,4 +299,4 @@ export default {
} }
} }
} }
</style>
\ No newline at end of file \ No newline at end of file
</style>
...@@ -83,7 +83,12 @@ export default { ...@@ -83,7 +83,12 @@ export default {
this.$refs.employeeBoxVisible.open() this.$refs.employeeBoxVisible.open()
return return
} }
uni.showLoading({
title: '加载中',
mask: true
})
await this.ensureEmployeeList() await this.ensureEmployeeList()
uni.hideLoading()
this.$refs.employeeBoxVisible.open() this.$refs.employeeBoxVisible.open()
}, },
async ensureEmployeeList () { async ensureEmployeeList () {
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
ref="formRef" ref="formRef"
@cancel="cancel" @cancel="cancel"
@confirm="submit" @confirm="submit"
@close="handleClose"
:cancelBtnText="`${step == 1 ? '取消' : '上一步'}`" :cancelBtnText="`${step == 1 ? '取消' : '上一步'}`"
:confirmBtnText="`${sceneType == 0 ? (step == 1 ? '下一步' : '完成接待') : '完成接待'}`" :confirmBtnText="`${sceneType == 0 ? (step == 1 ? '下一步' : '完成接待') : '完成接待'}`"
:title="`${step == 1 ? '客户信息完善' : '结果反馈'}`" :title="`${step == 1 ? '客户信息完善' : '结果反馈'}`"
...@@ -89,6 +90,7 @@ ...@@ -89,6 +90,7 @@
<employee <employee
ref="employeeBoxVisible" ref="employeeBoxVisible"
@select="handleSelect($event, 'employeeBoxVisible')" @select="handleSelect($event, 'employeeBoxVisible')"
:list="employeeList"
/> />
<uni-popup <uni-popup
ref="successRef" ref="successRef"
...@@ -159,6 +161,8 @@ export default { ...@@ -159,6 +161,8 @@ export default {
data () { data () {
return { return {
step: 1, step: 1,
// 完成接待弹框是否处于打开状态,供外层决定是否需要延时刷新。
visible: false,
formObject: [ formObject: [
{ {
label: "车主姓名", label: "车主姓名",
...@@ -230,6 +234,10 @@ export default { ...@@ -230,6 +234,10 @@ export default {
text = titleTips || '检测到“交车告知书”中未填写客户档案,请填写后再完成接待。' text = titleTips || '检测到“交车告知书”中未填写客户档案,请填写后再完成接待。'
if (sceneType == 1) text = '请确认“车型加装选购页”中的客户信息,并点击「完成接待」结束客户接待。' if (sceneType == 1) text = '请确认“车型加装选购页”中的客户信息,并点击「完成接待」结束客户接待。'
return text return text
},
employeeList () {
let { sceneType } = this
return sceneType == 1 ? null : this.$store.state.user.employeeList
} }
}, },
watch: { watch: {
...@@ -272,6 +280,11 @@ export default { ...@@ -272,6 +280,11 @@ export default {
this.receptionStatus = -1 this.receptionStatus = -1
this.$refs.formRef.close() this.$refs.formRef.close()
}, },
// 弹框实际关闭(取消、右上角关闭或提交后收起)时同步状态并通知外层。
handleClose () {
this.visible = false
this.$emit('close')
},
check (all = false) { check (all = false) {
let flag = true let flag = true
try { try {
...@@ -357,6 +370,7 @@ export default { ...@@ -357,6 +370,7 @@ export default {
} }
this.step = step this.step = step
this.$refs.formRef.open() this.$refs.formRef.open()
this.visible = true
this.updateViewKey = Date.now() this.updateViewKey = Date.now()
}) })
}, },
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
<view class="list-body"> <view class="list-body">
<template v-for="(i, index) in data"> <template v-for="(i, index) in data">
<view :class="['item', { active: i[idKey] == id }]" :key="index" @click="jump(i)"> <view :class="['item', { active: i[idKey] == id }]" :key="index" @click="jump(i)">
<image class="icon" :src="i.shortTitleUrl" mode="scaleToFill" /> <image v-if="!show" class="icon" :src="i.shortTitleUrl" mode="scaleToFill" />
{{ i.shortTitle }} {{ i.shortTitle }}
</view> </view>
</template> </template>
...@@ -59,6 +59,9 @@ export default { ...@@ -59,6 +59,9 @@ export default {
}, },
}, },
watch: { watch: {
show (hidden) {
this.$emit('visibility-change', !hidden)
},
watchStatus: { watchStatus: {
immediate: true, immediate: true,
handler (newval) { handler (newval) {
...@@ -209,4 +212,4 @@ export default { ...@@ -209,4 +212,4 @@ export default {
// 移除之前的 keyframes // 移除之前的 keyframes
// @keyframes scale-up-top-right { ... } // @keyframes scale-up-top-right { ... }
} }
</style>
\ No newline at end of file \ No newline at end of file
</style>
...@@ -111,8 +111,7 @@ if (!uni.$dbReady) { ...@@ -111,8 +111,7 @@ if (!uni.$dbReady) {
uni.$dbReady = (async _ => { uni.$dbReady = (async _ => {
try { try {
await uni.$dbRecord.init() await uni.$dbRecord.init()
// await uni.$storageMergeDone uni.$logger.local.info('数据库初始化完成')
uni.$logger.local.info('数据库初始化与路径合并已完成')
return true return true
} catch (e) { } catch (e) {
uni.$logger.local.error('数据库初始化失败: ' + e.message) uni.$logger.local.error('数据库初始化失败: ' + e.message)
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
"name" : "展业助手", "name" : "展业助手",
"appid" : "__UNI__D3BD3DF", "appid" : "__UNI__D3BD3DF",
"description" : "", "description" : "",
"versionName" : "2.26.5", "versionName" : "2.26.7",
"versionCode" : 2265, "versionCode" : 2267,
"transformPx" : false, "transformPx" : false,
"sassImplementationName" : "node-sass", "sassImplementationName" : "node-sass",
/* 5+App特有相关 */ /* 5+App特有相关 */
......
...@@ -34,6 +34,7 @@ ...@@ -34,6 +34,7 @@
import detail from './detail/detail' import detail from './detail/detail'
import { mapMutations } from 'vuex' import { mapMutations } from 'vuex'
import HomeFrame from '@/components/HomeFrame/index.vue' import HomeFrame from '@/components/HomeFrame/index.vue'
import materialCache from '@/utils/materialCache'
// import storge from "@/mixin/storge"; // import storge from "@/mixin/storge";
export default { export default {
// mixins: [storge], // mixins: [storge],
...@@ -78,7 +79,29 @@ export default { ...@@ -78,7 +79,29 @@ export default {
}, },
async onLoad () { async onLoad () {
uni.hideLoading() uni.hideLoading()
const mockdata = await uni.$api.systemApi.getMockData(true) //获取APP配置信息 this._sourceDisposed = false
this._sourceNetworkHandler = ({ isConnected }) => {
this.restoreSourceCache(isConnected).then(() => {
if (isConnected && !this._sourceDisposed) this.get_Vehicle_Sales_Data()
})
}
uni.onNetworkStatusChange(this._sourceNetworkHandler)
const online = await materialCache.getNetworkStatus()
// 素材恢复不能等待配置中心或品牌接口,否则断网冷启动无法展示缓存。
await this.restoreSourceCache(online)
if (this._sourceDisposed) return
if (!online) {
this.get_Vehicle_Sales_Data(false)
this.requested = true
return
}
let mockdata = uni.$storage.get('mock_data') || {}
try {
mockdata = await uni.$api.systemApi.getMockData(true) || mockdata
} catch (error) {
// 已恢复的素材不受配置接口失败影响。
}
if (this._sourceDisposed) return
if (this.channelType == 1 && mockdata.boutiqueDefaultCarBrandId) { if (this.channelType == 1 && mockdata.boutiqueDefaultCarBrandId) {
this.$store.state.user.boutiqueDefaultCarBrandId = mockdata.boutiqueDefaultCarBrandId //默认车辆品牌 this.$store.state.user.boutiqueDefaultCarBrandId = mockdata.boutiqueDefaultCarBrandId //默认车辆品牌
if (mockdata.defaultCarId) this.$store.state.user.defaultCarId = mockdata.defaultCarId //默认车系 if (mockdata.defaultCarId) this.$store.state.user.defaultCarId = mockdata.defaultCarId //默认车系
...@@ -87,6 +110,11 @@ export default { ...@@ -87,6 +110,11 @@ export default {
this.requested = true this.requested = true
this.$refs.home.updateApp(true) this.$refs.home.updateApp(true)
}, },
onUnload () {
this._sourceDisposed = true
this._sourceRequestId = (this._sourceRequestId || 0) + 1
if (this._sourceNetworkHandler) uni.offNetworkStatusChange(this._sourceNetworkHandler)
},
async onShow () { async onShow () {
const userInfo = uni.$storage.get('userInfo') const userInfo = uni.$storage.get('userInfo')
if (!userInfo.shopMerchantId || !userInfo.shopMerchantName) { if (!userInfo.shopMerchantId || !userInfo.shopMerchantName) {
...@@ -101,20 +129,23 @@ export default { ...@@ -101,20 +129,23 @@ export default {
}, },
methods: { methods: {
...mapMutations('audio', ['setReceptionStatus']), ...mapMutations('audio', ['setReceptionStatus']),
init () { async init () {
this.findPayInfo() if (!await materialCache.getNetworkStatus() || this._sourceDisposed) return
this.findPayInfo().catch(() => {})
if (this.requested && !this.id) this.$refs.home.updateApp() if (this.requested && !this.id) this.$refs.home.updateApp()
}, },
/**获取车型&销售数据 */ /**获取车型&销售数据 */
get_Vehicle_Sales_Data () { get_Vehicle_Sales_Data (online = true) {
const userInfo = uni.$storage.get('userInfo'), const userInfo = uni.$storage.get('userInfo'),
storageCarBrandList = uni.$storage.get('carBrandList'), storageCarBrandList = uni.$storage.get('carBrandList'),
storageEmployeeList = uni.$storage.get('employeeList'), storageEmployeeList = uni.$storage.get('employeeList'),
{ shopMerchantId } = userInfo { shopMerchantId } = userInfo
if (storageCarBrandList) this.$store.dispatch('setCarBrandsList', storageCarBrandList) if (storageCarBrandList) this.$store.dispatch('setCarBrandsList', storageCarBrandList)
if (storageEmployeeList) this.$store.dispatch('setEmployeeList', storageEmployeeList) if (storageEmployeeList) this.$store.dispatch('setEmployeeList', storageEmployeeList)
if (!online) return
/**获取品牌车型 */ /**获取品牌车型 */
uni.$api.commonApi.getMerchantCarBrandList([shopMerchantId]).then(({ data }) => { uni.$api.commonApi.getMerchantCarBrandList([shopMerchantId]).then(({ data }) => {
if (this._sourceDisposed) return
let list = data[0].carBrandList, let list = data[0].carBrandList,
carBrandList = [], carBrandList = [],
brandIdList = [], brandIdList = [],
...@@ -136,26 +167,64 @@ export default { ...@@ -136,26 +167,64 @@ export default {
this.getCarBrandsList(carBrandList, index) this.getCarBrandsList(carBrandList, index)
} }
}).catch(() => {
if (this._sourceDisposed) return
const brands = Array.isArray(storageCarBrandList) ? storageCarBrandList : []
this.getSoure(brands.map(item => item.brandId), brands.map(item => item.id))
}) })
/**获取销售人员 */ /**获取销售人员 */
uni.$api.commonApi.getEmployeeList({ // uni.$api.commonApi.getEmployeeList({
merchantId: shopMerchantId // merchantId: shopMerchantId
// }).then(res => {
// if (this._sourceDisposed) return
// this.$store.dispatch('setEmployeeList', res || [])
// uni.$storage.set('employeeList', res || [])
// }).catch(() => {})
uni.$api.popupApi.getOrderScreenEmployeeList({
merchantId: shopMerchantId,
sceneList: [0]
}).then(res => { }).then(res => {
this.$store.dispatch('setEmployeeList', res || []) this.$store.dispatch('setEmployeeList', res || [])
uni.$storage.set('employeeList', res || []) uni.$storage.set('employeeList', res || [])
}) })
}, },
async restoreSourceCache (online) {
const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1
const isCurrent = () => !this._sourceDisposed && requestId === this._sourceRequestId
const key = materialCache.getSourceKey(this.shopMerchantId, this.sceneType)
const data = await this.readHomeSource(key, online, isCurrent)
if (!isCurrent()) return
if (data) this.setViewInfo(data)
else this.loadComplete = true
},
async readHomeSource (key, online, isCurrent) {
const base = await materialCache.readSourceCache(key, online, { baseOnly: true, isCurrent })
if (!base || online || !isCurrent()) return base
// 首页只用封面,不读取详情页和所有车系的正文图片。
return materialCache.hydrateSourceImages(key, base, {
moduleIds: base.moduleList.map(item => item.id), toolIds: [],
fields: ['thumbnail', 'homeEntranceCover'], isCurrent
})
},
// 查询素材 // 查询素材
async getSoure (brandIdList, subBrandIdList) { async getSoure (brandIdList, subBrandIdList) {
const requestId = this._sourceRequestId = (this._sourceRequestId || 0) + 1
const isCurrent = () => !this._sourceDisposed && requestId === this._sourceRequestId
const { shopMerchantId, sceneType } = this const { shopMerchantId, sceneType } = this
let data = uni.getStorageSync(`source_${sceneType}_${shopMerchantId}`) const online = await materialCache.getNetworkStatus()
const key = materialCache.getSourceKey(shopMerchantId, sceneType)
const data = await this.readHomeSource(key, online, isCurrent)
if (!isCurrent()) return
if (data) this.setViewInfo(data) if (data) this.setViewInfo(data)
let requestData = await uni.$api.systemApi.getSoureData(shopMerchantId, sceneType, { if (!online) { this.loadComplete = true; return }
brandIdList, try {
subBrandIdList const requestData = await uni.$api.systemApi.getSoureData(shopMerchantId, sceneType, { brandIdList, subBrandIdList })
}) if (isCurrent() && requestData) this.setViewInfo(requestData)
if (requestData) this.setViewInfo(requestData) } catch (error) {
else this.loadComplete = true // 保留已经展示的缓存数据。
} finally {
if (isCurrent()) this.loadComplete = true
}
}, },
errorImg (index) { errorImg (index) {
this.moduleList[index].showAlt = true this.moduleList[index].showAlt = true
......
...@@ -14,7 +14,6 @@ import dayjs from 'dayjs' ...@@ -14,7 +14,6 @@ import dayjs from 'dayjs'
import store from '@/store' import store from '@/store'
import FileUploadManager from './FileUploadManager.js' import FileUploadManager from './FileUploadManager.js'
import { Command } from '../../ws/constants' import { Command } from '../../ws/constants'
import PathUtils from './PathUtils.js'
const UPLOAD_INTERVAL = 0.5 * 60 * 1000 const UPLOAD_INTERVAL = 0.5 * 60 * 1000
/** /**
...@@ -150,7 +149,7 @@ class RecordSaveService { ...@@ -150,7 +149,7 @@ class RecordSaveService {
} else if (this._currentKey) { } else if (this._currentKey) {
this._addToBlackList(this._recordIdFromTaskKey(this._currentKey), `Save failed: ${error.message}`) this._addToBlackList(this._recordIdFromTaskKey(this._currentKey), `Save failed: ${error.message}`)
} }
this.reportError(`【接待记录保存服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, data?.recordId, data?.filePath + data?.fileName) this.reportError(`【接待记录保存服务】 == 保存记录(save)异常 error: ${error.message}`, error.message, failRecordId, data?.filePath + data?.fileName)
this.endTask() this.endTask()
} }
} }
...@@ -382,6 +381,13 @@ class RecordSaveService { ...@@ -382,6 +381,13 @@ class RecordSaveService {
uni.$logger.local.warn(`【接待记录保存服务】 == 本条接待所有文件已经上传和处理完毕!!`) uni.$logger.local.warn(`【接待记录保存服务】 == 本条接待所有文件已经上传和处理完毕!!`)
// uni.$logger.local.info(`【接待记录保存服务】 == 已上传的文件: ${JSON.stringify(serverPaths)}`) // uni.$logger.local.info(`【接待记录保存服务】 == 已上传的文件: ${JSON.stringify(serverPaths)}`)
// 没有可上传的文件(本地文件均不存在 / 空录音):后端收到 recordUrlList=[] 会返回 false,
// 这里直接本地处理,不再请求后端,避免无意义的失败重试。
if (serverPaths.length === 0) {
this._addToBlackList(record.id, '无语音文件(本地文件均不存在)')
uni.$logger.local.warn(`【接待记录保存服务】 == 无语音文件或本地文件均不存在,跳过保存: ${record.id}`)
return
}
// 2. 准备提交参数 // 2. 准备提交参数
const params = { ...record, recordUrlList: serverPaths } const params = { ...record, recordUrlList: serverPaths }
if (!params.receptionEndTime) { if (!params.receptionEndTime) {
...@@ -396,9 +402,14 @@ class RecordSaveService { ...@@ -396,9 +402,14 @@ class RecordSaveService {
uni.$logger.local.info(`【上传服务】 == 开始删除客户端的文件!!`) uni.$logger.local.info(`【上传服务】 == 开始删除客户端的文件!!`)
await this._removeRecordFiles(localPaths) await this._removeRecordFiles(localPaths)
await this._removeRecordById(record.id) await this._removeRecordById(record.id)
return
} }
// 服务器明确返回失败:抛错,交给 save() 的 catch 把该记录加入黑名单。
// 否则本地记录不删除、状态不更新,下一轮 enQueue 会原样重新入队,形成 0 延迟死循环。
throw new Error(`服务器保存接待记录失败: ${JSON.stringify(res)}`)
} }
/** /**
* 向服务器请求接待结束时间 * 向服务器请求接待结束时间
* 这个函数用于向服务器请求接待结束时间 * 这个函数用于向服务器请求接待结束时间
...@@ -477,19 +488,13 @@ class RecordSaveService { ...@@ -477,19 +488,13 @@ class RecordSaveService {
continue continue
} }
for (const file of recordUrlList) { for (const file of recordUrlList) {
try { try {
file.file = PathUtils.normalizeLocalFilePath(file.file) if (file.status === FileStatus.Uploaded || file.status === FileStatus.Completed) continue
if (file.status === FileStatus.Uploaded || file.status === FileStatus.Completed) continue
const aFullPath = file.file.split('/') const aFullPath = file.file.split('/')
const fileName = aFullPath.pop() const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/' const filePath = aFullPath.join('/') + '/'
const file2Up = { ...file, recordId: cur.id, fileName, filePath } const file2Up = { ...file, recordId: cur.id, fileName, filePath }
const fileExists = await this.checkFileExists(file.file) result.push(file2Up)
if (!fileExists) {
this.reportError('【接待记录保存服务】 == 记录中有语音文件地址,但是文件不存在', { record: cur, file }, cur.id, file.file)
file2Up.status = FileStatus.NotExist
}
result.push(file2Up)
} catch (error) { } catch (error) {
this.reportError(`【接待记录保存服务】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file }) this.reportError(`【接待记录保存服务】 == 解析处理文件异常 error: ${error.message}`, { record: cur, file })
this._addToBlackList(cur.id, `Parse error: ${error.message}`) this._addToBlackList(cur.id, `Parse error: ${error.message}`)
...@@ -726,7 +731,7 @@ class RecordSaveService { ...@@ -726,7 +731,7 @@ class RecordSaveService {
() => { () => {
this._schedulerPump() this._schedulerPump()
}, },
Math.max(0, ms) ms
) )
} }
......
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
mergeRecordsToMain mergeRecordsToMain
} from './dbMerge.js' } from './dbMerge.js'
import { isRestrictedInternalPath, isOwnAppStoragePath } from './pathAccess.js' import { isRestrictedInternalPath, isOwnAppStoragePath } from './pathAccess.js'
import { resolveUniappSaveDir } from './docMediaMerge.js' import { resolveUniappSaveDir, resolveRecordDir } from './docMediaMerge.js'
import { verifyAndRepairRecordMediaPaths } from './recordMediaVerify.js' import { verifyAndRepairRecordMediaPaths } from './recordMediaVerify.js'
import { import {
planAlternateScan, planAlternateScan,
...@@ -290,7 +290,12 @@ class StoragePathMerge { ...@@ -290,7 +290,12 @@ class StoragePathMerge {
}) })
const appId = getAppId() const appId = getAppId()
const alternateSaveDirs = allAlternateRoots.map(root => resolveUniappSaveDir(root, appId)) // 备用副本目录必须同时包含 uniapp_save(历史 saveFile 副本)与 records(录音插件实际输出目录),
// 否则 verifyAndRepairRecordMediaPaths 永远找不到备用副本,包根切换后录音找不回。
const alternateSaveDirs = allAlternateRoots.flatMap(root => [
resolveUniappSaveDir(root, appId),
resolveRecordDir(root, appId)
])
if (scanPlan.skip) { if (scanPlan.skip) {
// 已在扫描计划里输出原因 // 已在扫描计划里输出原因
......
...@@ -14,6 +14,8 @@ export const MAIN_DB_PATH = `_doc/${DB_FILE}` ...@@ -14,6 +14,8 @@ export const MAIN_DB_PATH = `_doc/${DB_FILE}`
export const TEMP_DB_PATH = `_doc/${TEMP_DB_FILE}` export const TEMP_DB_PATH = `_doc/${TEMP_DB_FILE}`
/** 与 PathUtils.SAVE_DIR_NAME 一致 */ /** 与 PathUtils.SAVE_DIR_NAME 一致 */
export const UNIAPP_SAVE_DIR = 'uniapp_save' export const UNIAPP_SAVE_DIR = 'uniapp_save'
/** 录音插件实际输出目录:uni-recorder-x/utssdk/app-android/utils.uts 写死 `${dirPath}/records` */
export const RECORD_DIR = 'records'
/** 是否检测当前包根下扁平 zyzs.db(包根/zyzs.db,非 apps/.../doc) */ /** 是否检测当前包根下扁平 zyzs.db(包根/zyzs.db,非 apps/.../doc) */
export const ENABLE_LEGACY_FLAT_DB_MERGE = false export const ENABLE_LEGACY_FLAT_DB_MERGE = false
......
import { UNIAPP_SAVE_DIR } from './constants.js' import { UNIAPP_SAVE_DIR, RECORD_DIR } from './constants.js'
import { normalizePath } from './pathCache.js' import { normalizePath } from './pathCache.js'
export function resolveUniappSaveDir(packageRoot, appId) { export function resolveUniappSaveDir(packageRoot, appId) {
...@@ -6,6 +6,12 @@ export function resolveUniappSaveDir(packageRoot, appId) { ...@@ -6,6 +6,12 @@ export function resolveUniappSaveDir(packageRoot, appId) {
return `${root}/apps/${appId}/doc/${UNIAPP_SAVE_DIR}` return `${root}/apps/${appId}/doc/${UNIAPP_SAVE_DIR}`
} }
/** 录音实际所在目录(与 uni-recorder-x 的 records 对齐) */
export function resolveRecordDir(packageRoot, appId) {
const root = normalizePath(packageRoot)
return `${root}/apps/${appId}/doc/${RECORD_DIR}`
}
export function resolveDocRootFromPackageRoot(packageRoot, appId) { export function resolveDocRootFromPackageRoot(packageRoot, appId) {
const root = normalizePath(packageRoot) const root = normalizePath(packageRoot)
return `${root}/apps/${appId}/doc` return `${root}/apps/${appId}/doc`
......
...@@ -5,19 +5,14 @@ import { logStep, logStepFail } from './log.js' ...@@ -5,19 +5,14 @@ import { logStep, logStepFail } from './log.js'
const STAGE = '归并·媒体' const STAGE = '归并·媒体'
/** 与 UploadService.checkFileExists 一致:按表内路径用 uni.getFileInfo 判断可读 */ /** 与 RecordSaveService.checkFileExists 一致:表内路径可能是历史包根的绝对路径,
* targetSdk>=29 下 plus.io 读不到,必须走 fileIo.fileExists(Java File 优先 + plus.io 降级)。
* 否则会把"读不到"误判成"文件不存在",备用副本修复永远不触发。 */
export function checkMediaFileExists(filePath) { export function checkMediaFileExists(filePath) {
return new Promise(resolve => { if (!filePath || !String(filePath).toLowerCase().endsWith('.mp3')) {
if (!filePath || !String(filePath).toLowerCase().endsWith('.mp3')) { return Promise.resolve(false)
resolve(false) }
return return fileExists(filePath)
}
uni.getFileInfo({
filePath,
success: () => resolve(true),
fail: () => resolve(false)
})
})
} }
export function extractFileNameFromMediaPath(filePath) { export function extractFileNameFromMediaPath(filePath) {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!