浏览代码

人材机排序、人材机导入单价数据

zhongzewei 7 年之前
父节点
当前提交
52206345b7

+ 56 - 0
modules/std_glj_lib/controllers/gljController.js

@@ -7,10 +7,12 @@ import stdgljutil  from "../../../public/cache/std_glj_type_util";
 import GljDao from "../models/gljModel";
 import rationItemDao from "../../ration_repository/models/ration_item";
 const multiparty = require("multiparty");
+const excel = require("node-xlsx");
 const LZString = require('lz-string');
 const gljModel = mongoose.model('std_glj_lib_gljList');
 const stdRationModel = mongoose.model('std_ration_lib_ration_items');
 const cplRationModel = mongoose.model('complementary_ration_items');
+const fs = require('fs');
 
 let gljDao = new GljDao();
 let callback = function(req, res, err, message, data){
@@ -188,6 +190,60 @@ class GljController extends BaseController{
             res.json({error: 1, message: error, data: null});
         }
     }
+    async importPrice(request, response) {
+        let responseData = {
+            err: 0,
+            msg: ''
+        };
+        const allowHeader = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
+        const uploadOption = {
+            uploadDir: './public'
+        };
+        const form = new multiparty.Form(uploadOption);
+        let uploadFullName;
+        form.parse(request, async function(err, fields, files) {
+            try{
+                const gljLibId = fields.gljLibId !== undefined && fields.gljLibId.length > 0 ?
+                    fields.gljLibId[0] : 0;
+                if (gljLibId <= 0) {
+                    throw '参数错误';
+                }
+                const file = files.file !== undefined ? files.file[0] : null;
+                if (err || file === null) {
+                    throw '上传失败';
+                }
+                // 判断类型
+                if (file.headers['content-type'] === undefined || allowHeader.indexOf(file.headers['content-type']) < 0) {
+                    throw '不支持该类型';
+                }
+                // 重命名文件名
+                uploadFullName = uploadOption.uploadDir + '/' + file.originalFilename;
+                fs.renameSync(file.path, uploadFullName);
+
+                const sheet = excel.parse(uploadFullName);
+                if (sheet[0] === undefined || sheet[0].data === undefined || sheet[0].data.length <= 0) {
+                    throw 'excel没有对应数据';
+                }
+                //更新人材机价格
+                await gljDao.batchUpdateGljPrice(gljLibId, sheet[0].data);
+
+                // 删除文件
+                if(uploadFullName && fs.existsSync(uploadFullName)){
+                    fs.unlink(uploadFullName);
+                }
+                response.json(responseData);
+            }
+            catch (error){
+                console.log(error);
+                if(uploadFullName && fs.existsSync(uploadFullName)){
+                    fs.unlink(uploadFullName);
+                }
+                responseData.err = 1;
+                responseData.msg = error;
+                response.json(responseData);
+            }
+        });
+    }
 }
 
 export default GljController;

+ 81 - 0
modules/std_glj_lib/models/gljModel.js

@@ -6,6 +6,8 @@ const gljMapModel = mongoose.model('std_glj_lib_map');
 const gljModel = mongoose.model('std_glj_lib_gljList');
 const gljClassModel = mongoose.model('std_glj_lib_gljClass');
 const gljClassTemplateModel = mongoose.model('std_glj_lib_gljClassTemplate');
+const compilationModel = mongoose.model('compilation');
+const scMathUtil = require('../../../public/scMathUtil').getUtil();
 import {OprDao} from  "./gljMapModel";
 import moment from "moment";
 import counter from "../../../public/counter/counter";
