2
0

011-api.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. $(document).ready(function() {
  2. mass_action = false;
  3. function validateEmail(email) {
  4. var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  5. return re.test(email);
  6. }
  7. function validateRegex(e){var t=e.split("/"),n=e,r="";t.length>1&&(n=t[1],r=t[2]);try{return new RegExp(n,r),!0}catch(e){return!1}}
  8. function is_active(elem) {
  9. if ($(elem).data('submitted') == '1') {
  10. return true;
  11. } else {
  12. var parent_btn_grp = $(elem).parentsUntil(".btn-group").parent();
  13. if (parent_btn_grp.hasClass('btn-group')) {
  14. parent_btn_grp.replaceWith('<button class="btn btn-secondary btn-sm" disabled>' + lang_footer.loading + '</a>');
  15. }
  16. $(elem).text(lang_footer.loading);
  17. $(elem).attr('data-submitted', '1');
  18. function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };
  19. $(document).on("keydown", disableF5);
  20. return false;
  21. }
  22. }
  23. $.fn.serializeObject = function() {
  24. var o = {};
  25. var a = this.serializeArray();
  26. $.each(a, function() {
  27. if (o[this.name]) {
  28. if (!o[this.name].push) {
  29. o[this.name] = [o[this.name]];
  30. }
  31. o[this.name].push(this.value || '');
  32. } else {
  33. o[this.name] = this.value || '';
  34. }
  35. });
  36. return o;
  37. };
  38. // Collect values of input fields with name "multi_select" and same data-id to js array multi_data[data-id]
  39. var multi_data = [];
  40. $(document).on('change', 'input[name=multi_select]:checkbox', function(e) {
  41. if(mass_action === true) {
  42. multi_data = [];
  43. mass_action = false;
  44. }
  45. if ($(this).is(':checked') && $(this).data('id')) {
  46. var id = $(this).data('id');
  47. if (typeof multi_data[id] == "undefined") {
  48. multi_data[id] = [];
  49. }
  50. multi_data[id].push($(this).val());
  51. }
  52. else {
  53. var id = $(this).data('id');
  54. if (typeof multi_data[id] !== "undefined") {
  55. multi_data[id].splice($.inArray($(this).val(), multi_data[id]),1);
  56. }
  57. }
  58. });
  59. // Select checkbox by click on parent tr
  60. $(document).on('click', 'tbody>tr', function(e) {
  61. if(e.target.tagName.toLowerCase() === 'button') {
  62. e.stopPropagation();
  63. }
  64. else if(e.target.tagName.toLowerCase() === 'a') {
  65. e.stopPropagation();
  66. }
  67. else if (e.target.type == "checkbox") {
  68. e.stopPropagation();
  69. }
  70. else {
  71. var checkbox = $(this).find(':checkbox');
  72. checkbox.trigger('click');
  73. }
  74. });
  75. // Select or deselect all checkboxes with same data-id
  76. $(document).on('click', '#toggle_multi_select_all', function(e) {
  77. mass_action = true
  78. e.preventDefault();
  79. id = $(this).data("id");
  80. var all_checkboxes = $("input[data-id=" + id + "]:enabled");
  81. all_checkboxes.prop("checked", !all_checkboxes.prop("checked")).change();
  82. });
  83. // General API edit actions
  84. $(document).on('click', "[data-action='edit_selected']", function(e) {
  85. e.preventDefault();
  86. var id = $(this).data('id');
  87. var api_url = $(this).data('api-url');
  88. var api_attr = $(this).data('api-attr');
  89. if (typeof $(this).data('api-reload-window') !== 'undefined') {
  90. api_reload_window = $(this).data('api-reload-window');
  91. } else {
  92. api_reload_window = true;
  93. }
  94. if (typeof $(this).data('api-reload-location') !== 'undefined') {
  95. api_reload_location = $(this).data('api-reload-location');
  96. } else {
  97. api_reload_location = '#';
  98. }
  99. // If clicked element #edit_selected is in a form with the same data-id as the button,
  100. // we merge all input fields by {"name":"value"} into api-attr
  101. if ($(this).closest("form").data('id') == id) {
  102. var invalid = false;
  103. $(this).closest("form").find('select, textarea, input').each(function() {
  104. if ($(this).prop('required')) {
  105. if (!$(this).val() && $(this).prop('disabled') === false) {
  106. invalid = true;
  107. if ($(this).is("select")) {
  108. $(this).selectpicker('setStyle', 'btn-input-missing', 'add');
  109. }
  110. $(this).addClass('inputMissingAttr');
  111. } else {
  112. if ($(this).is("select")) {
  113. $(this).selectpicker('setStyle', 'btn-input-missing', 'remove');
  114. }
  115. $(this).removeClass('inputMissingAttr');
  116. }
  117. }
  118. if ($(this).val() && $(this).attr("type") == 'email') {
  119. if (!validateEmail($(this).val())) {
  120. invalid = true;
  121. $(this).addClass('inputMissingAttr');
  122. } else {
  123. $(this).removeClass('inputMissingAttr');
  124. }
  125. }
  126. if ($(this).attr("max")) {
  127. if (Number($(this).val()) > Number($(this).attr("max"))) {
  128. invalid = true;
  129. $(this).addClass('inputMissingAttr');
  130. } else {
  131. if ($(this).attr("min")) {
  132. if (Number($(this).val()) < Number($(this).attr("min"))) {
  133. invalid = true;
  134. $(this).addClass('inputMissingAttr');
  135. } else {
  136. $(this).removeClass('inputMissingAttr');
  137. }
  138. }
  139. }
  140. }
  141. if ($(this).val() && $(this).attr("regex")) {
  142. var regex_content = $(this).val();
  143. $(this).removeClass('inputMissingAttr');
  144. if(!validateRegex(regex_content)) {
  145. invalid = true;
  146. $(this).addClass('inputMissingAttr');
  147. }
  148. if(!regex_content.startsWith('/') || !/\/[ims]?$/.test(regex_content)){
  149. invalid = true;
  150. $(this).addClass('inputMissingAttr');
  151. }
  152. }
  153. });
  154. if (!invalid) {
  155. var attr_to_merge = $(this).closest("form").serializeObject();
  156. // parse possible JSON Strings
  157. for (var [key, value] of Object.entries(attr_to_merge)) {
  158. if (typeof value === "string" && /^[\[\{"].*[\}\]"]$/.test(value.trim())) {
  159. try {
  160. attr_to_merge[key] = JSON.parse(attr_to_merge[key]);
  161. } catch {}
  162. }
  163. }
  164. var api_attr = $.extend(api_attr, attr_to_merge)
  165. } else {
  166. return false;
  167. }
  168. }
  169. // alert(JSON.stringify(api_attr));
  170. // If clicked element #edit_selected has data-item attribute, it is added to "items"
  171. if (typeof $(this).data('item') !== 'undefined') {
  172. var id = $(this).data('id');
  173. if (typeof multi_data[id] == "undefined") {
  174. multi_data[id] = [];
  175. }
  176. multi_data[id].splice($.inArray($(this).data('item'), multi_data[id]), 1);
  177. multi_data[id].push($(this).data('item'));
  178. }
  179. if (typeof multi_data[id] == "undefined") return;
  180. api_items = multi_data[id];
  181. for (var i in api_items) {
  182. api_items[i] = decodeURIComponent(api_items[i]);
  183. }
  184. // alert(JSON.stringify(api_attr));
  185. if (Object.keys(api_items).length !== 0) {
  186. if (is_active($(this))) { return false; }
  187. $.ajax({
  188. type: "POST",
  189. dataType: "json",
  190. data: {
  191. "items": JSON.stringify(api_items),
  192. "attr": JSON.stringify(api_attr),
  193. "csrf_token": csrf_token
  194. },
  195. url: '/api/v1/' + api_url,
  196. jsonp: false,
  197. complete: function(data) {
  198. var response = (data.responseText);
  199. if (typeof response !== 'undefined' && response.length !== 0) {
  200. response_obj = JSON.parse(response);
  201. }
  202. if (api_reload_window === true) {
  203. if (api_reload_location != '#') {
  204. window.location.replace(api_reload_location)
  205. } else {
  206. window.location = window.location.href.split("#")[0];
  207. }
  208. }
  209. }
  210. });
  211. }
  212. });
  213. // General API add actions
  214. $(document).on('click', "[data-action='add_item']", function(e) {
  215. e.preventDefault();
  216. var id = $(this).data('id');
  217. var api_url = $(this).data('api-url');
  218. var api_attr = $(this).data('api-attr');
  219. if (typeof $(this).data('api-reload-window') !== 'undefined') {
  220. api_reload_window = $(this).data('api-reload-window');
  221. } else {
  222. api_reload_window = true;
  223. }
  224. // If clicked button is in a form with the same data-id as the button,
  225. // we merge all input fields by {"name":"value"} into api-attr
  226. if ($(this).closest("form").data('id') == id) {
  227. var invalid = false;
  228. $(this).closest("form").find('select, textarea, input').each(function() {
  229. if ($(this).prop('required')) {
  230. if (!$(this).val() && $(this).prop('disabled') === false) {
  231. invalid = true;
  232. if ($(this).is("select")) {
  233. $(this).selectpicker('setStyle', 'btn-input-missing', 'add');
  234. }
  235. $(this).addClass('inputMissingAttr');
  236. } else {
  237. if ($(this).is("select")) {
  238. $(this).selectpicker('setStyle', 'btn-input-missing', 'remove');
  239. }
  240. $(this).removeClass('inputMissingAttr');
  241. }
  242. }
  243. if ($(this).attr("type") == 'email') {
  244. var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  245. if (!emailReg.test($(this).val())) {
  246. invalid = true;
  247. $(this).addClass('inputMissingAttr');
  248. } else {
  249. $(this).removeClass('inputMissingAttr');
  250. }
  251. }
  252. if ($(this).attr("max")) {
  253. if (Number($(this).val()) > Number($(this).attr("max"))) {
  254. invalid = true;
  255. $(this).addClass('inputMissingAttr');
  256. } else {
  257. if ($(this).attr("min")) {
  258. if (Number($(this).val()) < Number($(this).attr("min"))) {
  259. invalid = true;
  260. $(this).addClass('inputMissingAttr');
  261. } else {
  262. $(this).removeClass('inputMissingAttr');
  263. }
  264. }
  265. }
  266. }
  267. });
  268. if (!invalid) {
  269. var attr_to_merge = $(this).closest("form").serializeObject();
  270. // parse possible JSON Strings
  271. for (var [key, value] of Object.entries(attr_to_merge)) {
  272. if (typeof value === "string" && /^[\[\{"].*[\}\]"]$/.test(value.trim())) {
  273. try {
  274. attr_to_merge[key] = JSON.parse(attr_to_merge[key]);
  275. } catch {}
  276. }
  277. }
  278. var api_attr = $.extend(api_attr, attr_to_merge)
  279. } else {
  280. return false;
  281. }
  282. }
  283. if (is_active($(this))) { return false; }
  284. // alert(JSON.stringify(api_attr));
  285. $.ajax({
  286. type: "POST",
  287. dataType: "json",
  288. data: {
  289. "attr": JSON.stringify(api_attr),
  290. "csrf_token": csrf_token
  291. },
  292. url: '/api/v1/' + api_url,
  293. jsonp: false,
  294. complete: function(data) {
  295. var response = (data.responseText);
  296. if (typeof response !== 'undefined' && response.length !== 0) {
  297. response_obj = JSON.parse(response);
  298. unset = true;
  299. $.each(response_obj, function(i, v) {
  300. if (v.type == "danger") {
  301. unset = false;
  302. }
  303. });
  304. if (unset === true) {
  305. unset = null;
  306. // Keep form data for sync jobs
  307. if (id != "add_syncjob") {
  308. $('form').formcache('clear');
  309. $('form').formcache('destroy');
  310. var i = localStorage.length;
  311. while(i--) {
  312. var key = localStorage.key(i);
  313. if(/formcache/.test(key)) {
  314. localStorage.removeItem(key);
  315. }
  316. }
  317. }
  318. }
  319. else {
  320. var add_modal = $('.modal.in').attr('id');
  321. localStorage.setItem("add_modal", add_modal);
  322. }
  323. }
  324. if (api_reload_window === true) {
  325. window.location = window.location.href.split("#")[0];
  326. }
  327. }
  328. });
  329. });
  330. // General API delete actions
  331. $(document).on('click', "[data-action='delete_selected']", function(e) {
  332. e.preventDefault();
  333. var id = $(this).data('id');
  334. // If clicked element #delete_selected has data-item attribute, it is added to "items"
  335. if (typeof $(this).data('item') !== 'undefined') {
  336. var id = $(this).data('id');
  337. if (typeof multi_data[id] == "undefined") {
  338. multi_data[id] = [];
  339. }
  340. multi_data[id].splice($.inArray($(this).data('item'), multi_data[id]), 1);
  341. multi_data[id].push($(this).data('item'));
  342. }
  343. if (typeof $(this).data('text') !== 'undefined') {
  344. $("#DeleteText").empty();
  345. $("#DeleteText").text($(this).data('text'));
  346. }
  347. if (typeof multi_data[id] == "undefined" || multi_data[id] == "") return;
  348. data_array = multi_data[id];
  349. api_url = $(this).data('api-url');
  350. $(document).on('show.bs.modal', '#ConfirmDeleteModal', function() {
  351. $("#ItemsToDelete").empty();
  352. for (var i in data_array) {
  353. data_array[i] = decodeURIComponent(data_array[i]);
  354. $("#ItemsToDelete").append("<li>" + escapeHtml(data_array[i]) + "</li>");
  355. }
  356. })
  357. $('#ConfirmDeleteModal').modal('show')
  358. .one('click', '#IsConfirmed', function(e) {
  359. if (is_active($('#IsConfirmed'))) { return false; }
  360. $.ajax({
  361. type: "POST",
  362. dataType: "json",
  363. cache: false,
  364. data: {
  365. "items": JSON.stringify(data_array),
  366. "csrf_token": csrf_token
  367. },
  368. url: '/api/v1/' + api_url,
  369. jsonp: false,
  370. complete: function(data) {
  371. window.location = window.location.href.split("#")[0];
  372. }
  373. });
  374. })
  375. .one('click', '#isCanceled', function(e) {
  376. // Remove event handler to allow to close modal and restart dialog without multiple submits
  377. $('#ConfirmDeleteModal').off();
  378. $('#ConfirmDeleteModal').modal('hide');
  379. });
  380. });
  381. // toggle jquery datatables child rows
  382. $('button[data-datatables-expand], a[data-datatables-expand]').on('click', function (e) {
  383. e.preventDefault();
  384. var tableId = e.target.getAttribute("data-datatables-expand");
  385. var table = $("#" + tableId).DataTable();
  386. table.rows(':not(.parent)').nodes().to$().find('td:first-child').trigger('click');
  387. });
  388. $('button[data-datatables-collapse], a[data-datatables-collapse]').on('click', function (e) {
  389. e.preventDefault();
  390. var tableId = e.target.getAttribute("data-datatables-collapse");
  391. var table = $("#" + tableId).DataTable();
  392. table.rows('.parent').nodes().to$().find('td:first-child').trigger('click');
  393. });
  394. });