/Diamond_Dev/Client/Web/Scripts/private.js
JavaScript | 2268 lines | 1959 code | 234 blank | 75 comment | 151 complexity | 89b465e37b0df4daf01fd5eb784b9af3 MD5 | raw file
Possible License(s): LGPL-2.0
- /// <reference path="jquery-1.11.3.js" />
- /// <reference path="jquery-ui-1.11.4.js" />
- /// <reference path="bootstrap.js" />
- /// <reference path="odatajs-4.0.0.js" />
- /// <reference path="common.js" />
-
- /* global odatajs, $home */
-
- // *** private helper ***
-
- $home.private = (function () {
- var result = {};
-
- result.productImportHelper = function () {
- this.params = arguments[0];
- this.prefix = "#" + this.params.prefix;
- };
- result.productImportHelper.prototype.init = function () {
- var self = this;
- $(this.prefix + "-import-append-update").prop("checked", true);
- $(this.prefix + "-import-running," + this.prefix + "-import-success," + this.prefix + "-import-failure").css("visibility", "hidden");
- $(this.prefix + "-import-upload").click(function () {
- $(self.prefix + "-import-form").submit();
- });
- };
- result.productImportHelper.prototype.submit = function () {
- $(this.prefix + "-import-running").css("visibility", "visible");
- $(this.prefix + "-import-success," + this.prefix + "-import-failure").css("visibility", "hidden");
- };
-
- result.productImportHistoryHelper = function () {
- this.params = arguments[0];
- this.prefix = "#" + this.params.prefix;
- this.url = this.params.url;
- }
- result.productImportHistoryHelper.prototype.init = function () {
- var page = $(this.prefix + "-import-history"),
- fromDatePicker = $(this.prefix + "-import-history-from"),
- toDatePicker = $(this.prefix + "-import-history-to"),
- personControl = $(this.prefix + "-import-history-person"),
- searchResult = $(this.prefix + "-import-history-result"),
- clearButton = $(this.prefix + "-import-history-clear"),
- searchUrl = null,
- pagination = new $home.pagination({
- callback: search,
- search: $(this.prefix + "-import-history-search"),
- previous: $(this.prefix + "-import-history-prev"),
- next: $(this.prefix + "-import-history-next")
- }),
- self = this;
-
- fromDatePicker.datepicker({ maxDate: "+0d" });
- toDatePicker.datepicker({ maxDate: "+0d" });
- clearButton.click(clear);
-
- function search(rebuild, skip) {
- if (rebuild) {
- var query = "Count ne null",
- from = fromDatePicker.datepicker("getDate"),
- to = toDatePicker.datepicker("getDate"),
- person = personControl.val();
-
- if (from) {
- from = $home.utility.odata.toODataDateTimeOffset(from);
- from = odatajs.oData.utils.formatDateTimeOffset(from);
- query += (" and Created ge " + from);
- }
-
- if (to) {
- to.setDate(to.getDate() + 1);
- to = $home.utility.odata.toODataDateTimeOffset(to);
- to = odatajs.oData.utils.formatDateTimeOffset(to);
- query += (" and Created lt " + to);
- }
-
- if (person.length > 0) {
- person = "'" + person + "'";
- query += (" and CreatedBy eq " + person);
- }
-
- searchUrl = self.url + "?" +
- "$filter=" +
- encodeURIComponent(query) +
- "&$orderby=" +
- encodeURIComponent("Created desc");
- }
-
- $home.ui.wait(true);
- var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
- odatajs.oData.read(url, function (data) {
- $("tbody", searchResult).empty();
-
- $.each(data.value, function (index, item) {
- $("<tr/>")
- .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(item.Created))))
- .append($("<td/>").text(item.CreatedBy))
- .append($("<td/>").text($home.business.getDisplayText($home.business.ImportTypes, item.Type)))
- .append($("<td class='text-right'/>").text(item.Count))
- .appendTo($("tbody", searchResult))
- .data(item);
- });
-
- pagination.searched(data.value.length);
-
- $home.ui.wait(false);
- }, function () {
- $home.ui.wait(false);
- alert("查询失败。");
- });
- }
-
- function clear() {
- $("form input,form select", page).val("");
- }
- };
-
- result.productUploadHelper = function () {
- this.params = arguments[0];
- this.prefix = "#" + this.params.prefix;
- this.type = this.params.type;
- };
- result.productUploadHelper.prototype.init = function () {
- var appendOrUpdateRadio = $(this.prefix + "-upload-append-update"),
- replaceRadio = $(this.prefix + "-upload-replace"),
- uploadTypeRadios = appendOrUpdateRadio.add(replaceRadio),
- uploadButton = $(this.prefix + "-upload-upload"),
- self = this;
- appendOrUpdateRadio.prop("checked", true);
-
- uploadButton.click(function () {
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/productservice/Upload()",
- method: "POST",
- data: {
- productType: self.type,
- uploadType: uploadTypeRadios.filter(":checked").val()
- }
- }, function () {
- $home.ui.wait(false);
- alert("上传成功。");
- }, function () {
- $home.ui.wait(false);
- alert("上传失败。");
- });
- });
- };
-
- result.productUploadHistoryHelper = function () {
- this.params = arguments[0];
- this.prefix = "#" + this.params.prefix;
- this.type = this.params.type;
- };
- result.productUploadHistoryHelper.prototype.init = function () {
- var page = $(this.prefix + "-upload-history"),
- fromDatePicker = $(this.prefix + "-upload-history-from"),
- toDatePicker = $(this.prefix + "-upload-history-to"),
- personControl = $(this.prefix + "-upload-history-person"),
- searchResult = $(this.prefix + "-upload-history-result"),
- clearButton = $(this.prefix + "-upload-history-clear"),
- searchUrl = null,
- pagination = new $home.pagination({
- callback: search,
- search: $(this.prefix + "-upload-history-search"),
- previous: $(this.prefix + "-upload-history-prev"),
- next: $(this.prefix + "-upload-history-next")
- }),
- self = this;
-
- fromDatePicker.datepicker({ maxDate: "+0d" });
- toDatePicker.datepicker({ maxDate: "+0d" });
- clearButton.click(clear);
-
- function search(rebuild, skip) {
- if (rebuild) {
- var query = "Count ne null",
- from = fromDatePicker.datepicker("getDate"),
- to = toDatePicker.datepicker("getDate"),
- person = personControl.val();
-
- if (from) {
- from = $home.utility.odata.toODataDateTimeOffset(from);
- from = odatajs.oData.utils.formatDateTimeOffset(from);
- query += (" and Created ge " + from);
- }
-
- if (to) {
- to.setDate(to.getDate() + 1);
- to = $home.utility.odata.toODataDateTimeOffset(to);
- to = odatajs.oData.utils.formatDateTimeOffset(to);
- query += (" and Created lt " + to);
- }
-
- if (person.length > 0) {
- person = "'" + person + "'";
- query += (" and CreatedBy eq " + person);
- }
-
- query += (" and ProductType eq Home.Services.ProductService.ProductType'" + self.type + "' ");
-
- searchUrl = "/productservice/Uploads?" +
- "$filter=" +
- encodeURIComponent(query) +
- "&$orderby=" +
- encodeURIComponent("Created desc");
- }
-
- $home.ui.wait(true);
- var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
- odatajs.oData.read(url, function (data) {
- $("tbody", searchResult).empty();
-
- $.each(data.value, function (index, item) {
- $("<tr/>")
- .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(item.Created))))
- .append($("<td/>").text(item.CreatedBy))
- .append($("<td/>").text($home.business.getDisplayText($home.business.ProductTypes, item.ProductType)))
- .append($("<td/>").text($home.business.getDisplayText($home.business.ProductUploadTypes, item.UploadType)))
- .append($("<td class='text-right'/>").text(item.Count))
- .append($("<td/>").text($home.business.getDisplayText($home.business.ProductUploadStatuses, item.Status)))
- .appendTo($("tbody", searchResult))
- .data(item);
- });
-
- pagination.searched(data.value.length);
-
- $home.ui.wait(false);
- }, function () {
- $home.ui.wait(false);
- alert("查询失败。");
- });
- }
-
- function clear() {
- $("form input,form select", page).val("");
- }
- };
-
- return result;
- })();
-
- // *** pages ***
-
- $home.pages = (function () {
- return {
- "dashboard-page": {
- title: $($("#home-navbar > ul > li > a").get(0)).text(),
- init: function () {
- $("#dashboard-page-print").click(function () {
- $home.navigation.modal("print-sale");
- });
- }
- },
-
- // "customer-management": {
- // title: $($("#home-navbar > ul > li > a").get(2)).text(),
- // init: function () {
- // }
- // },
-
- // "control-panel": {
- // title: $($("#home-navbar > ul > li > a").get(4)).text(),
- // init: function () {
- // }
- // },
-
- // "help-page": {
- // title: $($("#home-navbar > ul > li > a").get(5)).text(),
- // init: function () {
- // }
- // },
-
- "product-management": {
- title: $($("#home-navbar > ul > li > a").get(2)).text(),
- init: function () {
- $("#product-management-diamond-on-sale").click(function () {
- $home.navigation.navigate("diamond-on-sale");
- });
-
- $("#product-management-diamond-import").click(function () {
- $home.navigation.modal("diamond-import");
- });
-
- $("#product-management-diamond-import-history").click(function () {
- $home.navigation.navigate("diamond-import-history");
- });
-
- $("#product-management-diamond-upload").click(function () {
- $home.navigation.modal("diamond-upload");
- });
-
- $("#product-management-diamond-upload-history").click(function () {
- $home.navigation.navigate("diamond-upload-history");
- });
- }
- },
-
- "diamond-on-sale": {
- title: "裸钻数据",
- init: function () {
- var page = $("#diamond-on-sale"),
- shapeControl = $("#diamond-on-sale-shape"),
- reportNumberControl = $("#diamond-on-sale-report-number"),
- reportTypeControl = $("#diamond-on-sale-report-type"),
- priceFromControl = $("#diamond-on-sale-price-from"),
- priceToControl = $("#diamond-on-sale-price-to"),
- weightFromControl = $("#diamond-on-sale-weight-from"),
- weightToControl = $("#diamond-on-sale-weight-to"),
- colorControl = $("#diamond-on-sale-color"),
- clarityControl = $("#diamond-on-sale-clarity"),
- cutControl = $("#diamond-on-sale-cut"),
- polishControl = $("#diamond-on-sale-polish"),
- symmetryControl = $("#diamond-on-sale-symmetry"),
- typeControl = $("#diamond-on-sale-type"),
- coloredColorControl = $("#diamond-on-sale-colored-color"),
- clearButton = $("#diamond-on-sale-clear"),
- searchResult = $("#diamond-on-sale-result"),
- searchUrl = null,
- pagination = new $home.pagination({
- callback: search,
- search: $("#diamond-on-sale-search"),
- previous: $("#diamond-on-sale-prev"),
- next: $("#diamond-on-sale-next")
- });
-
- clearButton.click(clear);
-
- function search(rebuild, skip) {
- if (rebuild) {
- var query = "Index ne null",
- type = typeControl.val().trim(),
- shape = shapeControl.val().trim(),
- reportNumber = reportNumberControl.val().trim(),
- reportType = reportTypeControl.val().trim(),
- priceFrom = parseFloat(priceFromControl.val().trim()),
- priceTo = parseFloat(priceToControl.val().trim()),
- weightFrom = parseFloat(weightFromControl.val().trim()),
- weightTo = parseFloat(weightToControl.val().trim()),
- color = colorControl.val().trim(),
- coloredColor = coloredColorControl.val().trim(),
- clarity = clarityControl.val().trim(),
- cut = cutControl.val().trim(),
- polish = polishControl.val().trim(),
- symmetry = symmetryControl.val().trim();
-
- if (type.length !== 0) {
- query += (" and Type eq Home.Services.ProductService.DiamondType'" + type + "'");
- }
- if (shape.length !== 0) {
- query += (" and Shape eq Home.Services.ProductService.DiamondShape'" + shape + "'");
- }
- if (reportNumber.length !== 0) {
- query += (" and contains(ReportNumber,'" + reportNumber + "')");
- }
- if (reportType.length !== 0) {
- query += (" and ReportType eq Home.Services.ProductService.DiamondReport'" + reportType + "'");
- }
- if (!isNaN(priceFrom)) {
- query += (" and SalePrice ge " + priceFrom);
- }
- if (!isNaN(priceTo)) {
- query += (" and SalePrice le " + priceTo);
- }
- if (!isNaN(weightFrom)) {
- query += (" and Caret ge " + weightFrom);
- }
- if (!isNaN(weightTo)) {
- query += (" and Caret le " + weightTo);
- }
- if (color.length !== 0) {
- query += (" and Color eq Home.Services.ProductService.DiamondColor'" + color + "'");
- }
- if (coloredColor.length !== 0) {
- query += (" and contains(ColoredColor,'" + coloredColor + "')");
- }
- if (clarity.length !== 0) {
- query += (" and Clarity eq Home.Services.ProductService.DiamondClarity'" + clarity + "'");
- }
- if (cut.length !== 0) {
- query += (" and Cut eq Home.Services.ProductService.DiamondCut'" + cut + "'");
- }
- if (polish.length !== 0) {
- query += (" and Polish eq Home.Services.ProductService.DiamondPolish'" + polish + "'");
- }
- if (symmetry.length !== 0) {
- query += (" and Symmetry eq Home.Services.ProductService.DiamondSymmetry'" + symmetry + "'");
- }
-
- searchUrl = "/productservice/Diamonds?" +
- "$filter=" +
- encodeURIComponent(query) +
- "&$orderby=" +
- encodeURIComponent("Index");
- }
-
- $home.ui.wait(true);
- var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
- odatajs.oData.read(url, function (data) {
- $("tbody", searchResult).empty();
-
- $.each(data.value, function (index, product) {
- $("<tr/>")
- .append($("<td class='text-left'/>").text(formatText(product.Index)))
- .append($("<td/>").text($home.business.getDisplayText($home.business.DiamondTypes, product.Type)))
- .append($("<td/>").text(formatText(product.Shape)))
- .append($("<td/>").text(formatText(product.ReportNumber)))
- .append($("<td/>").text(formatText(product.ReportType)))
- .append($("<td class='text-right'/>").text(formatText(product.Caret)))
- .append($("<td/>").text((product.Color === null || product.Color === undefined || product.Color.length === 0) ? formatText(product.ColoredColor) : formatText(product.Color)))
- .append($("<td/>").text(formatText(product.Clarity)))
- .append($("<td/>").text(formatText(product.Cut)))
- .append($("<td/>").text(formatText(product.Polish)))
- .append($("<td/>").text(formatText(product.Symmetry)))
- .append($("<td/>").text(formatText(product.Fluorescence)))
- .append($("<td class='text-right'/>").text(formatText(product.Cost)))
- .append($("<td class='text-right'/>").text(formatText(product.SalePrice)))
- .append($("<td/>").text($home.business.getDisplayText($home.business.ProductStatuses, product.Status)))
- .append($("<td/>").text(formatText(product.Comment)))
- .appendTo($("tbody", searchResult))
- .data(product);
- });
-
- pagination.searched(data.value.length);
-
- $home.ui.wait(false);
- }, function () {
- $home.ui.wait(false);
- alert("查询失败。");
- });
- }
-
- function clear() {
- $("form input, form select", page).val("");
- }
-
- function formatText(value) {
- if (value === undefined || value === null) {
- return "";
- }
- return value.toString();
- }
- }
- },
-
- "diamond-import": {
- title: "导入裸钻数据",
- init: function () {
- new $home.private.productImportHelper({ prefix: "diamond" }).init();
- }
- },
-
- "diamond-import-history": {
- title: "导入裸钻数据的历史",
- init: function () {
- new $home.private.productImportHistoryHelper({ prefix: "diamond", url: "/productservice/DiamondImports" }).init();
- }
- },
-
- "diamond-upload": {
- title: "上传裸钻数据到网站",
- init: function () {
- new $home.private.productUploadHelper({ prefix: "diamond", type: "Diamond" }).init();
- }
- },
-
- "diamond-upload-history": {
- title: "上传裸钻数据到网站的历史",
- init: function () {
- new $home.private.productUploadHistoryHelper({ prefix: "diamond", type: "Diamond" }).init();
- }
- },
-
- "print-sale": {
- title: "销售开单",
- init: function () {
- var baseBehavior = function () { };
- baseBehavior.prototype.init = $.noop;
- baseBehavior.prototype.add = $.noop;
- baseBehavior.prototype.edit = $.noop;
- baseBehavior.prototype.clear = $.noop;
- baseBehavior.prototype.format = function () {
- return "";
- };
- baseBehavior.prototype.validate = function () {
- return true;
- };
-
- var diamondBehavior = function () {
- baseBehavior.call(this);
- this.goodCertificate = $("#print-sale-good-certificate");
- this.goodCaret = $("#print-sale-good-caret");
- this.goodCut = $("#print-sale-good-cut");
- this.goodClarity = $("#print-sale-good-clarity");
- this.goodColor = $("#print-sale-good-color");
- };
- $home.utility.oo.extend(baseBehavior, diamondBehavior);
- diamondBehavior.prototype.init = $.noop;
- diamondBehavior.prototype.add = function (entity) {
- if (this.goodCertificate.val().length > 0) {
- entity.Certificate = this.goodCertificate.val();
- }
- if (this.goodCaret.val().length > 0) {
- entity.Caret = parseFloat(this.goodCaret.val());
- }
- if (this.goodCut.val().length > 0) {
- entity.Cut = this.goodCut.val();
- }
- if (this.goodClarity.val().length > 0) {
- entity.Clarity = this.goodClarity.val();
- }
- if (this.goodColor.val().length > 0) {
- entity.Color = this.goodColor.val();
- }
- };
- diamondBehavior.prototype.edit = function (entity) {
- this.goodCertificate.val(entity.Certificate);
- this.goodCaret.val(entity.Caret);
- this.goodCut.val(entity.Cut);
- this.goodClarity.val(entity.Clarity);
- this.goodColor.val(entity.Color);
- };
- diamondBehavior.prototype.clear = function () {
- this.goodCertificate.val("");
- this.goodCaret.val("");
- this.goodCut.val("");
- this.goodClarity.val("");
- this.goodColor.val("");
- };
- diamondBehavior.prototype.format = function () {
- var result = "";
- if (this.goodCertificate.val().length > 0) {
- result += "证书:" + this.goodCertificate.val() + " ";
- }
- if (this.goodCaret.val().length > 0) {
- result += "钻重:" + this.goodCaret.val() + " ";
- }
- if (this.goodCut.val().length > 0) {
- result += "切工:" + this.goodCut.val() + " ";
- }
- if (this.goodClarity.val().length > 0) {
- result += "净度:" + this.goodClarity.val() + " ";
- }
- if (this.goodColor.val().length > 0) {
- result += "颜色:" + this.goodColor.val() + " ";
- }
- return result;
- };
- diamondBehavior.prototype.validate = function () {
- return $home.validation.validateRequired(this.goodCaret) && $home.validation.validateFloat(this.goodCaret);
- };
-
- // members
- var sale = {},
- behavior = new baseBehavior(),
-
- dialog = $("#print-sale"),
-
- userInfo = $("#print-sale-user-info"),
- customerInfo = $("#print-sale-customer-info"),
- goodInfo = $("#print-sale-good-info"),
- goodSpecificInfo = $("#print-sale-good-info-specific"),
-
- customerWayButton = $("#print-sale-customer-way-button"),
- goodNameButton = $("#print-sale-good-name-button"),
- addGoodButton = $("#print-sale-add-good"),
- saveButton = $("#print-sale-save"),
- printServiceButton = $("#print-sale-print-service"),
- printReceiptButton = $("#print-sale-print-receipt"),
-
- userName = $("#print-sale-user"),
- receiptNumber = $("#print-sale-receipt-number"),
-
- customerName = $("#print-sale-customer-name"),
- customerPhone = $("#print-sale-customer-phone"),
- customerContact = $("#print-sale-customer-contact"),
- customerWay = $("#print-sale-customer-way"),
-
- goodName = $("#print-sale-good-name"),
- goodDescription = $("#print-sale-good-description"),
- goodQuantity = $("#print-sale-good-quantity"),
- goodPrice = $("#print-sale-good-price");
-
- // dialog
- dialog.on("shown.bs.modal", function () {
- // user
- userName.val($home.authentication.getUserInfo().id);
- // customer name
- customerName.focus();
- // customer way
- $home.ui.selectbutton(customerWayButton.parent());
- $("ul > li > a:first", customerWayButton.parent()).click();
- // good name
- $home.ui.editableselect(goodName.parent());
- goodNameButton.parent().on("hidden.bs.dropdown", replaceGoodInfo);
- goodName.keypress(function (e) {
- if (e.keyCode === 13) {
- replaceGoodInfo();
- }
- }).on("input", replaceGoodInfo);
- // table
- dialog.on("click", "table a[home-data-action='edit']", editFromTable);
- dialog.on("click", "table a[home-data-action='remove']", removeFromTable);
- // enable UI
- setEditable(true);
- // add good
- addGoodButton.click(addToTable);
- // save
- saveButton.click(save);
- });
-
- // disable enable
- function setEditable(enabled) {
- $("fieldset input, fieldset textarea", dialog).not(receiptNumber).prop("readonly", !enabled);
- $("fieldset button, fieldset select", dialog).prop("disabled", !enabled);
- if (enabled) {
- saveButton.prop("disabled", false);
- printServiceButton.prop("disabled", true).addClass("disabled", true);
- printReceiptButton.prop("disabled", true).addClass("disabled", true);
- $("table > tbody > tr > td > a", dialog).removeClass("disabled");
- } else {
- saveButton.prop("disabled", true);
- printServiceButton.prop("disabled", false).removeClass("disabled");
- printReceiptButton.prop("disabled", false).removeClass("disabled");
- $("table > tbody > tr > td > a", dialog).addClass("disabled", true);
- }
- }
-
- // calculate total price
- function calculateTotalPrice() {
- var totalPrice = 0;
- $.each($("table > tbody > tr", dialog), function (index, row) {
- var detail = $(row).data();
- totalPrice += (detail.Quantity * detail.UnitPrice);
- });
- $("table > tfoot > tr > th:last", dialog).prev().text(totalPrice.toString());
- }
-
- // edit good
- function editFromTable() {
- if (!$(this).hasClass("disabled")) {
- var row = $(this).parent().parent();
- var detail = row.data();
- goodName.val(detail.ProductName);
- goodDescription.val(detail.ProductDescription);
- goodQuantity.val(detail.Quantity);
- goodPrice.val(detail.UnitPrice);
- behavior.edit(detail);
- row.remove();
- calculateTotalPrice();
- goodNameButton.focus();
- }
- }
-
- // remove good
- function removeFromTable() {
- if (!$(this).hasClass("disabled")) {
- var row = $(this).parent().parent();
- row.remove();
- calculateTotalPrice();
- goodNameButton.focus();
- }
- }
-
- // add good
- function addToTable() {
- function formatDescription() {
- var result = behavior.format();
- if (goodDescription.val().length > 0) {
- result += goodDescription.val();
- }
- return result;
- }
-
- $home.validation.cleanup(goodInfo);
- if (!($home.validation.validateRequired(goodName) &&
- $home.validation.validateRequired(goodQuantity) &&
- $home.validation.validateInteger(goodQuantity) &&
- $home.validation.validateRequired(goodPrice) &&
- $home.validation.validateInteger(goodPrice) &&
- behavior.validate())) {
- alert("请检查商品信息,有未填写的内容,请填写完整。");
- return;
- }
-
- var detail = {
- ProductName: goodName.val(),
- ProductDescription: goodDescription.val(),
- Quantity: parseInt(goodQuantity.val()),
- UnitPrice: parseInt(goodPrice.val())
- };
- behavior.add(detail);
-
- $("<tr></tr>")
- .append($("<td></td>").text(goodName.val()))
- .append($("<td></td>").text(formatDescription()))
- .append($("<td class='text-center'></td>").text(detail.Quantity.toString()))
- .append($("<td class='text-right'></td>").text(detail.UnitPrice.toString()))
- .append("<td>" +
- "<a href='javascript:void(0)' title='修改' role='button' home-data-action='edit'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a>" +
- "<a href='javascript:void(0)' title='删除' role='button' home-data-action='remove'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></a>" +
- "</td>")
- .data(detail)
- .appendTo("table > tbody", dialog);
- calculateTotalPrice();
-
- goodName.val("");
- goodDescription.val("");
- goodQuantity.val("");
- goodPrice.val("");
- behavior.clear();
- $home.validation.cleanup(goodInfo);
- goodNameButton.focus();
- }
-
- // save
- function save() {
- $home.validation.cleanup(userInfo);
- if (!($home.validation.validateRequired(userName))) {
- alert("请检查用户信息,有未填写的内容,请填写完整。");
- return;
- }
-
- $home.validation.cleanup(customerInfo);
- if (!($home.validation.validateRequired(customerName) &&
- $home.validation.validateRequired(customerPhone) &&
- $home.validation.validateRequired(customerContact))) {
- alert("请检查客户信息,有未填写的内容,请填写完整。");
- return;
- }
-
- sale.Items = [];
- $.each($("table > tbody > tr", dialog), function (index, row) {
- sale.Items.push($(row).data());
- });
- if (sale.Items.length === 0) {
- alert("没有添加任何商品,请添加商品之后继续。");
- return;
- }
-
- setEditable(false);
-
- sale.SalesPersonName = $("#print-sale-user-info option:selected").text();
- sale.CustomerName = customerName.val();
- sale.CustomerContacts = [
- { Method: "Phone", Value: customerPhone.val() },
- { Method: customerWay.val(), Value: customerContact.val() }
- ];
-
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/salesservice/Sales",
- method: "POST",
- data: sale
- }, function (data) {
- receiptNumber.val(data.NumberText);
- printServiceButton.attr("href", "/pages/print-service?id=" + data.Id);
- printReceiptButton.attr("href", "/pages/print-receipt?id=" + data.Id);
- setEditable(false);
- $home.ui.wait(false);
- alert("保存成功,可以开始打印。");
- }, function () {
- $home.ui.wait(false);
- alert("保存失败。");
- setEditable(true);
- });
- }
-
- // good name changed event
- function replaceGoodInfo() {
- goodSpecificInfo.empty();
- switch (goodName.val()) {
- case $home.business.ProductNames.Diamond:
- behavior = new diamondBehavior();
- replaceUI("print-sale-diamond");
- break;
- default:
- behavior = new baseBehavior();
- behavior.init();
- break;
- }
-
- function replaceUI(id) {
- $home.navigation.embed(id, goodSpecificInfo, function () {
- behavior.init();
- });
- }
- }
- }
- },
-
- "print-sale-diamond": {
- title: "裸钻",
- init: $.noop
- },
-
- "sale-management": {
- title: $($("#home-navbar > ul > li > a").get(1)).text(),
- init: function () {
- $("#sale-management-print").click(function () {
- $home.navigation.modal("print-sale");
- });
-
- $("#sale-management-history").click(function () {
- $home.navigation.navigate("sale-history");
- });
-
- $("#sale-management-report").click(function () {
- $home.navigation.modal("sale-report");
- });
- }
- },
-
- "sale-history": {
- title: "销售历史数据查询",
- init: function () {
- var page = $("#sale-history"),
- fromDatePicker = $("#sale-history-from"),
- toDatePicker = $("#sale-history-to"),
- salePersonControl = $("#sale-history-sale-person"),
- searchResult = $("#sale-history-result"),
- clearButton = $("#sale-history-clear"),
- searchUrl = null,
- pagination = new $home.pagination({
- callback: search,
- search: $("#sale-history-search"),
- previous: $("#sale-history-prev"),
- next: $("#sale-history-next")
- });
-
- fromDatePicker.datepicker({ maxDate: "+0d" });
- toDatePicker.datepicker({ maxDate: "+0d" });
- clearButton.click(clear);
-
- function calculateAmount(sale) {
- var result = 0;
- $.each(sale.Items, function (index, detail) {
- result += detail.UnitPrice * detail.Quantity;
- });
- return result;
- }
-
- function formatContact(sale) {
- var result = "";
- $.each(sale.CustomerContacts, function (index, contact) {
- var method = "";
- $.each($home.business.ContactMethods, function (index, item) {
- if (item.value === contact.Method) {
- method = item.text;
- }
- });
- if (result.length > 0) {
- result += ",";
- }
- result += method;
- result += ":";
- result += contact.Value;
- });
- result += "。";
- return result;
- }
-
- function search(rebuild, skip) {
- if (rebuild) {
- var query = "Status eq Home.Services.SaleService.SaleStatus'Ok'",
- from = fromDatePicker.datepicker("getDate"),
- to = toDatePicker.datepicker("getDate"),
- person = salePersonControl.val();
-
- if (from) {
- from = $home.utility.odata.toODataDateTimeOffset(from);
- from = odatajs.oData.utils.formatDateTimeOffset(from);
- query += (" and Created ge " + from);
- }
-
- if (to) {
- to.setDate(to.getDate() + 1);
- to = $home.utility.odata.toODataDateTimeOffset(to);
- to = odatajs.oData.utils.formatDateTimeOffset(to);
- query += (" and Created lt " + to);
- }
-
- if (person.length > 0) {
- person = "'" + person + "'";
- query += (" and SalesPersonName eq " + person);
- }
-
- searchUrl = "/salesservice/Sales?$expand=" +
- encodeURIComponent("CustomerContacts,Items(") +
- "$filter=" +
- encodeURIComponent("Status eq Home.Services.SaleService.SaleStatus'Ok')") +
- "&$filter=" +
- encodeURIComponent(query) +
- "&$orderby=" +
- encodeURIComponent("Created desc,SalesPersonName");
- }
-
- $home.ui.wait(true);
- var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
- odatajs.oData.read(url, function (data) {
- $("tbody", searchResult).empty();
-
- $.each(data.value, function (index, sale) {
- $("<tr/>")
- .append($("<td/>").append($("<a href='javascript:void(0)' role='button'/>").text(sale.NumberText)))
- .append($("<td/>").text(sale.CustomerName))
- .append($("<td/>").text(formatContact(sale)))
- .append($("<td class='text-right'/>").text(calculateAmount(sale)))
- .append($("<td/>").text(sale.SalesPersonName))
- .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(sale.Created))))
- .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(sale.Modified))))
- .appendTo($("tbody", searchResult))
- .data(sale);
- });
-
- $("tbody > tr > td > a", searchResult).click(function () {
- var sale = $(this).parent().parent().data();
- showSale(sale);
- });
-
- pagination.searched(data.value.length);
-
- $home.ui.wait(false);
- }, function () {
- $home.ui.wait(false);
- alert("查询失败。");
- });
- }
-
- function showSale(sale) {
- $home.navigation.modal("sale-view", function () {
- pagination.research();
- }, sale);
- }
-
- function clear() {
- $("form input,form select", page).val("");
- }
- }
- },
-
- "sale-view": {
- title: "销售记录",
- init: function (sale) {
- var baseBehavior = function () { };
- baseBehavior.prototype.init = $.noop;
- baseBehavior.prototype.save = function () { return true; };
-
- var diamondBehavior = function () {
- baseBehavior.call(this);
- };
- $home.utility.oo.extend(baseBehavior, diamondBehavior);
- diamondBehavior.prototype.init = function (entity, row, index) {
- var certificateId = "sale-view-product-certificate-" + (index + 1),
- caretId = "sale-view-product-caret-" + (index + 1),
- cutId = "sale-view-product-cut-" + (index + 1),
- clarityId = "sale-view-product-clarity-" + (index + 1),
- colorId = "sale-view-product-color-" + (index + 1),
- certificateField = $("<input type='text' class='form-control input-sm'/>").attr("id", certificateId),
- caretField = $("<input type='number' class='form-control input-sm'/>").attr("id", caretId),
- cutField = $("<select class='form-control input-sm'/>").attr("id", cutId),
- clarityField = $("<select class='form-control input-sm'/>").attr("id", clarityId),
- colorField = $("<select class='form-control input-sm'/>").attr("id", colorId);
- //// diamond cut
- cutField.append("<option value=''/>");
- $.each($home.business.DiamondCuts, function (index, item) {
- cutField.append($("<option/>").val(item).text(item));
- });
- //// diamond clarity
- clarityField.append("<option value=''/>");
- $.each($home.business.DiamondClarities, function (index, item) {
- clarityField.append($("<option/>").val(item).text(item));
- });
- //// diamond color
- colorField.append("<option value=''/>");
- $.each($home.business.DiamondColors, function (index, item) {
- colorField.append($("<option/>").val(item).text(item));
- });
-
- certificateField.val(entity.Certificate);
- caretField.val(entity.Caret);
- cutField.val(entity.Cut);
- clarityField.val(entity.Clarity);
- colorField.val(entity.Color);
-
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, certificateId, certificateField, "证书");
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, caretId, caretField, "钻重");
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, cutId, cutField, "切工");
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, clarityId, clarityField, "净度");
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, colorId, colorField, "颜色");
- };
- diamondBehavior.prototype.save = function (entity, row) {
- var caretField = $($("input[type=number]", row)[0]);
- if ($home.validation.validateRequired(caretField) && $home.validation.validateFloat(caretField)) {
- entity.Certificate = getString($("input[type=text]", row)[1]);
- entity.Caret = getFloat(caretField);
- entity.Cut = getString($("select", row)[0]);
- entity.Clarity = getString($("select", row)[1]);
- entity.Color = getString($("select", row)[2]);
- return true;
- }
- return false;
- }
-
- var CONTROL_TEMPLATE =
- "<div class='input-group'>" +
- " <div class='input-group-btn'>" +
- " <button type='button' class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown' aria-expanded='false'><span class='caret'></span></button>" +
- " <ul class='dropdown-menu' role='menu'></ul>" +
- " <input type='hidden'/>" +
- " </div>" +
- " <input type='text' class='form-control input-sm' />" +
- "</div>",
- CONTACT_TEMPLATE =
- "<div class='col-md-3'>" +
- " <div class='form-group'>" +
- " </div>" +
- "</div>",
- LINE_ROW_TEMPLATE =
- "<div class='row'>" +
- "</div>",
- LINE_FIELD_MIDDLE_TEMPLATE =
- "<div class='col-md-2'>" +
- " <div class='form-group'>" +
- " </div>" +
- "</div>",
- LINE_FIELD_LARGE_TEMPLATE =
- "<div class='col-md-6'>" +
- " <div class='form-group'>" +
- " </div>" +
- "</div>",
- receiptNumberField = $("#sale-view-receipt-number"),
- createdField = $("#sale-view-created"),
- createdByField = $("#sale-view-created-by"),
- modifiedField = $("#sale-view-modified"),
- modifiedByField = $("#sale-view-modified-by"),
- salerInfo = $("#sale-view-saler-info"),
- salerField = $("#sale-view-saler"),
- customerInfo = $("#sale-view-customer-info"),
- customerField = $("#sale-view-name"),
- lineInfo = $("#sale-view-line-info"),
- totalPriceField = $("#sale-view-total-price"),
- editButton = $("#sale-view-edit"),
- saveButton = $("#sale-view-save"),
- deleteButton = $("#sale-view-delete"),
- etag = sale["@odata.etag"];
-
- receiptNumberField.val(sale.NumberText);
- createdField.val($home.utility.date.toLocalDateString(new Date(sale.Created)));
- createdByField.val(sale.CreatedBy);
- modifiedField.val($home.utility.date.toLocalDateString(new Date(sale.Modified)));
- modifiedByField.val(sale.ModifiedBy);
- salerField.val(sale.SalesPersonName);
- customerField.val(sale.CustomerName);
- $.each(sale.CustomerContacts, function (index, contact) {
- var id = "sale-view-customer-contact-" + (index + 1);
- var method = $(CONTROL_TEMPLATE);
- $.each($home.business.ContactMethods, function (index, m) {
- var content = $("<li><a href='javascript:void(0)'></a></li>");
- $("a", content).attr("data-content", m.value).text(m.text);
- $("ul", method).append(content);
- });
- $("input[type=text]", method).attr("id", id);
- $home.ui.selectbutton(method);
-
- $("a", method).filter(function () {
- return $(this).attr("data-content") === contact.Method;
- }).click();
-
- $("input[type=text]", method).val(contact.Value);
-
- var template = $(CONTACT_TEMPLATE);
- $(".form-group", template).append($("<label/>").text("联系方式 " + (index + 1)).attr("for", id))
- .append(method);
- $(".row", customerInfo).append(template);
- });
- $.each(sale.Items, function (index, line) {
- // first row
- {
- function replaceLineInfo() {
- var behavior,
- parents = $(this).parentsUntil(".row"),
- row = $(parents[parents.size() - 1]).parent(),
- line = row.data("line"),
- index = row.data("index");
- removeDynamicProperties(line);
- row.children("div").not(":first").remove();
- switch (row.find("#sale-view-product-name-" + (index + 1)).val()) {
- case $home.business.ProductNames.Diamond:
- behavior = new diamondBehavior();
- break;
- default:
- behavior = new baseBehavior();
- break;
- }
- behavior.init(line, row, index);
- }
-
- var behavior,
- row = $(LINE_ROW_TEMPLATE),
- nameId = "sale-view-product-name-" + (index + 1),
- nameField = $(CONTROL_TEMPLATE),
- nameControl = $("input[type=text]", nameField);
-
- // product name
- nameControl.attr("id", nameId).keypress(function (e) {
- if (e.keyCode === 13) {
- replaceLineInfo();
- }
- }).on("input", replaceLineInfo).prev().on("hidden.bs.dropdown", replaceLineInfo);
- $.each($home.business.Products, function (index, item) {
- var anchor = $("<a href='javascript:void(0)'></a>").text(item),
- listItem = $("<li/>").append(anchor);
- $("ul", nameField).append(listItem);
- });
- $("input", nameField).val(line.ProductName);
- $home.ui.editableselect(nameField);
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, nameId, nameField, "名称");
-
- // behavior
- switch (line.ProductName) {
- case $home.business.ProductNames.Diamond:
- behavior = new diamondBehavior();
- break;
- default:
- behavior = new baseBehavior();
- break;
- }
- behavior.init(line, row, index);
-
- // append
- row.data("index", index).data("line", line);
- lineInfo.append(row);
- }
-
- // second row
- {
- var row = $(LINE_ROW_TEMPLATE),
- descriptionId = "sale-view-product-description-" + (index + 1),
- quantityId = "sale-view-product-quantity-" + (index + 1),
- unitPriceId = "sale-view-product-unit-price-" + (index + 1),
- descriptionField = $("<input type='text' class='form-control input-sm'/>").attr("id", descriptionId),
- quantityField = $("<input type='number' class='form-control input-sm quantity'/>").attr("id", quantityId),
- unitPriceField = $("<input type='number' class='form-control input-sm price'/>").attr("id", unitPriceId);
- descriptionField.val(line.ProductDescription);
- quantityField.val(line.Quantity);
- unitPriceField.val(line.UnitPrice);
- addFieldForInit(row, LINE_FIELD_LARGE_TEMPLATE, descriptionId, descriptionField, "描述");
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, quantityId, quantityField, "数量");
- addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, unitPriceId, unitPriceField, "价格");
- lineInfo.append(row);
- }
- });
- calculateTotalPrice();
- setUIEditable(false);
- editButton.click(function () {
- setUIEditable(true);
- });
- saveButton.click(save);
- deleteButton.click(remove);
- lineInfo.off("focusout", "input.quantity, input.price").on("focusout", "input.quantity, input.price", calculateTotalPrice);
-
- function setUIEditable(editable) {
- if (editable) {
- salerField.prop("disabled", false);
- customerField.prop("readonly", false);
- $("input", customerInfo).prop("readonly", false);
- $("select, button", customerInfo).prop("disabled", false);
- $("input", lineInfo).not("#sale-view-total-price").prop("readonly", false);
- $("select, button", lineInfo).prop("disabled", false);
- editButton.prop("disabled", true);
- saveButton.prop("disabled", false);
- deleteButton.prop("disabled", false);
- } else {
- salerField.prop("disabled", true);
- customerField.prop("readonly", true);
- $("input", customerInfo).prop("readonly", true);
- $("select, button", customerInfo).prop("disabled", true);
- $("input", lineInfo).prop("readonly", true);
- $("select, button", lineInfo).prop("disabled", true);
- editButton.prop("disabled", false);
- saveButton.prop("disabled", true);
- deleteButton.prop("disabled", true);
- }
- }
-
- function calculateTotalPrice() {
- var totalPrice = 0;
- $("> div", lineInfo).each(function () {
- var quantityField = $("input.quantity", $(this));
- var unitPriceField = $("input.price", $(this));
- if (quantityField.size() === 1 && unitPriceField.size() === 1) {
- var quantity = parseInt(quantityField.val());
- var unitPrice = parseInt(unitPriceField.val());
- totalPrice += quantity * unitPrice;
- }
- });
- totalPriceField.val(totalPrice);
- }
-
- function save() {
- $home.validation.cleanup(salerInfo);
- if (!($home.validation.validateRequired(salerField))) {
- alert("请检查用户信息,有未填写的内容,请填写完整。");
- return;
- }
- sale.SalesPersonName = salerField.val();
-
- $home.validation.cleanup(customerInfo);
- if (!($home.validation.validateRequired(customerField) &&
- $home.validation.validateRequired($("#sale-view-customer-contact-1")) &&
- $home.validation.validateRequired($("#sale-view-customer-contact-2")))) {
- alert("请检查客户信息,有未填写的内容,请填写完整。");
- return;
- }
- sale.CustomerName = customerField.val();
- sale.CustomerContacts[0].Method = $("input[type=hidden]", $("#sale-view-customer-contact-1").parent()).val();
- sale.CustomerContacts[0].Value = $("#sale-view-customer-contact-1").val();
- sale.CustomerContacts[1].Method = $("input[type=hidden]", $("#sale-view-customer-contact-2").parent()).val();
- sale.CustomerContacts[1].Value = $("#sale-view-customer-contact-2").val();
-
- $home.validation.cleanup(lineInfo);
- var line,
- lineIndex = 0,
- isValid = true;
- $("> div", lineInfo).not(":first").each(function (index) {
- var row = $(this);
- if (index % 2 === 0) {
- line = sale.Items[lineIndex];
- lineIndex++;
-
- if (!$home.validation.validateRequired($($("input[type=text]", row)[0]))) {
- isValid = false;
- return;
- }
- line.ProductName = $($("input[type=text]", row)[0]).val();
-
- var behavior;
- switch (line.ProductName) {
- case $home.business.ProductNames.Diamond:
- behavior = new diamondBehavior();
- break;
- default:
- behavior = new baseBehavior();
- break;
- }
- if (!behavior.save(line, row)) {
- isValid = false;
- return;
- }
- } else {
- if (!($home.validation.validateRequired($($("input[type=number]", row)[0])) &&
- $home.validation.validateInteger($($("input[type=number]", row)[0])) &&
- $home.validation.validateRequired($($("input[type=number]", row)[1])) &&
- $home.validation.validateInteger($($("input[type=number]", row)[1])))) {
- isValid = false;
- return;
- }
- line.ProductDescription = $($("input[type=text]", row)[0]).val();
- line.Quantity = parseInt($($("input[type=number]", row)[0]).val());
- line.UnitPrice = parseInt($($("input[type=number]", row)[1]).val());
- }
- });
-
- if (!isValid) {
- alert("请检查商品信息,有未填写的内容,请填写完整。");
- return;
- }
-
- $home.utility.odata.removeMetadataProperties(sale);
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/salesservice/Sales(" + sale.Id + ")",
- method: "PUT",
- data: sale,
- headers: {
- "if-match": etag
- }
- }, function () {
- $home.ui.wait(false);
- alert("保存成功。");
- $("#sale-view").modal("hide");
- }, function () {
- $home.ui.wait(false);
- alert("保存失败。");
- });
- }
-
- function remove() {
- if (confirm("确定要删除吗?")) {
- $home.utility.odata.removeMetadataProperties(sale);
- sale.CustomerContacts = undefined;
- sale.Items = undefined;
- sale.Status = "Deleted";
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/salesservice/Sales(" + sale.Id + ")",
- method: "PATCH",
- data: sale,
- headers: {
- "if-match": etag
- }
- }, function () {
- $home.ui.wait(false);
- alert("删除成功。");
- $("#sale-view").modal("hide");
- }, function () {
- $home.ui.wait(false);
- alert("删除失败。");
- });
- }
- }
-
- function addFieldForInit(row, template, id, field, text) {
- var ui = $(template);
- $(".form-group", ui).append($("<label/>").attr("for", id).text(text)).append(field);
- row.append(ui);
- }
-
- function removeDynamicProperties(line) {
- var properties = $home.odata.metadata.saleService.saleLineItem.properties;
- for (var property in line) {
- if (property.indexOf("@") >= 0) {
- continue;
- }
-
- var found = false;
- for (var i = 0; i < properties.length; i++) {
- if (properties[i] === property) {
- found = true;
- break;
- }
- }
-
- if (!found) {
- line[property] = undefined;
- }
- }
- }
-
- function getFloat(element) {
- var ui = $(element);
- return (ui.val().length > 0) ? parseFloat(ui.val()) : undefined;
- }
-
- function getString(element) {
- var ui = $(element);
- return (ui.val().length > 0) ? ui.val() : undefined;
- }
- }
- },
-
- "sale-report": {
- title: "销售报表",
- init: function () {
- var fromDatePicker = $("#sale-report-from"),
- toDatePicker = $("#sale-report-to"),
- viewButton = $("#sale-report-view"),
- cancelButton = $("#sale-report-cancel"),
- ssis = new $home.ssis({
- name: "sales",
- prefix: "sale-report",
- changed: changedCallback
- });
-
- // For long running operation, use the following code instead
- // fromDatePicker.prop("disabled", true).datepicker({ maxDate: "+0d" });
- // toDatePicker.prop("disabled", true).datepicker({ maxDate: "+0d" });
- // viewButton.prop("disabled", true);
- fromDatePicker.datepicker({ maxDate: "+0d" });
- toDatePicker.datepicker({ maxDate: "+0d" });
- cancelButton.prop("disabled", true);
-
- viewButton.click(function () {
- var from = fromDatePicker.datepicker("getDate"),
- to = toDatePicker.datepicker("getDate");
- if (!from || !to) {
- alert("请选择开始和结束日期。 ");
- return;
- }
- to.setDate(to.getDate() + 1);
- ssis.start([
- { Name: "StartDate", Type: "DateTime", Value: $home.utility.date.toServerDateString(from) },
- { Name: "EndDate", Type: "DateTime", Value: $home.utility.date.toServerDateString(to) },
- ]);
- });
-
- cancelButton.click(function () {
- ssis.stop();
- });
-
- function changedCallback(value) {
- switch (value.Status) {
- case "Completed":
- fromDatePicker.removeAttr("disabled");
- toDatePicker.removeAttr("disabled");
- viewButton.removeAttr("disabled");
- cancelButton.prop("disabled", true);
- break;
- case "Running":
- fromDatePicker.prop("disabled", true);
- toDatePicker.prop("disabled", true);
- viewButton.prop("disabled", true);
- cancelButton.removeAttr("disabled");
- break;
- }
- }
- }
- },
-
- "employee-management": {
- title: $($("#home-navbar > ul > li > a").get(3)).text(),
- init: function () {
- // currently employee management page is same as employee list page
- $home.pages["employee-list"].init();
- }
- },
-
- "employee-list": {
- title: "员工列表",
- init: function () {
- function search() {
- $home.ui.wait(true);
-
- odatajs.oData.read("/securityservice/Users?$orderby=DisplayName", function (data) {
- $("tbody", table).empty();
-
- $.each(data.value, function (index, user) {
- var viewDetailsHtml = $("<a href='javascript:void(0)' role='button' data-home-action='view-details'>编辑</a>"),
- viewPasswordHtml = $("<a href='javascript:void(0)' role='button' data-home-action='view-password' title='密码' data-toggle='popover' data-trigger='focus' data-content='正在获取密码……'>查看密码</a>"),
- updatePasswordHtml = $("<a href='javascript:void(0)' role='button' data-home-action='update-password'>修改密码</a>");
- if ($home.pages.internal.checkPasswordPermission(user.Role) < 0) {
- viewDetailsHtml.addClass("disabled");
- viewPasswordHtml.addClass("disabled");
- updatePasswordHtml.addClass("disabled");
- }
-
- $("<tr>")
- .append($("<td>").append($("<a href='javascript:void(0)' role='button' data-home-action='view-details'/>").text(user.DisplayName)))
- .append($("<td>").text(user.LoginName))
- .append($("<td>").text($home.business.getDisplayText($home.business.SecurityRoles, user.Role)))
- .append($("<td>").text(user.IsLocked ? "是" : "否").addClass(user.IsLocked ? "text-danger" : undefined))
- .append($("<td>").text(user.IsLocked && user.LockDateTime ? $home.utility.date.toLocalDateTimeString(new Date(user.LockDateTime)) : ""))
- .append($("<td>").append(viewDetailsHtml).append(viewPasswordHtml).append(updatePasswordHtml))
- .appendTo($("tbody", table))
- .data(user);
- });
-
- $home.ui.wait(false);
- }, function () {
- $home.ui.wait(false);
- alert("获取员工列表失败。");
- });
- }
-
- function viewDetails() {
- var button = $(this);
- if (button.hasClass("disabled")) {
- return false;
- }
-
- var user = getSelectedEmployee.call(button);
- $home.navigation.modal("employee-view", search, user);
- }
-
- function viewPassword() {
- var button = $(this);
- if (button.hasClass("disabled")) {
- return false;
- }
-
- var user = getSelectedEmployee.call(button);
- $home.ui.wait(true);
- odatajs.oData.read("/securityservice/Users(" + user.Id + ")/Home.Services.SecurityService.GetPassword()", function (data) {
- $home.ui.wait(false);
- button.attr("data-content", data.Value).on("hidden.bs.popover", function () {
- button.popover("destroy");
- }).popover("show");
- }, function () {
- $home.ui.wait(false);
- button.popover("destroy");
- alert("获取密码失败。");
- });
- }
-
- function updatePassword() {
- var button = $(this);
- if (button.hasClass("disabled")) {
- return false;
- }
-
- var user = getSelectedEmployee.call(button);
- $home.navigation.modal("employee-update-password", null, user);
- }
-
- function getSelectedEmployee() {
- return $(this).parent().parent().data();
- }
-
- function create() {
- $home.navigation.modal("employee-view", search);
- }
-
- var table = $("#employee-list-result"),
- createButton = $("#employee-list-create");
- table.on("click", "a[data-home-action='view-details']", viewDetails)
- .on("click", "a[data-home-action='view-password']", viewPassword)
- .on("click", "a[data-home-action='update-password']", updatePassword);
- createButton.click(create);
- search();
- }
- },
-
- "employee-view": {
- title: "员工信息",
- init: function (user) {
- function save() {
- $home.validation.cleanup(dialog);
-
- if (!$home.validation.validateRequired(displayNameField)) {
- alert("姓名不能为空。");
- return;
- }
-
- if (!$home.validation.validateRequired(loginNameField)) {
- alert("登录名不能为空。");
- return;
- }
-
- if (isCreate) {
- user = {};
- }
-
- user.DisplayName = displayNameField.val();
- user.LoginName = loginNameField.val();
- user.Role = roleField.filter(":checked").val();
- user.IsLocked = isLockedField.prop("checked");
-
- var params = {
- requestUri: undefined,
- method: undefined,
- headers: undefined,
- data: user
- };
- if (isCreate) {
- params.requestUri = "/securityservice/Users";
- params.method = "POST";
- } else {
- params.requestUri = "/securityservice/Users(" + user.Id + ")";
- params.method = "PUT";
- params.headers = {
- "if-match": etag
- };
- $home.utility.odata.removeMetadataProperties(user);
- }
-
- $home.ui.wait(true);
- odatajs.oData.request(
- params, function () {
- $home.ui.wait(false);
- alert("保存成功。");
- dialog.modal("hide");
- }, function () {
- $home.ui.wait(false);
- alert("保存失败。");
- });
- }
-
- function edit() {
- displayNameField.removeAttr("disabled");
- loginNameField.removeAttr("disabled");
- roleField.removeAttr("disabled");
- isLockedField.removeAttr("disabled");
- saveButton.removeAttr("disabled");
- editButton.attr("disabled", "disabled");
- }
-
- var dialog = $("#employee-view"),
- displayNameField = $("#employee-view-display-name"),
- loginNameField = $("#employee-view-login-name"),
- roleField = $("input[name='employee-view-role']", dialog),
- isLockedField = $("#employee-view-locked"),
- lockTimeField = $("#employee-view-lock-time"),
- lockTimeArea = $("#employee-view-lock-time-area"),
- saveButton = $("#employee-view-save"),
- editButton = $("#employee-view-edit"),
- etag,
- isCreate = user == null;
-
- saveButton.click(save);
- editButton.click(edit);
- if (isCreate) {
- roleField.filter("[value='" + $home.authentication.Role.Employee + "']").prop("checked", true);
- lockTimeArea.hide();
- editButton.hide();
- } else {
- displayNameField.attr("disabled", "disabled").val(user.DisplayName);
- loginNameField.attr("disabled", "disabled").val(user.LoginName);
- roleField.attr("disabled", "disabled").filter("[value='" + user.Role + "']").prop("checked", true);
- isLockedField.attr("disabled", "disabled").prop("checked", user.IsLocked);
- lockTimeField.val(user.IsLocked && user.LockDateTime ? $home.utility.date.toLocalDateTimeString(new Date(user.LockDateTime)) : "");
- saveButton.attr("disabled", "disabled");
- etag = user["@odata.etag"];
- }
-
- roleField.each(function () {
- var role = $(this).val();
- if ($home.pages.internal.checkPasswordPermission(role) < 0) {
- $(this).parent().hide();
- }
- });
- }
- },
-
- "employee-update-password": {
- title: "修改密码",
- init: function (user) {
- var dialog = $("#employee-update-password"),
- newPassword1Field = $("#employee-update-password-new"),
- newPassword2Field = $("#employee-update-password-confirm"),
- submitButton = $("#employee-update-password-submit");
-
- submitButton.click(function () {
- $home.validation.cleanup(dialog);
-
- var newPassword1 = newPassword1Field.val(),
- newPassword2 = newPassword2Field.val();
-
- if (!$home.validation.validate(newPassword1Field, function () { return $home.pages.internal.validatePassword(newPassword1); })) {
- alert("密码填写不正确,密码长度至少是 6 个字符,并且不超过 32 个字符。");
- return;
- }
-
- if (!$home.validation.validate(newPassword2Field, function () { return newPassword1 === newPassword2; })) {
- alert("新密码和确认新密码不一样。");
- return;
- }
-
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/securityservice/Users(" + user.Id + ")/Home.Services.SecurityService.UpdatePassword()",
- method: "POST",
- data: { "new": newPassword1 }
- }, function () {
- $home.ui.wait(false);
- alert("修改成功。");
- $("#employee-update-password").modal("hide");
- }, function () {
- $home.ui.wait(false);
- alert("修改失败。");
- });
- });
- }
- },
-
- "change-password": {
- title: "更改密码",
- init: function () {
- var dialog = $("#change-password"),
- oldPasswordField = $("#change-password-old"),
- newPassword1Field = $("#change-password-new"),
- newPassword2Field = $("#change-password-confirm"),
- submitButton = $("#change-password-submit");
-
- submitButton.click(function () {
- $home.validation.cleanup(dialog);
-
- var oldPassword = oldPasswordField.val(),
- newPassword1 = newPassword1Field.val(),
- newPassword2 = newPassword2Field.val();
-
- if (!($home.validation.validate(oldPasswordField, function () { return $home.pages.internal.validatePassword(oldPassword); }) &&
- $home.validation.validate(newPassword1Field, function () { return $home.pages.internal.validatePassword(newPassword1); }))) {
- alert("密码填写不正确,密码长度至少是 6 个字符,并且不超过 32 个字符。");
- return;
- }
-
- if (!$home.validation.validate(newPassword2Field, function () { return newPassword1 === newPassword2; })) {
- alert("新密码和确认新密码不一样。");
- return;
- }
-
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/securityservice/Users(" + $home.authentication.getUserInfo().id + ")/Home.Services.SecurityService.ChangePassword()",
- method: "POST",
- data: { old: oldPassword, "new": newPassword1 }
- }, function () {
- $home.ui.wait(false);
- alert("更改成功。");
- dialog.modal("hide");
- }, function () {
- $home.ui.wait(false);
- alert("更改失败。");
- });
- });
- }
- },
-
- internal: {
- validatePassword: function (password) {
- return password && password.length >= 6 && password.length <= 32;
- },
-
- checkPasswordPermission: function (role) {
- var current = $home.authentication.getUserInfo().Role;
- switch (current) {
- case $home.authentication.Role.Employee:
- switch (role) {
- case $home.authentication.Role.Employee: return 0;
- case $home.authentication.Role.Manager: return -1;
- case $home.authentication.Role.Administrator: return -1;
- }
- break;
- case $home.authentication.Role.Manager:
- switch (role) {
- case $home.authentication.Role.Employee: return 1;
- case $home.authentication.Role.Manager: return 0;
- case $home.authentication.Role.Administrator: return -1;
- }
- break;
- case $home.authentication.Role.Administrator:
- switch (role) {
- case $home.authentication.Role.Employee: return 1;
- case $home.authentication.Role.Manager: return 1;
- case $home.authentication.Role.Administrator: return 0;
- }
- break;
- }
- return -1;
- }
- }
- };
- })();
-
- // *** navigation ***
-
- $home.navigation = (function () {
- return {
- navigate: function (id) {
- $home.ui.wait(true);
- var setting = $home.pages[id];
- var args = $home.navigation.internal.createArguments(arguments, 1);
- $home.navigation.internal.invoke(id).done(function (html) {
- $home.ui.wait(false);
- $("h1").text(setting.title);
- $("#home-content").html(html);
- setting.init.apply(null, args);
- }).fail(function (xhr) {
- $home.ui.wait(false);
- if (xhr.status === 401) {
- alert("您没有权限导航到" + setting.title + "。");
- } else {
- alert("导航到" + setting.title + "失败。");
- }
- });
- },
-
- modal: function (id, handler) {
- $home.ui.wait(true);
- var setting = $home.pages[id];
- var args = $home.navigation.internal.createArguments(arguments, 2);
- $home.navigation.internal.invoke(id).done(function (html) {
- $home.ui.wait(false);
- $("#home-dialog").html(html);
- setting.init.apply(null, args);
- $("#" + id).on("hidden.bs.modal", function () {
- $("#home-dialog").empty();
- if (handler) {
- handler();
- }
- }).modal("show");
- }).fail(function (xhr) {
- $home.ui.wait(false);
- if (xhr.status === 401) {
- alert("您没有权限打开" + setting.title + "对话框。");
- } else {
- alert("打开" + setting.title + "对话框失败。");
- }
- });
- },
-
- embed: function (id, container, init) {
- $home.ui.wait(true);
- var setting = $home.pages[id];
- var args = $home.navigation.internal.createArguments(arguments, 2);
- $home.navigation.internal.invoke(id).done(function (html) {
- $home.ui.wait(false);
- $(container).html(html);
- setting.init.apply(null, args);
- if (init) {
- init.apply(null, args);
- }
- }).fail(function (xhr) {
- $home.ui.wait(false);
- if (xhr.status === 401) {
- alert("您没有权限查看" + setting.title + "。");
- } else {
- alert("查看" + setting.title + "失败。");
- }
- });
- },
-
- internal: {
- invoke: function (id) {
- return $.ajax({
- url: "/pages/" + id,
- method: "GET",
- cache: true
- });
- },
-
- createArguments: function (args, count) {
- if (args.length > count) {
- var result = [];
- $.each(args, function (index, item) {
- if (index > (count - 1)) {
- result.push(item);
- }
- });
- return result;
- }
- }
- }
- };
- })();
-
- // *** authentication ***
-
- $home.authentication = (function () {
- return {
- timeout: new $home.observable(),
-
- isTimeout: function () {
- return $home.authentication.internal.isTimeout;
- },
-
- restart: function () {
- if ($home.authentication.internal.timeoutHandle) {
- clearTimeout($home.authentication.internal.timeoutHandle);
- }
- $home.authentication.internal.timeoutHandle = setTimeout(function () {
- $.ajax({
- type: "POST",
- url: "/account/logout",
- headers: { RequestVerificationToken: $("#login-form input[name=__AjaxRequestVerificationToken]").val() },
- cache: false
- }).complete(function () {
- clearTimeout($home.authentication.internal.timeoutHandle);
- $home.authentication.internal.isTimeout = true;
- $home.authentication.timeout.fire();
- $home.authentication.exit();
- });
- }, 60 * 60 * 1000);
- },
-
- exit: function () {
- document.location = "/account/timeout";
- },
-
- initialize: function () {
- $home.authentication.restart();
- $home.authentication.internal.initializeAjax();
- $home.authentication.internal.initializeOData();
- $.ajax({
- type: "GET",
- url: "/account/check",
- dataType: "json",
- cache: false
- }).done(function (data) {
- if (data.IsLoggedIn) {
- $home.authentication.internal.userId = data.Id;
- $home.authentication.internal.userName = data.Name;
- $home.authentication.internal.userRole = data.Role;
- $home.authentication.internal.initializeUI();
- $("#home-identity").text(data.Name);
- $home.navigation.navigate("dashboard-page");
- } else {
- $home.authentication.login();
- }
- }).fail(function () {
- alert("检查登录状态失败。");
- });
- },
-
- login: function () {
- document.location.assign("/account/login");
- },
-
- logout: function () {
- $("#home-logout-form").get(0).submit();
- $home.authentication.internal.userId = null;
- $home.authentication.internal.userName = null;
- $home.authentication.internal.userRole = null;
- },
-
- getUserInfo: function () {
- return {
- id: $home.authentication.internal.userId,
- Name: $home.authentication.internal.userName,
- Role: $home.authentication.internal.userRole
- };
- },
-
- Role: {
- Administrator: "Administrator",
- Manager: "Manager",
- Employee: "Employee"
- },
-
- internal: {
- isTimeout: false,
- timeoutHandle: null,
- userId: null,
- userName: null,
- userRole: null,
- initializeUI: function () {
- $.ajax({
- type: "GET",
- url: "/permissions",
- dataType: "json"
- }).done(function (data) {
- function check(name, listItem) {
- var permitted;
- if ($home.authentication.internal.userRole === $home.authentication.Role.Administrator) {
- permitted = true;
- } else {
- $.each(data, function (index, record) {
- if (record.name === name) {
- $.each(record.roles, function (index, role) {
- if (role === $home.authentication.internal.userRole) {
- permitted = true;
- }
- });
- }
- });
- }
-
- if (!permitted) {
- $(listItem).addClass("disabled").hide();
- }
- }
-
- $.each($("#home-navigator > li"), function (index, listItem) {
- switch (index) {
- case 0: check("dashboard-page", listItem); break;
- case 1: check("sale-management", listItem); break;
- //// TODO: case 2: check("customer-management", listItem); break;
- case 2: check("product-management", listItem); break;
- case 3: check("employee-management", listItem); break;
- //// TODO: case 4: check("control-panel", listItem); break;
- //// TODO: case 5: check("help-page", listItem); break;
- }
- });
- }).fail(function () {
- alert("检查权限失败。");
- });
- },
-
- initializeAjax: function () {
- $(document).ajaxSuccess(function () {
- if (!$home.authentication.isTimeout()) {
- $home.authentication.restart();
- }
- }).ajaxError(function (event, xhr, settings, error) {
- if (!$home.authentication.isTimeout() && error.toLowerCase() !== "not authorized") {
- $home.authentication.restart();
- }
- });
- },
-
- initializeOData: function () {
- var odataSuccess = odatajs.oData.defaultSuccess || $.noop;
- var odataError = odatajs.oData.defaultError || $.noop;
- odatajs.oData.defaultSuccess = function () {
- odataSuccess();
- if (!$home.authentication.isTimeout()) {
- $home.authentication.restart();
- }
- };
- odatajs.oData.defaultError = function (error) {
- odataError(error);
- if (!$home.authentication.isTimeout() && error.response.statusCode !== 401) {
- $home.authentication.restart();
- }
- };
- }
- }
- };
- })();
-
- // *** SSIS ***
-
- $home.ssis = (function () {
- function triggerChanged() {
- var uiRunning = this.uiRunning,
- uiCompleted = this.uiCompleted,
- uiCancelled = this.uiCancelled,
- options = this.options,
- timerHandle = this.timerHandle;
- odatajs.oData.read("/ssisservice/GetStatus(name='" + encodeURIComponent(this.options.name) + "')", function (data) {
- switch (data.Status) {
- case "Completed":
- clearInterval(timerHandle);
- uiRunning.hide();
- uiCompleted.show();
- uiCancelled.hide();
- break;
- case "Running":
- uiRunning.hide();
- uiCompleted.hide();
- uiCancelled.show();
- break;
- }
- options.changed.call(ssis, data);
- });
- }
-
- // It subscribes the following events
- // 1. start
- // [ { Name: "", Type: "", Value: "" } ]
- // 2. stop
- // It fires the following events
- // 1. changed
- // { Status: "Running | Completed" }
- var ssis = function () {
- this.options = $.extend({
- name: null,
- prefix: null,
- changed: $.noop
- }, (arguments.length === 0 ? {} : arguments[0]));
- this.uiRunning = $("#" + this.options.prefix + "-ssis-running").hide();
- this.uiCompleted = $("#" + this.options.prefix + "-ssis-completed").hide();
- this.uiCancelled = $("#" + this.options.prefix + "-ssis-cancelled").hide();
- // TODO: for long running operation
- // triggerChanged.call(this);
- };
-
- ssis.prototype.start = function () {
- var uiRunning = this.uiRunning,
- uiCompleted = this.uiCompleted,
- uiCancelled = this.uiCancelled,
- timerHandle = this.timerHandle,
- createTimer = this.createTimer,
- self = this;
- $home.ui.wait(true);
- odatajs.oData.request({
- requestUri: "/ssisservice/Run()",
- method: "POST",
- data: {
- name: this.options.name,
- parameters: arguments[0]
- }
- }, function () {
- $home.ui.wait(false);
- uiRunning.show();
- uiCompleted.hide();
- uiCancelled.hide();
- clearInterval(timerHandle);
- createTimer.call(self);
- triggerChanged.call(self);
- }, function () {
- $home.ui.wait(false);
- alert("运行报表失败。");
- });
- };
-
- ssis.prototype.stop = function () {
- var uiRunning = this.uiRunning,
- uiCompleted = this.uiCompleted,
- uiCancelled = this.uiCancelled,
- timerHandle = this.timerHandle;
- odatajs.oData.request({
- requestUri: "/ssisservice/Stop()",
- method: "POST",
- data: {
- name: this.options.name
- }
- }, function () {
- uiRunning.hide();
- uiCompleted.hide();
- uiCancelled.show();
- clearInterval(timerHandle);
- }, function () {
- alert("取消报表运行失败。");
- });
- };
-
- ssis.prototype.createTimer = function () {
- var self = this;
- this.timerHandle = setInterval(function () {
- triggerChanged.call(self);
- }, 10 * 1000 /* 10 seconds */);
- };
-
- return ssis;
- })();
-
- // *** pagination ***
-
- $home.pagination = (function () {
- var pagination = function () {
- this.options = $.extend({
- callback: $.noop,
- max: 50,
- search: null,
- previous: null,
- next: null
- }, arguments[0]);
- this.store = {
- skipped: 0
- };
-
- var options = this.options,
- store = this.store;
-
- options.previous.parent().addClass("disabled");
- options.next.parent().addClass("disabled");
-
- options.search.click(function () {
- store.skipped = 0;
- options.callback(true, store.skipped);
- });
-
- options.previous.click(function () {
- if (!$(this).parent().hasClass("disabled")) {
- store.skipped -= options.max;
- if (store.skipped < 0) {
- store.skipped = 0;
- }
- options.callback(false, store.skipped);
- }
- });
-
- options.next.click(function () {
- if (!$(this).parent().hasClass("disabled")) {
- store.skipped += options.max;
- options.callback(false, store.skipped);
- }
- });
- };
-
- pagination.prototype.option = function () {
- if (arguments.length === 0) {
- return this.options;
- }
- var name = arguments[0].toString();
- if (arguments.length === 1) {
- return this.options[name];
- }
- return this.options[name] = arguments[1];
- };
-
- pagination.prototype.searched = function (count) {
- if (this.store.skipped === 0) {
- this.options.previous.parent().addClass("disabled");
- } else {
- this.options.previous.parent().removeClass("disabled");
- }
-
- if (count < this.options.max) {
- this.options.next.parent().addClass("disabled");
- } else {
- this.options.next.parent().removeClass("disabled");
- }
- };
-
- pagination.prototype.research = function () {
- this.options.callback(false, this.store.skipped);
- }
-
- return pagination;
- })();
-
- // *** business ***
-
- $home.business = (function () {
- return {
- getDisplayText: function (source, value) {
- var result = "";
- $.each(source, function (index, item) {
- if (item.value === value) {
- result = item.text;
- }
- });
- return result;
- }
- };
- })();
-
- // *** odata ***
-
- $home.odata = (function () {
- return {
- initialize: function () {
- process("/salesservice/$metadata", $home.odata.metadata.saleService.saleLineItem.properties, ["SaleLineItem"]);
-
- function process(url, container, types) {
- odatajs.oData.read(url, function (data) {
- handleMetadata(data, container, types);
- }, function () {
- alert("系统初始化数据服务失败。");
- }, odatajs.oData.metadataHandler);
- }
-
- function handleMetadata(metadata, container, types) {
- var entityTypes = metadata.dataServices.schema[0].entityType;
- for (var i = 0; i < entityTypes.length; i++) {
- var entityType = entityTypes[i];
- for (var j = 0; j < types.length; j++) {
- if (types[j] === entityType.name) {
- for (var k = 0; k < entityType.property.length; k++) {
- container.push(entityType.property[k].name);
- }
- }
- }
- }
- }
- },
-
- metadata: {
- saleService: {
- saleLineItem: {
- properties: []
- }
- }
- }
- };
- })();
-
- // *** init ***
-
- $(function () {
- $home.ui.wait(false);
-
- $home.authentication.initialize();
-
- $.ajax({
- type: "GET",
- url: "/businessjson",
- dataType: "json"
- }).done(function (data) {
- $home.business = $.extend($home.business, data);
- });
-
- $home.odata.initialize();
-
- $("#home-navigator > li > a").click(function () {
- var item = $(this).parent();
- if (!item.hasClass("disabled")) {
- var index = $("#home-navigator > li").index(item);
- switch (index) {
- case 0: $home.navigation.navigate("dashboard-page"); break;
- case 1: $home.navigation.navigate("sale-management"); break;
- //// TODO: case 2: $home.navigation.navigate("customer-management"); break;
- case 2: $home.navigation.navigate("product-management"); break;
- case 3: $home.navigation.navigate("employee-management"); break;
- //// TODO: case 4: $home.navigation.navigate("control-panel"); break;
- //// TODO: case 5: $home.navigation.navigate("help-page"); break;
- }
- }
- });
-
- $("#home-logout").click($home.authentication.logout);
-
- $("#home-change-password").click(function () {
- $home.navigation.modal("change-password");
- })
- });