Browse Source

Merge branch 'master' of http://smartcost.f3322.net:3000/SmartCost/ConstructionCost

Chenshilong 8 years atrás
parent
commit
eef2bc0ea6
41 changed files with 1661 additions and 319 deletions
  1. 657 0
      lib/bootstrap/bootstrap-paginator.js
  2. 9 2
      modules/common/base/base_controller.js
  3. 14 0
      modules/common/const/log_type_const.js
  4. 7 1
      modules/common/helper/mongoose_helper.js
  5. 16 3
      modules/ration_glj/facade/glj_calculate_facade.js
  6. 73 16
      modules/ration_glj/facade/quantity_detail_facade.js
  7. 8 2
      modules/ration_glj/facade/ration_glj_facade.js
  8. 1 1
      modules/ration_glj/models/ration_glj.js
  9. 2 1
      modules/ration_glj/models/ration_glj_temp.js
  10. 2 1
      modules/ration_repository/models/glj_repository.js
  11. 5 2
      modules/reports/controllers/rpt_controller.js
  12. 37 0
      modules/reports/models/rpt_tpl_data.js
  13. 1 2
      modules/reports/routes/report_router.js
  14. 8 3
      modules/reports/util/rpt_data_util.js
  15. 242 137
      modules/reports/util/rpt_excel_util.js
  16. 4 3
      modules/users/controllers/login_controller.js
  17. 31 5
      modules/users/controllers/user_controller.js
  18. 104 0
      modules/users/models/log_model.js
  19. 29 0
      modules/users/models/schema/log.js
  20. 24 7
      modules/users/models/schema/user.js
  21. 8 16
      modules/users/models/user_model.js
  22. 3 3
      modules/users/routes/user_route.js
  23. 2 0
      package.json
  24. 1 0
      public/web/rpt_value_define.js
  25. 2 0
      public/web/sheet/sheet_common.js
  26. 10 1
      public/web/tree_sheet/tree_sheet_helper.js
  27. 4 3
      test/tmp_data/bills_grid_setting.js
  28. 2 1
      web/building_saas/fee_rates/fee_rate.html
  29. 20 9
      web/building_saas/main/js/calc/bills_calc.js
  30. 4 0
      web/building_saas/main/js/calc/calc_fees.js
  31. 7 8
      web/building_saas/main/js/calc/ration_calc.js
  32. 1 0
      web/building_saas/main/js/models/bills.js
  33. 91 12
      web/building_saas/main/js/models/quantity_detail.js
  34. 27 11
      web/building_saas/main/js/models/ration_glj.js
  35. 4 3
      web/building_saas/main/js/views/glj_view.js
  36. 28 8
      web/building_saas/main/js/views/glj_view_contextMenu.js
  37. 23 2
      web/building_saas/main/js/views/main_tree_col.js
  38. 30 4
      web/building_saas/main/js/views/project_view.js
  39. 89 0
      web/common/html/page.html
  40. 1 1
      web/glj/html/header.html
  41. 30 51
      web/users/html/user-safe.html

+ 657 - 0
lib/bootstrap/bootstrap-paginator.js

@@ -0,0 +1,657 @@
+/**
+ * bootstrap-paginator.js v0.5
+ * --
+ * Copyright 2013 Yun Lai <lyonlai1984@gmail.com>
+ * --
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+(function ($) {
+
+    "use strict"; // jshint ;_;
+
+
+    /* Paginator PUBLIC CLASS DEFINITION
+     * ================================= */
+
+    /**
+     * Boostrap Paginator Constructor
+     *
+     * @param element element of the paginator
+     * @param options the options to config the paginator
+     *
+     * */
+    var BootstrapPaginator = function (element, options) {
+        this.init(element, options);
+    },
+        old = null;
+
+    BootstrapPaginator.prototype = {
+
+        /**
+         * Initialization function of the paginator, accepting an element and the options as parameters
+         *
+         * @param element element of the paginator
+         * @param options the options to config the paginator
+         *
+         * */
+        init: function (element, options) {
+
+            this.$element = $(element);
+
+            var version = (options && options.bootstrapMajorVersion) ? options.bootstrapMajorVersion : $.fn.bootstrapPaginator.defaults.bootstrapMajorVersion,
+                id = this.$element.attr("id");
+
+            if (version === 2 && !this.$element.is("div")) {
+
+                throw "in Bootstrap version 2 the pagination must be a div element. Or if you are using Bootstrap pagination 3. Please specify it in bootstrapMajorVersion in the option";
+            } else if (version > 2 && !this.$element.is("ul")) {
+                throw "in Bootstrap version 3 the pagination root item must be an ul element."
+            }
+
+
+
+            this.currentPage = 1;
+
+            this.lastPage = 1;
+
+            this.setOptions(options);
+
+            this.initialized = true;
+        },
+
+        /**
+         * Update the properties of the paginator element
+         *
+         * @param options options to config the paginator
+         * */
+        setOptions: function (options) {
+
+            this.options = $.extend({}, (this.options || $.fn.bootstrapPaginator.defaults), options);
+
+            this.totalPages = parseInt(this.options.totalPages, 10);  //setup the total pages property.
+            this.numberOfPages = parseInt(this.options.numberOfPages, 10); //setup the numberOfPages to be shown
+
+            //move the set current page after the setting of total pages. otherwise it will cause out of page exception.
+            if (options && typeof (options.currentPage)  !== 'undefined') {
+
+                this.setCurrentPage(options.currentPage);
+            }
+
+            this.listen();
+
+            //render the paginator
+            this.render();
+
+            if (!this.initialized && this.lastPage !== this.currentPage) {
+                this.$element.trigger("page-changed", [this.lastPage, this.currentPage]);
+            }
+
+        },
+
+        /**
+         * Sets up the events listeners. Currently the pageclicked and pagechanged events are linked if available.
+         *
+         * */
+        listen: function () {
+
+            this.$element.off("page-clicked");
+
+            this.$element.off("page-changed");// unload the events for the element
+
+            if (typeof (this.options.onPageClicked) === "function") {
+                this.$element.bind("page-clicked", this.options.onPageClicked);
+            }
+
+            if (typeof (this.options.onPageChanged) === "function") {
+                this.$element.on("page-changed", this.options.onPageChanged);
+            }
+
+            this.$element.bind("page-clicked", this.onPageClicked);
+        },
+
+
+        /**
+         *
+         *  Destroys the paginator element, it unload the event first, then empty the content inside.
+         *
+         * */
+        destroy: function () {
+
+            this.$element.off("page-clicked");
+
+            this.$element.off("page-changed");
+
+            this.$element.removeData('bootstrapPaginator');
+
+            this.$element.empty();
+
+        },
+
+        /**
+         * Shows the page
+         *
+         * */
+        show: function (page) {
+
+            this.setCurrentPage(page);
+
+            this.render();
+
+            if (this.lastPage !== this.currentPage) {
+                this.$element.trigger("page-changed", [this.lastPage, this.currentPage]);
+            }
+        },
+
+        /**
+         * Shows the next page
+         *
+         * */
+        showNext: function () {
+            var pages = this.getPages();
+
+            if (pages.next) {
+                this.show(pages.next);
+            }
+
+        },
+
+        /**
+         * Shows the previous page
+         *
+         * */
+        showPrevious: function () {
+            var pages = this.getPages();
+
+            if (pages.prev) {
+                this.show(pages.prev);
+            }
+
+        },
+
+        /**
+         * Shows the first page
+         *
+         * */
+        showFirst: function () {
+            var pages = this.getPages();
+
+            if (pages.first) {
+                this.show(pages.first);
+            }
+
+        },
+
+        /**
+         * Shows the last page
+         *
+         * */
+        showLast: function () {
+            var pages = this.getPages();
+
+            if (pages.last) {
+                this.show(pages.last);
+            }
+
+        },
+
+        /**
+         * Internal on page item click handler, when the page item is clicked, change the current page to the corresponding page and
+         * trigger the pageclick event for the listeners.
+         *
+         *
+         * */
+        onPageItemClicked: function (event) {
+
+            var type = event.data.type,
+                page = event.data.page;
+
+            this.$element.trigger("page-clicked", [event, type, page]);
+
+        },
+
+        onPageClicked: function (event, originalEvent, type, page) {
+
+            //show the corresponding page and retrieve the newly built item related to the page clicked before for the event return
+
+            var currentTarget = $(event.currentTarget);
+
+            switch (type) {
+            case "first":
+                currentTarget.bootstrapPaginator("showFirst");
+                break;
+            case "prev":
+                currentTarget.bootstrapPaginator("showPrevious");
+                break;
+            case "next":
+                currentTarget.bootstrapPaginator("showNext");
+                break;
+            case "last":
+                currentTarget.bootstrapPaginator("showLast");
+                break;
+            case "page":
+                currentTarget.bootstrapPaginator("show", page);
+                break;
+            }
+
+        },
+
+        /**
+         * Renders the paginator according to the internal properties and the settings.
+         *
+         *
+         * */
+        render: function () {
+
+            //fetch the container class and add them to the container
+            var containerClass = this.getValueFromOption(this.options.containerClass, this.$element),
+                size = this.options.size || "normal",
+                alignment = this.options.alignment || "left",
+                pages = this.getPages(),
+                listContainer = this.options.bootstrapMajorVersion === 2 ? $("<ul></ul>") : this.$element,
+                listContainerClass = this.options.bootstrapMajorVersion === 2 ? this.getValueFromOption(this.options.listContainerClass, listContainer) : null,
+                first = null,
+                prev = null,
+                next = null,
+                last = null,
+                p = null,
+                i = 0;
+
+
+            this.$element.prop("class", "");
+
+            this.$element.addClass("pagination");
+
+            switch (size.toLowerCase()) {
+            case "large":
+            case "small":
+            case "mini":
+                this.$element.addClass($.fn.bootstrapPaginator.sizeArray[this.options.bootstrapMajorVersion][size.toLowerCase()]);
+                break;
+            default:
+                break;
+            }
+
+            if (this.options.bootstrapMajorVersion === 2) {
+                switch (alignment.toLowerCase()) {
+                case "center":
+                    this.$element.addClass("pagination-centered");
+                    break;
+                case "right":
+                    this.$element.addClass("pagination-right");
+                    break;
+                default:
+                    break;
+                }
+            }
+
+
+            this.$element.addClass(containerClass);
+
+            //empty the outter most container then add the listContainer inside.
+            this.$element.empty();
+
+            if (this.options.bootstrapMajorVersion === 2) {
+                this.$element.append(listContainer);
+
+                listContainer.addClass(listContainerClass);
+            }
+
+            //update the page element reference
+            this.pageRef = [];
+
+            if (pages.first) {//if the there is first page element
+                first = this.buildPageItem("first", pages.first);
+
+                if (first) {
+                    listContainer.append(first);
+                }
+
+            }
+
+            if (pages.prev) {//if the there is previous page element
+
+                prev = this.buildPageItem("prev", pages.prev);
+
+                if (prev) {
+                    listContainer.append(prev);
+                }
+
+            }
+
+
+            for (i = 0; i < pages.length; i = i + 1) {//fill the numeric pages.
+
+                p = this.buildPageItem("page", pages[i]);
+
+                if (p) {
+                    listContainer.append(p);
+                }
+            }
+
+            if (pages.next) {//if there is next page
+
+                next = this.buildPageItem("next", pages.next);
+
+                if (next) {
+                    listContainer.append(next);
+                }
+            }
+
+            if (pages.last) {//if there is last page
+
+                last = this.buildPageItem("last", pages.last);
+
+                if (last) {
+                    listContainer.append(last);
+                }
+            }
+        },
+
+        /**
+         *
+         * Creates a page item base on the type and page number given.
+         *
+         * @param page page number
+         * @param type type of the page, whether it is the first, prev, page, next, last
+         *
+         * @return Object the constructed page element
+         * */
+        buildPageItem: function (type, page) {
+
+            var itemContainer = $("<li></li>"),//creates the item container
+                itemContent = $("<a></a>"),//creates the item content
+                text = "",
+                title = "",
+                itemContainerClass = this.options.itemContainerClass(type, page, this.currentPage),
+                itemContentClass = this.getValueFromOption(this.options.itemContentClass, type, page, this.currentPage),
+                tooltipOpts = null;
+
+
+            switch (type) {
+
+            case "first":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "last":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "prev":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "next":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            case "page":
+                if (!this.getValueFromOption(this.options.shouldShowPage, type, page, this.currentPage)) { return; }
+                text = this.options.itemTexts(type, page, this.currentPage);
+                title = this.options.tooltipTitles(type, page, this.currentPage);
+                break;
+            }
+
+            itemContainer.addClass(itemContainerClass).append(itemContent);
+
+            itemContent.addClass(itemContentClass).html(text).on("click", null, {type: type, page: page}, $.proxy(this.onPageItemClicked, this));
+
+            if (this.options.pageUrl) {
+                itemContent.attr("href", this.getValueFromOption(this.options.pageUrl, type, page, this.currentPage));
+            }
+
+            if (this.options.useBootstrapTooltip) {
+                tooltipOpts = $.extend({}, this.options.bootstrapTooltipOptions, {title: title});
+
+                itemContent.tooltip(tooltipOpts);
+            } else {
+                itemContent.attr("title", title);
+            }
+
+            return itemContainer;
+
+        },
+
+        setCurrentPage: function (page) {
+            if (page > this.totalPages || page < 1) {// if the current page is out of range, throw exception.
+
+                throw "Page out of range";
+
+            }
+
+            this.lastPage = this.currentPage;
+
+            this.currentPage = parseInt(page, 10);
+
+        },
+
+        /**
+         * Gets an array that represents the current status of the page object. Numeric pages can be access via array mode. length attributes describes how many numeric pages are there. First, previous, next and last page can be accessed via attributes first, prev, next and last. Current attribute marks the current page within the pages.
+         *
+         * @return object output objects that has first, prev, next, last and also the number of pages in between.
+         * */
+        getPages: function () {
+
+            var totalPages = this.totalPages,// get or calculate the total pages via the total records
+                pageStart = (this.currentPage % this.numberOfPages === 0) ? (parseInt(this.currentPage / this.numberOfPages, 10) - 1) * this.numberOfPages + 1 : parseInt(this.currentPage / this.numberOfPages, 10) * this.numberOfPages + 1,//calculates the start page.
+                output = [],
+                i = 0,
+                counter = 0;
+
+            pageStart = pageStart < 1 ? 1 : pageStart;//check the range of the page start to see if its less than 1.
+
+            for (i = pageStart, counter = 0; counter < this.numberOfPages && i <= totalPages; i = i + 1, counter = counter + 1) {//fill the pages
+                output.push(i);
+            }
+
+            output.first = 1;//add the first when the current page leaves the 1st page.
+
+            if (this.currentPage > 1) {// add the previous when the current page leaves the 1st page
+                output.prev = this.currentPage - 1;
+            } else {
+                output.prev = 1;
+            }
+
+            if (this.currentPage < totalPages) {// add the next page when the current page doesn't reach the last page
+                output.next = this.currentPage + 1;
+            } else {
+                output.next = totalPages;
+            }
+
+            output.last = totalPages;// add the last page when the current page doesn't reach the last page
+
+            output.current = this.currentPage;//mark the current page.
+
+            output.total = totalPages;
+
+            output.numberOfPages = this.options.numberOfPages;
+
+            return output;
+
+        },
+
+        /**
+         * Gets the value from the options, this is made to handle the situation where value is the return value of a function.
+         *
+         * @return mixed value that depends on the type of parameters, if the given parameter is a function, then the evaluated result is returned. Otherwise the parameter itself will get returned.
+         * */
+        getValueFromOption: function (value) {
+
+            var output = null,
+                args = Array.prototype.slice.call(arguments, 1);
+
+            if (typeof value === 'function') {
+                output = value.apply(this, args);
+            } else {
+                output = value;
+            }
+
+            return output;
+
+        }
+
+    };
+
+
+    /* TYPEAHEAD PLUGIN DEFINITION
+     * =========================== */
+
+    old = $.fn.bootstrapPaginator;
+
+    $.fn.bootstrapPaginator = function (option) {
+
+        var args = arguments,
+            result = null;
+
+        $(this).each(function (index, item) {
+            var $this = $(item),
+                data = $this.data('bootstrapPaginator'),
+                options = (typeof option !== 'object') ? null : option;
+
+            if (!data) {
+                data = new BootstrapPaginator(this, options);
+
+                $this = $(data.$element);
+
+                $this.data('bootstrapPaginator', data);
+
+                return;
+            }
+
+            if (typeof option === 'string') {
+
+                if (data[option]) {
+                    result = data[option].apply(data, Array.prototype.slice.call(args, 1));
+                } else {
+                    throw "Method " + option + " does not exist";
+                }
+
+            } else {
+                result = data.setOptions(option);
+            }
+        });
+
+        return result;
+
+    };
+
+    $.fn.bootstrapPaginator.sizeArray = {
+
+        "2": {
+            "large": "pagination-large",
+            "small": "pagination-small",
+            "mini": "pagination-mini"
+        },
+        "3": {
+            "large": "pagination-lg",
+            "small": "pagination-sm",
+            "mini": ""
+        }
+
+    };
+
+    $.fn.bootstrapPaginator.defaults = {
+        containerClass: "",
+        size: "normal",
+        alignment: "left",
+        bootstrapMajorVersion: 2,
+        listContainerClass: "",
+        itemContainerClass: function (type, page, current) {
+            return (page === current) ? "active" : "";
+        },
+        itemContentClass: function (type, page, current) {
+            return "";
+        },
+        currentPage: 1,
+        numberOfPages: 5,
+        totalPages: 1,
+        pageUrl: function (type, page, current) {
+            return null;
+        },
+        onPageClicked: null,
+        onPageChanged: null,
+        useBootstrapTooltip: false,
+        shouldShowPage: function (type, page, current) {
+
+            var result = true;
+
+            switch (type) {
+            case "first":
+                result = (current !== 1);
+                break;
+            case "prev":
+                result = (current !== 1);
+                break;
+            case "next":
+                result = (current !== this.totalPages);
+                break;
+            case "last":
+                result = (current !== this.totalPages);
+                break;
+            case "page":
+                result = true;
+                break;
+            }
+
+            return result;
+
+        },
+        itemTexts: function (type, page, current) {
+            switch (type) {
+            case "first":
+                return "&lt;&lt;";
+            case "prev":
+                return "&lt;";
+            case "next":
+                return "&gt;";
+            case "last":
+                return "&gt;&gt;";
+            case "page":
+                return page;
+            }
+        },
+        tooltipTitles: function (type, page, current) {
+
+            switch (type) {
+            case "first":
+                return "Go to first page";
+            case "prev":
+                return "Go to previous page";
+            case "next":
+                return "Go to next page";
+            case "last":
+                return "Go to last page";
+            case "page":
+                return (page === current) ? "Current page is " + page : "Go to page " + page;
+            }
+        },
+        bootstrapTooltipOptions: {
+            animation: true,
+            html: true,
+            placement: 'top',
+            selector: false,
+            title: "",
+            container: false
+        }
+    };
+
+    $.fn.bootstrapPaginator.Constructor = BootstrapPaginator;
+
+
+
+}(window.jQuery));

