Przeglądaj źródła

添加下载数据时候判断业务数据逻辑,添加数据库删除方法

zhangxike 4 dni temu
rodzic
commit
bfa3f37d9a
5 zmienionych plików z 291 dodań i 67 usunięć
  1. 53 1
      api/work.uts
  2. 7 7
      pages/work/index.uvue
  3. 12 2
      pages/work/record/InfoList.uvue
  4. 92 35
      utils/dataProcessor.uts
  5. 127 22
      utils/sqlite.uts

+ 53 - 1
api/work.uts

@@ -1,5 +1,5 @@
 // #ifdef APP-ANDROID
-import { selectTableData, insertTableData, updateTableData, selectJoinTableData, selectRecordData, selectRecordInfo } from '@/utils/sqlite'
+import { selectTableData, insertTableData, updateTableData, selectJoinTableData, selectRecordData, selectRecordInfo, selectLatestInfoData, deleteTableData } from '@/utils/sqlite'
 // #endif
 
 export type Download = {
@@ -193,6 +193,58 @@ export async function saveMediaRecord(values : string) : Promise<UTSJSONObject>
 	}
 	// #endif
 
+	// #ifdef H5
+	return offlineData({ success: true, data: [] } as UTSJSONObject);
+	// #endif
+}
+
+
+export async function getLatestRecord(productNo:string , initData ?: UTSJSONObject | null) : Promise<UTSJSONObject> {
+	// #ifdef APP-ANDROID
+	const result = await selectLatestInfoData(productNo);
+	console.log(result);
+	return result;
+	// #endif
+
+	// #ifdef H5
+	return offlineData({ success: true, data: [] } as UTSJSONObject)
+	// #endif
+}
+
+export async function removeTableData(tableName:string, field: string, value: string) : Promise<UTSJSONObject> {
+	// #ifdef APP-ANDROID
+
+	try {
+		// 调用sqlite的删除方法
+		const result = await deleteTableData(tableName, field, value);
+		console.log('删除数据成功:', result);
+		return result;
+	} catch (error) {
+		console.error('删除数据失败:', error);
+		return { errMsg: '删除失败', data: [] as any[] } as UTSJSONObject;
+	}
+	// #endif
+
+	// #ifdef H5
+	return offlineData({ success: true, data: [] } as UTSJSONObject);
+	// #endif
+}
+
+
+export async function removeInfoAndRecord(value:string) : Promise<UTSJSONObject> {
+	// #ifdef APP-ANDROID
+	
+	try {
+		// 调用sqlite的删除方法
+		const result = await deleteTableData('app_media_record', 'pid', value);
+		const result2 = await deleteTableData('app_media_info', 'pdid', value);
+		return result;
+	} catch (error) {
+		console.error('删除数据失败:', error);
+		return { errMsg: '删除失败', data: [] as any[] } as UTSJSONObject;
+	}
+	// #endif
+	
 	// #ifdef H5
 	return offlineData({ success: true, data: [] } as UTSJSONObject);
 	// #endif

+ 7 - 7
pages/work/index.uvue

@@ -52,13 +52,13 @@
       return {
 		items: [
 		      {colorClass: 'blue', iconType: "person-filled", text: "用户管理",path:"/pages/mine/index" },
-			  {colorClass: 'blue', iconType: "download", text: "数据下载",path:"/pages/work/download/DownloadList" },
-			  {colorClass: 'blue', iconType: "list", text: "任务管理",path:"/pages/work/task/TaskList" },
-			  {colorClass: 'orange', iconType: "mic", text: "声像记录", path:"/pages/work/record/InfoList"},
-			  {colorClass: 'orange', iconType: "calendar", text: "检验记录",path:"/pages/work/report/InspectionList" },
-			  {colorClass: 'orange', iconType: "gear-filled", text: "关键工序",path:"/pages/work/process/ProcessList" },
-			  {colorClass: 'green', iconType: "folder-add-filled", text: "文档查阅",path:"" },
-			  {colorClass: 'green', iconType: "cloud-upload", text: "数据上传",path:"" },
+			  {colorClass: 'blue', iconType: "list", text: "检验任务",path:"/pages/work/download/DownloadList" },
+			  // {colorClass: 'blue', iconType: "list", text: "任务管理",path:"/pages/work/task/TaskList" },
+			  {colorClass: 'orange', iconType: "camera", text: "声像记录", path:"/pages/work/record/InfoList"},
+			  // {colorClass: 'orange', iconType: "calendar", text: "检验记录",path:"/pages/work/report/InspectionList" },
+			  // {colorClass: 'orange', iconType: "gear-filled", text: "关键工序",path:"/pages/work/process/ProcessList" },
+			  // {colorClass: 'green', iconType: "folder-add-filled", text: "文档查阅",path:"" },
+			  // {colorClass: 'green', iconType: "cloud-upload", text: "数据上传",path:"" },
 			  {colorClass: 'green', iconType: "wallet-filled", text: "日志管理",path:"" }
 		] as Item[],
         current: 0 as number,

+ 12 - 2
pages/work/record/InfoList.uvue

@@ -163,11 +163,21 @@
   const download = async (e : any) => {
     console.log("开始下载...")
     // 调用数据处理工具中的方法下载数据
-    await downloadDataFromAPI(() => {
+	if(productNo.value == null || productNo.value == '') {
+		uni.showToast({
+		  title: '请先扫描或者输入产品号',
+		  icon: 'error'
+		});
+		return
+	}
+	
+    await downloadDataFromAPI(productNo.value, () => {
       
     }).then((res) => {
       // 刷新整个页面
-      uni.reLaunch({ url: '/pages/work/record/InfoList' })
+	  if (res) {
+		  uni.reLaunch({ url: '/pages/work/record/InfoList' })
+	  }
     })
   }
   

+ 92 - 35
utils/dataProcessor.uts

@@ -1,5 +1,5 @@
 import { getToken, getTokenFromApi } from './auth'
-import { saveMediaInfo, saveMediaRecord } from '@/api/work'
+import { saveMediaInfo, saveMediaRecord, getLatestRecord, removeInfoAndRecord } from '@/api/work'
 
 // 类型定义保持不变
 export type ApiResponse = {
@@ -42,64 +42,120 @@ export type MediaRecordData = {
 	updateuser ?: string;
 }
 
-export const downloadDataFromAPI = async (callback ?: () => void) : Promise<boolean> => {
+export const downloadDataFromAPI = async (productCode: string, callback ?: () => void) : Promise<boolean> => {
   try {
+	//校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
+	//如果没有则直接保存。如果有存在已经在执行的产品号,则提示已存在执行中的任务
+	const infoJson = await getLatestRecord(productCode, null);
+	let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
+	let ingNum = parseInt(info?.['statusRecordCount'] as string);
+	//覆盖标识位
+	let overwiteFlag = ref(false);
+	// 先检查是否有任务正在执行中
+	if (info != null && ingNum > 0) {
+		uni.showToast({ title: `当前产品号已有任务在执行中!`, icon: 'error' });
+		return false;
+	}
+	// 使用Promise来处理异步流程
+	let deleteDataPromise = new Promise<boolean>((resolve) => {
+		if(info != null && ingNum == 0) {
+			//可以被覆盖,需要有提示框,给用户确认
+			uni.showModal({
+				title: '系统提示',
+				content: '该产品号已存在任务是否覆盖掉?',
+				cancelText: '取消',
+				confirmText: '确定',
+				success: function (res) {
+					if (res.confirm) {
+						// 标记为需要覆盖
+						overwiteFlag.value = true;
+						// 执行删除数据操作
+						let pid = info?.['pdid'] as string;
+						removeInfoAndRecord(pid).then((recordDelResponse) => {
+							console.log('删除数据响应:', recordDelResponse);
+							// 删除成功,解析Promise并允许继续执行
+							// 确保模态框已完全关闭后再解析Promise
+							setTimeout(() => {
+								resolve(true);
+							}, 300);
+						}).catch((error) => {
+							console.error('删除数据失败:', error);
+							uni.showToast({ title: '删除旧数据失败', icon: 'error' });
+							resolve(false);
+						});
+					} else {
+						// 用户取消覆盖
+						overwiteFlag.value = false;
+						resolve(false);
+					}
+				}
+			});
+		} else {
+			// 不需要显示确认框,直接解析Promise
+			resolve(true);
+		}
+	});
+	
+	// 等待删除数据操作完成
+	const canContinue: boolean = await deleteDataPromise;
+	if (!canContinue) {
+		// 如果不能继续(删除失败或用户取消),则终止函数执行
+		return false;
+	}
+
+	// 继续执行后续代码...
     const apiToken = await getTokenFromApi();
-    uni.showLoading({ title: '数据下载中...' })
+    uni.showLoading({ title: '数据下载中...' });
 
+    // 使用Promise处理HTTP请求,避免嵌套Promise
     return new Promise<boolean>((resolve) => {
-      //http://127.0.0.1:4523/m1/7190626-6915798-default/m1/download
       uni.request({
-        url: 'http://192.168.43.62:4523/m1/7190626-6915798-default/loadQmImagetask?prodcode=YH07202507000005',
+        url: `http://192.168.43.62:4523/m1/7190626-6915798-default/loadQmImagetask?prodcode=${productCode}`,
         method: 'GET',
         header: {
           'token': apiToken
         },
         success: (res) => {
-          console.log('请求成功:', res);
-          console.log('token', apiToken);
-          console.log(res.data);
-          let singleObject = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
+          let singleObject = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
           if (singleObject != null && singleObject.code == 666) {
-            let mediaInfoList = singleObject?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
+            let mediaInfoList = singleObject?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
             if (mediaInfoList != null && mediaInfoList.length > 0) {
               mediaInfoList.forEach(item => {
                 if (item != null) {
                   let data = JSON.parse<MediaInfoData>(item.toJSONString());
                   if (data != null) {
-                    saveMediaInfo(item).then((res : UTSJSONObject) => {
-                      const lastIdStr = res?.['lastId'] as string | null;
+                    saveMediaInfo(item).then((resSave : UTSJSONObject) => {
+                      const lastIdStr = resSave?.['lastId'] as string | null;
                       const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
                       if (lastId != null) {
-                        let recordList = data?.['qmImageTaskClist'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
-                        console.log(recordList)
+                        let recordList = data?.['qmImageTaskClist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
                         if (recordList != null && recordList.length > 0) {
                           for(var i =0; i< recordList.length; i++) {
-                            // 将recordList[i]断言为MediaRecordData类型
                             const record: MediaRecordData = recordList[i] as MediaRecordData;
-                            console.log('完整对象:', record);
-                             
+
                             // 获取各个字段的值
-                            const senum = record.senum; // string类型
-                            const photoitem = record.photoitem; // string类型
-                            const part = record.part; // string类型
-                            const partno = record.partno; // string类型
-                            const descb = record.descb; // string类型
-                            const num = record.num; // number类型
-                            const urlspl = record.urlspl; // string类型
-                            const imgname = record.imgname; // string类型
-                            const urlpdt = record.urlpdt; // string类型
-                            const createtime = record.createtime; // string类型
-                            const createuser = record.createuser; // string类型
-                            const updatetime = record.updatetime; // string类型
-                            const updateuser = record.updateuser; // string类型
+                            const senum = record.senum;
+                            const photoitem = record.photoitem;
+                            const part = record.part;
+                            const partno = record.partno;
+                            const descb = record.descb;
+                            const num = record.num;
+                            const urlspl = record.urlspl;
+                            const imgname = record.imgname;
+                            const urlpdt = record.urlpdt;
+                            const createtime = record.createtime;
+                            const createuser = record.createuser;
+                            const updatetime = record.updatetime;
+                            const updateuser = record.updateuser;
 
-                            //senum,photoitem,productno,part,partno,descb,num,status,date,urlspl,imgname,urlpdt,createtime,createuser,updatetime,updateuser,pid
                             // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
-                            var values = `${senum === null ? '1' : `'${senum}'`}, ${photoitem === null ? 'null' : `'${photoitem}'`}, ${data?.['productcode'] === null ? 'null' : `'${data?.['productcode']}'`},${part === null ? 'null' : `'${part}'`},${partno === null ? 'null' : `'${partno}'`},${descb === null ? 'null' : `'${descb}'`},${num === null ? 0 : num},1,'', ${urlspl === null ? 'null' : `'${urlspl}'`},${imgname === null ? 'null' : `'${imgname}'`},${urlpdt === null ? 'null' : `'${urlpdt}'`}, ${createtime === null ? 'null' : `'${createtime}'`}, ${createuser === null ? 'null' : `'${createuser}'`}, ${updatetime === null ? 'null' : `'${updatetime}'`}, ${updateuser === null ? 'null' : `'${updateuser}'`}, ${lastId === null ? 0 : lastId}`
-                            saveMediaRecord(values)
-                            uni.showToast({ title: `下载完成`, icon: 'success' });
+                            var values = `${senum === null ? '1' : `'${senum}'`}, ${photoitem === null ? 'null' : `'${photoitem}'`}, ${data?.['productcode'] === null ? 'null' : `'${data?.['productcode']}'`},${part === null ? 'null' : `'${part}'`},${partno === null ? 'null' : `'${partno}'`},${descb === null ? 'null' : `'${descb}'`},${num === null ? 0 : num},1,'', ${urlspl === null ? 'null' : `'${urlspl}'`},${imgname === null ? 'null' : `'${imgname}'`},${urlpdt === null ? 'null' : `'${urlpdt}'`}, ${createtime === null ? 'null' : `'${createtime}'`}, ${createuser === null ? 'null' : `'${createuser}'`}, ${updatetime === null ? 'null' : `'${updatetime}'`}, ${updateuser === null ? 'null' : `'${updateuser}'`}, ${lastId === null ? 0 : lastId}`;
+                            saveMediaRecord(values);
                           }
+                          // 延迟显示完成提示,确保所有数据保存完成
+                          setTimeout(() => {
+                            uni.showToast({ title: `下载完成`, icon: 'success' });
+                          }, 500);
                         }
                       } else {
                         console.log('保存媒体信息成功,但未获取到主键ID');
@@ -110,7 +166,8 @@ export const downloadDataFromAPI = async (callback ?: () => void) : Promise<bool
               });
             }
           } else {
-            uni.showToast({ title: `请求失败: ${singleObject.msg}`, icon: 'error' });
+              const errorMsg = singleObject.msg != null ? singleObject.msg : '未知错误';
+              uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
           }
           resolve(true);
         },

+ 127 - 22
utils/sqlite.uts

@@ -424,27 +424,27 @@ export function selectRecordData(
 export function selectRecordInfo() : Promise<UTSJSONObject> {
 
 	var sql = `SELECT
-							m.*,
-							COUNT(r_stats.photoitem) AS totalRecord,
-							SUM(r_stats.is_status_3_4) AS statusRecordCount,
-							SUM(r_stats.is_status_4) AS status4RecordCount
-						FROM
-							app_media_info m
-						LEFT JOIN (
-							SELECT
-								r.pid,
-								r.photoitem,
-								MAX(CASE WHEN r.status IN (3,4) THEN 1 ELSE 0 END) AS is_status_3_4,
-								MAX(CASE WHEN r.status = 4 THEN 1 ELSE 0 END) AS is_status_4
-							FROM
-								app_media_record r
-							GROUP BY
-								r.pid, r.photoitem
-						) AS r_stats ON m.pdid = r_stats.pid
-						GROUP BY
-							m.pdid
-						ORDER BY
-							m.pdid DESC`;
+					m.*,
+					COUNT(r_stats.photoitem) AS totalRecord,
+					SUM(r_stats.is_status_3_4) AS statusRecordCount,
+					SUM(r_stats.is_status_4) AS status4RecordCount
+				FROM
+					app_media_info m
+				LEFT JOIN (
+					SELECT
+						r.pid,
+						r.photoitem,
+						MAX(CASE WHEN r.status IN (3,4) THEN 1 ELSE 0 END) AS is_status_3_4,
+						MAX(CASE WHEN r.status = 4 THEN 1 ELSE 0 END) AS is_status_4
+					FROM
+						app_media_record r
+					GROUP BY
+						r.pid, r.photoitem
+				) AS r_stats ON m.pdid = r_stats.pid
+				GROUP BY
+					m.pdid
+				ORDER BY
+					m.pdid DESC`;
 
 
 	const sqlite = createSQLiteContext(dbName);
@@ -473,4 +473,109 @@ export function selectRecordInfo() : Promise<UTSJSONObject> {
 
 }
 
- 
+
+// 普通函数
+// 查询获取数据库里的最新的一条数据 sql:'SELECT * FROM dbTable WHERE lname = 'lvalue' ORDER BY pdid desc LIMIT 1'
+// 查询 SELECT * FROM 、 dbTable 是表名、 WHERE 查找条件 lname,lvalue 是查询条件的列名和列值
+// @param {Object} dbTable:表名
+// @param {Object} lname:列名
+// @param {Object} lvalue:列中的属性值
+export function selectLatestInfoData (
+  productNo?: string,
+):Promise<UTSJSONObject>
+{
+  var sql = `SELECT
+					m.*,
+					COUNT(r_stats.photoitem) AS totalRecord,
+					SUM(r_stats.is_status_3_4) AS statusRecordCount,
+					SUM(r_stats.is_status_4) AS status4RecordCount
+				FROM
+					app_media_info m
+				LEFT JOIN (
+					SELECT
+						r.pid,
+						r.photoitem,
+						MAX(CASE WHEN r.status IN (3,4) THEN 1 ELSE 0 END) AS is_status_3_4,
+						MAX(CASE WHEN r.status = 4 THEN 1 ELSE 0 END) AS is_status_4
+					FROM
+						app_media_record r
+          where productno = '${productNo}'
+					GROUP BY
+						r.pid, r.photoitem
+				) AS r_stats ON m.pdid = r_stats.pid
+        where productno = '${productNo}'
+				GROUP BY
+					m.pdid
+				ORDER BY
+					m.pdid DESC
+          LIMIT 1`;
+  const sqlite = createSQLiteContext(dbName);
+  
+  return new Promise<UTSJSONObject>((resolve, reject) => {
+    const selectSqlOptions ={		
+  	  sql: sql,
+  	  success: (e: selectSqlOptionsResult) => {
+  	    console.log(e)
+  		
+  	  },
+  	  fail: (e: selectSqlOptionsResult) => {
+  	    console.error(e)
+  	  }		
+    } as selectSqlOptions
+  
+    const info = sqlite.selectSql(selectSqlOptions) as selectSqlOptionsResult
+    
+    const ret = {
+  	  errMsg: info?.errMsg ?? '',
+  	  data: info?.data[0] ?? ''
+    } as UTSJSONObject
+    resolve(ret)
+  });	
+  
+ } 
+ 
+ 
+ export function deleteTableData(
+ 	dbTable: string,
+ 	field : string,
+	value : string
+ ) : Promise<UTSJSONObject> {
+ 
+ 	var sql = '';
+ 	if (field !== null && dbTable !== null) {
+ 		sql = `delete from ${dbTable} where ${field} = '${value}'`
+ 		console.log(sql);	
+ 		const sqlite = createSQLiteContext(dbName);
+ 		// WHERE 前面是要修改的列名、列值,后面是条件的列名、列值
+ 		return new Promise((resolve, reject) => {
+ 		  const executeSqlOptions ={
+ 		  		  sql: sql,
+ 		  		  success: (e: executeSqlOptionsResult) => {
+ 		  		    console.log(e)
+ 		  			
+ 		  		  },
+ 		  		  fail: (e: executeSqlOptionsResult) => {
+ 		  		    console.error(e)
+ 		  		  }		
+ 		  } as executeSqlOptions
+ 		  
+ 		  const info = sqlite.executeSql(executeSqlOptions) as executeSqlOptionsResult
+ 		  console.log(info)
+ 		  const ret = {
+ 		  	errMsg: info?.errMsg ?? '',
+ 		  	data: info?.data ?? ['']
+ 		  } as UTSJSONObject
+ 		  sqlite.close();
+ 		  resolve(ret)
+ 		  
+ 		})
+ 	} else {
+ 		return new Promise<UTSJSONObject>((resolve, reject) => {
+ 			const ret = {
+ 				errMsg: '错误查询',
+ 				data: ['参数不存在']
+ 			} as UTSJSONObject
+ 			resolve(ret);
+ 		})
+ 	}
+ }