@@ -496,6 +498,85 @@ class GljDao  extends OprDao{
     async getGljItemsByRepId(repositoryId, returnFields = ''){
          return gljModel.find({"repositoryId": repositoryId}, returnFields);
     }
+
+    async batchUpdateGljPrice(gljLibId, sheetData){
+        let gljLib = await gljMapModel.findOne({ID: gljLibId});
+        if(!gljLib){
+            throw '不存在此人材机库';
+        }
+        let compilation = await compilationModel.findOne({_id: mongoose.Types.ObjectId(gljLib.compilationId)});
+        if(!compilation){
+            throw '不存在此费用定额';
+        }
+        let priceProperties = compilation.priceProperties ? compilation.priceProperties : [];
+        //根据第一行数据,获取列下标与字段名映射
+        let colMapping = {};
+        for(let col = 0; col < sheetData[0].length; col++){
+            let cData = sheetData[0][col];
+            if(cData === '编码'){
+                colMapping['code'] = col;
+            }
+            else {
+                if(priceProperties.length === 0){
+                    if(cData === '定额价'){
+                        colMapping['basePrice'] = col;
+                        break;
+                    }
+                }
+                else {
+                    for(let priceProp of priceProperties){
+                        if(priceProp.price.dataName === cData){
+                            colMapping[priceProp.price.dataCode] = col;
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+        let colMappingKeys = Object.keys(colMapping);
+        if(colMappingKeys.length < 2){
+            throw 'excel数据不正确'
+        }
+        let updateBulk = [];
+        //避免重复
+        let updateCodes = [];
+        for(let row = 0; row < sheetData.length; row++){
+            if(row === 0){
+                continue;
+            }
+            let gljCode = sheetData[row][colMapping.code];
+            if(gljCode && gljCode !== '' && !updateCodes.includes(gljCode)){
+                if(priceProperties.length > 0){
+                    let priceProperty = {};
+                    for(let priceProp of priceProperties){
+                        let dataCode = priceProp.price.dataCode;
+                        let priceCellData = sheetData[row][colMapping[dataCode]];
+                        priceProperty[dataCode] = colMapping[dataCode] && priceCellData && !isNaN(priceCellData) ?
+                            scMathUtil.roundTo(parseFloat(priceCellData), -2) : 0;
+                    }
+                    updateCodes.push(gljCode);
+                    updateBulk.push({
+                        updateOne: {filter: {repositoryId: gljLibId, code: gljCode}, update: {$set: {priceProperty: priceProperty}}}
+                    });
+                }
+                else {
+                    if(colMapping.basePrice){
+                        let priceCellData = sheetData[row][colMapping.basePrice];
+                        let basePrice = priceCellData  && !isNaN(priceCellData) ?
+                            scMathUtil.roundTo(priceCellData, -2) : 0;
+                        updateCodes.push(gljCode);
+                        updateBulk.push({
+                            updateOne: {filter: {repositoryId: gljLibId, code: gljCode}, update: {$set: {basePrice: basePrice}}}
+                        });
+                    }
+                }
+            }
+        }
+        if(updateBulk.length > 0){
+            await gljModel.bulkWrite(updateBulk);
+        }
+
+    }
 }
 
 export default GljDao;

+ 2 - 0
modules/std_glj_lib/routes/routes.js

@@ -40,6 +40,8 @@ module.exports = function (app) {
     router.post("/getGljItemsByCodes",gljController.auth, gljController.init, gljController.getGljItemsByCodes);
     router.post("/getGljItemsOccupied",gljController.auth, gljController.init, gljController.getGljItemsOccupied);
     router.post("/isUsed",gljController.auth, gljController.init, gljController.isUsed);//工料机是否被引用
+    router.post('/importPrice', gljController.auth, gljController.init, gljController.importPrice);
+
 
     app.use("/stdGljRepository/api", router);
 

+ 2 - 4
web/maintain/std_glj_lib/html/gongliao.html

@@ -299,10 +299,8 @@
             }
         };
         $(document).ready(function(){
-            let a = {a: 1, b: 2};
-            let b = {b:2, a: 1};
-            console.log(_.isEqual(a, b));
-            console.log(Object.keys(a));
+            let test = '1-1';
+            console.log(test.split('-'));
             //解决spreadjs sheet初始化没高度宽度
             $('#modalCon').width($(window).width()*0.5);
             $('#componentTreeDiv').height($(window).height() - 300);

+ 29 - 1
web/maintain/std_glj_lib/html/main.html

@@ -33,7 +33,7 @@
                   <div class="col-md-8">
                     <div class="warp-p2 mt-3">
                       <table class="table table-hover table-bordered">
-                        <thead><tr><th>人材机库名称</th><th>编办</th><th>定额库</th><th width="160">添加时间</th><th width="90">操作</th></tr></thead>
+                        <thead><tr><th>人材机库名称</th><th>编办</th><th>定额库</th><th width="160">添加时间</th><th width="90">操作</th><th width="90">价格数据</th></tr></thead>
                         <tbody id="showArea">
                       <!--    <tr><td><a href="gongliao.html">XX工料机库</a></td><td>重庆2018</td><td>XXX定额库(重庆2018)</td><td>2017-01-01 </td><td><a href="javacript:void(0);" data-toggle="modal" data-target="#edit" title="编辑"><i class="fa fa-pencil-square-o"></i></a> <a href="javacript:void(0);" data-toggle="modal" data-target="#del" class="text-danger" title="删除"><i class="fa fa-remove"></i></a></td></tr>
                           <tr><td><a href="gongliao.html">XX工料机库</a></td><td>重庆2018</td><td></td><td>2017-01-01 </td><td><a href="javacript:void(0);" data-toggle="modal" data-target="#edit" title="编辑"><i class="fa fa-pencil-square-o"></i></a> <a href="javacript:void(0);" data-toggle="modal" data-target="#del" class="text-danger" title="删除"><i class="fa fa-remove"></i></a></td></tr>
@@ -125,6 +125,34 @@
             </div>
         </div>
     </div>
+    <!--弹出导入数据-->
+    <div class="modal fade" id="import" data-backdrop="static" style="display: none;" aria-hidden="true">
+        <div class="modal-dialog" role="document">
+            <div class="modal-content">
+                <div class="modal-header">
+                    <h5 class="modal-title">导入数据</h5>
+                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                        <span aria-hidden="true">×</span>
+                    </button>
+                </div>
+                <div class="modal-body">
+                    <div class="alert alert-warning" role="alert">
+                        导入操作会覆盖数据,请谨慎操作!!
+                    </div>
+                    <form>
+                        <div class="form-group">
+                            <label>请选择Excel格式文件</label>
+                            <input class="form-control-file" type="file" accept=".xlsx,.xls" name="import_data"/>
+                        </div>
+                    </form>
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-primary" id="data-import">确定导入</button>
+                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
+                </div>
+            </div>
+        </div>
+    </div>
     <!-- JS. -->
     <script src="/lib/jquery/jquery.min.js"></script>
     <script src="/lib/tether/tether.min.js"></script>

+ 2 - 0
web/maintain/std_glj_lib/js/components.js

@@ -176,6 +176,7 @@ let componentOprObj = {
         let me = componentOprObj, re = repositoryGljObj;
         if (me.workBook) {
             let cacheSection = data;
+            re.sortGljDeep.call(me, data);
             sheetCommonObj.cleanSheet(me.workBook.getSheet(0), me.setting, -1);
             sheetsOprObj.showData(me, me.workBook.getSheet(0), me.setting, cacheSection, re.distTypeTree);
             me.workBook.getSheet(0).setRowCount(cacheSection.length);
@@ -337,6 +338,7 @@ let componentTypeTreeOprObj = {
                 me.currentOprParent = 1;
                 me.currentCache = me.getParentCache(re.parentNodeIds["_pNodeId_" + treeNode.ID]);
             } else {
+                me.currentOprParent = 0;
                 me.currentCache = me.getCache();
             }
         }

+ 44 - 3
web/maintain/std_glj_lib/js/glj.js

@@ -357,6 +357,7 @@ let repositoryGljObj = {
         let me = repositoryGljObj;
         if (me.workBook) {
             let cacheSection = data;
+            me.sortGljDeep(cacheSection);
             sheetCommonObj.cleanData(me.workBook.getSheet(0), me.setting, -1);
             sheetsOprObj.showData(me, me.workBook.getSheet(0), me.setting, cacheSection, me.distTypeTree, me.materialTypeIdx, me.machineModelIdx);
             let gljTypeCol = me.colMapping.fieldToCol['gljType'],
@@ -1431,14 +1432,13 @@ let repositoryGljObj = {
                     alert(result.message);
                 } else {
                     me.updateCache(addArr, updateArr, removeIds, result);
-                    me.sortGlj();
+                    //me.sortGlj();
                     if(me.currentOprParent === 1){
                         me.currentCache = me.getParentCache(me.parentNodeIds["_pNodeId_" + me.gljCurTypeId]);
                     }
                     else{
                         me.currentCache = me.getCache();
                     }
-                    //me.showGljItems(me.gljList, me.gljCurTypeId);
                     me.showGljItems(me.currentCache, me.gljCurTypeId);
                     //getCurrentGlj
                     let row = me.workBook.getSheet(0).getSelections()[0].row;
@@ -1552,6 +1552,48 @@ let repositoryGljObj = {
             private_build_parentNodeIds(null, nodes);
         }
     },
+    sortGljDeep: function (datas) {
+        if(this.currentOprParent){
+            datas.sort(function (a, b) {
+                let rst = 0;
+                if(a.code > b.code){
+                    rst = 1;
+                }
+                else if(a.code < b.code){
+                    rst = -1;
+                }
+                return rst;
+            });
+        }
+        else {
+            //排序符号-
+            datas.sort(function (a, b) {
+                let rst = 0;
+                let splitA = a.code.split('-'),
+                    splitB = b.code.split('-');
+                if(splitA[0] > splitB[0]){
+                    rst = 1;
+                }
+                else if(splitA[0] < splitB[0]){
+                    rst = -1;
+                }
+                else {
+                    if(splitA[1] && splitB[1]){
+                        let floatA = parseFloat(splitA[1]),
+                            floatB = parseFloat(splitB[1]);
+                        if(floatA > floatB){
+                            rst = 1;
+                        }
+                        else if(floatA < floatB){
+                            rst = -1;
+                        }
+                    }
+                }
+                return rst;
+            });
+        }
+    },
+    //工料机排序
     sortGlj: function() {
         let me = this;
         me.gljList.sort(function(a, b){
@@ -1579,7 +1621,6 @@ let gljTypeTreeOprObj = {
             me.currentOprParent = 0;
             me.currentCache = me.getCache();
         }
-        //me.showGljItems(me.gljList, gljTypeId);
         me.showGljItems(me.currentCache, gljTypeId);
     },
     beforeRename: function(treeId, treeNode, newName, isCancel) {

+ 73 - 2
web/maintain/std_glj_lib/js/main.js

@@ -120,6 +120,72 @@ $(function () {
 
         });
     });
+    let selLibId = -1;
+    $("#showArea").on("click", ".import-data", function () {
+        let id = $(this).data("id");
+        id = parseInt(id);
+        if (isNaN(id) || id <= 0) {
+            return false;
+        }
+        selLibId = id;
+        $("#import").modal("show");
+    });
+    //导入单价数据
+    $("#data-import").click(function() {
+        $.bootstrapLoading.start();
+        const self = $(this);
+        try {
+            let formData = new FormData();
+            let file = $("input[name='import_data']")[0];
+            if (file.files.length <= 0) {
+                throw '请选择文件!';
+            }
+            formData.append('file', file.files[0]);
+            // 获取人材机库id
+            if (selLibId <= 0) {
+                return false;
+            }
+            formData.append('gljLibId', selLibId);
+            $.ajax({
+                url: 'api/importPrice',
+                type: 'POST',
+                data: formData,
+                cache: false,
+                contentType: false,
+                processData: false,
+                beforeSend: function() {
+                    self.attr('disabled', 'disabled');
+                    self.text('上传中...');
+                },
+                success: function(response){
+                    self.removeAttr('disabled');
+                    self.text('确定导入');
+                    if (response.err === 0) {
+                        $.bootstrapLoading.end();
+                        const message = response.msg !== undefined ? response.msg : '';
+                        if (message !== '') {
+                            alert(message);
+                        }
+                        // 成功则关闭窗体
+                        $('#import').modal("hide");
+                    } else {
+                        $.bootstrapLoading.end();
+                        const message = response.msg !== undefined ? response.msg : '上传失败!';
+                        alert(message);
+                    }
+                },
+                error: function(){
+                    $.bootstrapLoading.end();
+                    alert("与服务器通信发生错误");
+                    self.removeAttr('disabled');
+                    self.text('确定导入');
+                }
+            });
+        } catch(error) {
+            alert(error);
+            $.bootstrapLoading.end();
+        }
+    });
 });
 
 function getAllGljLib(callback){
@@ -151,7 +217,9 @@ function getAllGljLib(callback){
                         "<td>"+createDate+" </td>" +
                         "<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></tr>");
+                        "<i class='fa fa-remove'></i></a></td>" +
+                        "<td><a class='btn btn-secondary btn-sm import-data' href='javacript:void(0);' data-id='"+ id +"' title='导入数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
+                        "</tr>");
                     var newHref = "/stdGljRepository/glj?gljLibId="+id;
                     $("#tempId td:first a").attr("href", newHref);
                     $("#tempId").attr("id", id);
@@ -201,7 +269,9 @@ function createGljLib(gljLibObj, dispNamesArr, usedCom){
                     "<td>"+createDate+" </td>" +
                     "<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></tr>");
+                    "<i class='fa fa-remove'></i></a></td>" +
+                    "<td><a class='btn btn-secondary btn-sm import-data' href='javacript:void(0);' data-id='"+ id +"' title='导入数据'><i class='fa fa-sign-in fa-rotate-90'></i>导入</a></td>" +
+                    "</tr>");
                 var newHref = "/stdGljRepository/glj?gljLibId="+id;
                 $("#tempId td:first a").attr("href", newHref);
                 $("#tempId").attr("id", id);
@@ -257,4 +327,5 @@ function removeGljLib(delObj, dispNames){
             $.bootstrapLoading.end();
         }
     })
+
 }