소스 검색

提交导入定额库原始数据的功能

olym 7 년 전
부모
커밋
8fbe6277d8

+ 21 - 4
modules/ration_repository/controllers/ration_repository_controller.js

@@ -14,6 +14,7 @@ const multiparty = require("multiparty");
 const fs = require("fs");
 // excel解析
 const excel = require("node-xlsx");
+const rationItem = require("../models/ration_item");
 
 class RationRepositoryController extends baseController {
     async getCompilationList(req, res) {
@@ -142,6 +143,10 @@ class RationRepositoryController extends baseController {
      * @return {void}
      */
     async uploadSourceData(request, response) {
+        let responseData = {
+            err: 0,
+            msg: ''
+        };
         const allowHeader = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
         try {
             const uploadOption = {
@@ -149,7 +154,12 @@ class RationRepositoryController extends baseController {
             };
             const form = new multiparty.Form(uploadOption);
             form.parse(request, function(err, fields, files) {
-                const file = files.source_file !== undefined ? files.source_file[0] : null;
+                const rationRepId = fields.rationRepId !== undefined && fields.rationRepId.length > 0 ?
+                    fields.rationRepId[0] : 0;
+                if (rationRepId <= 0) {
+                    throw '参数错误';
+                }
+                const file = files.file !== undefined ? files.file[0] : null;
                 if (err || file === null) {
                     throw '上传失败';
                 }
@@ -161,11 +171,18 @@ class RationRepositoryController extends baseController {
                 const uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
                 fs.renameSync(file.path, uploadFullName);
 
-                const test = excel.parse(uploadFullName);
-                console.log(test[0].data);
+                const sheet = excel.parse(uploadFullName);
+                if (sheet[0] === undefined || sheet[0].data === undefined) {
+                    throw 'excel没有对应数据';
+                }
+
+                rationItem.batchAddFromExcel(rationRepId, sheet[0].data);
+                response.json(responseData);
             });
         } catch (error) {
-            console.log(error);
+            responseData.err = 1;
+            responseData.msg = error;
+            response.json(responseData);
         }
 
         return;

+ 115 - 2
modules/ration_repository/models/ration_item.js

@@ -457,7 +457,120 @@ rationItemDAO.prototype.updateAnnotation = function (lastOpr, repId, updateArr,
             }
         });
     });
-}
+};
+
+/**
+ * 根据条件获取定额数据
+ *
+ * @param {Object} condition
+ * @param {Object} fields
+ * @param {String} indexBy
+ * @return {Promise|Array}
+ */
+rationItemDAO.prototype.getRationItemByCondition = async function (condition, fields = null, indexBy = null) {
+    let result = [];
+    if (Object.keys(condition).length <= 0) {
+        return result;
+    }
+    result = await rationItemModel.find(condition, fields);
+    if (indexBy !== null && result.length > 0) {
+        let tmpResult = {};
+        for(let tmp of result) {
+            tmpResult[tmp[indexBy]] = tmp;
+        }
+        result = tmpResult;
+    }
+    return result;
+};
+
+/**
+ * 从excel中批量新增数据
+ *
+ * @param {Number} rationRepId
+ * @param {Array} data
+ * @return {bool}
+ */
+rationItemDAO.prototype.batchAddFromExcel = async function(rationRepId, data) {
+    if (data.length <= 0) {
+        return false;
+    }
+    let lastData = {};
+    const rationData = [];
+    // 编码列表,用于查找库中是否有对应数据
+    let rationCodeList = [];
+    let gljCodeList = [];
+    for (const tmp of data) {
+        if (tmp.length <= 0) {
+            continue;
+        }
+        // 如果第一个字段为null则是工料机数据,放入上一个数据的工料机字段
+        if (tmp[0] === undefined && Object.keys(lastData).length > 0) {
+            const tmpRationGlj = {
+                gljId: 1,
+                consumeAmt: tmp[4],
+                proportion: 0,
+            };
+            lastData.rationGljList.push(tmpRationGlj);
+            if (gljCodeList.indexOf(tmp[1]) < 0) {
+                gljCodeList.push(tmp[1]);
+            }
+            continue;
+        }
+
+        if (tmp[0] === '定额' && Object.keys(lastData).length > 0) {
+            rationData.push(lastData);
+        }
+
+        // 组装数据
+        lastData = {
+            code: tmp[1],
+            name: tmp[2],
+            unit: tmp[3],
+            caption: tmp[2],
+            rationRepId: rationRepId,
+            rationGljList: []
+        };
+        // 防止重复加入
+        if (rationCodeList.indexOf(tmp[1]) < 0) {
+            rationCodeList.push(tmp[1]);
+        }
+    }
+    // 最后一个入数组
+    rationData.push(lastData);
+
+    // 查找数据库中是否已存在待插入数据
+    const condition = {
+        rationRepId: rationRepId,
+        code: { $in: rationCodeList}
+    };
+    const existCodeList = await this.getRationItemByCondition(condition, ['code'], 'code');
+    // 过滤插入数据
+    let insertData = [];
+    for (const ration of rationData) {
+        if (existCodeList[ration.code] !== undefined) {
+            continue;
+        }
+        insertData.push(ration);
+    }
+    // 如果都已经存在,直接返回
+    if (insertData.length <= 0) {
+        return true;
+    }
+
+    // 组织id
+    const counterInfo = await counter.counterDAO.getIDAfterCount(counter.moduleName.rations, insertData.length);
+    let maxId = counterInfo.value.sequence_value;
+    maxId = parseInt(maxId);
+
+    let count = 0;
+    for (const index in insertData) {
+        insertData[index].ID = maxId - (insertData.length - 1) + count;
+        count++;
+    }
+    // 插入数据库
+    const result = await rationItemModel.create(insertData);
+    console.log(result);
+};
 
