OutOfMilk.com Shopping List Enhancements

Collection of HTML/CSS enhancements for various bugs and/or shortcomings of the Shopping Lists page (/ShoppingList.aspx)

目前为 2018-08-06 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name OutOfMilk.com Shopping List Enhancements
  3. // @version 0.2.6
  4. // @description Collection of HTML/CSS enhancements for various bugs and/or shortcomings of the Shopping Lists page (/ShoppingList.aspx)
  5. // @namespace https://greasyfork.org/en/users/15562
  6. // @author Jonathan Brochu (https://greasyfork.org/en/users/15562)
  7. // @license GPLv3 or later (http://www.gnu.org/licenses/gpl-3.0.en.html)
  8. // @include http://outofmilk.com/ShoppingList.aspx*
  9. // @include http://www.outofmilk.com/ShoppingList.aspx*
  10. // @include https://outofmilk.com/ShoppingList.aspx*
  11. // @include https://www.outofmilk.com/ShoppingList.aspx*
  12. // @grant GM_addStyle
  13. // ==/UserScript==
  14.  
  15. /***
  16. * History:
  17. *
  18. * 0.2.6 Changes made:
  19. * - Improved declarations of tool methods injectCode(), injectFuncCode()
  20. * and replaceUnsafeFunc() to denote optional arguments supported for
  21. * each. Also, reworked their code a bit.
  22. * - For method replaceUnsafeFunc(), added support for two new optional
  23. * arguments: the first one to specify the parent object whose function
  24. * must be replaced, when it's not in the global scope (i.e. window);
  25. * and the second to specify a delay before which the function
  26. * replacement should be done, i.e. for objects or functions created
  27. * (or exposed) through deferred scripts.
  28. * - For methods injectCode() and injectFuncCode(), added as new optional
  29. * argument the possibility to specify an execution delay, just like
  30. * for replaceUnsafeFunc().
  31. * - Added the possibility to specify a UPC when adding a new item to the
  32. * shopping list. To do so, we add a new UPC field to the "New Item"
  33. * form and then replace that form's handling method with a version
  34. * supporting the new field.
  35. * Unfortunately, for the time being it seems like the web service
  36. * ignores any value used as the UPC (though to begin with the spec was
  37. * already there to show how it should be passed when making the call).
  38. * (2018-08-06)
  39. * 0.2.5 Changes made:
  40. * - Tweaked the UPC parsing code a bit.
  41. * - In the future, this script should be modified to allow users to
  42. * provide their own link templates for looking up products by their
  43. * stored UPC codes.
  44. * (2016-08-09) *not publicly released
  45. * 0.2.4 Change made:
  46. * - Completed the UPC parsing code, including expanding UPC-E barcodes,
  47. * as part of the product links building added in version 0.2.3.
  48. * (2016-06-21) *not publicly released
  49. * 0.2.3 Change made:
  50. * - On the "Edit Product History" dialog, added a column for links to
  51. * the corresponding product on a grocery store website (IGA.net).
  52. * (2016-06-02) *not publicly released
  53. * 0.2.2 Change made:
  54. * - For the fix around the "Tax Free" checkbox of the "Edit Product
  55. * History" dialog, a jQuery function call was failing so we're now
  56. * using its DOM native equivalent.
  57. * (2016-05-06)
  58. * 0.2.1 Changes made:
  59. * - Fixed the always-unchecked "Tax Free" checkbox for the dialog
  60. * "Edit Product History".
  61. * - Updated element id for the "Description" field of the dialog
  62. * "Edit Product History".
  63. * (2016-01-24)
  64. * 0.2.0 Changes made:
  65. * - Updated the "producthistory-template" template to match column
  66. * names recently added by outofmilk.com, while at the same time
  67. * disabling the CSS code previously used to display custom column
  68. * headers.
  69. * - Updated the "producthistory-template" template so that, like the
  70. * original one, "Yes" & "No" are used as values for the "Tax Free?"
  71. * column instead of "true" & "false".
  72. * - Fixed the non-working "Tax Free" checkbox and empty "How Much?"
  73. * dropdown list for dialog "shoppingeditpopup".
  74. * - Fixed the URL used for the "icon-taxfree.png" image whenever
  75. * adding or editing an item that is tax free.
  76. * (2015-09-17)
  77. * 0.1.7 Changes made:
  78. * - Updated script for use with the repository [greasyfork.org].
  79. * - No change made to the code.
  80. * (2015-09-14)
  81. * 0.1.6 Changes made:
  82. * - Kept being annoyed that everytime I added/changed a UPC from the
  83. * product history it wouldn't update, so now I re-implement method
  84. * saveProductHistory() (from "ProductManagement.js?v=...") with the
  85. * added tweaks (after all, I'm the one adding the column). Also,
  86. * updated the producthistory template with a new class for that
  87. * column.
  88. * NOTE: I'll have to watch out for any updates/changes to the site
  89. * as I replace the whole function, since obviously I cannot
  90. * just patch the existing code. Oh, wait...
  91. * NODO: I know they say "eval() is evil()", but what if I'd say the
  92. * words "toString()", "String.replace()" and "eval()" in that
  93. * particular order... OK, I'll leave that hanging in the air.
  94. * - Took the opportunity to fix the call that sets the initial width
  95. * of the "Product History Management" dialog, which was failing with
  96. * errors of the sort "Permission denied to access property".
  97. * (2015-06-30)
  98. * 0.1.5 Change made:
  99. * - Added outofmilk.com as a possible domain for include URLs.
  100. * (2015-04-02)
  101. * 0.1.4 Changes made:
  102. * - Changed how the initial width of the "Product History Management"
  103. * dialog is set.
  104. * - Implemented changes to add a "UPC" column to the product history
  105. * table (by changing its jQuery UI dialog template; this is possible
  106. * since the web service's "GetAllProductHistoryItems" method already
  107. * returns the stored UPC value for each history item).
  108. * - Removed keep-alive code since no longer necessary.
  109. * (2013-08-19)
  110. * 0.1.3 Changes made:
  111. * - Removed "!important" when setting the (initial) width property of
  112. * the "Product History Management" dialog (since the specified width
  113. * isn't meant to be permanent).
  114. * (2013-04-05)
  115. * 0.1.2 Changes made:
  116. * - Added javascript code to keep the session alive (without the
  117. * need to refresh the page).
  118. * (2013-04-04)
  119. * 0.1.1 Changes made:
  120. * - Added column names for dialog "Product History Management".
  121. * - Changed text alignment for (newly-named) column "Tax Exempt".
  122. * (2013-04-04)
  123. * 0.1.0 First implementation. (2013-04-02)
  124. *
  125. */
  126.  
  127. (function() {
  128. // constants
  129. var USERSCRIPT_NAME = 'OutOfMilk.com Shopping List Enhancements';
  130.  
  131. /*
  132. * The Payload
  133. */
  134.  
  135. // css definitions
  136. var css_fixes =
  137. '@namespace url(http://www.w3.org/1999/xhtml);\n' +
  138. // Changes & Overrides
  139. // background overlays for modal dialog with fixed postion
  140. '.ui-widget-overlay { position: fixed /* original: absolute */ !important ; }\n' +
  141. // "Product History Management" dialog - increase initial width
  142. // '-> now done through javascript
  143. // //'div[aria-describedby="manageproducthistoryform"] { width: 80% /* original: 600px */ ; }\n' +
  144. // "Product History Management" dialog - take full parent's width for table within dialog
  145. 'table.producthistory-table { width: 100% /* original: 550px */ !important ; }\n' +
  146. // "Product History Management" dialog - column headers
  147. // 2015-09-17: Column headers not needed anymore (done through the template itself)
  148. ///'table#producthistorytable.table-default > tr:nth-child(1) > th:nth-child(1) > strong:before { ' +
  149. /// 'content: "Item" /* original: (none specified) */ !important ; }\n' +
  150. ///'table#producthistorytable.table-default > tr:nth-child(1) > th:nth-child(3) > strong:before { ' +
  151. /// 'content: "Tax Exempt" /* original: (none specified) */ !important ; }\n' +
  152. ///'table#producthistorytable.table-default > tr:nth-child(1) > th:nth-child(4) > strong:before { ' +
  153. /// 'content: "Category" /* original: (none specified) */ !important ; }\n' +
  154. ///'table#producthistorytable.table-default > tr:nth-child(1) > th:nth-child(5) > strong:before { ' +
  155. /// 'content: "UPC" /* original: (none specified) */ !important ; }\n' +
  156. 'table#producthistorytable.table-default > tr:nth-child(1) > th:nth-child(6):before { ' +
  157. /// 'content: "Actions" /* original: (none specified) */ !important ; ' +
  158. 'text-align: center /* original: left (through inheritance) */ !important ; ' +
  159. '}\n' +
  160. 'table#producthistorytable.table-default > tr:nth-child(1) > th:nth-child(5) { ' +
  161. 'text-align: center /* original: left (through inheritance) */ !important ; ' +
  162. '}\n' +
  163. // "Product History Management" dialog - values for column "Tax Exempt" centered horizontally
  164. 'td.producthistorytaxfree { text-align: center /* original: left (through inheritance) */ !important ; }\n' +
  165. // "Edit Product History" dialog - wider "Description" field
  166. '#txtEditProductHistoryDescription { ' +
  167. 'width: 380px /* original: (none specified) */ !important ; }\n' +
  168. // <END>
  169. '';
  170.  
  171. // new "producthistory-template" template
  172. var templateProductHistory = function() {
  173. /**HEREDOC
  174. <script type="producthistory-template">
  175. <##
  176. if (!String.prototype.reverse) {
  177. String.prototype.reverse = function() {
  178. return this.split('').reverse().join('');
  179. };
  180. }
  181. var eanCheckDigit = function(s) {
  182. var result = 0;
  183. var rs = s.reverse();
  184. for (counter = 0; counter < rs.length; counter++) {
  185. result = result + parseInt(rs.charAt(counter)) * Math.pow(3, ((counter+1) % 2));
  186. }
  187. return (10 - (result % 10)) % 10;
  188. };
  189. ##>
  190. <# if(this.dataobjects.length > 0) { #>
  191. <tr>
  192. <th><strong>Description</strong></th>
  193. <th><strong>Price</strong></th>
  194. <th><strong>Tax Free?</strong></th>
  195. <th><strong>Category</strong></th>
  196. <th><strong>UPC</strong></th>
  197. <th><strong>Links</strong></th>
  198. <th colspan="3">Actions</th>
  199. </tr>
  200. <# $.each(this.dataobjects, function(i, object) { #>
  201. <tr>
  202. <td class="producthistoryid hidden"><#= object.ID #></td>
  203. <td>
  204. <span class="producthistorydescription"><#= trimDescription(object.Description,60,"<acronym title=\"" + object.Description + "\">...</acronym>") #></span>
  205. </td>
  206. <td class="producthistoryprice">
  207. <span><#= FormatNumberCurrency(object.Price) #></span>
  208. </td>
  209. <td class="producthistorytaxfree">
  210. <span>
  211. <# if (object.TaxFree) { #>
  212. Yes
  213. <# } else { #>
  214. No
  215. <# } #>
  216. </span>
  217. </td>
  218. <td class="producthistorycategory">
  219. <span><#= object.CategoryName #></span>
  220. </td>
  221. <td class="producthistoryupc">
  222. <span><#= object.UPC #></span>
  223. <##
  224. object.UPC = String(object.UPC);
  225. if (object.UPC.length >= 12) {
  226. object.UPC12 = object.UPC.substr(-12,12);
  227. if (object.UPC12.substr(0,2) === '00') {
  228. object.UPC12 = object.UPC12.substr(1,11);
  229. object.UPC12 += eanCheckDigit(object.UPC12);
  230. }
  231. } else if (object.UPC.length === 6 && object.UPC.substr(0,1) === "F") {
  232. object.UPC12 = '000000' + object.UPC.substr(1,5);
  233. object.UPC12 += eanCheckDigit(object.UPC12);
  234. } else if (object.UPC.length === 8) {
  235. object.UPC12 = object.UPC.charAt(0);
  236. switch (object.UPC.charAt(6)) {
  237. case '0':
  238. case '1':
  239. case '2':
  240. object.UPC12 += object.UPC.substr(1, 2) + object.UPC.substr(6, 1) + '0000' + object.UPC.substr(3, 3) + object.UPC.substr(7, 1);
  241. break;
  242. case '3':
  243. object.UPC12 += object.UPC.substr(1, 3) + '00000' + object.UPC.substr(4, 2) + object.UPC.substr(7, 1);
  244. break;
  245. case '4':
  246. object.UPC12 += object.UPC.substr(1, 4) + '00000' + object.UPC.substr(5, 1) + object.UPC.substr(7, 1);
  247. break;
  248. case '5':
  249. case '6':
  250. case '7':
  251. case '8':
  252. case '9':
  253. object.UPC12 += object.UPC.substr(1, 5) + '0000' + object.UPC.substr(6, 1) + object.UPC.substr(7, 1);
  254. break;
  255. default: object.UPC12 = '';
  256. }
  257. } else {
  258. object.UPC12 = '';
  259. }
  260. ##>
  261. </td>
  262. <td class="producthistorylink">
  263. <span><# if (object.UPC12.length > 0) { #>
  264. <a target="_blank" href="https://www.iga.net/en/search?k=00<#= object.UPC12.substr(0, 11) #>"><strong>IGA</strong></a>
  265. <# } else { #>
  266. &nbsp;
  267. <# } #></span>
  268. </td>
  269. <td>
  270. <a href="javascript:void(0);" class="btn-default addproducthistory"><span>Add To List</span></a>
  271. </td>
  272. <td>
  273. <a href="javascript:void(0);" class="btn-default editproducthistory"><span>Edit</span></a>
  274. </td>
  275. <td class="last-column">
  276. <a href="javascript:void(0);" class="btn-default deleteproducthistory"><span>Delete</span></a>
  277. </td>
  278. </tr>
  279. <# }); #>
  280. <# } else { #>
  281. <tr>
  282. <td colspan="5">There are no items to display</td>
  283. </tr>
  284. <# } #>
  285. </script>
  286. HEREDOC**/
  287. };
  288.  
  289. // new implementation of saveProductHistory()
  290. var mySaveProductHistory = function($this) {
  291. if(validateProductHistoryForm()){
  292. var ID = $(".editproducthistoryid").html();
  293. var description = $(".editproducthistorydescription").val();
  294. var price = $(".editproducthistoryprice").val();
  295. var taxfree = $(".editproducthistorytaxfree input").is(":checked");
  296. var upc = $(".editproducthistoryupc").val();
  297.  
  298. var Params = { "ID": ID, "description":description, "price": price, "upc":upc, "taxfree": taxfree };
  299. var jQueryParams = JSON.stringify(Params);
  300.  
  301. $.ajax({
  302. type: "POST",
  303. url: "Services/GenericService.asmx/UpdateProductHistoryItem",
  304. data: jQueryParams,
  305. contentType: "application/json; charset=utf-8",
  306. dataType: "json",
  307. success: function (msg) {
  308. if(msg.d === false){
  309. $(".producthistoryitemvalidation").html("An item already exists with this description and price!");
  310. } else {
  311. var $element = $(".producthistoryid:contains("+ID+")").parents("tr");
  312. $element.find(".producthistorydescription").html(description);
  313. $element.find(".producthistoryprice").html(FormatNumberCurrency(price));
  314. /* added --> */ $element.find(".producthistoryupc").html(upc);
  315. if(taxfree) {
  316. $element.find(".producthistorytaxfree").html("Yes");
  317. } else {
  318. $element.find(".producthistorytaxfree").html("No");
  319. }
  320.  
  321. $this.dialog("close");
  322. }
  323. },
  324. failure: function (msg) {
  325. }
  326. });
  327. }
  328. };
  329. // of course, I could also do something like:
  330. /*
  331. eval('var mySaveProductHistory = ' +
  332. unsafeWindow.saveProductHistory.toString().replace(/(html\(FormatNumberCurrency\(price\)\);)/, '$1\n$$element.find(".producthistoryupc").html(upc);')
  333. );
  334. */
  335. // but, would blindly patching code be actually better than
  336. // replacing a whole function? Yeah, I thought so.
  337.  
  338. // 2018-08-06: new implementation of ShoppingEngine.addShoppingItem() to add a UPC field
  339. // NOTE: Not my code; I only added not even half a line
  340. var myAddShoppingItem = function() {
  341. if (ShoppingEngine.validateShoppingItemForm($(".shoppinglistitem"), false) != false) {
  342. var $element = $(".shoppinglistitem");
  343.  
  344. var description = $element.find(".itemdescription").val();
  345. var quantity = $element.find(".itemquantity").val();
  346. var unit = $element.find(".itemunit").val();
  347. var unittext = $element.find(".itemunit option:selected").text();
  348. var price = $element.find(".itemprice").val();
  349. var note = $element.find(".itemnote").val();
  350. var taxfree = $element.find(".taxfree input").is(":checked");
  351. var category = $element.find(".itemcategory").val();
  352. // 2018-08-06: Added a UPC field
  353. var UPC = $element.find(".itemupc").val() || '';
  354.  
  355. if (usedAutoComplete == undefined) { usedAutoComplete = false; }
  356.  
  357. var Params = { "ID": ListID, "usedAutoComplete": usedAutoComplete, "description": description, "quantity": quantity, "unit": unit, "price": price, "note": note, "taxfree": taxfree, "upc": UPC, "category": category, "promoproviderpromotionid": "", "promoproviderstaticid": 0, "useMinOrdinal": false, "isEmailPromo": false };
  358. var jQueryParams = JSON.stringify(Params);
  359.  
  360. $.growlUI(gettext('Please Wait...'), gettext('Adding your item to the list!'));
  361.  
  362. $.ajax({
  363. type: "POST",
  364. url: "Services/GenericService.asmx/AddShoppingItem",
  365. data: jQueryParams,
  366. contentType: "application/json; charset=utf-8",
  367. dataType: "json",
  368. success: function (msg) {
  369. var Data = JSON.parse(msg.d);
  370.  
  371. var $template = $(".itemtemplate").clone();
  372.  
  373. var flagsText = "";
  374. if (taxfree || note.length > 0) {
  375. flagsText = "<div class='additionalitems clearfix'>";
  376. if (taxfree) {
  377. flagsText = flagsText + "&nbsp; <acronym title='" + globalRes.TaxFree + "'><img src='"+ STATIC_URL +"images/icon-taxfree.png' /></acronym>";
  378. }
  379. if (note.length > 0) {
  380. flagsText = flagsText + "&nbsp; <acronym title=\"" + note.replace(/\"/g, '\'') + "\"><img src='"+ STATIC_URL +"images/icon-note.png' /></acronym>";
  381. }
  382. flagsText = flagsText + "</div>";
  383. }
  384.  
  385. $template.find(".cell-title").html(flagsText).text(description);
  386. $template.find(".cell-qty").html(FormatNumber(quantity) + " " + unittext);
  387. $template.find(".cell-price").html(FormatNumberCurrency(Data.Price));
  388. $template.find(".productid").html(Data.ID);
  389. $template.find(".itemguid").html(Data.GUID);
  390. $template.find(".createddate").html(Data.Created);
  391. $template.removeClass("hidden");
  392. $template.removeClass("itemtemplate");
  393. $template.attr("id", "item_" + Data.ID);
  394.  
  395. //Find all categories on the list and then insert before if we have a category, and insert after the beginning if we don't.
  396.  
  397. //if we have a category but it's not actually on the list, that means it was a newly created category list from the add item
  398. //so we will check for that and do a full list refresh if that's the case
  399. var foundCategory = false;
  400. if (Data.Category) {
  401. $(".category").each(function () {
  402. var catID = $(this).attr("id").split("cat_")[1];
  403. if (Data.Category == catID) {
  404. $template.insertAfter($(this));
  405. foundCategory = true;
  406. }
  407. })
  408. } else {
  409. //if there was no category set this to true so that we dont have a full refresh
  410. foundCategory = true;
  411. $template.insertAfter("#table_totals");
  412. }
  413.  
  414. $("#sortable tbody").sortable('refresh', { items: 'tr:not(.tabletop):not(.itemtemplate)' });
  415. ListEngine.bindListItemsEdit();
  416. ShoppingEngine.updateShoppingListPrice();
  417. ListEngine.bindContextMenus();
  418.  
  419. sortLists(true);
  420.  
  421. usedAutoComplete = false;
  422.  
  423. if (!foundCategory) {
  424. $("#btn-refresh-list").click();
  425. }
  426.  
  427. //Bind the click event for toggling an items status
  428. ListEngine.toggleItemStatus();
  429. },
  430. error: function (msg) {
  431. Apprise(gettext("Failed to insert item. Please try again.") + "<br /><br />" + gettext("If this problem persists, please contact us at") + " <a href='https://outofmilk.zendesk.com/hc/en-us/requests/new'>Support Request</a>", { 'confirm': true });
  432. }
  433. });
  434.  
  435. return true;
  436. } else {
  437. return false;
  438. }
  439. };
  440.  
  441. // 2015-09-17: fix for the "Tax Free" checkbox not working in the "shoppingeditpopup" dialog
  442. var shoppingeditpopup_fix1 = function() {
  443. // find the "Tax Free" checkbox and its <div> container
  444. var $element = $(".shoppingeditpopup"),
  445. taxfree = $element.find("input#checkbox1"),
  446. taxfreeParentDiv = taxfree.parent();
  447. // add the missing "taxfree" class, such that in method
  448. // ShoppingEngine.updateShoppingItem() the line:
  449. // ---
  450. // var taxfree = $element.find(".taxfree input").is(":checked");
  451. // ---
  452. // works properly
  453. taxfreeParentDiv.addClass('taxfree');
  454. };
  455. // 2015-09-17: fix for the empty <select> element in the "shoppingeditpopup" dialog
  456. var shoppingeditpopup_fix2 = function() {
  457. // find the "How Much?" <select> element for units (removing any children in the process)
  458. var $element = $(".shoppingeditpopup"),
  459. editUnits = $element.find("select#drpUnitsEdit").find("option").remove().end(),
  460. itemUnitOptions = $(".shoppinglistitem").find("select.itemunit").find("option");
  461. // copy the options for the "shoppinglistitem" dialog
  462. $.each(itemUnitOptions, function() {
  463. editUnits.append($("<option />").val($(this).val()).text($(this).text()));
  464. });
  465. };
  466. // 2015-09-17: methods ShoppingEngine.addShoppingItem() & ShoppingEngine.updateShoppingItem()
  467. // don't use proper links for "icon-taxfree.png"; fix that
  468. var iconTaxFreeURLs_fix = function() {
  469. // patch using .toString() & eval()
  470. ///$.each(['addShoppingItem', 'updateShoppingItem'], function() {
  471. // 2018-08-06: Since we're now using our own implementation of ShoppingEngine.addShoppingItem(),
  472. // we took care to correct that bug too
  473. $.each(['updateShoppingItem'], function() {
  474. eval("ShoppingEngine." + this + " = " + ShoppingEngine[this].toString().replace("src='Images/icon-taxfree.png", "src='\"+ STATIC_URL +\"images/icon-taxfree.png'"));
  475. });
  476. };
  477. // 2016-01-24: fix for the missing "producthistorytaxfree" class in the "editproducthistoryform" dialog
  478. var editproducthistory_fix1 = function() {
  479. // find the "Tax Free" <input type="checkbox"> element and its <td> parent
  480. var taxfree = $("#txtEditProductHistorytaxfree"),
  481. taxfreeParentTD = taxfree.parent();
  482. // add the missing "producthistorytaxfree" class, so that the lines
  483. // $(".editproducthistorytaxfree input").attr("checked", true);
  484. // $(".editproducthistorytaxfree input").attr("checked", false);
  485. // work as intended
  486. taxfreeParentTD.addClass('editproducthistorytaxfree');
  487. };
  488. // 2016-01-24: fix for the "Tax Free" checkbox being always unchecked in the "editproducthistoryform" dialog
  489. var editproducthistory_fix2 = function() {
  490. $(".manageproducts").on("click", function() {
  491. $(".editproducthistory").off();
  492. $(".editproducthistory").on("click", function() {
  493. var $parent = $(this).parents("tr");
  494. var ID = $parent.find(".producthistoryid").html();
  495. var description = $parent.find(".producthistorydescription").html();
  496. var price = $parent.find(".producthistoryprice").html();
  497. var Params = { "ID": ID };
  498. var jQueryParams = JSON.stringify(Params);
  499. $.growlUI('<img src="' + STATIC_URL + 'images/monster-help.png" />Please Wait...', 'Loading Product History item...');
  500. $.ajax({
  501. type: "POST",
  502. url: "Services/GenericService.asmx/GetProductHistoryItem",
  503. data: jQueryParams,
  504. contentType: "application/json; charset=utf-8",
  505. dataType: "json",
  506. success: function (msg) {
  507. $(".editproducthistorydescription").val(msg.d.Description);
  508. $(".editproducthistoryprice").val(FormatNumber(msg.d.Price));
  509. $(".editproducthistoryid").html(msg.d.ID);
  510. $(".editproducthistoryupc").val(msg.d.UPC);
  511. $(".editproducthistorytaxfree input").removeAttribute("checked");
  512. if (msg.d.TaxFree) {
  513. $(".editproducthistorytaxfree input").checked = true;
  514. } else {
  515. $(".editproducthistorytaxfree input").checked = false;
  516. }
  517. $("#editproducthistoryform").find('input').keypress(function (e) {
  518. if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
  519. $(".ui-dialog[aria-labelledby='ui-dialog-title-editproducthistoryform']").find('.ui-dialog-buttonpane').find('button:first').click();
  520. return false;
  521. }
  522. });
  523. $("#editproducthistoryform").dialog("open");
  524. },
  525. failure: function (msg) {
  526. }
  527. });
  528. });
  529. });
  530. };
  531. // 2018-08-06: fix for adding a UPC field to the "New Item" form
  532. var listadditemform_fix = function() {
  533. // get form
  534. var $element = jQuery('.shoppinglistitem').first();
  535. // make sure we don't already have the UPC field present
  536. if ($element.length > 0 && $element.find('.itemupc').length == 0) {
  537. var itemPriceElem = $element.find('.itemprice').first();
  538. if (!itemPriceElem) { return; }
  539. itemPriceElem.parent().after('<strong><span>UPC (if any)</span><input type="text" value="" class="textbox itemupc"></strong>');
  540. }
  541. };
  542.  
  543. /*
  544. * The Tools
  545. */
  546.  
  547. // heredoc parser
  548. var getHeredoc = function(container, identifier) {
  549. // **WARNING**: Inputs not filtered (e.g. types, illegal chars within regex, etc.)
  550. var re = new RegExp("/\\*\\*" + identifier + "[\\n\\r]+[\\s\\S]*?[\\n\\r]+" + identifier + "\\*\\*/", "m");
  551. var str = container.toString();
  552. str = re.exec(str).toString();
  553. str = str.replace(new RegExp("/\\*\\*" + identifier + "[\\n\\r]+",'m'),'').toString();
  554. return str.replace(new RegExp("[\\n\\r]+" +identifier + "\\*\\*/",'m'),'').toString();
  555. };
  556.  
  557. // template substitution
  558. var replaceDialogTemplate = function(templateName, newContent) {
  559. var scripts = document.getElementsByTagName('script');
  560. if (scripts.length > 0) {
  561. for (var i = 0; i < scripts.length; i++) {
  562. if (scripts[i].getAttribute('type') == templateName) {
  563. var newText = newContent.toString();
  564. // remove comments
  565. newText = newText.replace(/\/\*(?:\r\n|\r|\n|.)+?\*\//gm, '').replace(/\/\/.+$/g, '');
  566. // remove empty lines
  567. newText = newText.replace(/$\s*\r\n/g, '');
  568. // make sure switch() blocks have their first case statement on the same line
  569. newText = newText.replace(/switch\s*\([^\{]+\)(\s*)\{(\s*)case/gm, function(match, p1, p2) {
  570. return match.replace(p1, ' ').replace(p2, ' ');
  571. });
  572. // process custom <## [..] ##> blocks
  573. newText = newText.replace(/\<##\s*((?:\r\n|\r|\n|.)+?)\s*##\>/gm, function(match, p) {
  574. return p.split(/\r\n|\r|\n/g).map(function(item, idx) {
  575. return item.replace(/^(\s*)(.*)/g, function(match, p1, p2) {
  576. return p1 + '<# ' + p2.trim() + ' #>';
  577. });
  578. }).join("\r\n");
  579. });
  580. // replace template content
  581. newText = newText.replace(/^[\r\n\s]*<script[^>]*>|<\/script>[\r\n\s]*$/g, '');
  582. scripts[i].innerHTML = newText;
  583. return;
  584. }
  585. }
  586. }
  587. };
  588.  
  589. // code injection
  590. var injectCode = function(code /* , idUniq = '', execDelay = 0 */){
  591. var idUniq = '',
  592. execDelay = 0,
  593. tmpScript = document.createElement('script');
  594. tmpScript.id = '__iC_script-'+Math.random().toString().slice(2);
  595. // argument #3 (optional): <script> element ID suffix
  596. if (arguments.length > 1) {
  597. idUniq = '_' + /[$_a-zA-Z][$_a-zA-Z0-9]*/.exec(arguments[1])[0] || '';
  598. }
  599. tmpScript.id = tmpScript.id + idUniq;
  600. // argument #3 (optional): execution delay
  601. if (arguments.length > 2) {
  602. execDelay = (arguments[2] === 'domready' ? arguments[2] : (parseInt(arguments[2]) || 0));
  603. }
  604. tmpScript.type = 'text/javascript';
  605. tmpScript.textContent = (function() {
  606. return [
  607. ';'+(
  608. execDelay === 'domready' ? '$(document).ready(' :
  609. (0+execDelay > 0 ? 'window.setTimeout(' : '(')
  610. )+(function () {
  611. /*code*/
  612. var thisScript = document.getElementById('/*scriptId*/');
  613. if (thisScript) { thisScript.parentNode.removeChild(thisScript); } // <-- oh no, you didn't!!
  614. }).toString()+(
  615. execDelay === 'domready' ? ')' :
  616. (0+execDelay > 0 ? ', '+execDelay+')' : ')()')
  617. )+';',
  618. { k: 'code', v: (typeof(code) == 'string' && code.trim().length > 0 ? code : '/*failed*/') },
  619. { k: 'scriptId', v: tmpScript.id }
  620. ].reduce(function(base, mapping){
  621. return base.replace('/*'+mapping.k+'*/', mapping.v);
  622. });
  623. })();
  624. document.head.appendChild(tmpScript);
  625. };
  626. var injectFuncCode = function(func /* , idUniq = '', execDelay = 0 */){
  627. if (typeof(func) !== 'function') return;
  628. var idUniq = (arguments.length > 1 ? arguments[1] : ''),
  629. execDelay = (arguments.length > 2 ? (arguments[2] === 'domready' ? arguments[2] : (parseInt(arguments[2]) || 0)) : 0),
  630. wrapper = '('+func.toString()+')();';
  631. injectCode(wrapper, idUniq, execDelay);
  632. };
  633.  
  634. // code injection, specialized
  635. var replaceUnsafeFunc = function(targetName, newFuncImpl /* , idUniq = '', thisScope = 'window', execDelay = 0 */){
  636. // inspiration: https://greasyfork.org/en/scripts/2599-gm-2-port-function-override-helper/code
  637. var idUniq = '',
  638. thisScope = 'window',
  639. execDelay = 0,
  640. tmpScript = document.createElement('script');
  641. tmpScript.id = '__rUF_script-'+Math.random().toString().slice(2);
  642. // argument #3 (optional): <script> element ID suffix
  643. if (arguments.length > 2) {
  644. idUniq = '_' + /[$_a-zA-Z][$_a-zA-Z0-9]*/.exec(arguments[2])[0] || '';
  645. }
  646. tmpScript.id = tmpScript.id + idUniq;
  647. // argument #4 (optional): scope of function to replace; by default, window (global)
  648. if (arguments.length > 3) {
  649. thisScope = ''+arguments[3].replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '') || 'window';
  650. }
  651. // argument #5 (optional): execution delay
  652. if (arguments.length > 4) {
  653. execDelay = (arguments[4] === 'domready' ? arguments[4] : (parseInt(arguments[4]) || 0));
  654. }
  655. tmpScript.type = 'text/javascript';
  656. tmpScript.textContent = (function() {
  657. return [
  658. ';'+(
  659. execDelay === 'domready' ? '$(document).ready(' :
  660. (0+execDelay > 0 ? 'window.setTimeout(' : '(')
  661. )+(function () {
  662. try {
  663. window/*scope*/ /*target*/ = /*newFunc*/window;
  664. } catch(_err) {
  665. console.log('Error in replaceUnsafeFunc() payload with id "/*scriptId*/": ' + _err.message);
  666. }
  667. var thisScript = document.getElementById('/*scriptId*/');
  668. if (thisScript) { thisScript.parentNode.removeChild(thisScript); } // <-- oh no, you didn't!!
  669. }).toString()+(
  670. execDelay === 'domready' ? ')' :
  671. (0+execDelay > 0 ? ', '+execDelay+')' : ')()')
  672. )+';',
  673. { k: 'scope', v: '.'+thisScope },
  674. { k: 'target', v: '.'+(typeof(targetName) == 'string' && targetName.trim().length > 0 ? targetName : '_void') },
  675. { k: 'newFunc', v: (typeof(newFuncImpl) == 'function' ? newFuncImpl : function(){}).toString()+';//' },
  676. { k: 'scriptId', v: tmpScript.id }
  677. ].reduce(function(base, mapping){
  678. // 2018-08-06: replaced [String].replace() with [String].split().join()
  679. ///return base.replace('/*'+mapping.k+'*/', mapping.v);
  680. return base.split('/*'+mapping.k+'*/').join(''+mapping.v);
  681. });
  682. })();
  683. document.head.appendChild(tmpScript);
  684. };
  685.  
  686. // reference some outside objects
  687. window.console = window.console || (function() {
  688. if (typeof(unsafeWindow) == 'undefined') return { 'log': function() {} };
  689. return unsafeWindow.console;
  690. })();
  691.  
  692. // self-explanatory
  693. document.addStyle = function(css) {
  694. if (typeof(GM_addStyle) != 'undefined') {
  695. GM_addStyle(css);
  696. } else {
  697. var heads = this.getElementsByTagName('head');
  698. if (heads.length > 0) {
  699. var node = this.createElement('style');
  700. node.type = 'text/css';
  701. node.appendChild(this.createTextNode(css));
  702. heads[0].appendChild(node);
  703. }
  704. }
  705. };
  706.  
  707. /*
  708. * The Action
  709. */
  710.  
  711. // css injection
  712. document.addStyle(css_fixes);
  713.  
  714. // javascript patching
  715. try {
  716. // replace template "producthistory-template"
  717. replaceDialogTemplate('producthistory-template', getHeredoc(templateProductHistory, 'HEREDOC'));
  718.  
  719. // replace saveProductHistory()
  720. replaceUnsafeFunc('saveProductHistory', mySaveProductHistory, 'mySaveProductHistory');
  721.  
  722. // 2018-08-06: replace ShoppingEngine.addShoppingItem()
  723. replaceUnsafeFunc('addShoppingItem', myAddShoppingItem, 'myAddShoppingItem', 'ShoppingEngine', 'domready');
  724. // 2018-08-06: add the UPC text field to the "New Item" form
  725. injectFuncCode(listadditemform_fix, 'listadditemform_fix');
  726.  
  727. // set initial width of "Product History Management" dialog
  728. ///replaceUnsafeFunc('onload', function(){ $("#manageproducthistoryform").dialog("option", "width", "80%"); }, 'onload');
  729. // 2018-08-06: now making use of new features added to injectCode() and injectFuncCode()
  730. injectFuncCode(function(){ $("#manageproducthistoryform").dialog("option", "width", "80%"); }, 'manageproducthistoryform_fix', 'domready');
  731.  
  732. // 2015-09-17: fixes for the "shoppingeditpopup" dialog
  733. injectFuncCode(shoppingeditpopup_fix1, 'shoppingeditpopup_fix1');
  734. injectFuncCode(shoppingeditpopup_fix2, 'shoppingeditpopup_fix2');
  735.  
  736. // 2016-01-24: fixes for the "editproducthistoryform" dialog
  737. injectFuncCode(editproducthistory_fix1, 'editproducthistory_fix1');
  738. injectFuncCode(editproducthistory_fix2, 'editproducthistory_fix2');
  739.  
  740. // 2015-09-17: fixes for "icon-taxfree.png" URLs
  741. injectFuncCode(iconTaxFreeURLs_fix, 'iconTaxFreeURLs_fix');
  742. } catch(err) {
  743. console.log(err);
  744. }
  745.  
  746. /*
  747. * The End
  748. */
  749.  
  750. console.log('User script "' + USERSCRIPT_NAME + '" has completed.');
  751. })();