Commit 7441db4b by 胡悦

Merge branch 'v1.0.7' of http://192.168.3.233:8090/glsx/gl_tape into v1.0.7

2 parents b58b4a3b ac346b4f
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:vue/recommended',
'plugin:prettier/recommended',
],
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: ['vue'],
rules: {
'no-underscore-dangle': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-unused-vars': 'warn',
'vue/component-name-in-template-casing': ['warn', 'kebab-case'],
'vue/multi-word-component-names': 'off',
'prefer-destructuring': 'off',
'no-plusplus': 'off',
},
globals: {
uni: 'readonly',
plus: 'readonly',
getCurrentPages: 'readonly',
getApp: 'readonly',
},
ignorePatterns: ['./pages.json', 'uni_modules', 'unpackage'],
};
\ No newline at end of file
{
"printWidth": 800,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "none",
"semi": false,
"wrap_line_length": 820,
"wrap_attributes": "auto",
"proseWrap": "always",
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "ignore",
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
"jsxBracketSameLine": true,
"files.insertFinalNewline": true,
"prettier.ignorePath": ".prettierignore",
"useTabs": false,
"eslintIntegration": false,
"overrides": [
{
"files": ".prettierrc",
"options": {
"parser": "json"
}
}
],
"endOfLine": "auto"
}
import { getOssToken } from "@/utils/ossUploadFile/uploadFile.js";
import Queue from "@/utils/Queue.js";
const interval = 60;
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js'
const interval = 60
export default {
onLoad() {},
data() {
return {
wv: null,
snapshot: null,
};
snapshot: null
}
},
mounted() {
this.init();
this.init()
},
methods: {
/**
......@@ -22,45 +22,41 @@ export default {
* @throws {Error} 如果初始化过程中出现错误,将抛出错误
*/
async init() {
this.wv = await this.initWebview();
await this.enQueue();
this.polling();
this.wv = await this.initWebview()
await this.enQueue()
this.polling()
},
/**
* 处理来自 UniApp 的消息
* 此函数接收一个包含消息详情的对象,并从其中解析出文件名、数据、记录标识、文件路径和客户端文件路径。如果消息代码为 0,表示上传成功,函数会调用 uploadSuccess 方法进行进一步处理。如果消息代码不为 0,则表示上传失败,函数会调用 polling 方法重新轮询。
* 处理消息函数
* 此函数用于处理接收到的消息
* 它解构参数对象,获取代码、文件名、数据、记录 ID、文件路径和客户端文件路径等信息
* 根据代码值决定下一步操作:若为 0,则上传成功,调用 uploadSuccess 函数;否则,开始轮询,调用 polling 函数
*
* @param {Object} result - 包含消息详情的对象
* @param {number} result.detail.data[0].code - 消息代码,0 表示上传成功
* @param {string} result.detail.data[0].fileName - 文件名
* @param {Object} result.detail.data[0].data - 包含文件路径的对象
* @param {string} result.detail.data[0].recordId - 记录标识,如果需要则进行后续处理
* @param {string} result.detail.data[0].filePath - 文件路径
* @param {string} [result.detail.data[0].filePathOnClient=filePath+fileName] - 客户端文件路径,默认为 filePath 和 fileName 的拼接
* @throws {Error} 如果消息中缺少必要的参数,将抛出错误
* @throws {Error} 如果解构对象时缺少关键属性,将抛出错误
*/
handlerMessage(result) {
const {
code,
fileName,
data,
recordId,
filePath,
filePathOnClient = filePath + fileName,
} = result.detail.data[0];
console.log(result.detail.data[0], "result.detail.data[0]");
const { code, fileName, data, recordId, filePath, filePathOnClient = filePath + fileName } = result.detail.data[0]
if (code == 0) {
this.uploadSuccess(
recordId,
data.oss.res.requestUrls[0].split("?")[0],
filePathOnClient,
fileName
);
const filePathOnServer = data.oss.res.requestUrls[0].split('?')[0]
this.uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName)
} else {
this.polling();
this.reportError(recordId,filePathOnClient)
this.polling()
}
},
/**
* 上报文件上传失败日志
*/
reportError(recordId, filePath) {
const { customerName, phoneNumber, carModel, staffName } =
uni.$recordManager.getRecordById(recordId) || {};
const { name } = uni.$storage.get("userInfo");
this.$sendSentry(
`上传失败:文件-${filePath} 手机号-${phoneNumber} 姓名-${customerName} 销售-${staffName} 车型-${carModel} 员工-${name}`
);
},
/**
* 初始化 WebView 的异步函数
* 这个函数返回一个 Promise,当初始化 WebView 完成时,它将解析为 WebView 对象。
* 在页面初始化调用时,这个函数会延迟 1 秒,以确保 WebView 对象已经创建。
......@@ -70,13 +66,13 @@ export default {
*/
initWebview() {
return new Promise((resolve, reject) => {
var currentWebview = this.$parent.$scope.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
var currentWebview = this.$parent.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
setTimeout(function () {
var wv = currentWebview.children()[0];
wv.setStyle({ top: "100%", height: 300 });
resolve(wv);
}, 1000); //如果是页面初始化调用时,需要延时一下
});
var wv = currentWebview.children()[0]
wv.setStyle({ top: '100%', height: 300 })
resolve(wv)
}, 1000) //如果是页面初始化调用时,需要延时一下
})
},
/**
* 入列操作
......@@ -90,10 +86,8 @@ export default {
* @throws {Error} 如果获取快照失败或扁平化数据失败,将抛出错误
*/
async enQueue() {
const _snapshot = await this.getRecordsSnapshotFlatten();
console.log(_snapshot, "_snapshot");
this.snapshot = new Queue(_snapshot);
console.log(this.snapshot, "_snapshot");
const _snapshot = await this.getRecordsSnapshotFlatten()
this.snapshot = new Queue(_snapshot)
},
/**
* 获取记录快照并展平数据
......@@ -105,10 +99,9 @@ export default {
* @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误
*/
async getRecordsSnapshotFlatten() {
const _records = await this.getRecordsSnapshot();
console.log(_records, "_records");
const _snapshot = this.flattenData(_records || []);
return _snapshot;
const _records = await this.getRecordsSnapshot()
const _snapshot = this.flattenData(_records || [])
return _snapshot
},
/**
* 将指定记录上传到服务器
......@@ -120,71 +113,100 @@ export default {
* @throws {Error} - 如果获取 OSS 令牌的过程中出现错误,将抛出错误
*/
async uploadRecord(record) {
const { lsaccessKeySecret, securityToken, lsaccessKeyId } =
await getOssToken();
console.log(record, "record");
this.wv.evalJS(
`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`
);
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
},
/**
* 处理上传成功后的逻辑
* 此函数在文件上传成功后被调用,它会更新本地记录的文件路径,
* 并根据情况决定是保存记录还是重新上传记录。
* 文件上传成功后的处理逻辑
* 这个函数在文件上传成功后执行,它接受四个参数:recordId、filePathOnServer、filePathOnClient 和 fileName
* 函数首先获取记录锁,然后尝试获取对应的记录。如果记录存在,它将客户端路径的文件记录更新为服务器路径,并移除 client 文件。
* 接着,它调用一个名为 _saveOrUpdate 的私有方法,这个方法可能会上传记录。
* 无论是尝试获取记录失败,还是在处理过程中出现任何其他错误,都会被捕获并作为 error 参数传递给 Promise.reject 方法,表明发生错误。
* 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。
*
* @async
* @param {string} recordId - 记录的唯一标识符
* @param {string} recordId - 要更新的记录的 ID
* @param {string} filePathOnServer - 文件在服务器上的新路径
* @param {string} filePathOnClient - 文件在客户端的原始路径
* @param {string} fileName - 文件名
* @returns {void} - 此函数不返回任何值
* @throws {error} - 如果在尝试获取记录或保存记录时发生错误,将抛出错误
* @param {string} filePathOnClient - 文件在客户端的旧路径
* @param {string} fileName - 文件的原始名称
* @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误
*/
async uploadSuccess(
recordId,
filePathOnServer,
filePathOnClient,
fileName
) {
const unlock = await uni.$recordManager.lock();
async uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) {
const unlock = await uni.$recordManager.lock()
try {
const record = uni.$recordManager.getRecordById(recordId);
if (!record) return;
const recordFileList = record.recordUrlList;
recordFileList.forEach((fileInfo) => {
if (
fileInfo.file === filePathOnClient ||
fileInfo.file.endsWith(fileName)
) {
fileInfo.file = filePathOnServer;
delete fileInfo.status;
}
});
//删除客户端的文件
uni.removeSavedFile({
filePath: filePathOnClient,
complete: function (res) {
console.log(res);
},
});
if (recordFileList.every((i) => i.status == undefined)) {
const pathArr = recordFileList.map((i) => i.file);
const params = { ...record, recordUrlList: pathArr };
const res = await uni.$api.commonApi.saveRecCustomer(params);
console.log(params, res, "record");
if (res) {
uni.$recordManager.removeRecord(recordId);
}
} else {
uni.$recordManager.updateRecord(record);
}
const record = uni.$recordManager.getRecordById(recordId)
if (!record) return
this._changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName)
this._removeFileOnClient(filePathOnClient)
await this._saveOrUpdate(record)
} catch (err) {
Promise.reject(error);
Promise.reject(error)
} finally {
unlock();
this.polling();
unlock()
this.polling()
}
},
/**
* 将记录中的文件路径更改为服务器路径
* 此函数遍历记录中的每个文件信息对象
* 将文件信息对象中的 file 属性值与 filePathOnClient 或 fileName 进行比较
* 如果匹配,则将 file 属性更新为 filePathOnServer,并删除 status 属性
*
* @param {Object} record - 包含文件信息列表的记录对象
* @param {string} filePathOnClient - 需要替换的客户端文件路径
* @param {string} filePathOnServer - 需要更新的服务器文件路径
* @param {string} fileName - 需要替换的文件名
* @throws {Error} 如果 record 参数无效或 recordFileList 属性不存在,将抛出错误
*/
_changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) {
record.recordUrlList?.forEach(fileInfo => {
if (fileInfo.file === filePathOnClient || fileInfo.file.endsWith(fileName)) {
fileInfo.file = filePathOnServer
delete fileInfo.status
}
})
},
/**
* 从客户端移除文件
* 此函数使用 uni.removeSavedFile 方法删除指定路径的文件。该方法是一个异步操作,完成时会调用传入的 complete 回调函数。
*
* @param {string} filePathOnClient - 要删除的文件在客户端的文件路径
* @param {Object} complete - (可选) uni.removeSavedFile 完成时调用的回调函数。函数参数是一个包含 statusCode 和 errMsg 的对象。
* @throws {Error} 如果 filePathOnClient 参数无效或文件删除过程中发生错误,将抛出错误
*/
_removeFileOnClient(filePathOnClient) {
//删除客户端的文件
uni.removeSavedFile({
filePath: filePathOnClient,
complete: function (res) {
console.log(res)
}
})
},
/**
* 保存或更新记录
* 这个函数检查记录中的文件列表,以确定是保存还是更新记录
* 如果所有文件记录条目状态都为未定义,函数将创建一个新的记录对象,调用保存 API,并在成功时移除记录
* 如果文件记录条目状态不全为未定义,函数将更新记录
*
* @async
* @param {Object} record - 要保存或更新的记录对象
* @throws {Error} 如果在保存或更新记录时发生错误,将抛出错误
*/
async _saveOrUpdate(record) {
if (record.recordUrlList?.every(i => i.status == undefined)) {
const pathArr = record.recordUrlList.map(i => i.file)
const params = { ...record, recordUrlList: pathArr }
const res = await uni.$api.commonApi.saveRecCustomer(params)
if (res) {
uni.$recordManager.removeRecord(record.id)
}
} else {
uni.$recordManager.updateRecord(record.id)
}
},
/**
* 获取记录快照的异步函数
* 此函数获取当前记录列表的快照,并返回这些记录
*
......@@ -192,10 +214,10 @@ export default {
* @returns {Promise<Array>} 解析为包含记录列表的 Promise
*/
async getRecordsSnapshot() {
const unlock = await uni.$recordManager.lock();
const records = uni.$recordManager.getRecords();
unlock();
return records;
const unlock = await uni.$recordManager.lock()
const records = uni.$recordManager.getRecords()
unlock()
return records
},
/**
* 展开数据
......@@ -207,54 +229,79 @@ export default {
flattenData(records) {
const result = records.reduce((acc, cur) => {
acc = acc.concat(
cur.recordUrlList.map((file) => {
const aFullPath = file.file.split("/");
const fileName = aFullPath.pop();
const filePath = aFullPath.join("/") + "/";
return { ...file, recordId: cur.id, fileName, filePath };
cur.recordUrlList.map(file => {
const aFullPath = file.file.split('/')
const fileName = aFullPath.pop()
const filePath = aFullPath.join('/') + '/'
return { ...file, recordId: cur.id, fileName, filePath }
})
);
return acc;
}, []);
return result;
)
return acc
}, [])
return result
},
/**
* 轮询函数
* 这个函数的目的是在一定条件下,通过持续轮询来执行上传记录的操作。它检查一个队列(snapshot)的大小。如果队列为空,它会等待十分钟(1000 毫秒 * 60 秒 * 10 分钟)后再次检查。如果队列中有记录,它会取出一条记录并上传它。
* 这个函数用于检查一个队列的大小,并在需要时执行文件上传操作
* 如果队列大小为 0,则调用 enQueue() 函数来获取新的文件进行上传,并延迟一段时间后再次轮询
* 如果队列不为 0,则从队列中取出一个记录并调用 uploadRecord(record) 函数进行上传
* 如果在获取网络状态或上传过程中出现错误,它将捕获错误并在指定的时间间隔后重新开始轮询
*
* @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
*/
polling() {
console.log(this.snapshot.size, "this.snapshot.size");
if (this.snapshot === null) return;
uni
.$isNetWork()
.then(() => {
this.upload();
})
.catch(() => {
this.pollingLater(interval);
});
console.log(this.snapshot.size, 'this.snapshot.size')
if (this.snapshot === null) return
// prettier-ignore
uni.$isNetWork().then(this.upload).catch(() =>this.pollingLater(interval))
},
/**
* 上传文件或执行队列操作
* 检查队列大小,以确定是上传单个文件还是通过 enQueue() 函数获取新的文件进行上传
*
* @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
*/
upload() {
if (this.snapshot.size == 0) {
this.enQueue();
this.pollingLater(interval);
this.enQueue()
this.pollingLater(interval)
} else {
const record = this.snapshot.dequeue();
this.uploadRecord(record);
const record = this.snapshot.dequeue()
this.uploadRecord(record)
}
},
/**
* 停止轮询并清除队列
* 这个函数用于停止轮询操作,并清除队列中的所有记录
* 首先,它调用 snapshot.clear() 方法清除队列
* 然后,它将 snapshot 对象设置为 null,以释放资源并停止轮询
*/
stopPolling() {
this.snapshot.clear();
this.snapshot = null;
this.snapshot.clear()
this.snapshot = null
},
/**
* 在指定的时间间隔后启动轮询
* 这个函数用于在指定的时间间隔后执行轮询操作
* @param {number} [interval=60*10] - 轮询间隔(默认为10分钟)
* @returns {void} - 此函数不返回任何值
*/
pollingLater(interval = 60 * 10) {
setTimeout(() => {
this.polling();
}, interval * 1000);
},
this.polling()
}, interval * 1000)
}
},
/**
* 在组件销毁之前执行的生命周期函数
* 这个函数在组件被销毁之前被调用,可以在这里进行一些清理工作
* 在这个例子中,使用 console.log 输出 'topPolling',并调用 this.stopPolling() 方法
*
* @private
* @returns {void} 没有返回值
* @throws {Error} 调用 this.stopPolling() 时可能出现的错误
*/
beforeDestroy() {
console.log("stopPolling");
this.stopPolling();
},
};
this.stopPolling()
}
}
This diff could not be displayed because it is too large.
{
"dependencies": {
"dayjs": "^1.11.11",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"hammerjs": "^2.0.8",
"prettier": "^3.3.2",
"webpack-spritesmith": "^1.1.0"
}
}
import { storageApi } from "./cache";
import utils from "./utils";
import { storageApi } from './cache'
import utils from './utils'
/**
* 记录管理器类
* 用于管理记录列表
......@@ -13,9 +13,9 @@ class RecordManager {
// this.fileSaveFolderOnClient = utils.getFileSaveFolderOnClient();
}
// 单例模式
static instance = null;
static instance = null
// 读写锁
locker = false;
locker = false
/**
* 获取 RecordManager 的单例实例
* 如果 instance 不存在,则创建一个新实例并赋值给 instance
......@@ -23,9 +23,9 @@ class RecordManager {
*/
static getInstance() {
if (!RecordManager.instance) {
RecordManager.instance = new RecordManager();
RecordManager.instance = new RecordManager()
}
return RecordManager.instance;
return RecordManager.instance
}
/**
* 异步获取锁
......@@ -34,22 +34,22 @@ class RecordManager {
* @return {Promise} 一个 Promise,在锁可用时兑现,并返回一个解锁函数
*/
async lock() {
return new Promise((resolve) => {
return new Promise(resolve => {
if (this.locker) {
setTimeout(() => {
this.lock();
}, 100);
this.lock()
}, 100)
} else {
this.locker = true;
resolve(this.unlock.bind(this));
this.locker = true
resolve(this.unlock.bind(this))
}
});
})
}
/**
* 释放本地存储的读写锁
*/
unlock() {
this.locker = false;
this.locker = false
}
/**
......@@ -59,10 +59,10 @@ class RecordManager {
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record) {
const records = this.getRecords() || [];
records.push(record);
this.setRecords(records);
return records;
const records = this.getRecords() || []
records.push(record)
this.setRecords(records)
return records
}
/**
* 移除一个ID对应的记录
......@@ -71,10 +71,10 @@ class RecordManager {
* @returns {Array} - 移除记录后的更新后的记录列表
*/
async removeRecord(id) {
let records = this.getRecords();
records = records.filter((i) => i.id !== id);
this.setRecords(records);
return records;
let records = this.getRecords()
records = records.filter(i => i.id !== id)
this.setRecords(records)
return records
}
/**
* 获取并移除当前对象记录列表中的最后一条记录
......@@ -82,8 +82,8 @@ class RecordManager {
* @returns {Object} - 被移除的最后一条记录对象,如果记录列表为空,则返回 undefined
*/
getRecord() {
const records = this.getRecords();
return records.pop();
const records = this.getRecords()
return records.pop()
}
/**
* 根据给定的 ID 获取一条记录
......@@ -93,8 +93,8 @@ class RecordManager {
*
*/
getRecordById(id) {
const records = this.getRecords();
return records.find((i) => i.id === id);
const records = this.getRecords()
return records.find(i => i.id === id)
}
/**
* 获取记录列表
......@@ -102,7 +102,7 @@ class RecordManager {
* @returns {Array} - 从 storageApi 获取的记录列表
*/
getRecords() {
return storageApi.getRecords();
return storageApi.getRecords()
}
/**
* 设置记录列表
......@@ -111,41 +111,63 @@ class RecordManager {
* @returns {void} - 此函数不返回任何值
*/
setRecords(records) {
storageApi.setRecords(records);
storageApi.setRecords(records)
}
/**
* 更新记录数组中的记录
* 这个函数用于更新给定记录数组中的特定记录
* 它接受一个参数 record,该参数是要更新的记录对象
*
* @param {Object} record - 要更新的记录对象,必须包含一个唯一的 id 属性
* @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误
*/
updateRecord(record) {
const records = this.getRecords();
const index = records.findIndex((i) => i.id === record.id);
const records = this.getRecords()
const index = records.findIndex(i => i.id === record.id)
if (index !== -1) {
records[index] = record;
this.setRecords(records);
records[index] = record
this.setRecords(records)
}
}
/**
* 兼容模式的异步处理函数
* 这个函数用于处理在兼容模式下的文件路径转换和记录属性的修正
* 它首先获取一个锁,以确保在操作过程中数据的一致性
* 然后,它获取客户端文件保存文件夹的路径,并检查是否获取成功
* 接着,它获取所有的记录,并对每个记录执行以下操作:
* - 检查记录的 recordUrlList 是否存在且不为空,对于每个 URL,判断其是否以 'file://' 开头
* - 如果不是,使用路径中的文件名构建一个新的客户端文件路径,并替换掉原来的 URL
* - 如果记录没有 id 属性,随机生成一个 UUID 并设置为记录的 id
*
* 在处理过程中,如果发生任何错误,它将抛出该错误
* 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。
*
* @async
* @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误
*/
async compatible() {
const unlock = await this.lock();
let path = await utils.getFileSaveFolderOnClient();
const unlock = await this.lock()
let path = await utils.getFileSaveFolderOnClient()
try {
let records = this.getRecords();
records.forEach((i) => {
let records = this.getRecords()
records.forEach(i => {
if (i.recordUrlList && i.recordUrlList.length) {
i.recordUrlList.forEach(async (j) => {
if (!j.file.startsWith("file://")) {
const fileName = j.file.split("/").pop();
j.file = path + fileName;
i.recordUrlList.forEach(async j => {
if (!j.file.startsWith('file://')) {
const fileName = j.file.split('/').pop()
j.file = path + fileName
}
});
})
}
if (!i.id) {
i.id = utils.uuid();
i.id = utils.uuid()
}
});
console.log(records);
this.setRecords(records);
})
this.setRecords(records)
} catch (e) {
throw e;
throw e
} finally {
unlock();
unlock()
}
}
......@@ -155,7 +177,7 @@ class RecordManager {
* @returns {void} - 此函数不返回任何值
*/
clearRecords() {
storageApi.removeRecords();
storageApi.removeRecords()
}
}
export default RecordManager;
export default RecordManager
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!