-module.exports = new rationItemDAO()
+module.exports = new rationItemDAO();
 

+ 6 - 2
public/counter/counter.js

@@ -45,14 +45,18 @@ var counterDAO = function(){};
  *     result.value.sequence_value Ϊ�޸ĺ��id
  * }
  */
-counterDAO.prototype.getIDAfterCount = function(moduleName, stepCount, callback) {
+counterDAO.prototype.getIDAfterCount = async function(moduleName, stepCount, callback = null) {
     var sc = stepCount;
     if (isNaN(stepCount) || (stepCount < 0)) {
         sc = 1;
     } else if (!(/^-?\d+$/.test(stepCount))) {
         sc = Math.round(stepCount + 0.5);
     }
-    counterModel.findAndModify({_id: moduleName}, [], { $inc: { sequence_value: sc } }, {'new':true}, callback);
+    if (callback === null) {
+        return await counterModel.findAndModify({_id: moduleName}, [], { $inc: { sequence_value: sc } }, {'new':true});
+    } else {
+        counterModel.findAndModify({_id: moduleName}, [], { $inc: { sequence_value: sc } }, {'new':true}, callback);
+    }
 }
 
 counterDAO.prototype.getCurrentID = function(moduleName, callback) {

+ 51 - 1
web/maintain/ration_repository/js/main.js

@@ -76,6 +76,56 @@ $(function () {
 
     });
     getCompilationList();
+
+    // 导入原始数据按钮
+    let rationRepId = 0;
+    $("#showArea").on("click", ".import-source", function () {
+        let id = $(this).data("id");
+        id = parseInt(id);
+        if (isNaN(id) || id <= 0) {
+            return false;
+        }
+        rationRepId = id;
+        $("#import").modal("show");
+    });
+
+    // 导入原始数据确认
+    $("#source-import").click(function() {
+        try {
+            let formData = new FormData();
+            let file = $("input[name='source_file']")[0];
+            if (file.files.length <= 0) {
+                throw '请选择文件!';
+            }
+            formData.append('file', file.files[0]);
+            // 获取定额库id
+            if (rationRepId <= 0) {
+                return false;
+            }
+            formData.append('rationRepId', rationRepId);
+            $.ajax({
+                url: '/rationRepository/api/upload',
+                type: 'POST',
+                data: formData,
+                cache: false,
+                contentType: false,
+                processData: false,
+                beforeSend: function() {
+
+                },
+                success: function(data){
+                    console.log(data);
+                    console.log('imgUploader upload success');
+                },
+                error: function(){
+                    alert("与服务器通信发生错误");
+                }
+            });
+        } catch(error) {
+            alert(error);
+        }
+
+    });
 });
 
 function getAllRationLib(callback){
@@ -104,7 +154,7 @@ function getAllRationLib(callback){
                         "<td><a href='javascript:void(0);' data-toggle='modal' data-target='#edit' title='编辑'>" +
                         "<i class='fa fa-pencil-square-o'></i></a> <a href='javascript:void(0);' data-toggle='modal' data-target='#del' class='text-danger' title='删除'>" +
                         "<i class='fa fa-remove'></i></a></td>" +
-                        "<td><a class='btn btn-secondary btn-sm' href='javacript:void(0);' data-toggle='modal' data-target='#import' title='导入原始数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
+                        "<td><a class='btn btn-secondary btn-sm import-source' href='javacript:void(0);' data-id='"+ id +"' title='导入原始数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
                         "<td><a class='btn btn-success btn-sm' href='javacript:void(0);' data-toggle='modal' data-target='#emport' title='导出内部数据'><i class='fa fa-sign-out fa-rotate-270'></i>导出</a> <a class='btn btn-secondary btn-sm' href='javacript:void(0);' data-toggle='modal' data-target='#import2' title='导入内部数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
                         "</tr>");
                     var newHref = "/rationRepository/ration?repository="+id;

+ 3 - 1
web/maintain/ration_repository/main.html

@@ -177,7 +177,8 @@
                     </div>
                     <div class="modal-footer">
                         <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
-                        <button type="submit" class="btn btn-primary">确定导入</button>
+                        <input type="hidden" name="rationRepId" value="0"/>
+                        <button type="button" class="btn btn-primary" id="source-import">确定导入</button>
                     </div>
                 </div>
             </div>
@@ -207,6 +208,7 @@
                 </div>
                 <div class="modal-footer">
                     <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
+                    <input type="hidden" name="rationRepId" value="0"/>
                     <a href="" class="btn btn-primary">确定导入</a>
                 </div>
             </div>