+ 9 - 2
modules/common/base/base_controller.js

@@ -5,6 +5,9 @@
  * @date 2017/6/29
  * @version
  */
+import Moment from "moment";
+import Url from "url";
+
 class BaseController {
 
     /**
@@ -34,8 +37,12 @@ class BaseController {
      * @return {void}
      */
     init(request, response, next) {
-        // 页面标题
-        response.locals.title = 'test';
+        // moment工具
+        response.locals.moment = Moment;
+
+        // url相关数据
+        let urlInfo = Url.parse(request.originalUrl, true);
+        response.locals.urlQuery = JSON.stringify(urlInfo.query);
 
         next();
     }

+ 14 - 0
modules/common/const/log_type_const.js

@@ -0,0 +1,14 @@
+/**
+ * 日志类型常量
+ *
+ * @author CaiAoLin
+ * @date 2017/7/27
+ * @version
+ */
+
+const logType = {
+    // 登录日志
+    LOGIN_LOG: 1
+};
+
+export default logType;

+ 7 - 1
modules/common/helper/mongoose_helper.js

@@ -51,6 +51,12 @@ class MongooseHelper {
      */
     find(conditions, fields = null, option = null) {
         let self = this;
+        let limit = 0;
+        let skip = 0;
+        if (Object.keys(option).length > 0) {
+            limit = option.pageSize !== undefined ? option.pageSize : limit;
+            skip = option.offset !== undefined ? option.offset : skip;
+        }
         return new Promise(function (resolve, reject) {
             self.model.find(conditions, fields, option, function (error, data) {
                 if (error) {
@@ -58,7 +64,7 @@ class MongooseHelper {
                 } else {
                     resolve(data);
                 }
-            });
+            }).skip(skip).limit(limit);
         });
     }
 

+ 16 - 3
modules/ration_glj/facade/glj_calculate_facade.js

@@ -9,9 +9,12 @@ let ration_glj = mongoose.model('ration_glj');
 let ration = mongoose.model('ration');
 let ration_coe = mongoose.model('ration_coe');
 let std_ration_lib_ration_items = mongoose.model('std_ration_lib_ration_items');
+let glj_type_util = require('../../../public/cache/std_glj_type_util');
+
 
 module.exports={
-    calculateQuantity:calculateQuantity
+    calculateQuantity:calculateQuantity,
+    getGLJTypeByID:getGLJTypeByID
 }
 //辅助定额调整、替换工料机、标准附注条件调整、添加工料机、自定义消耗量(包括删除工料机)、自定义乘系数、市场单价调整
 let stateSeq ={
@@ -197,7 +200,7 @@ function everyCoe(quantity,coe,glj) {
                 coeQuantity = getCalculateResult(coeQuantity,coe.coes[i]);
             } else if(coe.coes[i].coeType=='定额'){
                 coeQuantity = getCalculateResult(coeQuantity,coe.coes[i]);
-            }else if(coe.coes[i].coeType==glj.gljDistType){
+            }else if(coe.coes[i].coeType==getGLJTypeByID(glj.type)){
                 coeQuantity = getCalculateResult(coeQuantity,coe.coes[i]);
             }
         }
@@ -212,7 +215,7 @@ function calculateQuantityByCustomerCoes(quantify,coe,glj) {
         return getCalculateResult(quantify, coe.coes[0])
     }else {
         for(let i=1;i<coe.coes.length;i++){
-            if(coe.coes[i].coeType.search(glj.gljDistType)!=-1){
+            if(coe.coes[i].coeType.search(getGLJTypeByID(glj.type))!=-1){
                 return getCalculateResult(quantify,coe.coes[i])
             }
         }
@@ -240,5 +243,15 @@ function getCalculateResult(quantify,c) {
             break;
     }
     return q;
+}
 
+function getGLJTypeByID(id) {
+    let glj_type_object = glj_type_util.getStdGljTypeCacheObj();
+    let topTypeId = glj_type_object.getTopParentIdByItemId(id);
+    let type = glj_type_object.getItemById(topTypeId);
+    if(type!=undefined){
+        return type.fullName;
+    }else {
+        return '';
+    }
 }

+ 73 - 16
modules/ration_glj/facade/quantity_detail_facade.js

@@ -18,7 +18,9 @@ let bill_model=mongoose.model("bills");
 
 module.exports={
     save:save,
-    getData:getData
+    getData:getData,
+    deleteByRation:deleteByRation,
+    deleteByBill:deleteByBill
 };
 
 let operationMap={
@@ -62,7 +64,7 @@ function insertRecode(user_id,datas) {
         let doc = datas.doc;
         doc.ID = uuidV1();
         doInsertRecode(doc).then(function (result) {
-            console.log(result);
+            //console.log(result);
             if(result.err){
                 callback(result.err,'')
             }else {
@@ -508,23 +510,12 @@ function updateRecored(query,doc,callback) {
     })
 }
 
-function checkingRegex(datas) {
-    try{
-        if(datas.doc.hasOwnProperty('regex')){
-           // datas.doc.result=eval(datas.doc.regex);
-        }
-        return null;
-    }catch (error){
-        console.log(error.message);
-        return error
-    }
-
-}
 
 function update_quantity_detail(user_id,datas) {
     if(datas.updateFunction){
         return updateFunctionMap[datas.updateFunction](user_id,datas);
     }else {
+        console.log(datas);
         return normalUpdate(user_id,datas);
     }
 }
@@ -532,14 +523,56 @@ function update_quantity_detail(user_id,datas) {
 function delete_quantity_detail(user_id,datas) {
     return function (callback) {
         doQuantityDelete(datas.doc).then(function (result) {
-
+            console.log(result);
+            if(result.err){
+                callback(result.err,'')
+            }else {
+                callback(null,result.returndata)
+            }
         });
-        callback(null,'');
     }
 }
 
 async function doQuantityDelete(doc) {
    console.log(doc) ;
+    let result={
+        err:null
+    }
+    try{
+        let query = {
+            projectID:doc.projectID,
+            seq : { $gt: doc.seq }
+        }
+        if(doc.hasOwnProperty('rationID')){
+            query.rationID = doc.rationID;
+        }else {
+            query.billID = doc.billID;
+        }
+        let quantity_detail_List = await getDatailList(doc,{data:{}});
+        let update_task = getUpdateReferenceTask(quantity_detail_List,doc.seq,-1);
+        await quantity_detail_model.update(query,{$inc:{seq:-1}},{multi: true});
+        if(update_task.length>0){
+            await quantity_detail_model.bulkWrite(generateUpdateTaks(update_task));
+        }
+        await quantity_detail_model.deleteOne({ID:doc.ID,projectID:doc.projectID});
+        let returndata ={
+            moduleName:consts.projectConst.QUANTITY_DETAIL,
+            data:{
+                doc:doc,
+                resort:true,
+                update_task:update_task,
+                updateTpye:commonConsts.UT_DELETE
+            }
+        };
+        result.returndata =returndata
+        return result;
+    }catch (error){
+        console.log(error)
+        result.err;
+        return result
+    }
+
+
 }
 
 
@@ -573,4 +606,28 @@ function save (user_id, datas, callback) {
             }
         }
     })
+}
+
+function deleteByRation(data) {
+    return function (callback) {
+        quantity_detail_model.deleteMany({projectID: data.projectID, rationID: data.ID},(err,result)=>{
+            commonCallback(callback,result,err);
+        });
+    }
+}
+function deleteByBill(data) {
+    return function (callback) {
+        console.log({projectID: data.projectID, billID: data.ID});
+        quantity_detail_model.deleteMany({projectID: data.projectID, billID: data.ID},(err,result)=>{
+            commonCallback(callback,result,err);
+        });
+    }
+}
+
+function commonCallback(callback,result,err) {
+    if(err){
+        callback(err,'');
+    }else {
+        callback(null,result);
+    }
 }

+ 8 - 2
modules/ration_glj/facade/ration_glj_facade.js

@@ -17,6 +17,8 @@ let ration_coe_facade = require('./ration_coe_facade');
 let ration_coe = mongoose.model('ration_coe');
 let std_ration_lib_ration_items = mongoose.model('std_ration_lib_ration_items');
 let glj_calculate_facade = require('./glj_calculate_facade');
+let quantity_detail_facade = require('./quantity_detail_facade');
+
 
 
 module.exports={
@@ -92,7 +94,7 @@ function get_lib_glj_info(ration_glj) {
                 ration_glj.unit = glj.unit;
                 ration_glj.specs = glj.specs;
                 ration_glj.basePrice = glj.basePrice;
-                ration_glj.gljDistType = glj.gljDistType;
+                ration_glj.shortName = glj.shortName;
                 ration_glj.type = glj.gljType;
                 getInfoFromProjectGLJ(ration_glj).then(function (result) {
                     if(result){
@@ -121,6 +123,7 @@ async function getInfoFromProjectGLJ(ration_glj) {
          base_price: ration_glj.basePrice,
          market_price: ration_glj.basePrice
      };
+
      try {
          let projectGljModel = new GLJListModel();
          let result = await projectGljModel.addList(data);
@@ -329,7 +332,8 @@ function deleteByRation(datas,callback) {
     let data = datas.updateData;
     let tasks=[];
     tasks.push(deleteGLJList(data));
-    tasks.push(ration_coe_facade.delete_ration_coe(data))
+    tasks.push(ration_coe_facade.delete_ration_coe(data));
+    tasks.push(quantity_detail_facade.deleteByRation(data));
     async_n.parallel(tasks,function (err,result) {
         commonCallback(callback,result,err)
     })
@@ -429,7 +433,9 @@ function deleteByMultiRations(datas) {
         for(let i=0;i<rations.length;i++){
             delete_tasks.push(deleteOne(rations[i]._doc));
             delete_tasks.push(ration_coe_facade.delete_ration_coe(rations[i]._doc));
+            delete_tasks.push(quantity_detail_facade.deleteByRation(rations[i]._doc));
         }
+        delete_tasks.push(quantity_detail_facade.deleteByBill(datas.updateData));
         async_n.parallel(delete_tasks,(err,results)=>{
             if (err){
                 deleteCallBack(err,'')

+ 1 - 1
modules/ration_glj/models/ration_glj.js

@@ -15,7 +15,7 @@ var ration_glj = new Schema({
     specs:String,
     unit:String,
     basePrice:Number,
-    gljDistType:String,
+    shortName:String,
     type:Number,
     quantity:Number,
     customQuantity:Number,

+ 2 - 1
modules/ration_glj/models/ration_glj_temp.js

@@ -32,7 +32,8 @@ var gljSchema =new Schema({
     unit: String,
     basePrice: Number,
     gljType: Number, //这个是UI显示上的详细分类,对应gljTypeSchema
-    gljDistType: String  //人工,材料,机械
+    shortName: String,  //人工,材料,机械
+    gljClass:Number
 },{versionKey:false});
 
 mongoose.model("std_ration_lib_glj_list",gljSchema,"std_ration_lib_glj_list");

+ 2 - 1
modules/ration_repository/models/glj_repository.js

@@ -28,7 +28,8 @@ var gljSchema = mongoose.Schema({
     unit: String,
     basePrice: Number,
     gljType: Number, //这个是UI显示上的详细分类,对应gljTypeSchema
-    gljDistType: String  //人工,材料,机械
+    shortName: String,  //人工,材料,机械
+    gljClass:Number
 });
 var gljTypeModel = db.model("std_ration_lib_glj_type",gljTypeSchema, "std_ration_lib_glj_type");
 var gljItemModel = mongoose.model("std_ration_lib_glj_list");

+ 5 - 2
modules/reports/controllers/rpt_controller.js

@@ -62,15 +62,18 @@ module.exports = {
         let rpt_id = req.body.ID;
         let pageSize = req.body.pageSize;
         getAllPagesCommon(req, res, rpt_id, pageSize, function(pageRst){
+            //fs.writeFileSync('D:/GitHome/ConstructionOperation/tmp/testRpt.js', JSON.stringify(pageRst));
             callback(req, res, null, pageRst);
         })
     },
     getExcel: function(req, res) {
         let rpt_id = req.params.id,
             pageSize = req.params.size,
-            rptName = req.params.rptName;
+            rptName = req.params.rptName,
+            isOneSheet = req.params.isOneSheet;
+        ;
         getAllPagesCommon(req, res, rpt_id, pageSize, function(pageRst){
-            rpt_xl_util.exportExcel(pageRst, rptName, null, function(newName){
+            rpt_xl_util.exportExcel(pageRst, pageSize, rptName, isOneSheet, function(newName){
                 res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                 res.setHeader("Content-Disposition", "attachment; filename=" + strUtil.getPinYinCamelChars(rptName) + ".xlsx");
                 let filestream = fs.createReadStream(__dirname.slice(0, __dirname.length - 28) + '/tmp/' + newName + '.xlsx');

+ 37 - 0
modules/reports/models/rpt_tpl_data.js

@@ -0,0 +1,37 @@
+/**
+ * Created by Tony on 2017/7/24.
+ */
+
+let mongoose = require('mongoose');
+let dbm = require("../../../config/db/db_manager");
+let smartcostdb = dbm.getCfgConnection("scConstruct");
+let Schema = mongoose.Schema;
+
+let rptTplPrjSchema = new Schema({
+    "ID": Number,
+    "ParentID": Number,
+    "NextSiblingID": Number,
+    "name": String,         //项目名称
+    "location": String,     //工程地点
+    "constructor": String,  //建设单位
+    "supervisor": String,   //监理
+    "auditor": String       //审核
+});
+
+let rptTplBillsSchema = new Schema({
+
+});
+
+let rptTplRationSchema = new Schema({
+
+});
+
+let tplPrjData = smartcostdb.model("temp_tpl_data", rptTplPrjSchema, "projects");
+let tplBillsData = smartcostdb.model("temp_tpl_data", rptTplBillsSchema, "bills");
+let tplRationData = smartcostdb.model("temp_tpl_data", rptTplRationSchema, "ration");
+
+module.exports = {
+    prjMdl: tplPrjData,
+    billsMdl: tplBillsData,
+    rationMdl: tplRationData
+};

+ 1 - 2
modules/reports/routes/report_router.js

@@ -9,10 +9,9 @@ module.exports = function (app) {
     let reportController = require('./../controllers/rpt_controller');
 
     rptRouter.post('/getReport', reportController.getReportAllPages);
-    rptRouter.get('/getExcel/:id/:size/:rptName', reportController.getExcel);
+    rptRouter.get('/getExcel/:id/:size/:rptName/:isOneSheet', reportController.getExcel);
 
     app.use("/report_api", rptRouter);
 };
 
 
-

+ 8 - 3
modules/reports/util/rpt_data_util.js

@@ -11,7 +11,7 @@ class Rpt_Common{
 class Rpt_Data_Extractor {
     initialize(Projects) {
         this.Projects = Projects;
-        //Projects对象从前端传送过来,无需在后端重复查询及构建
+        //Projects对象应该从前端传送过来,无需在后端重复查询及构建
         /* 结构:
          {
             currentPrjId: int,
@@ -35,9 +35,14 @@ class Rpt_Data_Extractor {
          */
     };
 
-    prepare($CURRENT_RPT) {
+    prepareData($CURRENT_RPT) {
         //在报表提取数据前的准备工作,主要有:
-        //1. 确认指标数据的类型,
+        //1. 确认指标数据的类型(离散/主/从)
+        //2. 根据类型提取数据,排序
+        // 2.1. header类型
+        // 2.2. 章类型
+        // 2.3. detail类型
+        // 2.4. 排序
     };
 
 }

+ 242 - 137
modules/reports/util/rpt_excel_util.js

@@ -9,7 +9,7 @@ let jpcCmnHelper = require('../rpt_component/helper/jpc_helper_common');
 let DPI = jpcCmnHelper.getScreenDPI()[0];
 const dftHeadXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
 
-function writeContentTypes(sheets) {
+function writeContentTypes(sheets, isSinglePage) {
     let rst = [];
     rst.push(dftHeadXml + '\r\n');
     rst.push('<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">');
@@ -21,8 +21,12 @@ function writeContentTypes(sheets) {
     rst.push('<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>');
     rst.push('<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>');
     rst.push('<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>');
-    for (let i = 0; i < sheets.length; i++) {
-        rst.push('<Override PartName="/xl/worksheets/sheet' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>')
+    if (isSinglePage) {
+        rst.push('<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>')
+    } else {
+        for (let i = 0; i < sheets.length; i++) {
+            rst.push('<Override PartName="/xl/worksheets/sheet' + (i + 1) + '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>')
+        }
     }
     rst.push('<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>');
     rst.push('</Types>');
@@ -38,7 +42,7 @@ function writeRootRels(){
     rst.push('</Relationships>');
     return rst;
 }
-function writeApp(sheets) {
+function writeApp(sheets, isSinglePage) {
     let rst = [];
     rst.push(dftHeadXml + '\r\n');
     rst.push('<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">');
@@ -48,13 +52,19 @@ function writeApp(sheets) {
     rst.push('<HeadingPairs>');
     rst.push('<vt:vector size="2" baseType="variant">');
     rst.push('<vt:variant><vt:lpstr>工作表</vt:lpstr></vt:variant>');
-    rst.push('<vt:variant><vt:i4>' + sheets.length + '</vt:i4></vt:variant>');
+    if (isSinglePage) rst.push('<vt:variant><vt:i4>1</vt:i4></vt:variant>')
+    else rst.push('<vt:variant><vt:i4>' + sheets.length + '</vt:i4></vt:variant>');
     rst.push('</vt:vector>');
     rst.push('</HeadingPairs>');
     rst.push('<TitlesOfParts>');
-    rst.push('<vt:vector size="' + sheets.length + '" baseType="lpstr">');
-    for (let i = 0; i < sheets.length; i++) {
-        rst.push('<vt:lpstr>' + sheets[i].sheetName + '</vt:lpstr>')
+    if (isSinglePage) {
+        rst.push('<vt:vector size="1" baseType="lpstr">');
+        rst.push('<vt:lpstr>' + sheets[0].sheetName + '</vt:lpstr>')
+    } else {
+        rst.push('<vt:vector size="' + sheets.length + '" baseType="lpstr">');
+        for (let i = 0; i < sheets.length; i++) {
+            rst.push('<vt:lpstr>' + sheets[i].sheetName + '</vt:lpstr>')
+        }
     }
     rst.push('</vt:vector>');
     rst.push('</TitlesOfParts>');
@@ -88,7 +98,7 @@ function writeCore() {
     rst.push('</cp:coreProperties>');
     return rst;
 }
-function writeXlWorkBook(sheets){
+function writeXlWorkBook(sheets, isSinglePage){
     let rst = [];
     rst.push(dftHeadXml + '\r\n');
     rst.push('<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
@@ -96,8 +106,12 @@ function writeXlWorkBook(sheets){
     rst.push('<workbookPr defaultThemeVersion="124226"/>');
     rst.push('<bookViews><workbookView xWindow="360" yWindow="345" windowWidth="14655" windowHeight="4305"/></bookViews>');
     rst.push('<sheets>');
-    for (let i = 0; i < sheets.length; i++) {
-        rst.push('<sheet name="' + sheets[i].sheetName + '" sheetId="' + (i + 1) + '" r:id="rId' + (i + 1) + '"/>')
+    if (isSinglePage) {
+        rst.push('<sheet name="' + sheets[0].sheetName + '" sheetId="1" r:id="rId1"/>');
+    } else {
+        for (let i = 0; i < sheets.length; i++) {
+            rst.push('<sheet name="' + sheets[i].sheetName + '" sheetId="' + (i + 1) + '" r:id="rId' + (i + 1) + '"/>');
+        }
     }
     rst.push('</sheets>');
     rst.push('<calcPr calcId="124519"/>');
@@ -105,13 +119,18 @@ function writeXlWorkBook(sheets){
     rst.push('</workbook>');
     return rst;
 }
-function writeXlRels(sheets){
+function writeXlRels(sheets, isSinglePage){
     let rst = [], idx = 1;
     rst.push(dftHeadXml + '\r\n');
     rst.push('<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">');
-    for (let i = 0; i < sheets.length; i++) {
-        rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' + (i + 1) + '.xml"/>')
+    if (isSinglePage) {
+        rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>')
         idx++;
+    } else {
+        for (let i = 0; i < sheets.length; i++) {
+            rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet' + (i + 1) + '.xml"/>')
+            idx++;
+        }
     }
     rst.push('<Relationship Id="rId' + idx + '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>');
     idx++;
@@ -213,7 +232,7 @@ function writeSharedString(sharedStrList){
     }
     return rst;
 }
-function writeSheets(pageData, sharedStrList, stylesObj){
+function writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage){
     let rst = [];
     private_pushDftFont = function(){
         let font = {};
@@ -221,52 +240,73 @@ function writeSheets(pageData, sharedStrList, stylesObj){
             stylesObj.fonts = [];
         }
         font[JV.FONT_PROPS[0]] = "宋体"; //font name
-        font.size = 11;
+        font.size = 12;
         font.charset = 134;
         font.colorIdx = "8";
         stylesObj.fonts.push(font);
     };
     private_pushDftFont();
-    for (let i = 0; i < pageData.items.length; i++) {
-        rst.push(writeSheet(pageData, pageData.items[i], sharedStrList, stylesObj));
+    if (isSinglePage) {
+        rst.push(writeSheet(pageData, null, paperSize, sharedStrList, stylesObj));
+    } else {
+        for (let i = 0; i < pageData.items.length; i++) {
+            rst.push(writeSheet(pageData, pageData.items[i], paperSize, sharedStrList, stylesObj));
+        }
     }
     return rst;
 }
-function writeSheet(pageData, sheetData, sharedStrList, stylesObj){
-    let rst = [], xPos = [], yPos = [], headerStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+function writeSheet(pageData, sheetData, paperSize, sharedStrList, stylesObj){
+    let rst = [], xPos = [], yPos = [], yMultiPos = [], headerStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
     let cacheBorderCell = {};
-    xPos.push(0);
-    yPos.push(0);
     private_pre_analyze_pos = function(){
         let cell, pos;
-        sheetData.cells.sort(function(cell1, cell2) {
-            let rst = 0;
-            if (cell1[JV.PROP_AREA][JV.PROP_TOP] > cell2[JV.PROP_AREA][JV.PROP_TOP]) {
-                rst = 1;
-            } else if (cell1[JV.PROP_AREA][JV.PROP_TOP] < cell2[JV.PROP_AREA][JV.PROP_TOP]) {
-                rst = -1;
-            } else {
-                if (cell1[JV.PROP_AREA][JV.PROP_LEFT] > cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
+        self_analyze_sheet_pos = function (theShtData, theXPos, theYPos) {
+            theShtData.cells.sort(function(cell1, cell2) {
+                let rst = 0;
+                if (cell1[JV.PROP_AREA][JV.PROP_TOP] > cell2[JV.PROP_AREA][JV.PROP_TOP]) {
                     rst = 1;
-                } else if (cell1[JV.PROP_AREA][JV.PROP_LEFT] < cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
+                } else if (cell1[JV.PROP_AREA][JV.PROP_TOP] < cell2[JV.PROP_AREA][JV.PROP_TOP]) {
                     rst = -1;
+                } else {
+                    if (cell1[JV.PROP_AREA][JV.PROP_LEFT] > cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
+                        rst = 1;
+                    } else if (cell1[JV.PROP_AREA][JV.PROP_LEFT] < cell2[JV.PROP_AREA][JV.PROP_LEFT]) {
+                        rst = -1;
+                    }
                 }
+                return rst;
+            });
+            for (let i = 0; i < theShtData.cells.length; i++) {
+                cell = theShtData.cells[i];
+                pos = cell[JV.PROP_AREA][JV.PROP_LEFT];
+                if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
+                pos = cell[JV.PROP_AREA][JV.PROP_RIGHT];
+                if (theXPos.indexOf(pos) < 0) theXPos.push(pos);
+                pos = cell[JV.PROP_AREA][JV.PROP_TOP];
+                if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
+                pos = cell[JV.PROP_AREA][JV.PROP_BOTTOM];
+                if (theYPos.indexOf(pos) < 0) theYPos.push(pos);
+            }
+        };
+        xPos.push(0);
+        if (sheetData) {
+            //current sheet data
+            yPos.push(0);
+            self_analyze_sheet_pos(sheetData, xPos, yPos);
+            xPos.sort(private_array_sort);
+            yPos.sort(private_array_sort);
+        } else {
+            //total data in one sheet
+            for (let shtItemData of pageData.items) {
+                let tmpPos = [];
+                tmpPos.push(0);
+                self_analyze_sheet_pos(shtItemData, xPos, tmpPos);
+                tmpPos.sort(private_array_sort);
+                yMultiPos.push(tmpPos);
             }
-            return rst;
-        });
-        for (let i = 0; i < sheetData.cells.length; i++) {
-            cell = sheetData.cells[i];
-            pos = cell[JV.PROP_AREA][JV.PROP_LEFT];
-            if (xPos.indexOf(pos) < 0) xPos.push(pos);
-            pos = cell[JV.PROP_AREA][JV.PROP_RIGHT];
-            if (xPos.indexOf(pos) < 0) xPos.push(pos);
-            pos = cell[JV.PROP_AREA][JV.PROP_TOP];
-            if (yPos.indexOf(pos) < 0) yPos.push(pos);
-            pos = cell[JV.PROP_AREA][JV.PROP_BOTTOM];
-            if (yPos.indexOf(pos) < 0) yPos.push(pos);
-        }
-        xPos.sort(private_array_sort);
-        yPos.sort(private_array_sort);
+            xPos.sort(private_array_sort);
+            yPos = yMultiPos[0];
+        }
     };
     private_array_sort = function(i1, i2){
         let rst = 0;
@@ -466,15 +506,28 @@ function writeSheet(pageData, sheetData, sharedStrList, stylesObj){
         let cell, idxR, idxL, idxT, idxB, cnt = 0;
         rst.push('<mergeCells count="?">');
         let startIdx = rst.length - 1;
-        for (let i = 0; i < sheetData.cells.length; i++) {
-            cell = sheetData.cells[i];
-            idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
-            idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
-            idxB = yPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
-            idxT = yPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
-            if (idxR - idxL > 1 || idxB - idxT > 1) {
-                rst.push('<mergeCell ref="' + private_getCellIdxStr(idxL - 1) + idxT + ':' + private_getCellIdxStr(idxR - 2) + (idxB - 1) + '"/>');
-                cnt++;
+        self_setMergedCells = function (theData, theYPos, offsetY) {
+            for (let i = 0; i < theData.cells.length; i++) {
+                cell = theData.cells[i];
+                idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
+                idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
+                idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
+                idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
+                if (idxR - idxL > 1 || idxB - idxT > 1) {
+                    rst.push('<mergeCell ref="' + private_getCellIdxStr(idxL - 1) + (idxT + offsetY) + ':' + private_getCellIdxStr(idxR - 2) + (idxB - 1 + offsetY) + '"/>');
+                    cnt++;
+                }
+            }
+        }
+        if (sheetData) {
+            self_setMergedCells(sheetData, yPos, 0);
+        } else {
+            let osY = 0;
+            for (let i = 0; i < pageData.items.length; i++) {
+                let shtItemData = pageData.items[i];
+                let tmpPos = yMultiPos[i];
+                self_setMergedCells(shtItemData, tmpPos, osY);
+                osY += tmpPos.length;
             }
         }
         rst[startIdx] = '<mergeCells count="' + cnt + '">';
@@ -482,10 +535,10 @@ function writeSheet(pageData, sheetData, sharedStrList, stylesObj){
     };
     private_chkIfNeedCacheCell = function(cell){
         let rst = false;
-        if (cell[JV.PROP_AREA][JV.PROP_LEFT] == pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] ||
-            cell[JV.PROP_AREA][JV.PROP_RIGHT] == pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] ||
-            cell[JV.PROP_AREA][JV.PROP_TOP] == pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] ||
-            cell[JV.PROP_AREA][JV.PROP_BOTTOM] == pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM]){
+        if (cell[JV.PROP_AREA][JV.PROP_LEFT] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] ||
+            cell[JV.PROP_AREA][JV.PROP_RIGHT] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] ||
+            cell[JV.PROP_AREA][JV.PROP_TOP] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] ||
+            cell[JV.PROP_AREA][JV.PROP_BOTTOM] === pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_BOTTOM]){
             if (cell[JV.PROP_AREA][JV.PROP_LEFT] >= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_LEFT] &&
                 cell[JV.PROP_AREA][JV.PROP_RIGHT] <= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_RIGHT] &&
                 cell[JV.PROP_AREA][JV.PROP_TOP] >= pageData[JV.BAND_PROP_MERGE_BAND][JV.PROP_TOP] &&
@@ -497,22 +550,35 @@ function writeSheet(pageData, sheetData, sharedStrList, stylesObj){
     };
     private_cacheMergeBandBorderIdxs = function() {
         let cell, idxR, idxL, idxT, idxB;
-        for (let i = 0; i < sheetData.cells.length; i++) {
-            cell = sheetData.cells[i];
-            idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
-            idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
-            idxB = yPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
-            idxT = yPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
-            if (idxR - idxL > 1 || idxB - idxT > 1) {
-                if (private_chkIfNeedCacheCell(cell)) {
-                    for (let xi = idxL; xi < idxR; xi++) {
-                        for (let yj = idxT; yj < idxB; yj++) {
-                            cacheBorderCell[private_getCellIdxStr(xi - 1) + yj] = cell;
+        self_cachMergeIdxs = function (theData, theYPos, offsetY) {
+            for (let i = 0; i < theData.cells.length; i++) {
+                cell = theData.cells[i];
+                idxR = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_RIGHT]);
+                idxL = xPos.indexOf(cell[JV.PROP_AREA][JV.PROP_LEFT]);
+                idxB = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_BOTTOM]);
+                idxT = theYPos.indexOf(cell[JV.PROP_AREA][JV.PROP_TOP]);
+                if (idxR - idxL > 1 || idxB - idxT > 1) {
+                    if (private_chkIfNeedCacheCell(cell)) {
+                        for (let xi = idxL; xi < idxR; xi++) {
+                            for (let yj = idxT; yj < idxB; yj++) {
+                                cacheBorderCell[private_getCellIdxStr(xi - 1) + yj + offsetY] = cell;
+                            }
                         }
                     }
                 }
             }
         }
+        if (sheetData) {
+            self_cachMergeIdxs(sheetData, yPos, 0);
+        } else {
+            let osY = 0;
+            for (let i = 0; i < pageData.items.length; i++) {
+                let shtItemData = pageData.items[i];
+                let tmpPos = yMultiPos[i];
+                self_cachMergeIdxs(shtItemData, tmpPos, osY);
+                osY += tmpPos.length;
+            }
+        }
     };
     private_getMergedCellStyleId = function(preStyleId, colIdxStr) {
         let rst = preStyleId;
@@ -526,80 +592,98 @@ function writeSheet(pageData, sheetData, sharedStrList, stylesObj){
         rst.push('<sheetData>');
         let spanX = xPos.length - 2, cellIdx = 0, h = 0,
             hasMoreCols = true, nextColIdx = -1,
-            nextRowIdx = yPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP])
+            nextRowIdx = 0
             ;
-        private_cacheMergeBandBorderIdxs();
-        for (let i = 1; i < yPos.length - 1; i++) {
-            h = 1.0 * (yPos[i+1] - yPos[i]) / DPI * 25.4 / 0.3612;
-            h = Math.round(h * 1000) / 1000;
-            rst.push('<row r="' + i + '" spans="1:' + spanX + '" ht="' + h + '" customHeight="1">');
-            //then put the cells of this row
-            let colIdxStr = '';
-            hasMoreCols = true;
-            while (nextRowIdx < i) {
-                if (cellIdx >= sheetData.cells.length || nextRowIdx > i) {
-                    break;
-                } else {
-                    cellIdx++;
-                    nextRowIdx = yPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
-                }
-            }
-            if (nextRowIdx > i) {
-                hasMoreCols = false;
-            }
-            nextColIdx = xPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_LEFT]);
-            let preStyleIdx = 1;
-            for (let j = 1; j < xPos.length - 1; j++) {
-                colIdxStr = private_getCellIdxStr(j - 1);
-                if (hasMoreCols) {
-                    if (nextColIdx == j) {
-                        let styleIdx = private_getStyleId(sheetData.cells[cellIdx]);
-                        preStyleIdx = styleIdx;
-                        if (strUtil.isEmptyString(sheetData.cells[cellIdx][JV.PROP_VALUE])) {
-                            rst.push('<c r="' + colIdxStr + i + '" s="' + styleIdx + '"/>');
-                            //should setup the right style instead!
-                        } else {
-                            let valIdx = private_getSharedStrIdx(sheetData.cells[cellIdx][JV.PROP_VALUE]);
-                            rst.push('<c r="' + colIdxStr + i + '" s="' + styleIdx + '" t="s">');
-                            rst.push('<v>' + valIdx + '</v>');
-                            rst.push('</c>');
-                        }
+        self_setData = function (theShtData, theYPos, offsetY) {
+            for (let i = 1; i < theYPos.length - 1; i++) {
+                h = (theYPos[i+1] - theYPos[i]) / DPI * 25.4 / 0.3612;
+                h = Math.round(h * 1000) / 1000;
+                rst.push('<row r="' + (i + offsetY) + '" spans="1:' + spanX + '" ht="' + h + '" customHeight="1">');
+                let colIdxStr = '';
+                hasMoreCols = true;
+                while (nextRowIdx < i) {
+                    if (cellIdx >= theShtData.cells.length || nextRowIdx > i) {
+                        break;
+                    } else {
                         cellIdx++;
-                        if (cellIdx < sheetData.cells.length) {
-                            nextRowIdx = yPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
-                            if (nextRowIdx > i) {
-                                hasMoreCols = false;
+                        nextRowIdx = theYPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
+                    }
+                }
+                if (nextRowIdx > i) {
+                    hasMoreCols = false;
+                }
+                nextColIdx = xPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_LEFT]);
+                let preStyleIdx = 1;
+                for (let j = 1; j < xPos.length - 1; j++) {
+                    colIdxStr = private_getCellIdxStr(j - 1);
+                    if (hasMoreCols) {
+                        if (nextColIdx == j) {
+                            let styleIdx = private_getStyleId(theShtData.cells[cellIdx]);
+                            preStyleIdx = styleIdx;
+                            if (strUtil.isEmptyString(theShtData.cells[cellIdx][JV.PROP_VALUE])) {
+                                rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + styleIdx + '"/>');
+                                //should setup the right style instead!
                             } else {
-                                nextColIdx = xPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_LEFT]);
+                                let valIdx = private_getSharedStrIdx(theShtData.cells[cellIdx][JV.PROP_VALUE]);
+                                rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + styleIdx + '" t="s">');
+                                rst.push('<v>' + valIdx + '</v>');
+                                rst.push('</c>');
                             }
-                        } else {
+                            cellIdx++;
+                            if (cellIdx < theShtData.cells.length) {
+                                nextRowIdx = theYPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
+                                if (nextRowIdx > i) {
+                                    hasMoreCols = false;
+                                } else {
+                                    nextColIdx = xPos.indexOf(theShtData.cells[cellIdx][JV.PROP_AREA][JV.PROP_LEFT]);
+                                }
+                            } else {
+                                hasMoreCols = false;
+                            }
+                        } else if (nextColIdx < 0) {
+                            //impossible!
+                            console.log('has abnormal case!');
                             hasMoreCols = false;
+                        } else {
+                            //rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + preStyleIdx + '"/>');
+                            rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + private_getMergedCellStyleId(preStyleIdx, colIdxStr + i + offsetY) + '"/>');
                         }
-                    } else if (nextColIdx < 0) {
-                        //impossible!
-                        console.log('has abnormal case!');
-                        hasMoreCols = false;
                     } else {
-                        //rst.push('<c r="' + colIdxStr + i + '" s="' + preStyleIdx + '"/>');
-                        rst.push('<c r="' + colIdxStr + i + '" s="' + private_getMergedCellStyleId(preStyleIdx, colIdxStr + i) + '"/>');
+                        //rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + preStyleIdx + '"/>');
+                        rst.push('<c r="' + colIdxStr + (i + offsetY) + '" s="' + private_getMergedCellStyleId(preStyleIdx, colIdxStr + i + offsetY) + '"/>');
                     }
-                } else {
-                    //rst.push('<c r="' + colIdxStr + i + '" s="' + preStyleIdx + '"/>');
-                    rst.push('<c r="' + colIdxStr + i + '" s="' + private_getMergedCellStyleId(preStyleIdx, colIdxStr + i) + '"/>');
                 }
+                rst.push('</row>');
+            }
+        }
+        private_cacheMergeBandBorderIdxs();
+        if (sheetData) {
+            //current sheet data
+            nextRowIdx = yPos.indexOf(sheetData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
+            self_setData(sheetData, yPos, 0);
+        } else {
+            //total data in one sheet
+            let cnt = 0;
+            for (let i = 0; i < pageData.items.length; i++) {
+                let shtItemData = pageData.items[i];
+                let tmpPos = yMultiPos[i];
+                cellIdx = 0;
+                nextRowIdx = tmpPos.indexOf(shtItemData.cells[cellIdx][JV.PROP_AREA][JV.PROP_TOP]);
+                self_setData(shtItemData, tmpPos, cnt);
+                cnt += tmpPos.length;
             }
-            rst.push('</row>');
         }
-        //sheetData.cells.length
         rst.push('</sheetData>');
     };
+
     private_pre_analyze_pos();
     rst.push(dftHeadXml + '\r\n');
     rst.push('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
     let colStr = private_getCellIdxStr(xPos.length - 3);
     rst.push('<dimension ref="A1:' + colStr + '' + yPos.length + '"/>');
     rst.push('<sheetViews><sheetView tabSelected="1" workbookViewId="0">');
-    rst.push('<selection sqref="A1:' + colStr + '1"/>');
+    //rst.push('<selection sqref="A1:' + colStr + '1"/>');
+    rst.push('<selection sqref="A1:A1"/>');
     rst.push('</sheetView></sheetViews>');
     rst.push('<sheetFormatPr defaultRowHeight="13.5"/>');
     private_setCols();
@@ -607,23 +691,37 @@ function writeSheet(pageData, sheetData, sharedStrList, stylesObj){
     private_setMergedCells();
     rst.push('<phoneticPr fontId="1" type="noConversion"/>');
     rst.push('<pageMargins left="0.315" right="0.215" top="0.315" bottom="0.315" header="0" footer="0"/>');
-    //rst.push('<pageSetup paperSize="9" fitToWidth="0" fitToHeight="0" orientation="landscape" horizontalDpi="300" verticalDpi="300"/>');
+    let paperSizeIdx = JV.PAGES_SIZE_STR.indexOf(paperSize);
+    let pStr = '';
+    if (paperSizeIdx >= 0) {
+        pStr = 'paperSize="' + JV.PAGES_SIZE_IDX[paperSizeIdx] + '"';
+    }
+    let orientationStr = (pageData[JV.NODE_PAGE_INFO][0] > pageData[JV.NODE_PAGE_INFO][1])?'landscape':'portrait';
+    rst.push('<pageSetup ' + pStr + ' fitToWidth="0" fitToHeight="0" orientation="' + orientationStr + '" />');
     rst.push('<headerFooter alignWithMargins="0"/>');
     rst.push('</worksheet>');
-    //rst.push('');
     return rst;
 }
 
 module.exports = {
-    exportExcel: function (pageData, fName, options, callback) {
-        let rptOptions = (options || {singlePage: false, fileName: 'report'});
+    exportExcel: function (pageData, paperSize, fName, options, callback) {
+        let rptOptions = ({singlePage: false, fileName: 'report'});
+        if (options === 'true') {
+            rptOptions.singlePage = true;
+        }
+        let isSinglePage = rptOptions.singlePage;
         let sheets = [];
+        if (isSinglePage) {
+            //
+        } else {
+            //
+        }
         for (let i = 0; i < pageData.items.length; i++) {
             sheets.push({sheetName: '第' + (i + 1) + '页'});
         }
         //1.
         let file = '[Content_Types].xml';
-        let data = writeContentTypes(sheets);
+        let data = writeContentTypes(sheets, isSinglePage);
         let zip = new JSZip();
         zip.file(file, data.join(''), {compression: 'DEFLATE'});
         //2.
@@ -634,7 +732,7 @@ module.exports = {
         //3.
         let zip_docProps = zip.folder('docProps');
         file = 'app.xml';
-        data = writeApp(sheets);
+        data = writeApp(sheets, isSinglePage);
         zip_docProps.file(file, data.join(''), {compression: 'DEFLATE'});
         file = 'core.xml';
         data = writeCore();
@@ -642,11 +740,11 @@ module.exports = {
         //4.
         let zip_xl = zip.folder('xl');
         file = 'workbook.xml';
-        data = writeXlWorkBook(sheets);
+        data = writeXlWorkBook(sheets, isSinglePage);
         zip_xl.file(file, data.join(''), {compression: 'DEFLATE'});
         let zip_rels2 = zip_xl.folder('_rels');
         file = 'workbook.xml.rels';
-        data = writeXlRels(sheets);
+        data = writeXlRels(sheets, isSinglePage);
         zip_rels2.file(file, data.join(''), {compression: 'DEFLATE'});
         //5.
         let zip_theme = zip_xl.folder('theme');
@@ -656,10 +754,17 @@ module.exports = {
         //6.
         let zip_worksheets = zip_xl.folder('worksheets');
         let sharedStrList = [], stylesObj = {};
-        data = writeSheets(pageData, sharedStrList, stylesObj);
-        for (let i = 0; i < data.length; i++) {
-            file = 'sheet' + (i + 1) + '.xml';
-            zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
+        data = writeSheets(pageData, paperSize, sharedStrList, stylesObj, isSinglePage);
+        if (isSinglePage) {
+            for (let i = 0; i < 1; i++) {
+                file = 'sheet' + (i + 1) + '.xml';
+                zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
+            }
+        } else {
+            for (let i = 0; i < data.length; i++) {
+                file = 'sheet' + (i + 1) + '.xml';
+                zip_worksheets.file(file, data[i].join(''), {compression: 'DEFLATE'});
+            }
         }
         file = 'sharedStrings.xml';
         data = writeSharedString(sharedStrList);

+ 4 - 3
modules/users/controllers/login_controller.js

@@ -7,6 +7,7 @@
  */
 import UserModel from "../models/user_model";
 
+
 class LoginController {
 
     /**
@@ -55,11 +56,11 @@ class LoginController {
                 ssoId: userData.id,
                 username: userData.username,
                 email: userData.useremail,
-                mobile: userData.mobile
+                mobile: userData.mobile,
             };
             request.session.sessionUser = sessionUser;
             // 记录用户数据到数据库
-            let [result, exist] = await userModel.markUser(sessionUser);
+            let [result, exist] = await userModel.markUser(sessionUser, request);
             userExist = exist;
 
             if (!result) {
@@ -67,9 +68,9 @@ class LoginController {
             }
 
         } catch (error) {
+            console.log(error);
             return response.json({error: 1, msg: error});
         }
-
         response.json({error: 0, msg: '', exist: userExist ? 1 : 0});
     }
 

+ 31 - 5
modules/users/controllers/user_controller.js

@@ -7,6 +7,8 @@
  */
 import UserModel from "../models/user_model";
 import BaseController from "../../common/base/base_controller";
+import LogType from "../../common/const/log_type_const";
+import LogModel from "../models/log_model";
 
 class UserController extends BaseController {
 
@@ -75,14 +77,38 @@ class UserController extends BaseController {
      * @return {void}
      */
     async safe(request, response) {
-        // 获取当前用户信息
-        let sessionUser = request.session.sessionUser;
-        let userModel = new UserModel();
-        let userData = await userModel.findDataByName(sessionUser.username);
-        userData = userData.length <= 0 ? [] : userData[0];
+        let userData = [];
+        let logList = [];
+        let pageData = {};
+        try {
+            // 获取当前用户信息
+            let sessionUser = request.session.sessionUser;
+            let userModel = new UserModel();
+            userData = await userModel.findDataByName(sessionUser.username);
+            userData = userData.length <= 0 ? [] : userData[0];
+
+            let page = request.query.page === undefined ? 1 : request.query.page;
+
+            // 获取登录信息
+            let logModel = new LogModel();
+            let logCount = await logModel.count();
+            let pageSize = 3;
+            logList = await logModel.getLog(sessionUser.id, LogType.LOGIN_LOG, page, pageSize);
+
+            // 分页数据
+            pageData = {
+                current: page,
+                total: parseInt(logCount / pageSize),
+                queryData: response.locals.urlQuery
+            };
+        } catch (error) {
+            console.log(error);
+        }
 
         let renderData = {
             userData: userData,
+            logList: logList,
+            pages: pageData
         };
         response.render('users/html/user-safe', renderData);
     }

+ 104 - 0
modules/users/models/log_model.js

@@ -0,0 +1,104 @@
+/**
+ * 日志业务逻辑模型
+ *
+ * @author CaiAoLin
+ * @date 2017/7/27
+ * @version
+ */
+import BaseModel from "../../common/base/base_model";
+import LogType from "../../common/const/log_type_const";
+import LogSchema from "./schema/log";
+import UAParser from "ua-parser-js";
+
+class LogModel extends BaseModel {
+
+    /**
+     * 构造函数
+     *
+     * @return {void}
+     */
+    constructor() {
+        let parent = super();
+        parent.model = LogSchema;
+        parent.init();
+    }
+
+    /**
+     * 新增日志
+     *
+     * @param {String} userId
+     * @param {Number} type
+     * @param {String|Object} message
+     * @return {Promise}
+     */
+    addLog(userId, type, message) {
+        let result = null;
+        if (typeof message === 'string' && message === '') {
+            return result;
+        }
+        if (typeof message === 'object' && Object.keys(message).length <= 0) {
+            return result;
+        }
+
+        let addData = {
+            user_id: userId,
+            type: type,
+            message: message,
+            create_time: new Date().getTime()
+        };
+        result = this.db.create(addData);
+        return result;
+    }
+
+    /**
+     * 新增登录日志
+     *
+     * @param {String} userId
+     * @param {Object} request
+     * @return {Promise}
+     */
+    addLoginLog(userId, request) {
+        let ip = request.connection.remoteAddress;
+        ip = ip.split(':');
+        ip = ip[3] === undefined ? '' : ip[3];
+
+        let userAgentObject = new UAParser(request.headers['user-agent']);
+        let osInfo = userAgentObject.getOS();
+        let cpuInfo = userAgentObject.getCPU();
+        let browserInfo = userAgentObject.getBrowser();
+        let message = {
+            os: osInfo.name + ' ' + osInfo.version + ' ' + cpuInfo.architecture,
+            browser: browserInfo.name + ' ' + browserInfo.version,
+            ip: ip
+        };
+
+        return this.addLog(userId, LogType.LOGIN_LOG, message);
+    }
+
+    /**
+     * 获取log列表
+     *
+     * @param {String} userId
+     * @param {Number} type
+     * @param {Number} page
+     * @param {Number} pageSize
+     * @return {Promise}
+     */
+    async getLog(userId, type, page = 1, pageSize = 3) {
+        let condition = {
+            user_id: userId,
+            type: type
+        };
+        page = parseInt(page);
+        page = page <= 1 ? 1 : page;
+        let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize)};
+
+        let logList = await this.db.find(condition, null, option);
+        logList = logList.length > 0 ? logList : [];
+
+        return logList
+    }
+
+}
+
+export default LogModel;

+ 29 - 0
modules/users/models/schema/log.js

@@ -0,0 +1,29 @@
+/**
+ * 日志数据结构
+ *
+ * @author CaiAoLin
+ * @date 2017/7/27
+ * @version
+ */
+import mongoose from "mongoose";
+
+let Schema = mongoose.Schema;
+let collectionName = 'log';
+let modelSchema = {
+    // 日志类型
+    type: {
+        type: Number,
+        index: true
+    },
+    // 日志内容
+    message: Schema.Types.Mixed,
+    // 关联用户id
+    user_id: {
+        type: String,
+        index: true
+    },
+    // 创建时间
+    create_time: Number
+};
+let model = mongoose.model(collectionName, new Schema(modelSchema, {versionKey: false, collection: collectionName}));
+export {model as default, collectionName as collectionName};

+ 24 - 7
modules/users/models/schema/user.js

@@ -16,13 +16,30 @@ let schema = {
     username: String,
     email: String,
     mobile: String,
-    real_name: String,
-    company: String,
-    province: String,
-    area: Number,
-    company_type: Number,
-    company_scale: Number,
-    last_login: Number,
+    real_name: {
+        type: String,
+        default: ''
+    },
+    company: {
+        type: String,
+        default: ''
+    },
+    province: {
+        type: Number,
+        default: -1
+    },
+    area: {
+        type: Number,
+        default: 0
+    },
+    company_type: {
+        type: Number,
+        default: -1,
+    },
+    company_scale: {
+        type: Number,
+        default: -1
+    },
     create_time: Number
 };
 

+ 8 - 16
modules/users/models/user_model.js

@@ -8,6 +8,7 @@
 import userSchema from "./schema/user";
 import Request from "request";
 import BaseModel from "../../common/base/base_model"
+import LogModel from "./log_model";
 
 class UserModel extends BaseModel {
 
@@ -79,9 +80,10 @@ class UserModel extends BaseModel {
      * 标记用户
      *
      * @param {object} userData
+     * @param {Object} request
      * @return {Promise}
      */
-    async markUser(userData) {
+    async markUser(userData, request = null) {
         let userDataFromDb = await this.findDataByName(userData.username);
         let result = false;
 
@@ -91,15 +93,12 @@ class UserModel extends BaseModel {
             // 不存在用户则入库
             result = await this.addUser(userData);
         } else {
-            // 存在则更新用户信息
-            let updateData = {last_login: new Date().getTime()};
-            let condition = {email: userData.email};
-            result = await this.updateUser(condition, updateData);
-
-            userDataFromDb = userDataFromDb[0];
-            info = userDataFromDb.real_name !== undefined && userDataFromDb.real_name !== '';
-            result = result.ok === 1;
+            info = true;
+            // 存在则新增登录信息
+            let logModel = new LogModel();
+            result = await logModel.addLoginLog(userDataFromDb._id, request);
         }
+        request.session.sessionUser.id = userDataFromDb._id;
 
         return [result, info];
     }
@@ -141,14 +140,7 @@ class UserModel extends BaseModel {
             username: userData.username,
             email: userData.email,
             mobile: userData.mobile,
-            real_name: '',
-            company: '',
-            province: -1,
-            company_type: -1,
-            company_scale: -1,
-            last_login: 0,
             create_time: new Date().getTime(),
-            area: 0
         };
         return this.db.create(insertData);
     }

+ 3 - 3
modules/users/routes/user_route.js

@@ -14,8 +14,8 @@ module.exports = function (app) {
     const userController = new UserController();
 
 // action定义区域
-    router.get('/info', userController.info);
-    router.get('/safe', userController.safe);
-    router.post('/info', userController.saveData);
+    router.get('/info', userController.init, userController.info);
+    router.get('/safe', userController.init, userController.safe);
+    router.post('/info', userController.init, userController.saveData);
     app.use('/user',router);
 };

+ 2 - 0
package.json

@@ -24,7 +24,9 @@
   "dependencies": {
     "bluebird": "^3.5.0",
     "jszip": "^3.1.3",
+    "moment": "^2.18.1",
     "socket.io": "^2.0.3",
+    "ua-parser-js": "^0.7.14",
     "uuid": "^3.1.0"
   },
   "scripts": {

+ 1 - 0
public/web/rpt_value_define.js

@@ -188,6 +188,7 @@ let JV = {
     PAGE_SELF_DEFINE: "自定义",
 
     PAGES_SIZE_STR: ["A3", "A4", "A5", "B5", "LETTER", "LEGAL", "EXECUTIVE", "16K"],
+    PAGES_SIZE_IDX: [8, 9, 11, 13, 1, 5, 7, 93],
     PAGES_SIZE: [[11.69, 16.54], [8.27, 11.69], [5.83, 8.27], [6.93, 9.84], [8.5, 11.0], [8.5, 14.0], [7.25, 10.5], [7.25, 10.5]],
 
     HUNDRED_PERCENT : 100.0,

+ 2 - 0
public/web/sheet/sheet_common.js

@@ -10,6 +10,8 @@ var sheetCommonObj = {
         var spreadBook = new GC.Spread.Sheets.Workbook(container, { sheetCount: SheetCount });
         spreadBook.options.tabStripVisible = false;
         spreadBook.options.showHorizontalScrollbar = false;
+        spreadBook.options.allowCopyPasteExcelStyle = false;
+        spreadBook.options.allowUserDragDrop = true;
         return spreadBook;
     },
 

+ 10 - 1
public/web/tree_sheet/tree_sheet_helper.js

@@ -5,7 +5,7 @@
 var TREE_SHEET_HELPER = {
     getSheetCellStyle: function (setting) {
         var style = new GC.Spread.Sheets.Style();
-        style.locked = setting.readOnly ? true : false;
+        //style.locked = setting.readOnly ? true : false;
         style.name = setting.id;
         style.font = setting.data.font;
         style.hAlign = setting.data.hAlign;
@@ -99,6 +99,15 @@ var TREE_SHEET_HELPER = {
                 } else {
                     cell.value(getFieldText2());
                 }
+                if (colSetting.readOnly) {
+                    if (Object.prototype.toString.apply(colSetting.readOnly) === "[object Function]") {
+                        cell.locked(colSetting.readOnly(node));
+                    } else {
+                        cell.locked(true);
+                    }
+                } else {
+                    cell.locked(false);
+                }
             });
             sheet.autoFitRow(node.serialNo());
             if (recursive) {

+ 4 - 3
test/tmp_data/bills_grid_setting.js

@@ -41,7 +41,7 @@ var BillsGridSetting ={
         },
         {
             "width":50,
-            "readOnly":false,
+            "readOnly":true,
             "head":{
                 "titleNames":[
                     "类别"
@@ -66,7 +66,8 @@ var BillsGridSetting ={
                 "field":"type",
                 "vAlign":1,
                 "hAlign":1,
-                "font":"Arial"
+                "font":"Arial",
+                "getText": 'getText.type'
             }
         },
         {
@@ -255,7 +256,7 @@ var BillsGridSetting ={
         },
         {
             "width":120,
-            "readOnly":false,
+            "readOnly": 'readOnly.volumePrice',
             "head":{
                 "titleNames":[
                     "工程量计算规则"

+ 2 - 1
web/building_saas/fee_rates/fee_rate.html

@@ -9,12 +9,13 @@
     <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="/web/building_saas/css/main.css">
     <link rel="stylesheet" href="/lib/font-awesome/font-awesome.min.css">
+
     <link rel="stylesheet" href="/lib/spreadjs/views/gc.spread.views.dataview.10.0.0.css">
     <script src="/lib/spreadjs/views/common/gc.spread.common.10.0.0.min.js" type="text/javascript"></script>
     <script src="/lib/spreadjs/views/gc.spread.views.dataview.10.0.0.min.js" type="text/javascript"></script>
     <script src="/lib/spreadjs/views/plugins/gc.spread.views.gridlayout.10.0.0.min.js" type="text/javascript"></script>
     <script src="/lib/spreadjs/views/locale/gc.spread.views.dataview.locale.zh-CN.10.0.0.min.js" type="text/javascript"></script>
-    <script>GC.Spread.Sheets.LicenseKey = "559432293813965#A0y3iTOzEDOzkjMyMDN9UTNiojIklkI1pjIEJCLi4TPB9mM5AFNTd4cvZ7SaJUVy3CWKtWYXx4VVhjMpp7dYNGdx2ia9sEVlZGOTh7NRlTUwkWR9wEV4gmbjBDZ4ElR8N7cGdHVvEWVBtCOwIGW0ZmeYVWVr3mI0IyUiwCMzETN8kzNzYTM0IicfJye&Qf35VfiEzRwEkI0IyQiwiIwEjL6ByUKBCZhVmcwNlI0IiTis7W0ICZyBlIsIyNyMzM5ADI5ADNwcTMwIjI0ICdyNkIsIibj9SbvNmL4N7bjRnch56ciojIz5GRiwiI8+Y9sWY9QmZ0Jyp96uL9v6L0wap9biY9qiq95q197Wr9g+89iojIh94Wiqi";</script>
+    <script>GC.Spread.Views.LicenseKey = "559432293813965#A0y3iTOzEDOzkjMyMDN9UTNiojIklkI1pjIEJCLi4TPB9mM5AFNTd4cvZ7SaJUVy3CWKtWYXx4VVhjMpp7dYNGdx2ia9sEVlZGOTh7NRlTUwkWR9wEV4gmbjBDZ4ElR8N7cGdHVvEWVBtCOwIGW0ZmeYVWVr3mI0IyUiwCMzETN8kzNzYTM0IicfJye&Qf35VfiEzRwEkI0IyQiwiIwEjL6ByUKBCZhVmcwNlI0IiTis7W0ICZyBlIsIyNyMzM5ADI5ADNwcTMwIjI0ICdyNkIsIibj9SbvNmL4N7bjRnch56ciojIz5GRiwiI8+Y9sWY9QmZ0Jyp96uL9v6L0wap9biY9qiq95q197Wr9g+89iojIh94Wiqi";</script>
 
 
     <style>

+ 20 - 9
web/building_saas/main/js/calc/bills_calc.js

@@ -75,21 +75,21 @@ class BillsCalcHelper {
         this.digit = 2;
         switch (this.CalcFlag) {
             case rationContent:
-                this.calcFieldName = rationContentCalcFields;
+                this.calcField = rationContentCalcFields;
                 break;
             case rationPrice:
-                this.calcFieldName = rationPriceCalcFields;
+                this.calcField = rationPriceCalcFields;
                 break;
             case rationPriceConverse:
-                this.calcFieldName = rationPriceConverseCalcFields;
+                this.calcField = rationPriceConverseCalcFields;
                 break;
             case billsPrice:
-                this.calcFieldName = billsPriceCalcFields;
+                this.calcField = billsPriceCalcFields;
                 break;
             default:
-                this.calcFieldName = [];
+                this.calcField = [];
         }
-        this.InitFields(this.calcFieldName);
+        this.InitFields(this.calcField);
     };
 
     getBillsGLjs (node) {
@@ -100,7 +100,7 @@ class BillsCalcHelper {
         }
         return gljs;
     };
-    calcLeaf (node, fields) {
+    calcRationLeaf (node, fields) {
         nodeCalcObj.node = node;
         nodeCalcObj.digit = this.digit;
         calcFees.checkFields(node.data, fields);
@@ -141,6 +141,9 @@ class BillsCalcHelper {
             }
         }
     };
+    calcVolumePriceLeaf (node, fields) {
+
+    };
     calcParent (node, fields) {
         nodeCalcObj.node = node;
         calcFees.checkFields(node.data, fields);
@@ -157,9 +160,17 @@ class BillsCalcHelper {
 
             if (node.source.children.length > 0) {
                 this.calcNodes(node.children);
-                this.calcParent(node, this.calcFieldName);
+                this.calcParent(node, this.calcField);
             } else {
-                this.calcLeaf(node, this.calcFieldName);
+                if (node.children.length > 0) {
+                    if (node.firstChild().sourceType === this.project.Ration.getSourceType()) {
+                        this.calcRationLeaf(node, this.calcField);
+                    } else {
+                        this.calcVolumePriceLeaf(node, this.calcField);
+                    }
+                } else {
+
+                }
             }
         }
     };

+ 4 - 0
web/building_saas/main/js/calc/calc_fees.js

@@ -26,6 +26,10 @@ let calcFees = {
         data.feesIndex[fieldName] = fee;
     },
     checkFields: function (data, fields) {
+        if (!data.fees) {
+            data.fees = [];
+            data.feesIndex = {};
+        }
         for (let field of fields) {
             if (!this.findFee(data, field.type)) {
                 this.AddFee(data, field.type);

+ 7 - 8
web/building_saas/main/js/calc/ration_calc.js

@@ -156,12 +156,12 @@ let rationCalcFields = [
         statement: "基价人工费+基价材料费+基价机械费+未计价材料费"
     },
     {
-        type: 'management', code: "2", name: "企业管理费",
+        type: 'management', code: "2", name: "企业管理费", feeRate: 7,
         dispExpr: "1.1.1", expression: "at('1.1.1')", compiledExpr: "",
         statement: "定额基价人工费"
     },
     {
-        type: 'profit', code: "3", name: "利润",
+        type: 'profit', code: "3", name: "利润", feeRate: 13,
         dispExpr: "1.1.1", expression: "at('1.1.1')", compiledExpr: "",
         statement: "定额基价人工费"
     },
@@ -295,7 +295,8 @@ let rationCalcObj = {
         let result = {};
         for (let field of this.calcFields) {
             let calcExpr = this.getCalcExpr(field.expression);
-            field.fee = calcEvaluate(calcExpr).toDecimal(2);
+            let feeRate = (field.feeRate && field.feeRate !== 0) ? field.feeRate : 1;
+            field.fee = (calcEvaluate(calcExpr) * feeRate).toDecimal(2);
             result[field.type] = field.fee;
         }
         return result;
@@ -313,7 +314,8 @@ class RationCalcHelper {
         calcFees.checkFields(ration, rationCalcFields);
         for (let field of rationCalcFields) {
             let calcExpr = rationCalcObj.getCalcExpr(field.expression);
-            field.fee = calcEvaluate(calcExpr).toDecimal(2);
+            let feeRate = (field.feeRate && field.feeRate !== 0) ? field.feeRate : 1;
+            field.fee = (calcEvaluate(calcExpr) * feeRate).toDecimal(2);
             ration.feesIndex[field.type].unitFee = field.fee;
             ration.feesIndex[field.type].totalFee = (field.fee * calcFees.getFee(ration, 'quantity')).toDecimal(2);
             calcExpr = null;
@@ -322,10 +324,7 @@ class RationCalcHelper {
 
     calculateAll () {
         for (let rationData of this.project.Ration.datas) {
-            let cnt = 1;
-            for (let i = 0 ; i< cnt; i++) {
-                this.calculate(rationData);
-            }
+            this.calculate(rationData);
         }
     };
 }

+ 1 - 0
web/building_saas/main/js/models/bills.js

@@ -167,6 +167,7 @@ var Bills = {
             var moudles =[ModuleNames.bills,ModuleNames.ration_glj];
             var deleteDatas=[tools.coverseTreeUpdateData(deleteData, this.project.ID()),ration_glj.getDeleteDataByBills(deleteData)];
             project.ration_glj.deleteByBills(deleteData);
+            project.quantity_detail.deleteByBills(deleteData);
             project.pushNow('deleteBILL', moudles, deleteDatas);
             this.delete(deleteData);
 

+ 91 - 12
web/building_saas/main/js/models/quantity_detail.js

@@ -44,28 +44,27 @@ var quantity_detail = {
             console.log(data);
             var me = this;
             if(data.hasOwnProperty('resort')){
-                this.resortData(data.doc);
+                this.resortData(data.doc,1);
                 _.forEach(data.update_task,function (item) {
                     me.refreshEachItme(item.query,item.doc);
                 })
+                gljOprObj.detailData.push(data.doc);
+                this.datas.push(data.doc);
             }else {
                 this.datas.push(data);
                 gljOprObj.detailData.push(data);
             }
             gljOprObj.detailData=_.sortBy(gljOprObj.detailData,'seq');
-            console.log(gljOprObj.detailData);
             this.refreshSheetData();
         };
-        quantity_detail.prototype.resortData=function(data){
+        quantity_detail.prototype.resortData=function(data,req){
 
             for(var i =0;i<gljOprObj.detailData.length;i++){
                 var item = gljOprObj.detailData[i];
                 if(item.seq>=data.seq){
-                    item.seq=item.seq+1;
+                    item.seq=item.seq+req;
                 }
             }
-            gljOprObj.detailData.push(data);
-            this.datas.push(data);
         };
         quantity_detail.prototype.refreshAfterUpdate=function(data){
             var me = this;
@@ -79,6 +78,7 @@ var quantity_detail = {
             }
             var showList = _.filter(this.datas,filter_object);
             gljOprObj.detailData=showList;
+            gljOprObj.detailData=_.sortBy(gljOprObj.detailData,'seq');
             this.refreshSheetData();
         };
         quantity_detail.prototype.refreshEachItme = function(query,doc){
@@ -98,9 +98,15 @@ var quantity_detail = {
             return filter_object;
         };
         quantity_detail.prototype.refreshAfterDelete=function(data){
-            var glj_list = projectObj.project.ration_coe.datas;
-            _.remove(glj_list,data.query);
-            _.remove(gljOprObj.sheetData,data.query);
+            var me = this;
+            if(data.doc.seq != gljOprObj.detailData.length - 1){
+                this.resortData(data.doc,-1);
+            }
+            _.forEach(data.update_task,function (item) {
+                me.refreshEachItme(item.query,item.doc);
+            });
+            _.remove(this.datas,{ID:data.doc.ID});
+            _.remove(gljOprObj.detailData,{ID:data.doc.ID});
             this.refreshSheetData();
         };
         quantity_detail.prototype.refreshSheetData=function () {
@@ -186,9 +192,57 @@ var quantity_detail = {
                     break;
                 }
             }
-
             return deleteable;
         };
+
+        quantity_detail.prototype.moveDown = function (row) {
+            this.swapRow(row);
+        };
+        quantity_detail.prototype.moveUp = function (row) {
+            this.swapRow(row-1);
+        };
+        quantity_detail.prototype.swapRow = function (preRow) {
+            var me = this;
+            var update_task = [];
+            var a_row = gljOprObj.detailData[preRow];//
+            var b_row = gljOprObj.detailData[preRow +1];//
+            var temA = a_row.seq;
+            var temB = b_row.seq;
+            a_row.seq = temB;
+            update_task.push({query:{ID:a_row.ID,projectID:a_row.projectID},doc:{seq:a_row.seq}});
+            b_row.seq = temA;
+            update_task.push({query:{ID:b_row.ID,projectID:b_row.projectID},doc:{seq:b_row.seq}});
+            gljOprObj.detailData.forEach(function (item) {
+                if(_.includes(item.referenceIndexs,temA+1)||_.includes(item.referenceIndexs,temB+1)){
+                    var regex = item.regex;
+                    for (var i=0;i<item.referenceIndexs.length;i++){
+                        if(item.referenceIndexs[i]==temA+1){
+                            regex = me.replaceAll('C'+item.referenceIndexs[i],'B'+(temB+1),regex);
+                            regex = me.replaceAll('c'+item.referenceIndexs[i],'b'+(temB+1),regex);
+                            item.referenceIndexs[i]=temB+1;
+                        }else if(item.referenceIndexs[i]==temB+1){
+                            regex = me.replaceAll('C'+item.referenceIndexs[i],'B'+(temA+1),regex);
+                            regex = me.replaceAll('c'+item.referenceIndexs[i],'b'+(temA+1),regex);
+                            item.referenceIndexs[i]=temA+1;
+                        }
+                    }
+                    regex =  me.replaceAll('B','C',regex);
+                    regex =  me.replaceAll('b','c',regex);
+                    update_task.push({query:{ID:item.ID,projectID:item.projectID},doc:{regex:regex,referenceIndexs:item.referenceIndexs}});
+                }
+            })
+
+            var updateData=[];
+            update_task.forEach(function (task) {
+                updateData.push({'updateType': 'ut_update', 'query': task.query,'doc':task.doc});
+            })
+            project.pushNow('updateQuantityDetail',[this.getSourceType()],[updateData]);
+
+        };
+        quantity_detail.prototype.replaceAll=function(FindText, RepText,str) {
+            let regExp = new RegExp(FindText, "g");
+            return str.replace(regExp, RepText);
+        };
         quantity_detail.prototype.updateQuantityDetail=function (args,dataCode,recode) {
             var doc ={};
             var query={
@@ -229,6 +283,9 @@ var quantity_detail = {
             if(needupdate){
                 var updateData = this.getUpdateData('ut_update',query,doc,'updateQuantityRegex');
                 project.pushNow('updateQuantityDetail',[this.getSourceType()],updateData);
+            }else {
+                var sheet = subSpread.getActiveSheet();
+                sheet.getCell(args.row,args.col).value(gljOprObj.detailData[args.row].regex);
             }
         };
 
@@ -364,10 +421,32 @@ var quantity_detail = {
                 var temStr = x_arr.join('*');
                 temp = temp.replace(item, temStr);
             });
-            console.log(temp);
             return temp;
         };
-
+        quantity_detail.prototype.deleteByRation = function(ration){
+            var detail_list = this.datas;
+            var newList =_.filter(detail_list,(d)=>{
+                return d.rationID!=ration.ID;
+            });
+            if(newList!=undefined){
+                this.datas = newList;
+            }
+        };
+        quantity_detail.prototype.deleteByBills=function(deleteData){
+            var detail_list = this.datas;
+            var billIDList = [];
+            for(var i=0;i<deleteData.length;i++){
+                if(deleteData[i].type=='delete'){
+                    billIDList.push(deleteData[i].data.ID);
+                }
+            }
+            var newList =_.filter(detail_list,(d)=>{
+                return !_.includes(billIDList,d.billID);
+            });
+            if(newList!=undefined){
+                this.datas = newList;
+            }
+        };
         return new quantity_detail(project);
     }
 

+ 27 - 11
web/building_saas/main/js/models/ration_glj.js

@@ -48,12 +48,21 @@ var ration_glj = {
         };
         ration_glj.prototype.getGatherGljArrByRations = function (rations) {
             let result = [];
+            let clone = function (obj) {
+                if (obj === null) return null;
+
+                var o = Object.prototype.toString.apply(obj) === "[object Array]" ? [] : {};
+                for (var i in obj) {
+                    o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? clone(obj[i]) : obj[i]);
+                }
+                return o;
+            }
             let findGlj = function (sourceGlj, gljArr) {
-                gljArr.forEach(function (glj) {
+                for (let glj of gljArr) {
                     if (glj.projectGLJID === sourceGlj.projectGLJID) {
-                        return glj
+                        return glj;
                     }
-                });
+                }
                 return null;
             }
             for (let ration of rations) {
@@ -61,7 +70,9 @@ var ration_glj = {
                 for (let glj of rationGljs) {
                     let sameGlj = findGlj(glj, result);
                     if (!sameGlj) {
-                        result.push(glj);
+                        sameGlj = clone(glj);
+                        sameGlj.quantity = (sameGlj.quantity * ration.quantity).toDecimal(4);
+                        result.push(sameGlj);
                     } else {
                         sameGlj.quantity = sameGlj.quantity + (glj.quantity * ration.quantity).toDecimal(4);
                     }
@@ -200,8 +211,10 @@ var ration_glj = {
         ration_glj.prototype.getDeleteDataByBills=function(datas){
             var updateData = [];
             datas.forEach(function (deleteData) {
-                var billData = deleteData.data;
-                updateData.push({'deleteType':'BILL','updateType': 'ut_delete', 'updateData': {'ID': billData.ID, 'projectID': billData.projectID}});
+                if(deleteData.type=='delete'){
+                    var billData = deleteData.data;
+                    updateData.push({'deleteType':'BILL','updateType': 'ut_delete', 'updateData': {'ID': billData.ID, 'projectID': billData.projectID}});
+                }
             })
             return updateData;
         };
@@ -218,15 +231,18 @@ var ration_glj = {
             var rationList = projectObj.project.Ration.datas;
             var deleteRationList = [];
             for(var i=0;i<deleteData.length;i++){
-                var billID = deleteData[i].data.ID;
-                var raList =_.filter(rationList,(ration)=>{
-                    return ration.billsItemID==billID;
-                });
-                deleteRationList = deleteRationList.concat(raList);
+                if(deleteData[i].type=='delete'){
+                    var billID = deleteData[i].data.ID;
+                    var raList =_.filter(rationList,(ration)=>{
+                        return ration.billsItemID==billID;
+                    });
+                    deleteRationList = deleteRationList.concat(raList);
+                }
             }
             for(var i=0;i<deleteRationList.length;i++){
                 this.deleteByRation(deleteRationList[i]);
                 projectObj.project.ration_coe.deleteByRation(deleteRationList[i]);
+                projectObj.project.quantity_detail.deleteByRation(deleteRationList[i]);
                 projectObj.project.Ration.datas.splice(projectObj.project.Ration.datas.indexOf(deleteRationList[i]), 1);
             }
         }

+ 4 - 3
web/building_saas/main/js/views/glj_view.js

@@ -20,7 +20,7 @@ var gljOprObj = {
             {headerName: "名称", headerWidth: 120, dataCode: "name", dataType: "String"},
             {headerName: "规格型号", headerWidth: 80, dataCode: "specs", dataType: "String", hAlign: "center"},
             {headerName: "单位", headerWidth: 60, dataCode: "unit", dataType: "String", hAlign: "center"},
-            {headerName: "类别", headerWidth: 50, dataCode: "gljDistType", dataType: "String", hAlign: "center"},
+            {headerName: "类别", headerWidth: 50, dataCode: "shortName", dataType: "String", hAlign: "center"},
             {headerName: "定额消耗量", headerWidth: 80, dataCode: "rationItemQuantity", dataType: "Number", hAlign: "right",formatter:"0.000",tofix:3},    // dataType: "Number", formatter: "0.00"
             {headerName: "自定义消耗量", headerWidth: 80, dataCode: "customQuantity", dataType: "Number", hAlign: "right",formatter:"0.000",tofix:3},
             {headerName: "消耗量", headerWidth: 80, dataCode: "quantity", dataType: "Number", hAlign: "right",formatter:"0.000",tofix:3},
@@ -131,7 +131,8 @@ var gljOprObj = {
 
     onClipboardPasted: function(e, info) {
         var me = gljOprObj;
-        if (!me.ration) {return;};
+        console.log('past');
+      //  if (!me.ration) {return;};
         // your code...
     },
 
@@ -239,7 +240,7 @@ var gljOprObj = {
             return;
         }
         if(me.setting.header[args.col].dataCode=='marketPriceAdjust'){//市场单价调整
-            var type = me.sheetData[args.row].gljDistType;
+            var type = me.sheetData[args.row].shortName;
             var index= _.indexOf(me.setting.notEditedType,type);
             if(index!=-1){
                 me.sheet.getCell(args.row, args.col, GC.Spread.Sheets.SheetArea.viewport).locked(true);

+ 28 - 8
web/building_saas/main/js/views/glj_view_contextMenu.js

@@ -4,6 +4,8 @@
 
 var gljContextMenu = {
     selectedRow :null,
+    selectedCol:null,
+    clipboard:null,
     loadGLJSpreadContextMenu: function () {
         $.contextMenu({
             selector: '#subSpread',
@@ -60,40 +62,57 @@ var gljContextMenu = {
                     name: '上移',
                     icon: 'fa-arrow-up',
                     disabled: function () {
-
+                        var sheetData = gljOprObj.detailData;
+                        return gljContextMenu.selectedRow==0||gljContextMenu.selectedRow>sheetData.length-1;
                     },
                     callback: function () {
-
+                        projectObj.project.quantity_detail.moveUp(gljContextMenu.selectedRow);
                     }
                 },
                 "move_down": {
                     name: '下移',
                     icon: 'fa-arrow-down',
                     disabled: function () {
-
+                        var sheetData = gljOprObj.detailData;
+                        return gljContextMenu.selectedRow>sheetData.length-2;
                     },
                     callback: function () {
-
+                        projectObj.project.quantity_detail.moveDown(gljContextMenu.selectedRow);
                     }
                 },
                 "copy": {
                     name: '复制',
                     icon: 'fa-files-o',
                     disabled: function () {
-
+                        var sheet = subSpread.getActiveSheet();
+                        var sheetData = gljOprObj.detailData;
+                        var value = sheet.getCell(gljContextMenu.selectedRow,gljContextMenu.selectedCol).value();
+                        return gljContextMenu.selectedRow>sheetData.length-1||value==null;
                     },
                     callback: function () {
-
+                        gljContextMenu.clipboard={
+                          row:gljContextMenu.selectedRow,
+                          col:gljContextMenu.selectedCol
+                        };
                     }
                 },
                 "paste": {
                     name: '粘贴',
                     icon: 'fa-clipboard',
                     disabled: function () {
-
+                        var sheetData = gljOprObj.detailData;
+                        return gljContextMenu.selectedRow>sheetData.length||gljContextMenu.clipboard==null;
                     },
                     callback: function () {
-
+                        var sheet = subSpread.getActiveSheet();
+                        var c=gljContextMenu.clipboard;
+                        console.log(sheet.getCell(c.row,c.col).value());
+                        var args={
+                            'row':gljContextMenu.selectedRow,
+                            'col':gljContextMenu.selectedCol,
+                            'editingText':sheet.getCell(c.row,c.col).value()
+                        }
+                        gljOprObj.onEditDetailSheet(args);
                     }
                 }
             }
@@ -103,6 +122,7 @@ var gljContextMenu = {
     onbuild:function ($trigger, e) {
         var target = SheetDataHelper.safeRightClickSelection($trigger, e, subSpread);
         gljContextMenu.selectedRow = target.row;
+        gljContextMenu.selectedCol = target.col;
         //controller.setTreeSelected(controller.tree.items[target.row]);
         return target.hitTestType === GC.Spread.Sheets.SheetArea.viewport || target.hitTestType === GC.Spread.Sheets.SheetArea.rowHeader;
     }

+ 23 - 2
web/building_saas/main/js/views/main_tree_col.js

@@ -2,8 +2,8 @@
  * Created by Mai on 2017/7/25.
  */
 
-let ColGetText = {
-    mainTree: {
+let MainTreeCol = {
+    getText: {
         type: function (node) {
             if (node.sourceType === projectObj.project.Bills.getSourceType()) {
                 return '';
@@ -15,5 +15,26 @@ let ColGetText = {
                 return '主';
             }
         }
+    },
+    readOnly: {
+        volumePrice: function (node) {
+            return node.sourceType === projectObj.project.VolumePrice.getSourceType();
+        }
+    },
+    getEvent: function (eventName) {
+        let names = eventName.split('.');
+        let event = this;
+        for (let name of names) {
+            if (event[name]) {
+                event = event[name];
+            } else {
+                return null;
+            }
+        }
+        if (event && Object.prototype.toString.apply(event) !== "[object Function]") {
+            return null;
+        } else {
+            return event;
+        }
     }
 }

+ 30 - 4
web/building_saas/main/js/views/project_view.js

@@ -25,8 +25,11 @@ var projectObj = {
             if (!err) {
                 BillsGridSetting.cols.forEach(function (col) {
                     col.data.splitFields = col.data.field.split('.');
-                    if (col.data.field === 'type') {
-                        col.data.getText = ColGetText.mainTree.type;
+                    if (col.data.getText && Object.prototype.toString.apply(col.data.getText) === "[object String]") {
+                        col.data.getText = MainTreeCol.getEvent(col.data.getText);
+                    }
+                    if (col.readOnly && Object.prototype.toString.apply(col.readOnly) === "[object String]") {
+                        col.readOnly = MainTreeCol.getEvent(col.readOnly);
                     }
                 });
                 that.mainController = TREE_SHEET_CONTROLLER.createNew(that.project.mainTree, that.mainSpread.getActiveSheet(), BillsGridSetting);
@@ -40,8 +43,30 @@ var projectObj = {
                         }
                     };
                     let selected = tree.selected;
-                    setButtonValid(selected && selected.canUpLevel(), $('#upLevel'));
-                    setButtonValid(selected && selected.canDownLevel(), $('#downLevel'));
+                    let canUpLevel = function (node) {
+                        if (selected && selected.depth() > 0 && selected.canUpLevel()) {
+                            if (selected.sourceType === that.project.Bills.getSourceType()) {
+                                return (!selected.nextSibling) || (selected.children.length === 0) || (selected.source.children.length > 0);
+                            } else {
+                                return false;
+                            }
+                        } else {
+                            return false;
+                        }
+                    };
+                    let canDownLevel = function (node) {
+                        if (selected && selected.depth() > 0 && selected.canDownLevel()) {
+                            if (selected.sourceType === that.project.Bills.getSourceType()) {
+                                return (selected.preSibling.children.length === 0) || (selected.preSibling.source.children.length > 0);
+                            } else {
+                                return false;
+                            }
+                        } else {
+                            return false;
+                        }
+                    };
+                    setButtonValid(canUpLevel(selected), $('#upLevel'));
+                    setButtonValid(canDownLevel(selected), $('#downLevel'));
                     setButtonValid(selected && (selected.depth() > 0) && selected.canUpMove(), $('#upMove'));
                     setButtonValid(selected && (selected.depth() > 0) && selected.canDownMove(), $('#downMove'));
                     setButtonValid(selected, $('#delete'));
@@ -215,6 +240,7 @@ $('#delete').click(function () {
             project.Ration.delete(selected.source);
             project.ration_glj.deleteByRation(selected.source);
             project.ration_coe.deleteByRation(selected.source);
+            project.quantity_detail.deleteByRation(selected.source);
             controller.delete();
         } else if (selected.sourceType === project.VolumePrice.getSourceType()) {
             project.VolumePrice.delete(selected.source);

+ 89 - 0
web/common/html/page.html

@@ -0,0 +1,89 @@
+<nav aria-label="...">
+    <ul aria-label="pagination" id="pages"></ul>
+</nav>
+<script type="text/javascript">
+    let options = {
+        bootstrapMajorVersion: 3,
+        currentPage: "<%= pages.current %>",
+        totalPages: "<%= pages.total %>",
+        size: "normal",
+        itemContainerClass: function(type, page, current) {
+            let className = 'page-item';
+            this.currentPage = parseInt(this.currentPage);
+            this.totalPages = parseInt(this.totalPages);
+
+            switch (type) {
+                case "prev":
+                    className = this.currentPage === 1 ? className + ' disabled' : className;
+                    break;
+                case "next":
+                    className = this.currentPage === this.totalPages ? className + ' disabled' : className;
+                    break;
+                case "page":
+                    className = page === this.currentPage ? className + ' active' : className;
+                    break;
+            }
+
+            return className;
+        },
+        itemContentClass: function(type, page, current) {
+            return 'page-link';
+        },
+        itemTexts: function(type, page, current) {
+            switch (type) {
+                case "first":
+                    return "&laquo;";
+                case "prev":
+                    return "上一页";
+                case "next":
+                    return "下一页";
+                case "last":
+                    return "最后一页";
+                case "page":
+                    return page;
+            }
+        },
+        shouldShowPage: function (type, page, current) {
+            let result = true;
+            switch (type) {
+                case "first":
+                    result = (current !== 1);
+                    break;
+                case "prev":
+                    break;
+                case "next":
+                    break;
+                case "last":
+                    result = false;
+                    break;
+                case "page":
+                    result = true;
+                    break;
+            }
+            return result;
+
+        },
+        pageUrl: function(type, page, current){
+            let queryData = JSON.parse('<%- pages.queryData %>');
+
+            // 如果没有附带查询条件则直接返回
+            if (Object.keys(queryData).length <= 0) {
+                return "?page=" + page;
+            }
+            // 有其它数据则重新赋值page,然后组合字符串
+            queryData.page = page;
+            let queryArray = [];
+            for(let tmp in queryData) {
+                let tempString = tmp + '=' + queryData[tmp];
+                queryArray.push(tempString);
+            }
+
+            let firstQuery = queryArray.shift();
+            let queryString = queryArray.join('&');
+            return  queryString === '' ? '?' + firstQuery : '?' + firstQuery + '&' + queryString;
+        }
+    };
+    if (options.totalPages > 0) {
+        $("#pages").bootstrapPaginator(options);
+    }
+</script>

+ 1 - 1
web/glj/html/header.html

@@ -6,7 +6,7 @@
     <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="/web/building_saas/css/main.css">
     <link rel="stylesheet" href="/lib/font-awesome/font-awesome.min.css">
-    <link rel="stylesheet" href="/lib/spreadjs/sheets/css/gc.spread.sheets.excel2013white.10.0.1.css">
+    <link rel="stylesheet" href="/lib/spreadjs/sheets/css/gc.spread.sheets.excel2013lightGray.10.0.1.css">
     <script type="text/javascript" src="/public/web/sheet/sheet_common.js"></script>
     <script type="text/javascript" src="/public/web/sheet/sheet_data_helper.js"></script>
     <script src="/lib/spreadjs/sheets/gc.spread.sheets.all.10.0.1.min.js"></script>

+ 30 - 51
web/users/html/user-safe.html

@@ -9,6 +9,12 @@
     <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
     <link rel="stylesheet" href="/web/building_saas/css/main.css">
     <link rel="stylesheet" href="/lib/font-awesome/font-awesome.min.css">
+    <!-- JS. -->
+    <script src="/lib/jquery/jquery.min.js"></script>
+    <script src="/lib/tether/tether.min.js"></script>
+    <script src="/lib/bootstrap/bootstrap.min.js"></script>
+    <script type="text/javascript" src="/lib/bootstrap/bootstrap-paginator.js"></script>
+    <script src="/web/building_saas/js/global.js"></script>
 </head>
 
 <body>
@@ -80,52 +86,30 @@
                         </div>
                     </from>
                 </div>
-                <!--<div class="mt-5">-->
-                    <!--<legend>访问日志</legend>-->
-                    <!--<table class="table table-hover">-->
-                        <!--<thead>-->
-                        <!--<tr>-->
-                            <!--<th>系统</th>-->
-                            <!--<th>浏览器</th>-->
-                            <!--<th>访问日期</th>-->
-                            <!--<th>地址</th>-->
-                        <!--</tr>-->
-                        <!--</thead>-->
-                        <!--<tbody>-->
-                        <!--<tr>-->
-                            <!--<td>Windows NT 10.0 64-bit</td>-->
-                            <!--<td>Chrome 55.0.2883.87 m (64-bit)</td>-->
-                            <!--<td>2017-01-12 09:09</td>-->
-                            <!--<td>广东省珠海市 电信(116.19.86.133)</td>-->
-                        <!--</tr>-->
-                        <!--<tr>-->
-                            <!--<td>Windows NT 10.0 64-bit</td>-->
-                            <!--<td>Chrome 55.0.2883.87 m (64-bit)</td>-->
-                            <!--<td>2017-01-12 09:09</td>-->
-                            <!--<td>广东省珠海市 电信(116.19.86.133)</td>-->
-                        <!--</tr>-->
-                        <!--<tr>-->
-                            <!--<td>Windows NT 10.0 64-bit</td>-->
-                            <!--<td>Chrome 55.0.2883.87 m (64-bit)</td>-->
-                            <!--<td>2017-01-12 09:09</td>-->
-                            <!--<td>广东省珠海市 电信(116.19.86.133)</td>-->
-                        <!--</tr>-->
-                        <!--</tbody>-->
-                    <!--</table>-->
-                    <!--<nav aria-label="...">-->
-                        <!--<ul class="pagination">-->
-                            <!--<li class="page-item disabled">-->
-                                <!--<a class="page-link" href="#" tabindex="-1">上一页</a>-->
-                            <!--</li>-->
-                            <!--<li class="page-item active"><a class="page-link" href="#">1</a></li>-->
-                            <!--<li class="page-item"><a class="page-link" href="#">2</a></li>-->
-                            <!--<li class="page-item"><a class="page-link" href="#">3</a></li>-->
-                            <!--<li class="page-item">-->
-                                <!--<a class="page-link" href="#">下一页</a>-->
-                            <!--</li>-->
-                        <!--</ul>-->
-                    <!--</nav>-->
-                <!--</div>-->
+                <div class="mt-5">
+                    <legend>访问日志</legend>
+                    <table class="table table-hover">
+                        <thead>
+                        <tr>
+                            <th>系统</th>
+                            <th>浏览器</th>
+                            <th>访问日期</th>
+                            <th>地址</th>
+                        </tr>
+                        </thead>
+                        <tbody>
+                        <% logList.forEach(function (log){ %>
+                        <tr>
+                            <td><%= log.message.os %></td>
+                            <td><%= log.message.browser %></td>
+                            <td><%= moment(log.create_time).format('YYYY-MM-DD HH:mm:ss') %></td>
+                            <td>(<%= log.message.ip %>)</td>
+                        </tr>
+                        <% }) %>
+                        </tbody>
+                    </table>
+                    <%include ../../common/html/page.html %>
+                </div>
             </div>
         </div>
     </div>
@@ -144,11 +128,6 @@
         </div>
     </div>
 </div>
-<!-- JS. -->
-<script src="/lib/jquery/jquery.min.js"></script>
-<script src="/lib/tether/tether.min.js"></script>
-<script src="/lib/bootstrap/bootstrap.min.js"></script>
-<script src="/web/building_saas/js/global.js"></script>
 </body>
 <script type="text/javascript">
     autoFlashHeight();