浏览代码

导入excel调整

maixinrong 5 年之前
父节点
当前提交
78c1300c0f
共有 5 个文件被更改,包括 193 次插入12 次删除
  1. 46 1
      app/controller/ledger_controller.js
  2. 25 1
      app/lib/analysis_excel.js
  3. 91 0
      app/public/js/global.js
  4. 15 3
      app/public/js/ledger.js
  5. 16 7
      app/view/shares/import_excel_modal.ejs

+ 46 - 1
app/controller/ledger_controller.js

@@ -23,6 +23,7 @@ const LzString = require('lz-string');
 const accountGroup = require('../const/account_group').group;
 const path = require('path');
 const exportExcel = require('../lib/export_excel');
+const xlsx = require('js-xlsx');
 
 module.exports = app => {
 
@@ -499,8 +500,52 @@ module.exports = app => {
                 this.log(err);
                 ctx.body = { err: 1, msg: err.toString(), data: null };
             }
-
         }
+        // async uploadExcel(ctx) {
+        //     let stream;
+        //     try {
+        //         const responseData = { err: 0, msg: '', data: {}, };
+
+        //         // 保存文件
+        //         stream = await ctx.getFileStream();
+        //         const create_time = Date.parse(new Date());
+        //         const fileInfo = path.parse(stream.filename);
+        //         const fileName = this.app.config.filePath + '/cache/ledger/uploads/' + create_time + fileInfo.ext;
+        //         await ctx.helper.saveStreamFile(stream, fileName);
+                
+        //         // 读取excel
+        //         console.log(ctx.query);
+        //         const name = ctx.query.sheetName;
+        //         if (!name) throw '未选择需要导入的工作簿';
+        //         const wb = xlsx.readFile(fileName);
+        //         const sheetData = {
+        //             rows: xlsx.utils.sheet_to_json(wb.Sheets[name], {header: 1}),
+        //             merge: wb.Sheets[name]["!merges"],
+        //         };
+        //         if (!sheetData.rows) throw '读取工作簿数据错误';
+
+        //         const ueType = ctx.query.ueType;
+        //         switch (ueType) {
+        //             case 'tz':
+        //                 const templateId = await this.ctx.service.valuation.getValuationTemplate(
+        //                     this.ctx.tender.data.valuation, this.ctx.tender.data.measure_type);
+        //                 responseData.data = await ctx.service.ledger.importExcel(templateId, sheetData);
+        //                 break;
+        //             case 'gcl2xmj':
+        //                 responseData.data = await ctx.service.ledger.importGclExcel(ctx.tender.id, sheetData);
+        //                 break;
+        //             default:
+        //                 throw '数据错误';
+        //         }
+        //         ctx.body = responseData;
+        //     } catch (err) {
+        //         console.log(err);
+        //         this.log(err);
+        //         // 失败需要消耗掉stream 以防卡死
+        //         if (stream) await sendToWormhole(stream);
+        //         ctx.body = {err: 1, msg: err.toString(), data: null};
+        //     }
+        // }        
 
         /**
          * 下载(清单Excel模板 or 导出项目台账Excel)

+ 25 - 1
app/lib/analysis_excel.js

@@ -113,6 +113,28 @@ class ImportBaseTree {
         }
     }
 
+    getPosterity(node) {
+        let posterity = [].concat(node.children);
+        for (const c of node.children) {
+            posterity = posterity.concat(this.getPosterity(c));
+        }
+        return posterity;
+    }
+
+    findGclParent(code, xmj) {
+        let parent;
+        const codePath = code.split(this.splitChar);
+        if (codePath.length > 1) {
+            codePath.splice(codePath.length - 1, 1);
+            const parentCode = codePath.join(this.splitChar);
+            const posterity = this.getPosterity(xmj);
+            parent = posterity.find(function (x) {
+                return x.b_code === parentCode;
+            })
+        }
+        return parent ? parent : xmj;
+    } 
+
     /**
      * 添加 树节点 并完善该节点的树结构
      * @param {Object} node - 添加节点
@@ -187,8 +209,10 @@ class ImportBaseTree {
         node.id = this.ctx.app.uuid.v4();
         node.tender_id = this.ctx.tender.id;
         node.pos = [];
+        node.children = [];
         if (this.finalXmjNode) {
-            return this.addNodeWithParent(node, this.finalXmjNode);
+            const parent = node.b_code ? this.findGclParent(node.b_code, this.finalXmjNode) : this.finalXmjNode;
+            return this.addNodeWithParent(node, parent);
         }
     }
 

+ 91 - 0
app/public/js/global.js

@@ -261,6 +261,60 @@ const postDataWithFile = function (url, formData, successCallback, errorCallBack
     });
 };
 
+const postDataWithFileProgress = function (url, formData, successCallback, errorCallBack) {
+    showUploadFileProgress();
+    $.ajax({
+        type:"POST",
+        url: url,
+        data: formData,
+        dataType: 'json', 
+        cache: false,
+        // 告诉jQuery不要去设置Content-Type请求头
+        contentType: false,
+        // 告诉jQuery不要去处理发送的数据
+        processData: false,
+        beforeSend: function(xhr) {
+            let csrfToken = Cookies.get('csrfToken');
+            xhr.setRequestHeader('x-csrf-token', csrfToken);
+        },
+        success: function(result){
+            doneProgress();
+            if (result.err === 0) {
+                if (successCallback) {
+                    successCallback(result.data);
+                }
+            } else {
+                toastr.error('error: ' + result.msg);
+                if (errorCallBack) {
+                    errorCallBack();
+                }
+            }
+            closeProgress();
+        },
+        error: function(jqXHR, textStatus, errorThrown){
+            toastr.error('error: ' + textStatus + " " + errorThrown);
+            if (errorCallBack) {
+                errorCallBack();
+            }
+            closeProgress();
+        },
+        xhr: function() {
+            var xhr = new XMLHttpRequest();
+            //使用XMLHttpRequest.upload监听上传过程,注册progress事件,打印回调函数中的event事件
+            xhr.upload.addEventListener('progress', function (e) {
+                console.log(e);
+                //loaded代表上传了多少
+                //total代表总数为多少
+                var progressRate = (e.loaded / e.total) * 95;
+                //通过设置进度条的宽度达到效果
+                setUploadFileProgress(progressRate);
+            })
+
+            return xhr;
+        }
+    });
+}
+
 /**
  * 获取url中参数
  * @param variable
@@ -477,6 +531,43 @@ function closeProgress() {
     }, 500);
 }
 
+function showUploadFileProgress() {
+    var sWidth, sHeight;
+    sWidth = document.body.clientWidth;
+    sHeight = document.body.clientHeight;
+    //背景遮罩层div
+    var bgObj = document.createElement("div");
+    bgObj.setAttribute('id', 'bgDiv');
+    bgObj.style.zIndex = '9998';
+    bgObj.style.position = "absolute";
+    bgObj.style.top = "0px";
+    bgObj.style.background = "#888";
+    bgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75";
+    bgObj.style.opacity = "0.6";
+    bgObj.style.left = "0px";
+    bgObj.style.width = sWidth + "px";
+    bgObj.style.height = sHeight + "px";
+    document.body.appendChild(bgObj);
+
+    //信息提示层div
+    var msgObj = document.createElement("div");
+    msgObj.classList.add('progress');
+    msgObj.style.zIndex = '9999';
+    msgObj.style.position = "absolute";
+    msgObj.setAttribute("id", "progressDiv");
+    msgObj.style.height = "2px";
+    msgObj.style.width = "600px";
+    msgObj.style.top = (document.documentElement.scrollTop + sHeight / 2) + "px";
+    msgObj.style.left = (sWidth - 600) / 2 + "px";
+    document.body.appendChild(msgObj);
+    msgObj.innerHTML = '<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>';
+}
+function setUploadFileProgress(pos) {
+    const processObj = $('.progress-bar');
+    processObj.attr('aria-valuenow', pos);
+    processObj.width(pos + '%');    
+}
+
 /**
  * 设置本地缓存
  *

+ 15 - 3
app/public/js/ledger.js

@@ -1225,7 +1225,7 @@ $(document).ready(function() {
                         hint: '0号台账',
                         url: '/template/导入分项清单EXCEL格式.xls',
                     },
-                    callback: function (sheet) {
+                    callback: function (sheet) {     
                         postDataCompress(window.location.pathname + '/upload-excel/tz', sheet, function (result) {
                             ledgerTree.loadDatas(result.bills);
                             treeCalc.calculateAll(ledgerTree);
@@ -1233,7 +1233,19 @@ $(document).ready(function() {
                             pos.loadDatas(result.pos);
                             posOperationObj.loadCurPosData();
                         }, null);
-                    }
+                    },
+                    // callback: function (file, select) {
+                    //     const formData = new FormData();
+                    //     formData.append('file', file.files[0]);     
+                    //     postDataWithFileProgress(window.location.pathname + '/upload-excel?ueType=tz&sheetName=' + select, formData, function (result) {
+                    //         ledgerTree.loadDatas(result.bills);
+                    //         treeCalc.calculateAll(ledgerTree);
+                    //         SpreadJsObj.loadSheetData(ledgerSpread.getActiveSheet(), 'tree', ledgerTree);
+                    //         pos.loadDatas(result.pos);
+                    //         posOperationObj.loadCurPosData();
+                    //     }, null);
+                    // }
+                    //u_type: importExcel.uploadType.file,
                 });
                 //$('#upload-ledger').modal('show');
             },
@@ -1988,7 +2000,7 @@ $(document).ready(function() {
                     const file = $('#deal-bills-file')[0];
                     const formData = new FormData();
                     formData.append('file', file.files[0]);
-                    postDataWithFile(self.url+'/upload-excel', formData, function (data) {
+                    postDataWithFileProgress(self.url+'/upload-excel', formData, function (data) {
                         self.data = data;
                         SpreadJsObj.loadSheetData(self.spread.getActiveSheet(), 'data', data);
                         $('#upload-deal').modal('hide');

+ 16 - 7
app/view/shares/import_excel_modal.ejs

@@ -26,7 +26,11 @@
 </div>
 <script>
     const importExcel = (function () {
-        let callback;
+        const uploadType = {
+            file: 1,
+            data: 2
+        }
+        let callback, u_type;
         // 选择excel文件后,加载全部sheet
         $('#import-excel-file').change(function () {
             if (this.files.length === 0) {
@@ -79,11 +83,15 @@
         $('#import-excel-ok').click(function () {
             const sheetName = $('input[name=sheetName]:checked').val();
             if (sheetName) {
-                const sheet = {
-                    rows: xlsxUtils.getSheetByName(sheetName, {header: 1}),
-                    merge: xlsxUtils._wb.Sheets[sheetName]["!merges"]
-                };
-                if (callback) callback(sheet);
+                if (u_type === uploadType.file) {
+                    if (callback) callback($('#import-excel-file')[0], sheetName);
+                } else if (u_type === uploadType.data) {
+                    const sheet = {
+                        rows: xlsxUtils.getSheetByName(sheetName, {header: 1}),
+                        merge: xlsxUtils._wb.Sheets[sheetName]["!merges"]
+                    };
+                    if (callback) callback(sheet);
+                }
                 $('#import-excel').modal('hide');
             }
         });
@@ -97,7 +105,8 @@
             }
             $('#import-excel').modal('show');
             callback = setting.callback;
+            u_type = setting.u_type ? setting.u_type : uploadType.data;
         }
-        return { doImport };
+        return { doImport, uploadType };
     })();
 </script>