PageRenderTime 74ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  1. /// <reference path="jquery-1.11.3.js" />
  2. /// <reference path="jquery-ui-1.11.4.js" />
  3. /// <reference path="bootstrap.js" />
  4. /// <reference path="odatajs-4.0.0.js" />
  5. /// <reference path="common.js" />
  6. /* global odatajs, $home */
  7. // *** private helper ***
  8. $home.private = (function () {
  9. var result = {};
  10. result.productImportHelper = function () {
  11. this.params = arguments[0];
  12. this.prefix = "#" + this.params.prefix;
  13. };
  14. result.productImportHelper.prototype.init = function () {
  15. var self = this;
  16. $(this.prefix + "-import-append-update").prop("checked", true);
  17. $(this.prefix + "-import-running," + this.prefix + "-import-success," + this.prefix + "-import-failure").css("visibility", "hidden");
  18. $(this.prefix + "-import-upload").click(function () {
  19. $(self.prefix + "-import-form").submit();
  20. });
  21. };
  22. result.productImportHelper.prototype.submit = function () {
  23. $(this.prefix + "-import-running").css("visibility", "visible");
  24. $(this.prefix + "-import-success," + this.prefix + "-import-failure").css("visibility", "hidden");
  25. };
  26. result.productImportHistoryHelper = function () {
  27. this.params = arguments[0];
  28. this.prefix = "#" + this.params.prefix;
  29. this.url = this.params.url;
  30. }
  31. result.productImportHistoryHelper.prototype.init = function () {
  32. var page = $(this.prefix + "-import-history"),
  33. fromDatePicker = $(this.prefix + "-import-history-from"),
  34. toDatePicker = $(this.prefix + "-import-history-to"),
  35. personControl = $(this.prefix + "-import-history-person"),
  36. searchResult = $(this.prefix + "-import-history-result"),
  37. clearButton = $(this.prefix + "-import-history-clear"),
  38. searchUrl = null,
  39. pagination = new $home.pagination({
  40. callback: search,
  41. search: $(this.prefix + "-import-history-search"),
  42. previous: $(this.prefix + "-import-history-prev"),
  43. next: $(this.prefix + "-import-history-next")
  44. }),
  45. self = this;
  46. fromDatePicker.datepicker({ maxDate: "+0d" });
  47. toDatePicker.datepicker({ maxDate: "+0d" });
  48. clearButton.click(clear);
  49. function search(rebuild, skip) {
  50. if (rebuild) {
  51. var query = "Count ne null",
  52. from = fromDatePicker.datepicker("getDate"),
  53. to = toDatePicker.datepicker("getDate"),
  54. person = personControl.val();
  55. if (from) {
  56. from = $home.utility.odata.toODataDateTimeOffset(from);
  57. from = odatajs.oData.utils.formatDateTimeOffset(from);
  58. query += (" and Created ge " + from);
  59. }
  60. if (to) {
  61. to.setDate(to.getDate() + 1);
  62. to = $home.utility.odata.toODataDateTimeOffset(to);
  63. to = odatajs.oData.utils.formatDateTimeOffset(to);
  64. query += (" and Created lt " + to);
  65. }
  66. if (person.length > 0) {
  67. person = "'" + person + "'";
  68. query += (" and CreatedBy eq " + person);
  69. }
  70. searchUrl = self.url + "?" +
  71. "$filter=" +
  72. encodeURIComponent(query) +
  73. "&$orderby=" +
  74. encodeURIComponent("Created desc");
  75. }
  76. $home.ui.wait(true);
  77. var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
  78. odatajs.oData.read(url, function (data) {
  79. $("tbody", searchResult).empty();
  80. $.each(data.value, function (index, item) {
  81. $("<tr/>")
  82. .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(item.Created))))
  83. .append($("<td/>").text(item.CreatedBy))
  84. .append($("<td/>").text($home.business.getDisplayText($home.business.ImportTypes, item.Type)))
  85. .append($("<td class='text-right'/>").text(item.Count))
  86. .appendTo($("tbody", searchResult))
  87. .data(item);
  88. });
  89. pagination.searched(data.value.length);
  90. $home.ui.wait(false);
  91. }, function () {
  92. $home.ui.wait(false);
  93. alert("查询失败。");
  94. });
  95. }
  96. function clear() {
  97. $("form input,form select", page).val("");
  98. }
  99. };
  100. result.productUploadHelper = function () {
  101. this.params = arguments[0];
  102. this.prefix = "#" + this.params.prefix;
  103. this.type = this.params.type;
  104. };
  105. result.productUploadHelper.prototype.init = function () {
  106. var appendOrUpdateRadio = $(this.prefix + "-upload-append-update"),
  107. replaceRadio = $(this.prefix + "-upload-replace"),
  108. uploadTypeRadios = appendOrUpdateRadio.add(replaceRadio),
  109. uploadButton = $(this.prefix + "-upload-upload"),
  110. self = this;
  111. appendOrUpdateRadio.prop("checked", true);
  112. uploadButton.click(function () {
  113. $home.ui.wait(true);
  114. odatajs.oData.request({
  115. requestUri: "/productservice/Upload()",
  116. method: "POST",
  117. data: {
  118. productType: self.type,
  119. uploadType: uploadTypeRadios.filter(":checked").val()
  120. }
  121. }, function () {
  122. $home.ui.wait(false);
  123. alert("上传成功。");
  124. }, function () {
  125. $home.ui.wait(false);
  126. alert("上传失败。");
  127. });
  128. });
  129. };
  130. result.productUploadHistoryHelper = function () {
  131. this.params = arguments[0];
  132. this.prefix = "#" + this.params.prefix;
  133. this.type = this.params.type;
  134. };
  135. result.productUploadHistoryHelper.prototype.init = function () {
  136. var page = $(this.prefix + "-upload-history"),
  137. fromDatePicker = $(this.prefix + "-upload-history-from"),
  138. toDatePicker = $(this.prefix + "-upload-history-to"),
  139. personControl = $(this.prefix + "-upload-history-person"),
  140. searchResult = $(this.prefix + "-upload-history-result"),
  141. clearButton = $(this.prefix + "-upload-history-clear"),
  142. searchUrl = null,
  143. pagination = new $home.pagination({
  144. callback: search,
  145. search: $(this.prefix + "-upload-history-search"),
  146. previous: $(this.prefix + "-upload-history-prev"),
  147. next: $(this.prefix + "-upload-history-next")
  148. }),
  149. self = this;
  150. fromDatePicker.datepicker({ maxDate: "+0d" });
  151. toDatePicker.datepicker({ maxDate: "+0d" });
  152. clearButton.click(clear);
  153. function search(rebuild, skip) {
  154. if (rebuild) {
  155. var query = "Count ne null",
  156. from = fromDatePicker.datepicker("getDate"),
  157. to = toDatePicker.datepicker("getDate"),
  158. person = personControl.val();
  159. if (from) {
  160. from = $home.utility.odata.toODataDateTimeOffset(from);
  161. from = odatajs.oData.utils.formatDateTimeOffset(from);
  162. query += (" and Created ge " + from);
  163. }
  164. if (to) {
  165. to.setDate(to.getDate() + 1);
  166. to = $home.utility.odata.toODataDateTimeOffset(to);
  167. to = odatajs.oData.utils.formatDateTimeOffset(to);
  168. query += (" and Created lt " + to);
  169. }
  170. if (person.length > 0) {
  171. person = "'" + person + "'";
  172. query += (" and CreatedBy eq " + person);
  173. }
  174. query += (" and ProductType eq Home.Services.ProductService.ProductType'" + self.type + "' ");
  175. searchUrl = "/productservice/Uploads?" +
  176. "$filter=" +
  177. encodeURIComponent(query) +
  178. "&$orderby=" +
  179. encodeURIComponent("Created desc");
  180. }
  181. $home.ui.wait(true);
  182. var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
  183. odatajs.oData.read(url, function (data) {
  184. $("tbody", searchResult).empty();
  185. $.each(data.value, function (index, item) {
  186. $("<tr/>")
  187. .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(item.Created))))
  188. .append($("<td/>").text(item.CreatedBy))
  189. .append($("<td/>").text($home.business.getDisplayText($home.business.ProductTypes, item.ProductType)))
  190. .append($("<td/>").text($home.business.getDisplayText($home.business.ProductUploadTypes, item.UploadType)))
  191. .append($("<td class='text-right'/>").text(item.Count))
  192. .append($("<td/>").text($home.business.getDisplayText($home.business.ProductUploadStatuses, item.Status)))
  193. .appendTo($("tbody", searchResult))
  194. .data(item);
  195. });
  196. pagination.searched(data.value.length);
  197. $home.ui.wait(false);
  198. }, function () {
  199. $home.ui.wait(false);
  200. alert("查询失败。");
  201. });
  202. }
  203. function clear() {
  204. $("form input,form select", page).val("");
  205. }
  206. };
  207. return result;
  208. })();
  209. // *** pages ***
  210. $home.pages = (function () {
  211. return {
  212. "dashboard-page": {
  213. title: $($("#home-navbar > ul > li > a").get(0)).text(),
  214. init: function () {
  215. $("#dashboard-page-print").click(function () {
  216. $home.navigation.modal("print-sale");
  217. });
  218. }
  219. },
  220. // "customer-management": {
  221. // title: $($("#home-navbar > ul > li > a").get(2)).text(),
  222. // init: function () {
  223. // }
  224. // },
  225. // "control-panel": {
  226. // title: $($("#home-navbar > ul > li > a").get(4)).text(),
  227. // init: function () {
  228. // }
  229. // },
  230. // "help-page": {
  231. // title: $($("#home-navbar > ul > li > a").get(5)).text(),
  232. // init: function () {
  233. // }
  234. // },
  235. "product-management": {
  236. title: $($("#home-navbar > ul > li > a").get(2)).text(),
  237. init: function () {
  238. $("#product-management-diamond-on-sale").click(function () {
  239. $home.navigation.navigate("diamond-on-sale");
  240. });
  241. $("#product-management-diamond-import").click(function () {
  242. $home.navigation.modal("diamond-import");
  243. });
  244. $("#product-management-diamond-import-history").click(function () {
  245. $home.navigation.navigate("diamond-import-history");
  246. });
  247. $("#product-management-diamond-upload").click(function () {
  248. $home.navigation.modal("diamond-upload");
  249. });
  250. $("#product-management-diamond-upload-history").click(function () {
  251. $home.navigation.navigate("diamond-upload-history");
  252. });
  253. }
  254. },
  255. "diamond-on-sale": {
  256. title: "裸钻数据",
  257. init: function () {
  258. var page = $("#diamond-on-sale"),
  259. shapeControl = $("#diamond-on-sale-shape"),
  260. reportNumberControl = $("#diamond-on-sale-report-number"),
  261. reportTypeControl = $("#diamond-on-sale-report-type"),
  262. priceFromControl = $("#diamond-on-sale-price-from"),
  263. priceToControl = $("#diamond-on-sale-price-to"),
  264. weightFromControl = $("#diamond-on-sale-weight-from"),
  265. weightToControl = $("#diamond-on-sale-weight-to"),
  266. colorControl = $("#diamond-on-sale-color"),
  267. clarityControl = $("#diamond-on-sale-clarity"),
  268. cutControl = $("#diamond-on-sale-cut"),
  269. polishControl = $("#diamond-on-sale-polish"),
  270. symmetryControl = $("#diamond-on-sale-symmetry"),
  271. typeControl = $("#diamond-on-sale-type"),
  272. coloredColorControl = $("#diamond-on-sale-colored-color"),
  273. clearButton = $("#diamond-on-sale-clear"),
  274. searchResult = $("#diamond-on-sale-result"),
  275. searchUrl = null,
  276. pagination = new $home.pagination({
  277. callback: search,
  278. search: $("#diamond-on-sale-search"),
  279. previous: $("#diamond-on-sale-prev"),
  280. next: $("#diamond-on-sale-next")
  281. });
  282. clearButton.click(clear);
  283. function search(rebuild, skip) {
  284. if (rebuild) {
  285. var query = "Index ne null",
  286. type = typeControl.val().trim(),
  287. shape = shapeControl.val().trim(),
  288. reportNumber = reportNumberControl.val().trim(),
  289. reportType = reportTypeControl.val().trim(),
  290. priceFrom = parseFloat(priceFromControl.val().trim()),
  291. priceTo = parseFloat(priceToControl.val().trim()),
  292. weightFrom = parseFloat(weightFromControl.val().trim()),
  293. weightTo = parseFloat(weightToControl.val().trim()),
  294. color = colorControl.val().trim(),
  295. coloredColor = coloredColorControl.val().trim(),
  296. clarity = clarityControl.val().trim(),
  297. cut = cutControl.val().trim(),
  298. polish = polishControl.val().trim(),
  299. symmetry = symmetryControl.val().trim();
  300. if (type.length !== 0) {
  301. query += (" and Type eq Home.Services.ProductService.DiamondType'" + type + "'");
  302. }
  303. if (shape.length !== 0) {
  304. query += (" and Shape eq Home.Services.ProductService.DiamondShape'" + shape + "'");
  305. }
  306. if (reportNumber.length !== 0) {
  307. query += (" and contains(ReportNumber,'" + reportNumber + "')");
  308. }
  309. if (reportType.length !== 0) {
  310. query += (" and ReportType eq Home.Services.ProductService.DiamondReport'" + reportType + "'");
  311. }
  312. if (!isNaN(priceFrom)) {
  313. query += (" and SalePrice ge " + priceFrom);
  314. }
  315. if (!isNaN(priceTo)) {
  316. query += (" and SalePrice le " + priceTo);
  317. }
  318. if (!isNaN(weightFrom)) {
  319. query += (" and Caret ge " + weightFrom);
  320. }
  321. if (!isNaN(weightTo)) {
  322. query += (" and Caret le " + weightTo);
  323. }
  324. if (color.length !== 0) {
  325. query += (" and Color eq Home.Services.ProductService.DiamondColor'" + color + "'");
  326. }
  327. if (coloredColor.length !== 0) {
  328. query += (" and contains(ColoredColor,'" + coloredColor + "')");
  329. }
  330. if (clarity.length !== 0) {
  331. query += (" and Clarity eq Home.Services.ProductService.DiamondClarity'" + clarity + "'");
  332. }
  333. if (cut.length !== 0) {
  334. query += (" and Cut eq Home.Services.ProductService.DiamondCut'" + cut + "'");
  335. }
  336. if (polish.length !== 0) {
  337. query += (" and Polish eq Home.Services.ProductService.DiamondPolish'" + polish + "'");
  338. }
  339. if (symmetry.length !== 0) {
  340. query += (" and Symmetry eq Home.Services.ProductService.DiamondSymmetry'" + symmetry + "'");
  341. }
  342. searchUrl = "/productservice/Diamonds?" +
  343. "$filter=" +
  344. encodeURIComponent(query) +
  345. "&$orderby=" +
  346. encodeURIComponent("Index");
  347. }
  348. $home.ui.wait(true);
  349. var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
  350. odatajs.oData.read(url, function (data) {
  351. $("tbody", searchResult).empty();
  352. $.each(data.value, function (index, product) {
  353. $("<tr/>")
  354. .append($("<td class='text-left'/>").text(formatText(product.Index)))
  355. .append($("<td/>").text($home.business.getDisplayText($home.business.DiamondTypes, product.Type)))
  356. .append($("<td/>").text(formatText(product.Shape)))
  357. .append($("<td/>").text(formatText(product.ReportNumber)))
  358. .append($("<td/>").text(formatText(product.ReportType)))
  359. .append($("<td class='text-right'/>").text(formatText(product.Caret)))
  360. .append($("<td/>").text((product.Color === null || product.Color === undefined || product.Color.length === 0) ? formatText(product.ColoredColor) : formatText(product.Color)))
  361. .append($("<td/>").text(formatText(product.Clarity)))
  362. .append($("<td/>").text(formatText(product.Cut)))
  363. .append($("<td/>").text(formatText(product.Polish)))
  364. .append($("<td/>").text(formatText(product.Symmetry)))
  365. .append($("<td/>").text(formatText(product.Fluorescence)))
  366. .append($("<td class='text-right'/>").text(formatText(product.Cost)))
  367. .append($("<td class='text-right'/>").text(formatText(product.SalePrice)))
  368. .append($("<td/>").text($home.business.getDisplayText($home.business.ProductStatuses, product.Status)))
  369. .append($("<td/>").text(formatText(product.Comment)))
  370. .appendTo($("tbody", searchResult))
  371. .data(product);
  372. });
  373. pagination.searched(data.value.length);
  374. $home.ui.wait(false);
  375. }, function () {
  376. $home.ui.wait(false);
  377. alert("查询失败。");
  378. });
  379. }
  380. function clear() {
  381. $("form input, form select", page).val("");
  382. }
  383. function formatText(value) {
  384. if (value === undefined || value === null) {
  385. return "";
  386. }
  387. return value.toString();
  388. }
  389. }
  390. },
  391. "diamond-import": {
  392. title: "导入裸钻数据",
  393. init: function () {
  394. new $home.private.productImportHelper({ prefix: "diamond" }).init();
  395. }
  396. },
  397. "diamond-import-history": {
  398. title: "导入裸钻数据的历史",
  399. init: function () {
  400. new $home.private.productImportHistoryHelper({ prefix: "diamond", url: "/productservice/DiamondImports" }).init();
  401. }
  402. },
  403. "diamond-upload": {
  404. title: "上传裸钻数据到网站",
  405. init: function () {
  406. new $home.private.productUploadHelper({ prefix: "diamond", type: "Diamond" }).init();
  407. }
  408. },
  409. "diamond-upload-history": {
  410. title: "上传裸钻数据到网站的历史",
  411. init: function () {
  412. new $home.private.productUploadHistoryHelper({ prefix: "diamond", type: "Diamond" }).init();
  413. }
  414. },
  415. "print-sale": {
  416. title: "销售开单",
  417. init: function () {
  418. var baseBehavior = function () { };
  419. baseBehavior.prototype.init = $.noop;
  420. baseBehavior.prototype.add = $.noop;
  421. baseBehavior.prototype.edit = $.noop;
  422. baseBehavior.prototype.clear = $.noop;
  423. baseBehavior.prototype.format = function () {
  424. return "";
  425. };
  426. baseBehavior.prototype.validate = function () {
  427. return true;
  428. };
  429. var diamondBehavior = function () {
  430. baseBehavior.call(this);
  431. this.goodCertificate = $("#print-sale-good-certificate");
  432. this.goodCaret = $("#print-sale-good-caret");
  433. this.goodCut = $("#print-sale-good-cut");
  434. this.goodClarity = $("#print-sale-good-clarity");
  435. this.goodColor = $("#print-sale-good-color");
  436. };
  437. $home.utility.oo.extend(baseBehavior, diamondBehavior);
  438. diamondBehavior.prototype.init = $.noop;
  439. diamondBehavior.prototype.add = function (entity) {
  440. if (this.goodCertificate.val().length > 0) {
  441. entity.Certificate = this.goodCertificate.val();
  442. }
  443. if (this.goodCaret.val().length > 0) {
  444. entity.Caret = parseFloat(this.goodCaret.val());
  445. }
  446. if (this.goodCut.val().length > 0) {
  447. entity.Cut = this.goodCut.val();
  448. }
  449. if (this.goodClarity.val().length > 0) {
  450. entity.Clarity = this.goodClarity.val();
  451. }
  452. if (this.goodColor.val().length > 0) {
  453. entity.Color = this.goodColor.val();
  454. }
  455. };
  456. diamondBehavior.prototype.edit = function (entity) {
  457. this.goodCertificate.val(entity.Certificate);
  458. this.goodCaret.val(entity.Caret);
  459. this.goodCut.val(entity.Cut);
  460. this.goodClarity.val(entity.Clarity);
  461. this.goodColor.val(entity.Color);
  462. };
  463. diamondBehavior.prototype.clear = function () {
  464. this.goodCertificate.val("");
  465. this.goodCaret.val("");
  466. this.goodCut.val("");
  467. this.goodClarity.val("");
  468. this.goodColor.val("");
  469. };
  470. diamondBehavior.prototype.format = function () {
  471. var result = "";
  472. if (this.goodCertificate.val().length > 0) {
  473. result += "证书:" + this.goodCertificate.val() + " ";
  474. }
  475. if (this.goodCaret.val().length > 0) {
  476. result += "钻重:" + this.goodCaret.val() + " ";
  477. }
  478. if (this.goodCut.val().length > 0) {
  479. result += "切工:" + this.goodCut.val() + " ";
  480. }
  481. if (this.goodClarity.val().length > 0) {
  482. result += "净度:" + this.goodClarity.val() + " ";
  483. }
  484. if (this.goodColor.val().length > 0) {
  485. result += "颜色:" + this.goodColor.val() + " ";
  486. }
  487. return result;
  488. };
  489. diamondBehavior.prototype.validate = function () {
  490. return $home.validation.validateRequired(this.goodCaret) && $home.validation.validateFloat(this.goodCaret);
  491. };
  492. // members
  493. var sale = {},
  494. behavior = new baseBehavior(),
  495. dialog = $("#print-sale"),
  496. userInfo = $("#print-sale-user-info"),
  497. customerInfo = $("#print-sale-customer-info"),
  498. goodInfo = $("#print-sale-good-info"),
  499. goodSpecificInfo = $("#print-sale-good-info-specific"),
  500. customerWayButton = $("#print-sale-customer-way-button"),
  501. goodNameButton = $("#print-sale-good-name-button"),
  502. addGoodButton = $("#print-sale-add-good"),
  503. saveButton = $("#print-sale-save"),
  504. printServiceButton = $("#print-sale-print-service"),
  505. printReceiptButton = $("#print-sale-print-receipt"),
  506. userName = $("#print-sale-user"),
  507. receiptNumber = $("#print-sale-receipt-number"),
  508. customerName = $("#print-sale-customer-name"),
  509. customerPhone = $("#print-sale-customer-phone"),
  510. customerContact = $("#print-sale-customer-contact"),
  511. customerWay = $("#print-sale-customer-way"),
  512. goodName = $("#print-sale-good-name"),
  513. goodDescription = $("#print-sale-good-description"),
  514. goodQuantity = $("#print-sale-good-quantity"),
  515. goodPrice = $("#print-sale-good-price");
  516. // dialog
  517. dialog.on("shown.bs.modal", function () {
  518. // user
  519. userName.val($home.authentication.getUserInfo().id);
  520. // customer name
  521. customerName.focus();
  522. // customer way
  523. $home.ui.selectbutton(customerWayButton.parent());
  524. $("ul > li > a:first", customerWayButton.parent()).click();
  525. // good name
  526. $home.ui.editableselect(goodName.parent());
  527. goodNameButton.parent().on("hidden.bs.dropdown", replaceGoodInfo);
  528. goodName.keypress(function (e) {
  529. if (e.keyCode === 13) {
  530. replaceGoodInfo();
  531. }
  532. }).on("input", replaceGoodInfo);
  533. // table
  534. dialog.on("click", "table a[home-data-action='edit']", editFromTable);
  535. dialog.on("click", "table a[home-data-action='remove']", removeFromTable);
  536. // enable UI
  537. setEditable(true);
  538. // add good
  539. addGoodButton.click(addToTable);
  540. // save
  541. saveButton.click(save);
  542. });
  543. // disable enable
  544. function setEditable(enabled) {
  545. $("fieldset input, fieldset textarea", dialog).not(receiptNumber).prop("readonly", !enabled);
  546. $("fieldset button, fieldset select", dialog).prop("disabled", !enabled);
  547. if (enabled) {
  548. saveButton.prop("disabled", false);
  549. printServiceButton.prop("disabled", true).addClass("disabled", true);
  550. printReceiptButton.prop("disabled", true).addClass("disabled", true);
  551. $("table > tbody > tr > td > a", dialog).removeClass("disabled");
  552. } else {
  553. saveButton.prop("disabled", true);
  554. printServiceButton.prop("disabled", false).removeClass("disabled");
  555. printReceiptButton.prop("disabled", false).removeClass("disabled");
  556. $("table > tbody > tr > td > a", dialog).addClass("disabled", true);
  557. }
  558. }
  559. // calculate total price
  560. function calculateTotalPrice() {
  561. var totalPrice = 0;
  562. $.each($("table > tbody > tr", dialog), function (index, row) {
  563. var detail = $(row).data();
  564. totalPrice += (detail.Quantity * detail.UnitPrice);
  565. });
  566. $("table > tfoot > tr > th:last", dialog).prev().text(totalPrice.toString());
  567. }
  568. // edit good
  569. function editFromTable() {
  570. if (!$(this).hasClass("disabled")) {
  571. var row = $(this).parent().parent();
  572. var detail = row.data();
  573. goodName.val(detail.ProductName);
  574. goodDescription.val(detail.ProductDescription);
  575. goodQuantity.val(detail.Quantity);
  576. goodPrice.val(detail.UnitPrice);
  577. behavior.edit(detail);
  578. row.remove();
  579. calculateTotalPrice();
  580. goodNameButton.focus();
  581. }
  582. }
  583. // remove good
  584. function removeFromTable() {
  585. if (!$(this).hasClass("disabled")) {
  586. var row = $(this).parent().parent();
  587. row.remove();
  588. calculateTotalPrice();
  589. goodNameButton.focus();
  590. }
  591. }
  592. // add good
  593. function addToTable() {
  594. function formatDescription() {
  595. var result = behavior.format();
  596. if (goodDescription.val().length > 0) {
  597. result += goodDescription.val();
  598. }
  599. return result;
  600. }
  601. $home.validation.cleanup(goodInfo);
  602. if (!($home.validation.validateRequired(goodName) &&
  603. $home.validation.validateRequired(goodQuantity) &&
  604. $home.validation.validateInteger(goodQuantity) &&
  605. $home.validation.validateRequired(goodPrice) &&
  606. $home.validation.validateInteger(goodPrice) &&
  607. behavior.validate())) {
  608. alert("请检查商品信息,有未填写的内容,请填写完整。");
  609. return;
  610. }
  611. var detail = {
  612. ProductName: goodName.val(),
  613. ProductDescription: goodDescription.val(),
  614. Quantity: parseInt(goodQuantity.val()),
  615. UnitPrice: parseInt(goodPrice.val())
  616. };
  617. behavior.add(detail);
  618. $("<tr></tr>")
  619. .append($("<td></td>").text(goodName.val()))
  620. .append($("<td></td>").text(formatDescription()))
  621. .append($("<td class='text-center'></td>").text(detail.Quantity.toString()))
  622. .append($("<td class='text-right'></td>").text(detail.UnitPrice.toString()))
  623. .append("<td>" +
  624. "<a href='javascript:void(0)' title='修改' role='button' home-data-action='edit'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></a>" +
  625. "<a href='javascript:void(0)' title='删除' role='button' home-data-action='remove'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></a>" +
  626. "</td>")
  627. .data(detail)
  628. .appendTo("table > tbody", dialog);
  629. calculateTotalPrice();
  630. goodName.val("");
  631. goodDescription.val("");
  632. goodQuantity.val("");
  633. goodPrice.val("");
  634. behavior.clear();
  635. $home.validation.cleanup(goodInfo);
  636. goodNameButton.focus();
  637. }
  638. // save
  639. function save() {
  640. $home.validation.cleanup(userInfo);
  641. if (!($home.validation.validateRequired(userName))) {
  642. alert("请检查用户信息,有未填写的内容,请填写完整。");
  643. return;
  644. }
  645. $home.validation.cleanup(customerInfo);
  646. if (!($home.validation.validateRequired(customerName) &&
  647. $home.validation.validateRequired(customerPhone) &&
  648. $home.validation.validateRequired(customerContact))) {
  649. alert("请检查客户信息,有未填写的内容,请填写完整。");
  650. return;
  651. }
  652. sale.Items = [];
  653. $.each($("table > tbody > tr", dialog), function (index, row) {
  654. sale.Items.push($(row).data());
  655. });
  656. if (sale.Items.length === 0) {
  657. alert("没有添加任何商品,请添加商品之后继续。");
  658. return;
  659. }
  660. setEditable(false);
  661. sale.SalesPersonName = $("#print-sale-user-info option:selected").text();
  662. sale.CustomerName = customerName.val();
  663. sale.CustomerContacts = [
  664. { Method: "Phone", Value: customerPhone.val() },
  665. { Method: customerWay.val(), Value: customerContact.val() }
  666. ];
  667. $home.ui.wait(true);
  668. odatajs.oData.request({
  669. requestUri: "/salesservice/Sales",
  670. method: "POST",
  671. data: sale
  672. }, function (data) {
  673. receiptNumber.val(data.NumberText);
  674. printServiceButton.attr("href", "/pages/print-service?id=" + data.Id);
  675. printReceiptButton.attr("href", "/pages/print-receipt?id=" + data.Id);
  676. setEditable(false);
  677. $home.ui.wait(false);
  678. alert("保存成功,可以开始打印。");
  679. }, function () {
  680. $home.ui.wait(false);
  681. alert("保存失败。");
  682. setEditable(true);
  683. });
  684. }
  685. // good name changed event
  686. function replaceGoodInfo() {
  687. goodSpecificInfo.empty();
  688. switch (goodName.val()) {
  689. case $home.business.ProductNames.Diamond:
  690. behavior = new diamondBehavior();
  691. replaceUI("print-sale-diamond");
  692. break;
  693. default:
  694. behavior = new baseBehavior();
  695. behavior.init();
  696. break;
  697. }
  698. function replaceUI(id) {
  699. $home.navigation.embed(id, goodSpecificInfo, function () {
  700. behavior.init();
  701. });
  702. }
  703. }
  704. }
  705. },
  706. "print-sale-diamond": {
  707. title: "裸钻",
  708. init: $.noop
  709. },
  710. "sale-management": {
  711. title: $($("#home-navbar > ul > li > a").get(1)).text(),
  712. init: function () {
  713. $("#sale-management-print").click(function () {
  714. $home.navigation.modal("print-sale");
  715. });
  716. $("#sale-management-history").click(function () {
  717. $home.navigation.navigate("sale-history");
  718. });
  719. $("#sale-management-report").click(function () {
  720. $home.navigation.modal("sale-report");
  721. });
  722. }
  723. },
  724. "sale-history": {
  725. title: "销售历史数据查询",
  726. init: function () {
  727. var page = $("#sale-history"),
  728. fromDatePicker = $("#sale-history-from"),
  729. toDatePicker = $("#sale-history-to"),
  730. salePersonControl = $("#sale-history-sale-person"),
  731. searchResult = $("#sale-history-result"),
  732. clearButton = $("#sale-history-clear"),
  733. searchUrl = null,
  734. pagination = new $home.pagination({
  735. callback: search,
  736. search: $("#sale-history-search"),
  737. previous: $("#sale-history-prev"),
  738. next: $("#sale-history-next")
  739. });
  740. fromDatePicker.datepicker({ maxDate: "+0d" });
  741. toDatePicker.datepicker({ maxDate: "+0d" });
  742. clearButton.click(clear);
  743. function calculateAmount(sale) {
  744. var result = 0;
  745. $.each(sale.Items, function (index, detail) {
  746. result += detail.UnitPrice * detail.Quantity;
  747. });
  748. return result;
  749. }
  750. function formatContact(sale) {
  751. var result = "";
  752. $.each(sale.CustomerContacts, function (index, contact) {
  753. var method = "";
  754. $.each($home.business.ContactMethods, function (index, item) {
  755. if (item.value === contact.Method) {
  756. method = item.text;
  757. }
  758. });
  759. if (result.length > 0) {
  760. result += ",";
  761. }
  762. result += method;
  763. result += ":";
  764. result += contact.Value;
  765. });
  766. result += "。";
  767. return result;
  768. }
  769. function search(rebuild, skip) {
  770. if (rebuild) {
  771. var query = "Status eq Home.Services.SaleService.SaleStatus'Ok'",
  772. from = fromDatePicker.datepicker("getDate"),
  773. to = toDatePicker.datepicker("getDate"),
  774. person = salePersonControl.val();
  775. if (from) {
  776. from = $home.utility.odata.toODataDateTimeOffset(from);
  777. from = odatajs.oData.utils.formatDateTimeOffset(from);
  778. query += (" and Created ge " + from);
  779. }
  780. if (to) {
  781. to.setDate(to.getDate() + 1);
  782. to = $home.utility.odata.toODataDateTimeOffset(to);
  783. to = odatajs.oData.utils.formatDateTimeOffset(to);
  784. query += (" and Created lt " + to);
  785. }
  786. if (person.length > 0) {
  787. person = "'" + person + "'";
  788. query += (" and SalesPersonName eq " + person);
  789. }
  790. searchUrl = "/salesservice/Sales?$expand=" +
  791. encodeURIComponent("CustomerContacts,Items(") +
  792. "$filter=" +
  793. encodeURIComponent("Status eq Home.Services.SaleService.SaleStatus'Ok')") +
  794. "&$filter=" +
  795. encodeURIComponent(query) +
  796. "&$orderby=" +
  797. encodeURIComponent("Created desc,SalesPersonName");
  798. }
  799. $home.ui.wait(true);
  800. var url = searchUrl + "&$skip=" + skip + "&$top=" + pagination.option("max");
  801. odatajs.oData.read(url, function (data) {
  802. $("tbody", searchResult).empty();
  803. $.each(data.value, function (index, sale) {
  804. $("<tr/>")
  805. .append($("<td/>").append($("<a href='javascript:void(0)' role='button'/>").text(sale.NumberText)))
  806. .append($("<td/>").text(sale.CustomerName))
  807. .append($("<td/>").text(formatContact(sale)))
  808. .append($("<td class='text-right'/>").text(calculateAmount(sale)))
  809. .append($("<td/>").text(sale.SalesPersonName))
  810. .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(sale.Created))))
  811. .append($("<td/>").text($home.utility.date.toLocalDateTimeString(new Date(sale.Modified))))
  812. .appendTo($("tbody", searchResult))
  813. .data(sale);
  814. });
  815. $("tbody > tr > td > a", searchResult).click(function () {
  816. var sale = $(this).parent().parent().data();
  817. showSale(sale);
  818. });
  819. pagination.searched(data.value.length);
  820. $home.ui.wait(false);
  821. }, function () {
  822. $home.ui.wait(false);
  823. alert("查询失败。");
  824. });
  825. }
  826. function showSale(sale) {
  827. $home.navigation.modal("sale-view", function () {
  828. pagination.research();
  829. }, sale);
  830. }
  831. function clear() {
  832. $("form input,form select", page).val("");
  833. }
  834. }
  835. },
  836. "sale-view": {
  837. title: "销售记录",
  838. init: function (sale) {
  839. var baseBehavior = function () { };
  840. baseBehavior.prototype.init = $.noop;
  841. baseBehavior.prototype.save = function () { return true; };
  842. var diamondBehavior = function () {
  843. baseBehavior.call(this);
  844. };
  845. $home.utility.oo.extend(baseBehavior, diamondBehavior);
  846. diamondBehavior.prototype.init = function (entity, row, index) {
  847. var certificateId = "sale-view-product-certificate-" + (index + 1),
  848. caretId = "sale-view-product-caret-" + (index + 1),
  849. cutId = "sale-view-product-cut-" + (index + 1),
  850. clarityId = "sale-view-product-clarity-" + (index + 1),
  851. colorId = "sale-view-product-color-" + (index + 1),
  852. certificateField = $("<input type='text' class='form-control input-sm'/>").attr("id", certificateId),
  853. caretField = $("<input type='number' class='form-control input-sm'/>").attr("id", caretId),
  854. cutField = $("<select class='form-control input-sm'/>").attr("id", cutId),
  855. clarityField = $("<select class='form-control input-sm'/>").attr("id", clarityId),
  856. colorField = $("<select class='form-control input-sm'/>").attr("id", colorId);
  857. //// diamond cut
  858. cutField.append("<option value=''/>");
  859. $.each($home.business.DiamondCuts, function (index, item) {
  860. cutField.append($("<option/>").val(item).text(item));
  861. });
  862. //// diamond clarity
  863. clarityField.append("<option value=''/>");
  864. $.each($home.business.DiamondClarities, function (index, item) {
  865. clarityField.append($("<option/>").val(item).text(item));
  866. });
  867. //// diamond color
  868. colorField.append("<option value=''/>");
  869. $.each($home.business.DiamondColors, function (index, item) {
  870. colorField.append($("<option/>").val(item).text(item));
  871. });
  872. certificateField.val(entity.Certificate);
  873. caretField.val(entity.Caret);
  874. cutField.val(entity.Cut);
  875. clarityField.val(entity.Clarity);
  876. colorField.val(entity.Color);
  877. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, certificateId, certificateField, "证书");
  878. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, caretId, caretField, "钻重");
  879. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, cutId, cutField, "切工");
  880. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, clarityId, clarityField, "净度");
  881. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, colorId, colorField, "颜色");
  882. };
  883. diamondBehavior.prototype.save = function (entity, row) {
  884. var caretField = $($("input[type=number]", row)[0]);
  885. if ($home.validation.validateRequired(caretField) && $home.validation.validateFloat(caretField)) {
  886. entity.Certificate = getString($("input[type=text]", row)[1]);
  887. entity.Caret = getFloat(caretField);
  888. entity.Cut = getString($("select", row)[0]);
  889. entity.Clarity = getString($("select", row)[1]);
  890. entity.Color = getString($("select", row)[2]);
  891. return true;
  892. }
  893. return false;
  894. }
  895. var CONTROL_TEMPLATE =
  896. "<div class='input-group'>" +
  897. " <div class='input-group-btn'>" +
  898. " <button type='button' class='btn btn-default btn-sm dropdown-toggle' data-toggle='dropdown' aria-expanded='false'><span class='caret'></span></button>" +
  899. " <ul class='dropdown-menu' role='menu'></ul>" +
  900. " <input type='hidden'/>" +
  901. " </div>" +
  902. " <input type='text' class='form-control input-sm' />" +
  903. "</div>",
  904. CONTACT_TEMPLATE =
  905. "<div class='col-md-3'>" +
  906. " <div class='form-group'>" +
  907. " </div>" +
  908. "</div>",
  909. LINE_ROW_TEMPLATE =
  910. "<div class='row'>" +
  911. "</div>",
  912. LINE_FIELD_MIDDLE_TEMPLATE =
  913. "<div class='col-md-2'>" +
  914. " <div class='form-group'>" +
  915. " </div>" +
  916. "</div>",
  917. LINE_FIELD_LARGE_TEMPLATE =
  918. "<div class='col-md-6'>" +
  919. " <div class='form-group'>" +
  920. " </div>" +
  921. "</div>",
  922. receiptNumberField = $("#sale-view-receipt-number"),
  923. createdField = $("#sale-view-created"),
  924. createdByField = $("#sale-view-created-by"),
  925. modifiedField = $("#sale-view-modified"),
  926. modifiedByField = $("#sale-view-modified-by"),
  927. salerInfo = $("#sale-view-saler-info"),
  928. salerField = $("#sale-view-saler"),
  929. customerInfo = $("#sale-view-customer-info"),
  930. customerField = $("#sale-view-name"),
  931. lineInfo = $("#sale-view-line-info"),
  932. totalPriceField = $("#sale-view-total-price"),
  933. editButton = $("#sale-view-edit"),
  934. saveButton = $("#sale-view-save"),
  935. deleteButton = $("#sale-view-delete"),
  936. etag = sale["@odata.etag"];
  937. receiptNumberField.val(sale.NumberText);
  938. createdField.val($home.utility.date.toLocalDateString(new Date(sale.Created)));
  939. createdByField.val(sale.CreatedBy);
  940. modifiedField.val($home.utility.date.toLocalDateString(new Date(sale.Modified)));
  941. modifiedByField.val(sale.ModifiedBy);
  942. salerField.val(sale.SalesPersonName);
  943. customerField.val(sale.CustomerName);
  944. $.each(sale.CustomerContacts, function (index, contact) {
  945. var id = "sale-view-customer-contact-" + (index + 1);
  946. var method = $(CONTROL_TEMPLATE);
  947. $.each($home.business.ContactMethods, function (index, m) {
  948. var content = $("<li><a href='javascript:void(0)'></a></li>");
  949. $("a", content).attr("data-content", m.value).text(m.text);
  950. $("ul", method).append(content);
  951. });
  952. $("input[type=text]", method).attr("id", id);
  953. $home.ui.selectbutton(method);
  954. $("a", method).filter(function () {
  955. return $(this).attr("data-content") === contact.Method;
  956. }).click();
  957. $("input[type=text]", method).val(contact.Value);
  958. var template = $(CONTACT_TEMPLATE);
  959. $(".form-group", template).append($("<label/>").text("联系方式 " + (index + 1)).attr("for", id))
  960. .append(method);
  961. $(".row", customerInfo).append(template);
  962. });
  963. $.each(sale.Items, function (index, line) {
  964. // first row
  965. {
  966. function replaceLineInfo() {
  967. var behavior,
  968. parents = $(this).parentsUntil(".row"),
  969. row = $(parents[parents.size() - 1]).parent(),
  970. line = row.data("line"),
  971. index = row.data("index");
  972. removeDynamicProperties(line);
  973. row.children("div").not(":first").remove();
  974. switch (row.find("#sale-view-product-name-" + (index + 1)).val()) {
  975. case $home.business.ProductNames.Diamond:
  976. behavior = new diamondBehavior();
  977. break;
  978. default:
  979. behavior = new baseBehavior();
  980. break;
  981. }
  982. behavior.init(line, row, index);
  983. }
  984. var behavior,
  985. row = $(LINE_ROW_TEMPLATE),
  986. nameId = "sale-view-product-name-" + (index + 1),
  987. nameField = $(CONTROL_TEMPLATE),
  988. nameControl = $("input[type=text]", nameField);
  989. // product name
  990. nameControl.attr("id", nameId).keypress(function (e) {
  991. if (e.keyCode === 13) {
  992. replaceLineInfo();
  993. }
  994. }).on("input", replaceLineInfo).prev().on("hidden.bs.dropdown", replaceLineInfo);
  995. $.each($home.business.Products, function (index, item) {
  996. var anchor = $("<a href='javascript:void(0)'></a>").text(item),
  997. listItem = $("<li/>").append(anchor);
  998. $("ul", nameField).append(listItem);
  999. });
  1000. $("input", nameField).val(line.ProductName);
  1001. $home.ui.editableselect(nameField);
  1002. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, nameId, nameField, "名称");
  1003. // behavior
  1004. switch (line.ProductName) {
  1005. case $home.business.ProductNames.Diamond:
  1006. behavior = new diamondBehavior();
  1007. break;
  1008. default:
  1009. behavior = new baseBehavior();
  1010. break;
  1011. }
  1012. behavior.init(line, row, index);
  1013. // append
  1014. row.data("index", index).data("line", line);
  1015. lineInfo.append(row);
  1016. }
  1017. // second row
  1018. {
  1019. var row = $(LINE_ROW_TEMPLATE),
  1020. descriptionId = "sale-view-product-description-" + (index + 1),
  1021. quantityId = "sale-view-product-quantity-" + (index + 1),
  1022. unitPriceId = "sale-view-product-unit-price-" + (index + 1),
  1023. descriptionField = $("<input type='text' class='form-control input-sm'/>").attr("id", descriptionId),
  1024. quantityField = $("<input type='number' class='form-control input-sm quantity'/>").attr("id", quantityId),
  1025. unitPriceField = $("<input type='number' class='form-control input-sm price'/>").attr("id", unitPriceId);
  1026. descriptionField.val(line.ProductDescription);
  1027. quantityField.val(line.Quantity);
  1028. unitPriceField.val(line.UnitPrice);
  1029. addFieldForInit(row, LINE_FIELD_LARGE_TEMPLATE, descriptionId, descriptionField, "描述");
  1030. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, quantityId, quantityField, "数量");
  1031. addFieldForInit(row, LINE_FIELD_MIDDLE_TEMPLATE, unitPriceId, unitPriceField, "价格");
  1032. lineInfo.append(row);
  1033. }
  1034. });
  1035. calculateTotalPrice();
  1036. setUIEditable(false);
  1037. editButton.click(function () {
  1038. setUIEditable(true);
  1039. });
  1040. saveButton.click(save);
  1041. deleteButton.click(remove);
  1042. lineInfo.off("focusout", "input.quantity, input.price").on("focusout", "input.quantity, input.price", calculateTotalPrice);
  1043. function setUIEditable(editable) {
  1044. if (editable) {
  1045. salerField.prop("disabled", false);
  1046. customerField.prop("readonly", false);
  1047. $("input", customerInfo).prop("readonly", false);
  1048. $("select, button", customerInfo).prop("disabled", false);
  1049. $("input", lineInfo).not("#sale-view-total-price").prop("readonly", false);
  1050. $("select, button", lineInfo).prop("disabled", false);
  1051. editButton.prop("disabled", true);
  1052. saveButton.prop("disabled", false);
  1053. deleteButton.prop("disabled", false);
  1054. } else {
  1055. salerField.prop("disabled", true);
  1056. customerField.prop("readonly", true);
  1057. $("input", customerInfo).prop("readonly", true);
  1058. $("select, button", customerInfo).prop("disabled", true);
  1059. $("input", lineInfo).prop("readonly", true);
  1060. $("select, button", lineInfo).prop("disabled", true);
  1061. editButton.prop("disabled", false);
  1062. saveButton.prop("disabled", true);
  1063. deleteButton.prop("disabled", true);
  1064. }
  1065. }
  1066. function calculateTotalPrice() {
  1067. var totalPrice = 0;
  1068. $("> div", lineInfo).each(function () {
  1069. var quantityField = $("input.quantity", $(this));
  1070. var unitPriceField = $("input.price", $(this));
  1071. if (quantityField.size() === 1 && unitPriceField.size() === 1) {
  1072. var quantity = parseInt(quantityField.val());
  1073. var unitPrice = parseInt(unitPriceField.val());
  1074. totalPrice += quantity * unitPrice;
  1075. }
  1076. });
  1077. totalPriceField.val(totalPrice);
  1078. }
  1079. function save() {
  1080. $home.validation.cleanup(salerInfo);
  1081. if (!($home.validation.validateRequired(salerField))) {
  1082. alert("请检查用户信息,有未填写的内容,请填写完整。");
  1083. return;
  1084. }
  1085. sale.SalesPersonName = salerField.val();
  1086. $home.validation.cleanup(customerInfo);
  1087. if (!($home.validation.validateRequired(customerField) &&
  1088. $home.validation.validateRequired($("#sale-view-customer-contact-1")) &&
  1089. $home.validation.validateRequired($("#sale-view-customer-contact-2")))) {
  1090. alert("请检查客户信息,有未填写的内容,请填写完整。");
  1091. return;
  1092. }
  1093. sale.CustomerName = customerField.val();
  1094. sale.CustomerContacts[0].Method = $("input[type=hidden]", $("#sale-view-customer-contact-1").parent()).val();
  1095. sale.CustomerContacts[0].Value = $("#sale-view-customer-contact-1").val();
  1096. sale.CustomerContacts[1].Method = $("input[type=hidden]", $("#sale-view-customer-contact-2").parent()).val();
  1097. sale.CustomerContacts[1].Value = $("#sale-view-customer-contact-2").val();
  1098. $home.validation.cleanup(lineInfo);
  1099. var line,
  1100. lineIndex = 0,
  1101. isValid = true;
  1102. $("> div", lineInfo).not(":first").each(function (index) {
  1103. var row = $(this);
  1104. if (index % 2 === 0) {
  1105. line = sale.Items[lineIndex];
  1106. lineIndex++;
  1107. if (!$home.validation.validateRequired($($("input[type=text]", row)[0]))) {
  1108. isValid = false;
  1109. return;
  1110. }
  1111. line.ProductName = $($("input[type=text]", row)[0]).val();
  1112. var behavior;
  1113. switch (line.ProductName) {
  1114. case $home.business.ProductNames.Diamond:
  1115. behavior = new diamondBehavior();
  1116. break;
  1117. default:
  1118. behavior = new baseBehavior();
  1119. break;
  1120. }
  1121. if (!behavior.save(line, row)) {
  1122. isValid = false;
  1123. return;
  1124. }
  1125. } else {
  1126. if (!($home.validation.validateRequired($($("input[type=number]", row)[0])) &&
  1127. $home.validation.validateInteger($($("input[type=number]", row)[0])) &&
  1128. $home.validation.validateRequired($($("input[type=number]", row)[1])) &&
  1129. $home.validation.validateInteger($($("input[type=number]", row)[1])))) {
  1130. isValid = false;
  1131. return;
  1132. }
  1133. line.ProductDescription = $($("input[type=text]", row)[0]).val();
  1134. line.Quantity = parseInt($($("input[type=number]", row)[0]).val());
  1135. line.UnitPrice = parseInt($($("input[type=number]", row)[1]).val());
  1136. }
  1137. });
  1138. if (!isValid) {
  1139. alert("请检查商品信息,有未填写的内容,请填写完整。");
  1140. return;
  1141. }
  1142. $home.utility.odata.removeMetadataProperties(sale);
  1143. $home.ui.wait(true);
  1144. odatajs.oData.request({
  1145. requestUri: "/salesservice/Sales(" + sale.Id + ")",
  1146. method: "PUT",
  1147. data: sale,
  1148. headers: {
  1149. "if-match": etag
  1150. }
  1151. }, function () {
  1152. $home.ui.wait(false);
  1153. alert("保存成功。");
  1154. $("#sale-view").modal("hide");
  1155. }, function () {
  1156. $home.ui.wait(false);
  1157. alert("保存失败。");
  1158. });
  1159. }
  1160. function remove() {
  1161. if (confirm("确定要删除吗?")) {
  1162. $home.utility.odata.removeMetadataProperties(sale);
  1163. sale.CustomerContacts = undefined;
  1164. sale.Items = undefined;
  1165. sale.Status = "Deleted";
  1166. $home.ui.wait(true);
  1167. odatajs.oData.request({
  1168. requestUri: "/salesservice/Sales(" + sale.Id + ")",
  1169. method: "PATCH",
  1170. data: sale,
  1171. headers: {
  1172. "if-match": etag
  1173. }
  1174. }, function () {
  1175. $home.ui.wait(false);
  1176. alert("删除成功。");
  1177. $("#sale-view").modal("hide");
  1178. }, function () {
  1179. $home.ui.wait(false);
  1180. alert("删除失败。");
  1181. });
  1182. }
  1183. }
  1184. function addFieldForInit(row, template, id, field, text) {
  1185. var ui = $(template);
  1186. $(".form-group", ui).append($("<label/>").attr("for", id).text(text)).append(field);
  1187. row.append(ui);
  1188. }
  1189. function removeDynamicProperties(line) {
  1190. var properties = $home.odata.metadata.saleService.saleLineItem.properties;
  1191. for (var property in line) {
  1192. if (property.indexOf("@") >= 0) {
  1193. continue;
  1194. }
  1195. var found = false;
  1196. for (var i = 0; i < properties.length; i++) {
  1197. if (properties[i] === property) {
  1198. found = true;
  1199. break;
  1200. }
  1201. }
  1202. if (!found) {
  1203. line[property] = undefined;
  1204. }
  1205. }
  1206. }
  1207. function getFloat(element) {
  1208. var ui = $(element);
  1209. return (ui.val().length > 0) ? parseFloat(ui.val()) : undefined;
  1210. }
  1211. function getString(element) {
  1212. var ui = $(element);
  1213. return (ui.val().length > 0) ? ui.val() : undefined;
  1214. }
  1215. }
  1216. },
  1217. "sale-report": {
  1218. title: "销售报表",
  1219. init: function () {
  1220. var fromDatePicker = $("#sale-report-from"),
  1221. toDatePicker = $("#sale-report-to"),
  1222. viewButton = $("#sale-report-view"),
  1223. cancelButton = $("#sale-report-cancel"),
  1224. ssis = new $home.ssis({
  1225. name: "sales",
  1226. prefix: "sale-report",
  1227. changed: changedCallback
  1228. });
  1229. // For long running operation, use the following code instead
  1230. // fromDatePicker.prop("disabled", true).datepicker({ maxDate: "+0d" });
  1231. // toDatePicker.prop("disabled", true).datepicker({ maxDate: "+0d" });
  1232. // viewButton.prop("disabled", true);
  1233. fromDatePicker.datepicker({ maxDate: "+0d" });
  1234. toDatePicker.datepicker({ maxDate: "+0d" });
  1235. cancelButton.prop("disabled", true);
  1236. viewButton.click(function () {
  1237. var from = fromDatePicker.datepicker("getDate"),
  1238. to = toDatePicker.datepicker("getDate");
  1239. if (!from || !to) {
  1240. alert("请选择开始和结束日期。 ");
  1241. return;
  1242. }
  1243. to.setDate(to.getDate() + 1);
  1244. ssis.start([
  1245. { Name: "StartDate", Type: "DateTime", Value: $home.utility.date.toServerDateString(from) },
  1246. { Name: "EndDate", Type: "DateTime", Value: $home.utility.date.toServerDateString(to) },
  1247. ]);
  1248. });
  1249. cancelButton.click(function () {
  1250. ssis.stop();
  1251. });
  1252. function changedCallback(value) {
  1253. switch (value.Status) {
  1254. case "Completed":
  1255. fromDatePicker.removeAttr("disabled");
  1256. toDatePicker.removeAttr("disabled");
  1257. viewButton.removeAttr("disabled");
  1258. cancelButton.prop("disabled", true);
  1259. break;
  1260. case "Running":
  1261. fromDatePicker.prop("disabled", true);
  1262. toDatePicker.prop("disabled", true);
  1263. viewButton.prop("disabled", true);
  1264. cancelButton.removeAttr("disabled");
  1265. break;
  1266. }
  1267. }
  1268. }
  1269. },
  1270. "employee-management": {
  1271. title: $($("#home-navbar > ul > li > a").get(3)).text(),
  1272. init: function () {
  1273. // currently employee management page is same as employee list page
  1274. $home.pages["employee-list"].init();
  1275. }
  1276. },
  1277. "employee-list": {
  1278. title: "员工列表",
  1279. init: function () {
  1280. function search() {
  1281. $home.ui.wait(true);
  1282. odatajs.oData.read("/securityservice/Users?$orderby=DisplayName", function (data) {
  1283. $("tbody", table).empty();
  1284. $.each(data.value, function (index, user) {
  1285. var viewDetailsHtml = $("<a href='javascript:void(0)' role='button' data-home-action='view-details'>编辑</a>"),
  1286. viewPasswordHtml = $("<a href='javascript:void(0)' role='button' data-home-action='view-password' title='密码' data-toggle='popover' data-trigger='focus' data-content='正在获取密码……'>查看密码</a>"),
  1287. updatePasswordHtml = $("<a href='javascript:void(0)' role='button' data-home-action='update-password'>修改密码</a>");
  1288. if ($home.pages.internal.checkPasswordPermission(user.Role) < 0) {
  1289. viewDetailsHtml.addClass("disabled");
  1290. viewPasswordHtml.addClass("disabled");
  1291. updatePasswordHtml.addClass("disabled");
  1292. }
  1293. $("<tr>")
  1294. .append($("<td>").append($("<a href='javascript:void(0)' role='button' data-home-action='view-details'/>").text(user.DisplayName)))
  1295. .append($("<td>").text(user.LoginName))
  1296. .append($("<td>").text($home.business.getDisplayText($home.business.SecurityRoles, user.Role)))
  1297. .append($("<td>").text(user.IsLocked ? "是" : "否").addClass(user.IsLocked ? "text-danger" : undefined))
  1298. .append($("<td>").text(user.IsLocked && user.LockDateTime ? $home.utility.date.toLocalDateTimeString(new Date(user.LockDateTime)) : ""))
  1299. .append($("<td>").append(viewDetailsHtml).append(viewPasswordHtml).append(updatePasswordHtml))
  1300. .appendTo($("tbody", table))
  1301. .data(user);
  1302. });
  1303. $home.ui.wait(false);
  1304. }, function () {
  1305. $home.ui.wait(false);
  1306. alert("获取员工列表失败。");
  1307. });
  1308. }
  1309. function viewDetails() {
  1310. var button = $(this);
  1311. if (button.hasClass("disabled")) {
  1312. return false;
  1313. }
  1314. var user = getSelectedEmployee.call(button);
  1315. $home.navigation.modal("employee-view", search, user);
  1316. }
  1317. function viewPassword() {
  1318. var button = $(this);
  1319. if (button.hasClass("disabled")) {
  1320. return false;
  1321. }
  1322. var user = getSelectedEmployee.call(button);
  1323. $home.ui.wait(true);
  1324. odatajs.oData.read("/securityservice/Users(" + user.Id + ")/Home.Services.SecurityService.GetPassword()", function (data) {
  1325. $home.ui.wait(false);
  1326. button.attr("data-content", data.Value).on("hidden.bs.popover", function () {
  1327. button.popover("destroy");
  1328. }).popover("show");
  1329. }, function () {
  1330. $home.ui.wait(false);
  1331. button.popover("destroy");
  1332. alert("获取密码失败。");
  1333. });
  1334. }
  1335. function updatePassword() {
  1336. var button = $(this);
  1337. if (button.hasClass("disabled")) {
  1338. return false;
  1339. }
  1340. var user = getSelectedEmployee.call(button);
  1341. $home.navigation.modal("employee-update-password", null, user);
  1342. }
  1343. function getSelectedEmployee() {
  1344. return $(this).parent().parent().data();
  1345. }
  1346. function create() {
  1347. $home.navigation.modal("employee-view", search);
  1348. }
  1349. var table = $("#employee-list-result"),
  1350. createButton = $("#employee-list-create");
  1351. table.on("click", "a[data-home-action='view-details']", viewDetails)
  1352. .on("click", "a[data-home-action='view-password']", viewPassword)
  1353. .on("click", "a[data-home-action='update-password']", updatePassword);
  1354. createButton.click(create);
  1355. search();
  1356. }
  1357. },
  1358. "employee-view": {
  1359. title: "员工信息",
  1360. init: function (user) {
  1361. function save() {
  1362. $home.validation.cleanup(dialog);
  1363. if (!$home.validation.validateRequired(displayNameField)) {
  1364. alert("姓名不能为空。");
  1365. return;
  1366. }
  1367. if (!$home.validation.validateRequired(loginNameField)) {
  1368. alert("登录名不能为空。");
  1369. return;
  1370. }
  1371. if (isCreate) {
  1372. user = {};
  1373. }
  1374. user.DisplayName = displayNameField.val();
  1375. user.LoginName = loginNameField.val();
  1376. user.Role = roleField.filter(":checked").val();
  1377. user.IsLocked = isLockedField.prop("checked");
  1378. var params = {
  1379. requestUri: undefined,
  1380. method: undefined,
  1381. headers: undefined,
  1382. data: user
  1383. };
  1384. if (isCreate) {
  1385. params.requestUri = "/securityservice/Users";
  1386. params.method = "POST";
  1387. } else {
  1388. params.requestUri = "/securityservice/Users(" + user.Id + ")";
  1389. params.method = "PUT";
  1390. params.headers = {
  1391. "if-match": etag
  1392. };
  1393. $home.utility.odata.removeMetadataProperties(user);
  1394. }
  1395. $home.ui.wait(true);
  1396. odatajs.oData.request(
  1397. params, function () {
  1398. $home.ui.wait(false);
  1399. alert("保存成功。");
  1400. dialog.modal("hide");
  1401. }, function () {
  1402. $home.ui.wait(false);
  1403. alert("保存失败。");
  1404. });
  1405. }
  1406. function edit() {
  1407. displayNameField.removeAttr("disabled");
  1408. loginNameField.removeAttr("disabled");
  1409. roleField.removeAttr("disabled");
  1410. isLockedField.removeAttr("disabled");
  1411. saveButton.removeAttr("disabled");
  1412. editButton.attr("disabled", "disabled");
  1413. }
  1414. var dialog = $("#employee-view"),
  1415. displayNameField = $("#employee-view-display-name"),
  1416. loginNameField = $("#employee-view-login-name"),
  1417. roleField = $("input[name='employee-view-role']", dialog),
  1418. isLockedField = $("#employee-view-locked"),
  1419. lockTimeField = $("#employee-view-lock-time"),
  1420. lockTimeArea = $("#employee-view-lock-time-area"),
  1421. saveButton = $("#employee-view-save"),
  1422. editButton = $("#employee-view-edit"),
  1423. etag,
  1424. isCreate = user == null;
  1425. saveButton.click(save);
  1426. editButton.click(edit);
  1427. if (isCreate) {
  1428. roleField.filter("[value='" + $home.authentication.Role.Employee + "']").prop("checked", true);
  1429. lockTimeArea.hide();
  1430. editButton.hide();
  1431. } else {
  1432. displayNameField.attr("disabled", "disabled").val(user.DisplayName);
  1433. loginNameField.attr("disabled", "disabled").val(user.LoginName);
  1434. roleField.attr("disabled", "disabled").filter("[value='" + user.Role + "']").prop("checked", true);
  1435. isLockedField.attr("disabled", "disabled").prop("checked", user.IsLocked);
  1436. lockTimeField.val(user.IsLocked && user.LockDateTime ? $home.utility.date.toLocalDateTimeString(new Date(user.LockDateTime)) : "");
  1437. saveButton.attr("disabled", "disabled");
  1438. etag = user["@odata.etag"];
  1439. }
  1440. roleField.each(function () {
  1441. var role = $(this).val();
  1442. if ($home.pages.internal.checkPasswordPermission(role) < 0) {
  1443. $(this).parent().hide();
  1444. }
  1445. });
  1446. }
  1447. },
  1448. "employee-update-password": {
  1449. title: "修改密码",
  1450. init: function (user) {
  1451. var dialog = $("#employee-update-password"),
  1452. newPassword1Field = $("#employee-update-password-new"),
  1453. newPassword2Field = $("#employee-update-password-confirm"),
  1454. submitButton = $("#employee-update-password-submit");
  1455. submitButton.click(function () {
  1456. $home.validation.cleanup(dialog);
  1457. var newPassword1 = newPassword1Field.val(),
  1458. newPassword2 = newPassword2Field.val();
  1459. if (!$home.validation.validate(newPassword1Field, function () { return $home.pages.internal.validatePassword(newPassword1); })) {
  1460. alert("密码填写不正确,密码长度至少是 6 个字符,并且不超过 32 个字符。");
  1461. return;
  1462. }
  1463. if (!$home.validation.validate(newPassword2Field, function () { return newPassword1 === newPassword2; })) {
  1464. alert("新密码和确认新密码不一样。");
  1465. return;
  1466. }
  1467. $home.ui.wait(true);
  1468. odatajs.oData.request({
  1469. requestUri: "/securityservice/Users(" + user.Id + ")/Home.Services.SecurityService.UpdatePassword()",
  1470. method: "POST",
  1471. data: { "new": newPassword1 }
  1472. }, function () {
  1473. $home.ui.wait(false);
  1474. alert("修改成功。");
  1475. $("#employee-update-password").modal("hide");
  1476. }, function () {
  1477. $home.ui.wait(false);
  1478. alert("修改失败。");
  1479. });
  1480. });
  1481. }
  1482. },
  1483. "change-password": {
  1484. title: "更改密码",
  1485. init: function () {
  1486. var dialog = $("#change-password"),
  1487. oldPasswordField = $("#change-password-old"),
  1488. newPassword1Field = $("#change-password-new"),
  1489. newPassword2Field = $("#change-password-confirm"),
  1490. submitButton = $("#change-password-submit");
  1491. submitButton.click(function () {
  1492. $home.validation.cleanup(dialog);
  1493. var oldPassword = oldPasswordField.val(),
  1494. newPassword1 = newPassword1Field.val(),
  1495. newPassword2 = newPassword2Field.val();
  1496. if (!($home.validation.validate(oldPasswordField, function () { return $home.pages.internal.validatePassword(oldPassword); }) &&
  1497. $home.validation.validate(newPassword1Field, function () { return $home.pages.internal.validatePassword(newPassword1); }))) {
  1498. alert("密码填写不正确,密码长度至少是 6 个字符,并且不超过 32 个字符。");
  1499. return;
  1500. }
  1501. if (!$home.validation.validate(newPassword2Field, function () { return newPassword1 === newPassword2; })) {
  1502. alert("新密码和确认新密码不一样。");
  1503. return;
  1504. }
  1505. $home.ui.wait(true);
  1506. odatajs.oData.request({
  1507. requestUri: "/securityservice/Users(" + $home.authentication.getUserInfo().id + ")/Home.Services.SecurityService.ChangePassword()",
  1508. method: "POST",
  1509. data: { old: oldPassword, "new": newPassword1 }
  1510. }, function () {
  1511. $home.ui.wait(false);
  1512. alert("更改成功。");
  1513. dialog.modal("hide");
  1514. }, function () {
  1515. $home.ui.wait(false);
  1516. alert("更改失败。");
  1517. });
  1518. });
  1519. }
  1520. },
  1521. internal: {
  1522. validatePassword: function (password) {
  1523. return password && password.length >= 6 && password.length <= 32;
  1524. },
  1525. checkPasswordPermission: function (role) {
  1526. var current = $home.authentication.getUserInfo().Role;
  1527. switch (current) {
  1528. case $home.authentication.Role.Employee:
  1529. switch (role) {
  1530. case $home.authentication.Role.Employee: return 0;
  1531. case $home.authentication.Role.Manager: return -1;
  1532. case $home.authentication.Role.Administrator: return -1;
  1533. }
  1534. break;
  1535. case $home.authentication.Role.Manager:
  1536. switch (role) {
  1537. case $home.authentication.Role.Employee: return 1;
  1538. case $home.authentication.Role.Manager: return 0;
  1539. case $home.authentication.Role.Administrator: return -1;
  1540. }
  1541. break;
  1542. case $home.authentication.Role.Administrator:
  1543. switch (role) {
  1544. case $home.authentication.Role.Employee: return 1;
  1545. case $home.authentication.Role.Manager: return 1;
  1546. case $home.authentication.Role.Administrator: return 0;
  1547. }
  1548. break;
  1549. }
  1550. return -1;
  1551. }
  1552. }
  1553. };
  1554. })();
  1555. // *** navigation ***
  1556. $home.navigation = (function () {
  1557. return {
  1558. navigate: function (id) {
  1559. $home.ui.wait(true);
  1560. var setting = $home.pages[id];
  1561. var args = $home.navigation.internal.createArguments(arguments, 1);
  1562. $home.navigation.internal.invoke(id).done(function (html) {
  1563. $home.ui.wait(false);
  1564. $("h1").text(setting.title);
  1565. $("#home-content").html(html);
  1566. setting.init.apply(null, args);
  1567. }).fail(function (xhr) {
  1568. $home.ui.wait(false);
  1569. if (xhr.status === 401) {
  1570. alert("您没有权限导航到" + setting.title + "。");
  1571. } else {
  1572. alert("导航到" + setting.title + "失败。");
  1573. }
  1574. });
  1575. },
  1576. modal: function (id, handler) {
  1577. $home.ui.wait(true);
  1578. var setting = $home.pages[id];
  1579. var args = $home.navigation.internal.createArguments(arguments, 2);
  1580. $home.navigation.internal.invoke(id).done(function (html) {
  1581. $home.ui.wait(false);
  1582. $("#home-dialog").html(html);
  1583. setting.init.apply(null, args);
  1584. $("#" + id).on("hidden.bs.modal", function () {
  1585. $("#home-dialog").empty();
  1586. if (handler) {
  1587. handler();
  1588. }
  1589. }).modal("show");
  1590. }).fail(function (xhr) {
  1591. $home.ui.wait(false);
  1592. if (xhr.status === 401) {
  1593. alert("您没有权限打开" + setting.title + "对话框。");
  1594. } else {
  1595. alert("打开" + setting.title + "对话框失败。");
  1596. }
  1597. });
  1598. },
  1599. embed: function (id, container, init) {
  1600. $home.ui.wait(true);
  1601. var setting = $home.pages[id];
  1602. var args = $home.navigation.internal.createArguments(arguments, 2);
  1603. $home.navigation.internal.invoke(id).done(function (html) {
  1604. $home.ui.wait(false);
  1605. $(container).html(html);
  1606. setting.init.apply(null, args);
  1607. if (init) {
  1608. init.apply(null, args);
  1609. }
  1610. }).fail(function (xhr) {
  1611. $home.ui.wait(false);
  1612. if (xhr.status === 401) {
  1613. alert("您没有权限查看" + setting.title + "。");
  1614. } else {
  1615. alert("查看" + setting.title + "失败。");
  1616. }
  1617. });
  1618. },
  1619. internal: {
  1620. invoke: function (id) {
  1621. return $.ajax({
  1622. url: "/pages/" + id,
  1623. method: "GET",
  1624. cache: true
  1625. });
  1626. },
  1627. createArguments: function (args, count) {
  1628. if (args.length > count) {
  1629. var result = [];
  1630. $.each(args, function (index, item) {
  1631. if (index > (count - 1)) {
  1632. result.push(item);
  1633. }
  1634. });
  1635. return result;
  1636. }
  1637. }
  1638. }
  1639. };
  1640. })();
  1641. // *** authentication ***
  1642. $home.authentication = (function () {
  1643. return {
  1644. timeout: new $home.observable(),
  1645. isTimeout: function () {
  1646. return $home.authentication.internal.isTimeout;
  1647. },
  1648. restart: function () {
  1649. if ($home.authentication.internal.timeoutHandle) {
  1650. clearTimeout($home.authentication.internal.timeoutHandle);
  1651. }
  1652. $home.authentication.internal.timeoutHandle = setTimeout(function () {
  1653. $.ajax({
  1654. type: "POST",
  1655. url: "/account/logout",
  1656. headers: { RequestVerificationToken: $("#login-form input[name=__AjaxRequestVerificationToken]").val() },
  1657. cache: false
  1658. }).complete(function () {
  1659. clearTimeout($home.authentication.internal.timeoutHandle);
  1660. $home.authentication.internal.isTimeout = true;
  1661. $home.authentication.timeout.fire();
  1662. $home.authentication.exit();
  1663. });
  1664. }, 60 * 60 * 1000);
  1665. },
  1666. exit: function () {
  1667. document.location = "/account/timeout";
  1668. },
  1669. initialize: function () {
  1670. $home.authentication.restart();
  1671. $home.authentication.internal.initializeAjax();
  1672. $home.authentication.internal.initializeOData();
  1673. $.ajax({
  1674. type: "GET",
  1675. url: "/account/check",
  1676. dataType: "json",
  1677. cache: false
  1678. }).done(function (data) {
  1679. if (data.IsLoggedIn) {
  1680. $home.authentication.internal.userId = data.Id;
  1681. $home.authentication.internal.userName = data.Name;
  1682. $home.authentication.internal.userRole = data.Role;
  1683. $home.authentication.internal.initializeUI();
  1684. $("#home-identity").text(data.Name);
  1685. $home.navigation.navigate("dashboard-page");
  1686. } else {
  1687. $home.authentication.login();
  1688. }
  1689. }).fail(function () {
  1690. alert("检查登录状态失败。");
  1691. });
  1692. },
  1693. login: function () {
  1694. document.location.assign("/account/login");
  1695. },
  1696. logout: function () {
  1697. $("#home-logout-form").get(0).submit();
  1698. $home.authentication.internal.userId = null;
  1699. $home.authentication.internal.userName = null;
  1700. $home.authentication.internal.userRole = null;
  1701. },
  1702. getUserInfo: function () {
  1703. return {
  1704. id: $home.authentication.internal.userId,
  1705. Name: $home.authentication.internal.userName,
  1706. Role: $home.authentication.internal.userRole
  1707. };
  1708. },
  1709. Role: {
  1710. Administrator: "Administrator",
  1711. Manager: "Manager",
  1712. Employee: "Employee"
  1713. },
  1714. internal: {
  1715. isTimeout: false,
  1716. timeoutHandle: null,
  1717. userId: null,
  1718. userName: null,
  1719. userRole: null,
  1720. initializeUI: function () {
  1721. $.ajax({
  1722. type: "GET",
  1723. url: "/permissions",
  1724. dataType: "json"
  1725. }).done(function (data) {
  1726. function check(name, listItem) {
  1727. var permitted;
  1728. if ($home.authentication.internal.userRole === $home.authentication.Role.Administrator) {
  1729. permitted = true;
  1730. } else {
  1731. $.each(data, function (index, record) {
  1732. if (record.name === name) {
  1733. $.each(record.roles, function (index, role) {
  1734. if (role === $home.authentication.internal.userRole) {
  1735. permitted = true;
  1736. }
  1737. });
  1738. }
  1739. });
  1740. }
  1741. if (!permitted) {
  1742. $(listItem).addClass("disabled").hide();
  1743. }
  1744. }
  1745. $.each($("#home-navigator > li"), function (index, listItem) {
  1746. switch (index) {
  1747. case 0: check("dashboard-page", listItem); break;
  1748. case 1: check("sale-management", listItem); break;
  1749. //// TODO: case 2: check("customer-management", listItem); break;
  1750. case 2: check("product-management", listItem); break;
  1751. case 3: check("employee-management", listItem); break;
  1752. //// TODO: case 4: check("control-panel", listItem); break;
  1753. //// TODO: case 5: check("help-page", listItem); break;
  1754. }
  1755. });
  1756. }).fail(function () {
  1757. alert("检查权限失败。");
  1758. });
  1759. },
  1760. initializeAjax: function () {
  1761. $(document).ajaxSuccess(function () {
  1762. if (!$home.authentication.isTimeout()) {
  1763. $home.authentication.restart();
  1764. }
  1765. }).ajaxError(function (event, xhr, settings, error) {
  1766. if (!$home.authentication.isTimeout() && error.toLowerCase() !== "not authorized") {
  1767. $home.authentication.restart();
  1768. }
  1769. });
  1770. },
  1771. initializeOData: function () {
  1772. var odataSuccess = odatajs.oData.defaultSuccess || $.noop;
  1773. var odataError = odatajs.oData.defaultError || $.noop;
  1774. odatajs.oData.defaultSuccess = function () {
  1775. odataSuccess();
  1776. if (!$home.authentication.isTimeout()) {
  1777. $home.authentication.restart();
  1778. }
  1779. };
  1780. odatajs.oData.defaultError = function (error) {
  1781. odataError(error);
  1782. if (!$home.authentication.isTimeout() && error.response.statusCode !== 401) {
  1783. $home.authentication.restart();
  1784. }
  1785. };
  1786. }
  1787. }
  1788. };
  1789. })();
  1790. // *** SSIS ***
  1791. $home.ssis = (function () {
  1792. function triggerChanged() {
  1793. var uiRunning = this.uiRunning,
  1794. uiCompleted = this.uiCompleted,
  1795. uiCancelled = this.uiCancelled,
  1796. options = this.options,
  1797. timerHandle = this.timerHandle;
  1798. odatajs.oData.read("/ssisservice/GetStatus(name='" + encodeURIComponent(this.options.name) + "')", function (data) {
  1799. switch (data.Status) {
  1800. case "Completed":
  1801. clearInterval(timerHandle);
  1802. uiRunning.hide();
  1803. uiCompleted.show();
  1804. uiCancelled.hide();
  1805. break;
  1806. case "Running":
  1807. uiRunning.hide();
  1808. uiCompleted.hide();
  1809. uiCancelled.show();
  1810. break;
  1811. }
  1812. options.changed.call(ssis, data);
  1813. });
  1814. }
  1815. // It subscribes the following events
  1816. // 1. start
  1817. // [ { Name: "", Type: "", Value: "" } ]
  1818. // 2. stop
  1819. // It fires the following events
  1820. // 1. changed
  1821. // { Status: "Running | Completed" }
  1822. var ssis = function () {
  1823. this.options = $.extend({
  1824. name: null,
  1825. prefix: null,
  1826. changed: $.noop
  1827. }, (arguments.length === 0 ? {} : arguments[0]));
  1828. this.uiRunning = $("#" + this.options.prefix + "-ssis-running").hide();
  1829. this.uiCompleted = $("#" + this.options.prefix + "-ssis-completed").hide();
  1830. this.uiCancelled = $("#" + this.options.prefix + "-ssis-cancelled").hide();
  1831. // TODO: for long running operation
  1832. // triggerChanged.call(this);
  1833. };
  1834. ssis.prototype.start = function () {
  1835. var uiRunning = this.uiRunning,
  1836. uiCompleted = this.uiCompleted,
  1837. uiCancelled = this.uiCancelled,
  1838. timerHandle = this.timerHandle,
  1839. createTimer = this.createTimer,
  1840. self = this;
  1841. $home.ui.wait(true);
  1842. odatajs.oData.request({
  1843. requestUri: "/ssisservice/Run()",
  1844. method: "POST",
  1845. data: {
  1846. name: this.options.name,
  1847. parameters: arguments[0]
  1848. }
  1849. }, function () {
  1850. $home.ui.wait(false);
  1851. uiRunning.show();
  1852. uiCompleted.hide();
  1853. uiCancelled.hide();
  1854. clearInterval(timerHandle);
  1855. createTimer.call(self);
  1856. triggerChanged.call(self);
  1857. }, function () {
  1858. $home.ui.wait(false);
  1859. alert("运行报表失败。");
  1860. });
  1861. };
  1862. ssis.prototype.stop = function () {
  1863. var uiRunning = this.uiRunning,
  1864. uiCompleted = this.uiCompleted,
  1865. uiCancelled = this.uiCancelled,
  1866. timerHandle = this.timerHandle;
  1867. odatajs.oData.request({
  1868. requestUri: "/ssisservice/Stop()",
  1869. method: "POST",
  1870. data: {
  1871. name: this.options.name
  1872. }
  1873. }, function () {
  1874. uiRunning.hide();
  1875. uiCompleted.hide();
  1876. uiCancelled.show();
  1877. clearInterval(timerHandle);
  1878. }, function () {
  1879. alert("取消报表运行失败。");
  1880. });
  1881. };
  1882. ssis.prototype.createTimer = function () {
  1883. var self = this;
  1884. this.timerHandle = setInterval(function () {
  1885. triggerChanged.call(self);
  1886. }, 10 * 1000 /* 10 seconds */);
  1887. };
  1888. return ssis;
  1889. })();
  1890. // *** pagination ***
  1891. $home.pagination = (function () {
  1892. var pagination = function () {
  1893. this.options = $.extend({
  1894. callback: $.noop,
  1895. max: 50,
  1896. search: null,
  1897. previous: null,
  1898. next: null
  1899. }, arguments[0]);
  1900. this.store = {
  1901. skipped: 0
  1902. };
  1903. var options = this.options,
  1904. store = this.store;
  1905. options.previous.parent().addClass("disabled");
  1906. options.next.parent().addClass("disabled");
  1907. options.search.click(function () {
  1908. store.skipped = 0;
  1909. options.callback(true, store.skipped);
  1910. });
  1911. options.previous.click(function () {
  1912. if (!$(this).parent().hasClass("disabled")) {
  1913. store.skipped -= options.max;
  1914. if (store.skipped < 0) {
  1915. store.skipped = 0;
  1916. }
  1917. options.callback(false, store.skipped);
  1918. }
  1919. });
  1920. options.next.click(function () {
  1921. if (!$(this).parent().hasClass("disabled")) {
  1922. store.skipped += options.max;
  1923. options.callback(false, store.skipped);
  1924. }
  1925. });
  1926. };
  1927. pagination.prototype.option = function () {
  1928. if (arguments.length === 0) {
  1929. return this.options;
  1930. }
  1931. var name = arguments[0].toString();
  1932. if (arguments.length === 1) {
  1933. return this.options[name];
  1934. }
  1935. return this.options[name] = arguments[1];
  1936. };
  1937. pagination.prototype.searched = function (count) {
  1938. if (this.store.skipped === 0) {
  1939. this.options.previous.parent().addClass("disabled");
  1940. } else {
  1941. this.options.previous.parent().removeClass("disabled");
  1942. }
  1943. if (count < this.options.max) {
  1944. this.options.next.parent().addClass("disabled");
  1945. } else {
  1946. this.options.next.parent().removeClass("disabled");
  1947. }
  1948. };
  1949. pagination.prototype.research = function () {
  1950. this.options.callback(false, this.store.skipped);
  1951. }
  1952. return pagination;
  1953. })();
  1954. // *** business ***
  1955. $home.business = (function () {
  1956. return {
  1957. getDisplayText: function (source, value) {
  1958. var result = "";
  1959. $.each(source, function (index, item) {
  1960. if (item.value === value) {
  1961. result = item.text;
  1962. }
  1963. });
  1964. return result;
  1965. }
  1966. };
  1967. })();
  1968. // *** odata ***
  1969. $home.odata = (function () {
  1970. return {
  1971. initialize: function () {
  1972. process("/salesservice/$metadata", $home.odata.metadata.saleService.saleLineItem.properties, ["SaleLineItem"]);
  1973. function process(url, container, types) {
  1974. odatajs.oData.read(url, function (data) {
  1975. handleMetadata(data, container, types);
  1976. }, function () {
  1977. alert("系统初始化数据服务失败。");
  1978. }, odatajs.oData.metadataHandler);
  1979. }
  1980. function handleMetadata(metadata, container, types) {
  1981. var entityTypes = metadata.dataServices.schema[0].entityType;
  1982. for (var i = 0; i < entityTypes.length; i++) {
  1983. var entityType = entityTypes[i];
  1984. for (var j = 0; j < types.length; j++) {
  1985. if (types[j] === entityType.name) {
  1986. for (var k = 0; k < entityType.property.length; k++) {
  1987. container.push(entityType.property[k].name);
  1988. }
  1989. }
  1990. }
  1991. }
  1992. }
  1993. },
  1994. metadata: {
  1995. saleService: {
  1996. saleLineItem: {
  1997. properties: []
  1998. }
  1999. }
  2000. }
  2001. };
  2002. })();
  2003. // *** init ***
  2004. $(function () {
  2005. $home.ui.wait(false);
  2006. $home.authentication.initialize();
  2007. $.ajax({
  2008. type: "GET",
  2009. url: "/businessjson",
  2010. dataType: "json"
  2011. }).done(function (data) {
  2012. $home.business = $.extend($home.business, data);
  2013. });
  2014. $home.odata.initialize();
  2015. $("#home-navigator > li > a").click(function () {
  2016. var item = $(this).parent();
  2017. if (!item.hasClass("disabled")) {
  2018. var index = $("#home-navigator > li").index(item);
  2019. switch (index) {
  2020. case 0: $home.navigation.navigate("dashboard-page"); break;
  2021. case 1: $home.navigation.navigate("sale-management"); break;
  2022. //// TODO: case 2: $home.navigation.navigate("customer-management"); break;
  2023. case 2: $home.navigation.navigate("product-management"); break;
  2024. case 3: $home.navigation.navigate("employee-management"); break;
  2025. //// TODO: case 4: $home.navigation.navigate("control-panel"); break;
  2026. //// TODO: case 5: $home.navigation.navigate("help-page"); break;
  2027. }
  2028. }
  2029. });
  2030. $("#home-logout").click($home.authentication.logout);
  2031. $("#home-change-password").click(function () {
  2032. $home.navigation.modal("change-password");
  2033. })
  2034. });