jqgrid_utils 1.36.0 → 1.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1,2144 @@
1
- !function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Jqgrid_utils=e()}(function(){return function e(t,r,n){function a(o,s){if(!r[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(i)return i(o,!0);var d=new Error("Cannot find module '"+o+"'");throw d.code="MODULE_NOT_FOUND",d}var c=r[o]={exports:{}};t[o][0].call(c.exports,function(e){return a(t[o][1][e]||e)},c,c.exports,e,t,r,n)}return r[o].exports}for(var i="function"==typeof require&&require,o=0;o<n.length;o++)a(n[o]);return a}({1:[function(e,t,r){"use strict";t.exports=class{constructor(e=!1){e&&e.hasOwnProperty("page")&&(this.page=e.page,localStorage.setItem("page",this.page))}async add_class(e,t,r){for(let n=0;n<e.length;n++)e[n].name===t&&(e[n].classes?e[n].classes+=" "+r:e[n].classes=r);return e}async _grid_substract_on(e,t=[],r=[],n,a=!1){return await this.grid_substract_on(e,t,r,n,a)}async grid_substract_on(e,t=[],r=[],n,a=!1){let i=jQuery(e),o=i.jqGrid("getGridParam","data"),s={invdate:"Total"},l=0,d=0;for(let e in t){let r=0;for(let n in o)if(o[n].hasOwnProperty(t[e])){let a=o[n][t[e]];"string"==typeof a&&is_digit(a)&&(a=parseFloat(a)),r+=a}r!=Math.floor(r)&&(r=r.toFixed(2)),s[t[e]]=r,l=r}for(let e in r){let t=0;for(let n in o)if(o[n].hasOwnProperty(r[e])){let a=o[n][r[e]];"string"==typeof a&&is_digit(a)&&(a=parseFloat(a)),t+=a}t!=Math.floor(t)&&(t=t.toFixed(2)),s[r[e]]=t,d=t}let c=l-d;return a&&c<0&&(c=0),s[n]=c,i.jqGrid("footerData","set",s),s}_grid_ratio_on(e,t,r,n){return this.grid_ratio_on(e,t,r,n)}async grid_ratio_on(e,t,r,n){jQuery("#grid").jqGrid("getGridParam","data");let a=jQuery(e),i=a.jqGrid("getGridParam","data"),o={invdate:"Total"};fraction_sum=0,denominator_sum=0,ratio_sum=0;for(let e in i)i[e].hasOwnProperty(t)&&(fraction_sum+=i[e][t]),i[e].hasOwnProperty(r)&&(denominator_sum+=i[e][r]);return o.qc_eta_ratio=(fraction_sum/denominator_sum).toFixed(2),a.jqGrid("footerData","set",o),o}is_html(e){let t=!1;try{const r=(new DOMParser).parseFromString(e,"text/html");Array.from(r.body.childNodes).some(e=>1===e.nodeType)&&(t=!0)}catch(e){}return t}async _grid_sum_on(e,t=[]){return await this.grid_sum_on(e,t)}async grid_sum_on(e,t=[]){let r=jQuery(e),n=r.jqGrid("getGridParam","data"),a={invdate:"Total"};for(let e in t){let r=0;for(let a in n){let i=0;if(n[a].hasOwnProperty(t[e])){let o=n[a][t[e]];if(o){if("string"==typeof o)if(this.is_html(o)){const e=(new DOMParser).parseFromString(o,"text/html").querySelectorAll("a"),t=Array.from(e).map(e=>e.text);if(t.length){const e=t[0].replace(",","");is_digit(e)&&(i=parseFloat(e))}}else is_digit(o)&&(i=parseFloat(o));else"number"==typeof o&&(i=o);r+=i}}}r!=Math.floor(r)&&(r=r.toFixed(2)),a[t[e]]=r}return r.jqGrid("footerData","set",a),a}_grid_avg_on(e,t=[]){return this.grid_avg_on(e,t)}async grid_avg_on(e,t=[]){let r=jQuery(e),n=r.jqGrid("getGridParam","data"),a=0,i={invdate:"Total"};for(let e in t){let r=0;for(let i in n)if(n[i].hasOwnProperty(t[e])){let o=n[i][t[e]];"string"==typeof o&&is_digit(o)&&(o=parseFloat(o)),r+=o,a++}r/=a,r!=Math.floor(r)&&(r=r.toFixed(2)),i[t[e]]=r}return r.jqGrid("footerData","set",i),i}_grid_percent_on(e,t){return grid_percent_on(e,t)}async grid_percent_on(e,t){let r=jQuery(e),n=r.jqGrid("getGridParam","data"),a={},i=t.id?t.id:"invate";footer[i]="Total";let o=t.total,s=JSON.parse(JSON.stringify(t.percent));s.push(o);for(let e in s){let t=s[e],r=0,i=0;for(let e in n)if(n[e].hasOwnProperty(t)){let a=n[e][t];"string"==typeof a?is_digit(a)&&(a=parseFloat(a),r+=a,i++):(r+=a,i++)}a[t]=r}for(let e in s){let t=s[e],r=a[t]/(a[o]/100);r=r.toFixed(2),footer[t]=r+"%"}r.jqGrid("footerData","set",footer)}async update_row_to_api(e,t="",r=["id"],n={},a){let i=this,o=[],s={},l={},d={};const c=e.jqGrid("getGridParam","record_data");if(""!=t&&Object.keys(n).length>0&&"edit"==n.inputData.oper){for(let e in c)if(c[e].id===n.rowid){for(let t in r)c[e].hasOwnProperty(r[t])&&(s[r[t]]=c[e][r[t]]);for(let t in n.inputData)"oper"!=t&&Object.keys(s).indexOf(t)<0&&n.inputData[t]!=c[e][t]&&(d[t]=n.inputData[t])}for(let e in d)if(Object.keys(s).indexOf(e)<0&&"oper"!=e){let r={};r[e]=d[e],a.ids=s,a.values=r,a.operator="edit";const n=await i.post_json(t,JSON.stringify(a));o.push(n)}}else if(""!=t&&Object.keys(n).length>0&&"add"==n.inputData.oper){for(let e in n.inputData)n.inputData[e]&&"id"!=e&&"oper"!=e&&(l[e]=n.inputData[e]);a.ids=s,a.values=l,a.operator="add";let e=await i.post_json(t,JSON.stringify(a));o.push(e)}return o}async delete_row_to_api(e,t="",r,n=[],a={}){let i={msg:"failed"},o=[],s={};const l=e.jqGrid("getGridParam","record_data");for(let e in l)if(l[e].id===r){for(let t in n)l[e].hasOwnProperty(n[t])&&(s[n[t]]=l[e][n[t]],o.push(n[t]));break}return""!=t&&Object.keys(s).length==o.length&&(a.ids=o,a.values=s,i=await this.adelete_api(t,JSON.stringify(a))),i}async append_seperator_link_column(e,t,r,n,a="",i){return t+="/",n.formatter=function(e,n){let o=r;if("object"==typeof i){let r="";for(let e in i){let t=e,a=i[e],o=n.rowData[a];o&&o&&(r+=""!=t?t+"/"+encodeURIComponent(o)+"/":encodeURIComponent(o))}r&&("&"!==r.slice(-1)&&"/"!==r.slice(-1)||(r=r.slice(0,-1)),e="<a "+a+'href="'+t+r+'"> '+o+"</a>")}return e},e.push(n),e}async add_edit(e,t,r,n){for(let a=0;a<e.length;a++)e[a].name===t&&(Object.assign(e[a],r),Object.assign(e[a],n));return e}async add_textarea(e,t,r='style="width:100%;height:100px"'){for(let n=0;n<e.length;n++)e[n].name===t&&(e[n].formatter=function(e){return"<textarea "+r+">"+e+"</textarea>"});return e}async get_col_model_from_data(e,t,r=[],n=[]){let a=[];for(let e in t){const r=Object.keys(t[e]);for(let e in r){const t=r[e];a.push(t)}}a=a.filter((e,t)=>a.indexOf(e)===t);let i=[];for(let e in n)i.push(n[e].name);let o=a.filter(e=>!i.includes(e));const s=new Set(r);o=o.filter(e=>!s.has(e)),o.sort();for(let e=0;e<o.length;e++)n.push({name:o[e],label:o[e]});return n}binary_replace(e,t="zero",r="one"){let n=t;return 1!=e&&0!=e||1==e&&(n=r),n}_date112_to_DMY(e,t="/"){let r=e;if(e.length>=8&&-1===e.indexOf(t)){let n=[];n.push(e.substr(6,2)),n.push(e.substr(4,2)),n.push(e.substr(0,4)),r=n.join(t)}return r}async date112_to_DMY(e,t,r="/"){for(let n=0;n<e.length;n++)e[n].name===t&&(e[n].formatter=function(e,t){if(e){let t=e=e.toString();if(e.length>=8&&-1===e.indexOf(r)){let n=[];n.push(e.substr(6,2)),n.push(e.substr(4,2)),n.push(e.substr(0,4)),t=n.join(r)}return t}return e});return e}async add_formatter(e,t,r){for(let n=0;n<e.length;n++)e[n].name===t&&r.hasOwnProperty("formatter")&&r.hasOwnProperty("formatoptions")&&(e[n].formatter=r.formatter,e[n].formatoptions=r.formatoptions,e[n].edittype=r.formatter,e[n].editoptions=r.formatoptions);return e}async natural_sort(e,t){for(let r=0;r<e.length;r++)e[r].name===t&&(e[r].sortfunc=function(e,t,r){void 0===r&&(r=1);var n,a,i=/(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,o=/(^[ ]*|[ ]*$)/g,s=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,l=/^0x[0-9a-f]+$/i,d=/^0/,c=function(e){return self.insensitive&&(""+e).toLowerCase()||""+e},f=c(e).replace(o,"")||"",u=c(t).replace(o,"")||"",p=f.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),_=u.replace(i,"\0$1\0").replace(/\0$/,"").replace(/^\0/,"").split("\0"),h=parseInt(f.match(l))||1!=p.length&&f.match(s)&&Date.parse(f),m=parseInt(u.match(l))||h&&u.match(s)&&Date.parse(u)||null;if(m){if(h<m)return-r;if(h>m)return r}for(var y=0,g=Math.max(p.length,_.length);y<g;y++){if(n=!(p[y]||"").match(d)&&parseFloat(p[y])||p[y]||0,a=!(_[y]||"").match(d)&&parseFloat(_[y])||_[y]||0,isNaN(n)!==isNaN(a))return isNaN(n)?r:-r;if(typeof n!=typeof a&&(n+="",a+=""),n<a)return-r;if(n>a)return r}return 0});return e}async add_html_formatter(e,t,r){for(let n=0;n<e.length;n++)e[n].name===t&&(e[n].formatter=function(e,t){return r});return e}async add_ok_button(e,t){let r=this;for(let n=0;n<e.length;n++)t.indexOf(e[n].name)>-1&&(e[n].formatter=function(e){return null!=e?r.__cell_format(e,"format_ok"):""});return e}async get_filled_cell_table_data(e,t=[]){let r=jQuery(e).jqGrid("getGridParam","data"),n=t,a=[];for(let e in r)if(r[e].hasOwnProperty("id")){let t=[r[e].id];for(let a in n)r[e].hasOwnProperty(n[a])?t.push(r[e][n[a]]):t.push("");var i=t.filter(function(e,t,r){return""!==e});Object.keys(i).length>1&&a.push(t)}return a}async get_filled_cell_data(e,t=[]){let r=jQuery(e).jqGrid("getGridParam","data"),n=t,a=[];for(let e in r)if(r[e].hasOwnProperty("id")){let t={id:r[e].id};for(let a in n)r[e].hasOwnProperty(n[a])&&""!=r[e][n[a]]&&(t[n[a]]=r[e][n[a]]);Object.keys(t).length>1&&a.push(t)}return a}async set_link(e,t,r,n=""){for(let a=0;a<e.length;a++)e[a].name===t&&(e[a].formatter=function(e,t){return'<a class="gl" '+n+'href="'+t.rowData[r]+'">'+e+"</a>"});return e}async hide_all_columns_except(e,t){for(let r=0;r<e.length;r++)t.indexOf(e[r].name)>-1?e[r].hidden=!1:e[r].hidden=!0;return e}async hide_column(e,t){for(let r=0;r<e.length;r++)e[r].name===t&&(e[r].hidden=!0);return e}s_grid_set_caption(e,t=[]){this.grid_set_captionn(e,[])}async grid_set_caption(e,t=[]){if(e){const r=jQuery(e);let n=0;n=0===t.length?r.jqGrid("getGridParam","records"):t.length;const a=/\d.*x/,i=r.jqGrid("getGridParam","caption").replace(a,"");r.jqGrid("setCaption",i+" "+n+"x")}}s_resize_saved_cell_width(e,t=!1,r=!1){this.grid_set_caption(e,t,r)}async resize_saved_cell_width(e,t=!1,r=!1){let n=t||this.page;n+=r?"-"+r+"-w-":"-grid-w-";for(let t=0;t<=e.length;t++)if(e[t]&&e[t].name){const r=e[t].name,a=localStorage.getItem(n+r);a&&(e[t].width=a)}return e}resize_cell(e,t,r=!1){const n=jQuery(this).jqGrid("getGridParam","colModel");if(n[t]&&n[t].name){const a=n[t].name;let i=(r||localStorage.getItem("page"))+"-"+this.id+"-w-"+a;localStorage.setItem(i,e),localStorage.getItem(i)}}async upsert_row(e,t,r={}){return e.rowid.startsWith("jqg")?await this.insert_row(e,t):await this.update_row(e,t)}async insert_row(e,t){let r={},n="";if(e.inputData.hasOwnProperty("id")){r._id="id",r._id_val=e.inputData.id;for(let t in e.inputData)r[t]=e.inputData[t];delete r.id,delete r.oper,n=await this.put_json(t,JSON.stringify(r))}return n}async update_row(e,t,r={}){let n="";r._id||(r._id="id"),r._id_val=e.inputData.id;for(let t in e.inputData)r[t]=e.inputData[t];return delete r.id,delete r.oper,n=await this.post_json(t,JSON.stringify(r)),n}async delete_row(e,t){let r="";return t.indexOf("?")>-1?t+="&_id="+encodeURIComponent(unescape(e)):t+="?_id="+encodeURIComponent(unescape(e)),r=JSON.parse(await this.adelete_api(t)),r.message}async adelete_api(e,t=!1){let r="application/x-www-form-urlencoded",n=null;return t&&(r="application/json;charset=UTF-8",n=t),new Promise((t,a)=>{let i=new XMLHttpRequest;i.open("DELETE",e),i.setRequestHeader("Content-type",r),i.onload=()=>t(i.responseText),i.onerror=()=>a(i.statusText),i.send(n)})}async post_json(e,t){return new Promise((r,n)=>{let a=new XMLHttpRequest;a.open("POST",e),a.setRequestHeader("Content-type","application/json"),a.onload=()=>r(a.responseText),a.onerror=()=>n(a.statusText),a.send(t)})}async put_json(e,t){return new Promise((r,n)=>{let a=new XMLHttpRequest;a.open("PUT",e),a.setRequestHeader("Content-type","application/json"),a.onload=()=>r(a.responseText),a.onerror=()=>n(a.statusText),a.send(t)})}s_hide_del_icon(){hide_del_icon()}async hide_del_icon(){jQuery(".ui-inline-del").each(function(e){jQuery(this).html("")})}async add_link_details_csv(e,t,r,n="",a,i,o=","){let s=this;t.indexOf("?")>-1?t+="&":t+="?";for(let l=0;l<e.length;l++)e[l].name===r&&(e[l].formatter=function(e,r){let l=e;const d=s.__cell_format(e,i),c=d.split(o);let f="";for(let i in c){const s=c[i].trim();if(s&&"object"==typeof a){let e="";for(let t in a){let n=t,i=a[t];l=r.rowData[i],l&&(e=-1!==n.indexOf("=")?e+""+n+encodeURIComponent(s)+"&":e+""+n+"="+encodeURIComponent(s)+"&")}"&"===e.slice(-1)&&(e=e.slice(0,-1)),f+="<a "+n+'href="'+t+e+'"> '+s+"</a>"+o+" "}(e=f.trim()).slice(-1)===o&&(e=e.slice(0,-1))}return e||d});return e}async compare(e,t,r,n){const a=jQuery(e).jqGrid("getGridParam","data");for(let i in a)a[i][t]!=a[i][r]&&(jQuery(e).jqGrid("setCell",a[i].id,t,"",n),jQuery(e).jqGrid("setCell",a[i].id,r,"",n))}async compare_smaller(e,t,r,n){const a=jQuery(e).jqGrid("getGridParam","data");for(let i in a)a[i][t]<a[i][r]&&(jQuery(e).jqGrid("setCell",a[i].id,t,"",n),jQuery(e).jqGrid("setCell",a[i].id,r,"",n))}async compare_bigger(e,t,r,n){const a=jQuery(e).jqGrid("getGridParam","data");for(let i in a)a[i][t]>a[i][r]&&(jQuery(e).jqGrid("setCell",a[i].id,t,"",n),jQuery(e).jqGrid("setCell",a[i].id,r,"",n))}async set_styles(e,t="styles"){const r=jQuery(e).jqGrid("getGridParam","data");for(let n in r)if(r[n][t]){const a=JSON.parse(r[n][t]);for(let t in a){const i=r[n].id,o=t;r[n].hasOwnProperty(o)&&jQuery(e).jqGrid("setCell",i,o,"",a[t])}}}async set_classes(e){const t=jQuery(e).getDataIDs();for(var r=0;r<t.length;r+=1){const a=jQuery(e).getRowData(t[r]);var n=jQuery("#"+t[r],jQuery(e));n.removeClass("ui-widget-content"),n.addClass(a.class)}}async add_link_details(e,t,r,n="",a,i){let o=this;t.indexOf("?")>-1?t+="&":t+="?";for(let s=0;s<e.length;s++)e[s].name===r&&(e[s].formatter=function(e,r){let s="";(e=String(e))&&(s=e);let l="";if(e&&(l=e.toString()),"object"==typeof a){let d="";for(let e in a){let t=e,n=a[e];s=r.rowData[n],s&&s&&(d=-1!==t.indexOf("=")?d+""+t+encodeURIComponent(s)+"&":d+""+t+"="+encodeURIComponent(s)+"&")}if(d){"&"===d.slice(-1)&&(d=d.slice(0,-1));const r=o.__cell_format(e,i);e=""!=l&&r&&l?"<a "+n+'href="'+t+d+'"> '+r+"</a>":""}}return l?e:""});return e}async add_link_details_separator(e,t,r,n="",a,i){t+="/";let o=this;for(let s=0;s<e.length;s++)e[s].name===r&&(e[s].formatter=function(e,r){let s=e;if("object"==typeof a){let l="";for(let e in a){let t=e,n=a[e];s=r.rowData[n],s&&s&&(l+=""!=t?t+"/"+encodeURIComponent(s)+"/":encodeURIComponent(s))}if(l){"&"!==l.slice(-1)&&"/"!==l.slice(-1)||(l=l.slice(0,-1));const r=o.__cell_format(e,i);e="<a "+n+'href="'+t+l+'"> '+r+"</a>"}}return e});return e}async add_link_separator(e,t,r,n,a=""){t+="/";for(let i=0;i<e.length;i++)e[i].name===r&&(e[i].formatter=function(e,r){let i="";for(let e in n)for(let t in n[e])if("field"===t&&(i+=r.rowData[n[e][t]]),"extension"===t&&(i+=n[e][t]),"fields"===t){i+="?";for(let a in n[e][t]){let o=r.rowData[n[e][t][a]];i=i+""+a+"="+encodeURIComponent(o)+"&"}}return i&&("&"!==i.slice(-1)&&"/"!==i.slice(-1)||(i=i.slice(0,-1)),e="<a "+a+'href="'+t+i+'"> '+e+"</a>"),e});return e}__cell_format(e,t){return"format_ok"==t&&(e=0==e||"fail"===e?'<i data-check="failed" class="fa fa-times-circle" aria-hidden="true" style="color:#ff0000;"></i>':'<i data-check="ok" class="fa fa-check-circle" aria-hidden="true" style="color:#008000;"></i>'),e}async subgrid(e,t,r,n,a=""){a=""!=a?a+" ":"",t?r+=t:t="";let i=jQuery("<table style='margin: 5px 0' class='"+e+"_t'></table>");i.appendTo("#"+jQuery.jgrid.jqID(e)),i.jqGrid({caption:a+t,colModel:n,datatype:"json",url:r,gridview:!0,rownumbers:!0,autoencode:!0,sortname:"c1",sortorder:"desc"})}async add_image(e,t,r,n=!1){void 0===r&&(r=60);for(let a=0;a<e.length;a++)e[a].name===t&&(e[a].picture=!0,e[a].width=r,e[a].height=r,e[a].formatter=function(e){const t=e.toLowerCase();return(t.startsWith("https://",0)||t.startsWith("http://",0))&&(t.includes(".png")||t.includes(".jpg")||t.includes(".jpeg")||t.includes(".gif")||t.includes(".svg")||t.includes(".svgz")||t.includes(".webp"))?n?'<a target="blank" href="'+e+'"><img src="'+e+'" alt="my image" width="'+r+'" /></a>':'<img src="'+e+'" alt="my image" width="'+r+'" />':e});return e}async set_filter(e,t,r,n="#filter"){jQuery(e).jqGrid("setGridParam",{fdata:t});let a=document.querySelector(n);for(const e in t)for(let n in r)r[n].push(t[e][n]);for(let e in r)r[e]=r[e].filter((e,t,r)=>r.indexOf(e)===t),r[e].sort();for(let t in r){let n=document.createElement("ul"),i=document.createElement("lh");i.innerHTML=t,n.appendChild(i);for(let a in r[t]){let i=document.createElement("li"),o=document.createElement("label");o.innerHTML=r[t][a];let s=document.createElement("input");s.setAttribute("type","checkbox"),s.setAttribute("class",t),s.setAttribute("id",t+"_"+r[t][a]),o.setAttribute("for",t+"_"+r[t][a]),s.value=r[t][a],s.onchange=async()=>{await this._filter(e,r)},i.appendChild(o),i.appendChild(s),n.appendChild(i)}a.appendChild(n)}}async _filter(e,t){let r=[],n=jQuery(e).jqGrid("getGridParam","fdata"),a=[];for(let e in t){let t=document.querySelectorAll("."+e);a[e]=[];for(let r in t)t[r].checked&&a[e].push(t[r].value)}for(let e in n){let i=!1;for(let r in t)-1!=a[r].indexOf(n[e][r])&&(i=!0);i&&r.push(n[e])}jQuery(e).jqGrid("clearGridData"),jQuery(e).jqGrid("setGridParam",{data:r}),jQuery(e).trigger("reloadGrid")}}},{}]},{},[1])(1)});
1
+ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Jqgrid_utils = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2
+ /**
3
+ * A module for Jqgrid_utils
4
+ * @module Jqgrid_utils
5
+ */
6
+
7
+ "use strict";
8
+
9
+ module.exports = class Vanilla_website_utils {
10
+ constructor(settings = false) {
11
+ if (settings) {
12
+ if (settings.hasOwnProperty("page")) {
13
+ this.page = settings["page"];
14
+ localStorage.setItem("page", this.page);
15
+ }
16
+ }
17
+ }
18
+
19
+ /**
20
+ * Format a number into a currency
21
+ @alias module:Jqgrid_utils
22
+ @param {object} - col_model of the grid
23
+ @param {string} - name of column to be formatter
24
+ @param {string} - currency symbol, default is $
25
+ @example
26
+ var jqu = new Jqgrid_utils();
27
+ let _data = await jqu.format_currency(this,'my_field','$');
28
+ console.log(_data);
29
+ */
30
+ async format_currency(col_model, edit_field, currency = "$") {
31
+ for (let i = 0; i < col_model.length; i++) {
32
+ if (col_model[i]["name"] === edit_field) {
33
+ col_model[i]["formatter"] = "currency";
34
+ col_model[i]["formatoptions"] = {
35
+ prefix: currency,
36
+ decimalSeparator: ".",
37
+ thousandsSeparator: ",",
38
+ decimalPlaces: 2,
39
+ };
40
+ }
41
+ }
42
+ return col_model;
43
+ }
44
+
45
+ /**
46
+ * Add a Checkbox to the Model
47
+ @alias module:Jqgrid_utils
48
+ @param {array} - grid col_model
49
+ @param {string} - column_name
50
+ @example
51
+ var jqu = new Jqgrid_utils();
52
+ ol_model = await jqu.add_checkbox(col_model, "closed");
53
+ */
54
+ async add_checkbox(col_model, field_name) {
55
+ for (let i = 0; i < col_model.length; i++) {
56
+ if (col_model[i]["name"] === field_name) {
57
+ col_model[i]["formatter"] = "checkbox";
58
+ col_model[i]["formatoptions"] = { disabled: false };
59
+ col_model[i]["edittype"] = "checkbox";
60
+ col_model[i]["editoptions"] = { value: "Yes:No", defaultValue: "Yes" };
61
+ }
62
+ }
63
+ return col_model;
64
+ }
65
+
66
+ /**
67
+ * Add a Class to the Model
68
+ @alias module:Jqgrid_utils
69
+ @param {array} - grid col_model
70
+ @param {string} - column_name
71
+ @param {string} - class_name
72
+ @example
73
+ var jqu = new Jqgrid_utils();
74
+ col_model = await jqu.add_class(col_model,field_name,class_name)
75
+ */
76
+
77
+ async add_class(col_model, field_name, class_name) {
78
+ for (let i = 0; i < col_model.length; i++) {
79
+ if (col_model[i]["name"] === field_name) {
80
+ if (col_model[i]["classes"]) {
81
+ col_model[i]["classes"] += " " + class_name;
82
+ } else {
83
+ col_model[i]["classes"] = class_name;
84
+ }
85
+ }
86
+ }
87
+ return col_model;
88
+ }
89
+
90
+ /**
91
+ * Syncron Alias grid_sum_on
92
+ @alias module:Jqgrid_utils
93
+ */
94
+ async _grid_substract_on(
95
+ grid,
96
+ minuend = [],
97
+ subtrahend = [],
98
+ difference,
99
+ no_negative = false,
100
+ ) {
101
+ return await this.grid_substract_on(
102
+ grid,
103
+ minuend,
104
+ subtrahend,
105
+ difference,
106
+ no_negative,
107
+ );
108
+ }
109
+
110
+ /**
111
+ * Sum the columns values together
112
+ @alias module:Jqgrid_utils
113
+ @param {object} - Grid Object (required)
114
+ @param {array} - string array list of field_names used as minuend(number from which the other number is subtracted)
115
+ @param {array} - string array list of field_names used as subtrahend(number which is to be subtracted from the minuend)
116
+ @param {string} - string field name for the difference(number which is to be subtracted from the minuend)
117
+ @param {bolen} - true or 1 to not show negative numbers
118
+
119
+ @example
120
+ var jqu = new Jqgrid_utils({page:page});
121
+ gridComplete: function () {
122
+ jqu._jqu._grid_sum_on(this, [
123
+ "qty_icollect",
124
+ "qty_ordered",
125
+ "need_for_qty_ordered",
126
+ "wait_icollect",
127
+ ]);
128
+ },
129
+ */
130
+ async grid_substract_on(
131
+ grid,
132
+ minuend = [],
133
+ subtrahend = [],
134
+ difference,
135
+ no_negative = false,
136
+ ) {
137
+ let $self = jQuery(grid);
138
+ let rows = $self.jqGrid("getGridParam", "data");
139
+ let footer = { invdate: "Total" };
140
+ let _minuend = 0.0;
141
+ let _subtrahend = 0.0;
142
+ for (let i in minuend) {
143
+ let sum = 0;
144
+ for (let r in rows) {
145
+ if (rows[r].hasOwnProperty(minuend[i])) {
146
+ let val = rows[r][minuend[i]];
147
+ if (typeof val === "string") {
148
+ if (is_digit(val)) {
149
+ val = parseFloat(val);
150
+ }
151
+ }
152
+ sum += val;
153
+ }
154
+ }
155
+ if (sum != Math.floor(sum)) {
156
+ sum = sum.toFixed(2);
157
+ }
158
+ footer[minuend[i]] = sum;
159
+ _minuend = sum;
160
+ }
161
+
162
+ for (let i in subtrahend) {
163
+ let sum = 0;
164
+ for (let r in rows) {
165
+ if (rows[r].hasOwnProperty(subtrahend[i])) {
166
+ let val = rows[r][subtrahend[i]];
167
+ if (typeof val === "string") {
168
+ if (is_digit(val)) {
169
+ val = parseFloat(val);
170
+ }
171
+ }
172
+ sum += val;
173
+ }
174
+ }
175
+ if (sum != Math.floor(sum)) {
176
+ sum = sum.toFixed(2);
177
+ }
178
+ footer[subtrahend[i]] = sum;
179
+ _subtrahend = sum;
180
+ }
181
+
182
+ let diff = _minuend - _subtrahend;
183
+ if (no_negative) {
184
+ if (diff < 0) {
185
+ diff = 0;
186
+ }
187
+ }
188
+ footer[difference] = diff;
189
+
190
+ $self.jqGrid("footerData", "set", footer);
191
+
192
+ return footer;
193
+ }
194
+
195
+ /**
196
+ * Syncron Alias grid_ratio_on
197
+ @alias module:Jqgrid_utils
198
+ */
199
+ _grid_ratio_on(grid, fraction_col, denominator_col, ratio_col) {
200
+ return this.grid_ratio_on(grid, fraction_col, denominator_col, ratio_col);
201
+ }
202
+
203
+ /**
204
+ * Get the ratio the columns values together
205
+ @alias module:Jqgrid_utils
206
+ @param {object} - Grid Object (required)
207
+ @param {string} - Column/Field Name for value 1
208
+ @param {string} - Column/Field Name for value 2
209
+ @param {string} - Column/Field Name to the set the target ratio
210
+ @example
211
+ var jqu = new Jqgrid_utils({page:page});
212
+ gridComplete: function()
213
+ {
214
+ jqu._grid_ratio_on(this, 'actual_days', 'plan_days', 'qc_eta_ratio');
215
+ },
216
+
217
+ */
218
+ async grid_ratio_on(grid, fraction_col, denominator_col, ratio_col) {
219
+ var allrows = jQuery("#grid").jqGrid("getGridParam", "data");
220
+ let $self = jQuery(grid);
221
+ let rows = $self.jqGrid("getGridParam", "data");
222
+ let footer = {
223
+ invdate: "Total",
224
+ };
225
+ let sum = 0;
226
+ fraction_sum = 0;
227
+ denominator_sum = 0;
228
+ ratio_sum = 0;
229
+ for (let r in rows) {
230
+ if (rows[r].hasOwnProperty(fraction_col)) {
231
+ fraction_sum += rows[r][fraction_col];
232
+ }
233
+ if (rows[r].hasOwnProperty(denominator_col)) {
234
+ denominator_sum += rows[r][denominator_col];
235
+ }
236
+ }
237
+ footer["qc_eta_ratio"] = (fraction_sum / denominator_sum).toFixed(2);
238
+ $self.jqGrid("footerData", "set", footer);
239
+ return footer;
240
+ }
241
+
242
+ /**
243
+ * Check if the string is html
244
+ @alias module:Jqgrid_utils
245
+ @param {string} - String of any kind
246
+ @returns {boolean} - true or false
247
+ */
248
+ is_html(str) {
249
+ let r = false;
250
+ try {
251
+ const doc = new DOMParser().parseFromString(str, "text/html");
252
+ const a = Array.from(doc.body.childNodes).some((n) => n.nodeType === 1);
253
+ if (a) {
254
+ r = true;
255
+ }
256
+ } catch (err) {}
257
+ return r;
258
+ }
259
+
260
+ /**
261
+ * Syncron Alias grid_sum_on
262
+ @alias module:Jqgrid_utils
263
+ */
264
+ async _grid_sum_on(grid, fields = []) {
265
+ return await this.grid_sum_on(grid, fields);
266
+ }
267
+
268
+ /**
269
+ * Sum the columns values together
270
+ @alias module:Jqgrid_utils
271
+ @param {object} - Grid Object (required)
272
+ @param {string} - Column/Field Name to sum
273
+ @example
274
+ var jqu = new Jqgrid_utils({page:page});
275
+ gridComplete: function () {
276
+ jqu._jqu._grid_sum_on(this, [
277
+ "qty_icollect",
278
+ "qty_ordered",
279
+ "need_for_qty_ordered",
280
+ "wait_icollect",
281
+ ]);
282
+ },
283
+ */
284
+ async grid_sum_on(grid, fields = []) {
285
+ let $self = jQuery(grid);
286
+ let rows = $self.jqGrid("getGridParam", "data");
287
+ let footer = {
288
+ invdate: "Total",
289
+ };
290
+ for (let i in fields) {
291
+ let sum = 0;
292
+ for (let r in rows) {
293
+ let _val = 0;
294
+ if (rows[r].hasOwnProperty(fields[i])) {
295
+ let val = rows[r][fields[i]];
296
+ if (val) {
297
+ if (typeof val === "string") {
298
+ if (this.is_html(val)) {
299
+ const doc = new DOMParser().parseFromString(val, "text/html");
300
+ const _a = doc.querySelectorAll("a");
301
+ const a = Array.from(_a).map((a) => a.text);
302
+ if (a.length) {
303
+ const n = a[0].replace(",", "");
304
+ if (is_digit(n)) {
305
+ _val = parseFloat(n);
306
+ }
307
+ }
308
+ } else {
309
+ if (is_digit(val)) {
310
+ _val = parseFloat(val);
311
+ }
312
+ }
313
+ } else if (typeof val === "number") {
314
+ _val = val;
315
+ }
316
+ sum += _val;
317
+ }
318
+ }
319
+ }
320
+ //let number = new Intl.NumberFormat('en-En', { style: 'currency', currency: 'USD' }).format(sum);
321
+ if (sum != Math.floor(sum)) {
322
+ sum = sum.toFixed(2);
323
+ }
324
+ footer[fields[i]] = sum;
325
+ }
326
+ $self.jqGrid("footerData", "set", footer);
327
+ return footer;
328
+ }
329
+
330
+ /**
331
+ * Syncron Alias grid_avg_on
332
+ @alias module:Jqgrid_utils
333
+ */
334
+ _grid_avg_on(grid, fields = []) {
335
+ return this.grid_avg_on(grid, fields);
336
+ }
337
+
338
+ /**
339
+ * Average the column values together
340
+ @alias module:Jqgrid_utils
341
+ @param {object} - Grid Object (required)
342
+ @param {array} - Column/Field Names to where the average of each column should be calculated
343
+ @example
344
+ var jqu = new Jqgrid_utils({page:page});
345
+
346
+ gridComplete: function()
347
+ {
348
+ jqu._grid_avg_on(this, ['diff_plan_to_actual', 'days_early', 'days_late']);
349
+ },
350
+
351
+
352
+ */
353
+
354
+ async grid_avg_on(grid, fields = []) {
355
+ let $self = jQuery(grid);
356
+ let rows = $self.jqGrid("getGridParam", "data");
357
+ let count = 0;
358
+ let footer = {
359
+ invdate: "Total",
360
+ };
361
+ for (let i in fields) {
362
+ let sum = 0;
363
+ for (let r in rows) {
364
+ if (rows[r].hasOwnProperty(fields[i])) {
365
+ let val = rows[r][fields[i]];
366
+ if (typeof val === "string") {
367
+ if (is_digit(val)) {
368
+ val = parseFloat(val);
369
+ }
370
+ }
371
+ sum += val;
372
+ count++;
373
+ }
374
+ }
375
+ sum = sum / count;
376
+ if (sum != Math.floor(sum)) {
377
+ sum = sum.toFixed(2);
378
+ }
379
+ footer[fields[i]] = sum;
380
+ }
381
+ $self.jqGrid("footerData", "set", footer);
382
+ return footer;
383
+ }
384
+
385
+ /**
386
+ * Syncron Alias grid_percent_on
387
+ @alias module:Jqgrid_utils
388
+ */
389
+ _grid_percent_on(grid, obj) {
390
+ return grid_percent_on(grid, obj);
391
+ }
392
+
393
+ /**
394
+ * Percent the columns values together
395
+ @alias module:Jqgrid_utils
396
+ @param {object} - Grid Object (required)
397
+ @param {string} - Column/Field Name to sum
398
+ @example
399
+ var jqu = new Jqgrid_utils({page:page});
400
+ gridComplete: function () {
401
+ jqu._jqu._grid_sum_on(this, [
402
+ "qty_icollect",
403
+ "qty_ordered",
404
+ "need_for_qty_ordered",
405
+ "wait_icollect",
406
+ ]);
407
+ },
408
+ */
409
+ async grid_percent_on(grid, obj) {
410
+ let $self = jQuery(grid);
411
+ let rows = $self.jqGrid("getGridParam", "data");
412
+ let footer_sum = {};
413
+ let id = obj["id"] ? obj["id"] : "invate";
414
+ footer[id] = "Total";
415
+ let total = obj["total"];
416
+ let sums = JSON.parse(JSON.stringify(obj["percent"]));
417
+ sums.push(total);
418
+ for (let i in sums) {
419
+ let field = sums[i];
420
+ let sum = 0;
421
+ let _rows = 0;
422
+ for (let r in rows) {
423
+ if (rows[r].hasOwnProperty(field)) {
424
+ let val = rows[r][field];
425
+ if (typeof val === "string") {
426
+ if (is_digit(val)) {
427
+ val = parseFloat(val);
428
+ sum += val;
429
+ _rows++;
430
+ }
431
+ } else {
432
+ sum += val;
433
+ _rows++;
434
+ }
435
+ }
436
+ }
437
+ footer_sum[field] = sum;
438
+ }
439
+
440
+ for (let i in sums) {
441
+ let field = sums[i];
442
+ let percent = footer_sum[field] / (footer_sum[total] / 100);
443
+ percent = percent.toFixed(2);
444
+ footer[field] = percent + "%";
445
+ }
446
+ $self.jqGrid("footerData", "set", footer);
447
+ }
448
+
449
+ /**
450
+ * Takes the updated columns data and send it to your API post server
451
+ * loadComplete: async function() for the old record needs to be called, see example !
452
+ @alias module:Jqgrid_utils
453
+ @param {object} - Grid Object (required)
454
+ @param {string} - API URL like https://foo.com (required)
455
+ @param {array} - id list, ids from the column header (required)
456
+ @param {object} - settings - extra key:value to send to your server
457
+
458
+ @example
459
+ var jqu = new Jqgrid_utils({page:page});
460
+
461
+ ....},
462
+ loadComplete: async function()
463
+ {
464
+ $grid.jqGrid('setGridParam',{record_data:$grid.jqGrid("getGridParam").data});
465
+ },
466
+ afterSetRow: async function(row)
467
+ {
468
+ const _api = await get_api_url('sapir');
469
+ const api = _api + '/column2';
470
+ let info = {"msg":"failed"};
471
+ var jqu = new Jqgrid_utils();
472
+ info = await jqu.update_row_to_api($grid, api,['id'],row,{server : '232',db : 'sl_h',table : 'kpi',});
473
+ for(let i in info)
474
+ {
475
+ log.info(info[i]);
476
+ }
477
+ },
478
+ */
479
+
480
+ async update_row_to_api(_self, api = "", _ids = ["id"], row = {}, data) {
481
+ let self = this;
482
+ let infos = [];
483
+ let ids = {};
484
+ let values = {};
485
+ let changed = {};
486
+ const rd = _self.jqGrid("getGridParam", "record_data");
487
+
488
+ if (
489
+ api != "" &&
490
+ Object.keys(row).length > 0 &&
491
+ row.inputData.oper == "edit"
492
+ ) {
493
+ for (let i in rd) {
494
+ if (rd[i]["id"] === row.rowid) {
495
+ for (let ii in _ids) {
496
+ if (rd[i].hasOwnProperty(_ids[ii])) {
497
+ ids[_ids[ii]] = rd[i][_ids[ii]];
498
+ }
499
+ }
500
+
501
+ for (let iii in row.inputData) {
502
+ if (iii != "oper") {
503
+ if (Object.keys(ids).indexOf(iii) < 0) {
504
+ //console.log(iii);
505
+ //console.log(row.inputData[iii]);
506
+ //console.log(rd[i][iii]);
507
+ if (row.inputData[iii] != rd[i][iii]) {
508
+ changed[iii] = row.inputData[iii];
509
+ }
510
+ }
511
+ }
512
+ }
513
+ }
514
+ }
515
+
516
+ for (let i in changed) {
517
+ if (Object.keys(ids).indexOf(i) < 0 && i != "oper") {
518
+ const col_name = i;
519
+ let col_value = {};
520
+ col_value[col_name] = changed[i];
521
+ data["ids"] = ids;
522
+ data["values"] = col_value;
523
+ data["operator"] = "edit";
524
+ //console.log(data)
525
+ const info = await self.post_json(api, JSON.stringify(data));
526
+ infos.push(info);
527
+ }
528
+ }
529
+ } else if (
530
+ api != "" &&
531
+ Object.keys(row).length > 0 &&
532
+ row.inputData.oper == "add"
533
+ ) {
534
+ //console.log("...add");
535
+ for (let i in row.inputData) {
536
+ if (row.inputData[i] && i != "id" && i != "oper") {
537
+ values[i] = row.inputData[i];
538
+ }
539
+ }
540
+ data["ids"] = ids;
541
+ data["values"] = values;
542
+ data["operator"] = "add";
543
+ //console.log(data);
544
+ let info = await self.post_json(api, JSON.stringify(data));
545
+ infos.push(info);
546
+ }
547
+
548
+ return infos;
549
+ }
550
+
551
+ /**
552
+ * After Delete a Grid Row send to and DELETE REST Request
553
+ * You need to define loadComplete and afterDelRow
554
+ * The Grid data needs to be saved as record within loadComplete
555
+ @alias module:Jqgrid_utils
556
+ @param {object} - Grid Object (required)
557
+ @param {string} - API URL like https://foo.com (required)
558
+ @param {string} - the row id value from afterDelRow (required)
559
+ @param {array} - id list, ids from the column header colmodel (required)
560
+ @param {object} - settings - extra key:value to send to your server
561
+ @example
562
+
563
+ loadComplete: async function()
564
+ {
565
+ $grid.jqGrid('setGridParam',{record_data:$grid.jqGrid("getGridParam").data});
566
+ },
567
+ afterDelRow: async function(rowid)
568
+ {
569
+ const _api = await get_api_url('sapir');
570
+ const api = _api + '/column2';
571
+ let info = {"msg":"failed"};
572
+ var jqu = new Jqgrid_utils();
573
+
574
+ info = await jqu.delete_row_to_api($grid,api,rowid,['id'],{
575
+ server : '232',
576
+ db : 'sl_h',
577
+ table : 'kpi',
578
+ operator: 'delete',
579
+ });
580
+ log.info(JSON.parse(info).msg);
581
+ },
582
+
583
+
584
+
585
+
586
+
587
+ */
588
+
589
+ async delete_row_to_api(_self, api = "", rowid, _ids = [], data = {}) {
590
+ let info = { msg: "failed" };
591
+ let self = this;
592
+ let ids = [];
593
+ let values = {};
594
+ const rd = _self.jqGrid("getGridParam", "record_data");
595
+ for (let i in rd) {
596
+ if (rd[i]["id"] === rowid) {
597
+ for (let ii in _ids) {
598
+ if (rd[i].hasOwnProperty(_ids[ii])) {
599
+ values[_ids[ii]] = rd[i][_ids[ii]];
600
+ ids.push(_ids[ii]);
601
+ }
602
+ }
603
+ break;
604
+ }
605
+ }
606
+
607
+ if (api != "" && Object.keys(values).length == ids.length) {
608
+ data["ids"] = ids;
609
+ data["values"] = values;
610
+ //console.log(data);
611
+ info = await self.adelete_api(api, JSON.stringify(data));
612
+ }
613
+ return info;
614
+ }
615
+
616
+ /**
617
+ *Append and sperator based link column to the end of a row
618
+ @alias module:Jqgrid_utils
619
+ @param {object} - col_model of the grid
620
+ @param {string} - URL string
621
+ @param {string} - field value - the visible text of the anchor
622
+ @param {object} - base row key value - like {"name":'wiki','label':"Wiki"}
623
+ @param {string} - URL Attributes
624
+ @param {object} - keys and fields value to use
625
+ @example
626
+ var jqu = new Jqgrid_utils();
627
+ col_model = await jqu.append_seperator_link_column(col_model, 'http://wiki.foo.com/index.php' ,'Wiki',{"name":'wiki','label':"Wiki","width":"65px","align":"center"} ,'target="_blank"',{"report_central":"name"});
628
+
629
+ */
630
+
631
+ async append_seperator_link_column(
632
+ col_model,
633
+ url,
634
+ field_value,
635
+ base,
636
+ attr = "",
637
+ keys,
638
+ ) {
639
+ url = url + "/";
640
+ let self = this;
641
+ base["formatter"] = function (cell_val, obj) {
642
+ let _cell_val = field_value;
643
+ if (typeof keys === "object") {
644
+ let pref = "";
645
+ for (let i in keys) {
646
+ let key = i;
647
+ let v = keys[i];
648
+ let key_val = obj.rowData[v];
649
+ if (key_val) {
650
+ if (key_val) {
651
+ if (key != "") {
652
+ pref += key + "" + "/" + encodeURIComponent(key_val) + "/";
653
+ } else {
654
+ pref += encodeURIComponent(key_val);
655
+ }
656
+ }
657
+ }
658
+ }
659
+ if (pref) {
660
+ if (pref.slice(-1) === "&" || pref.slice(-1) === "/") {
661
+ pref = pref.slice(0, -1);
662
+ }
663
+ cell_val =
664
+ "<a " + attr + 'href="' + url + pref + '"> ' + _cell_val + "</a>";
665
+ }
666
+ }
667
+
668
+ return cell_val;
669
+ };
670
+
671
+ col_model.push(base);
672
+
673
+ return col_model;
674
+ }
675
+
676
+ /**
677
+ * add textarea
678
+ @alias module:Jqgrid_utils
679
+ @param {object} - edittype like
680
+ @example
681
+ let col_model = JSON.parse(await aget_api(url + "/model"));
682
+ col_model = await jqu.add_edit(col_model, 'mon',{ edittype:'textarea', editoptions:{rows:6,cols:100} });
683
+ see for other inputfields:
684
+ http://www.trirand.com/blog/phpjqgrid/doc/_2v80w6oam.htm
685
+ */
686
+ async add_edit(col_model, edit_field, edittype, editoptions) {
687
+ for (let i = 0; i < col_model.length; i++) {
688
+ if (col_model[i]["name"] === edit_field) {
689
+ Object.assign(col_model[i], edittype);
690
+ Object.assign(col_model[i], editoptions);
691
+ }
692
+ }
693
+ return col_model;
694
+ }
695
+
696
+ /**
697
+ * add textarea
698
+ @alias module:Jqgrid_utils
699
+ @param {string} - edit_filed
700
+ @param {string} - style of the textaread
701
+ @example
702
+ let col_model = JSON.parse(await aget_api(url + "/model"));
703
+ col_model = await jqu.add_textarea(col_model, 'worker','style="width:100%;height:100px"');
704
+ */
705
+ async add_textarea(
706
+ col_model,
707
+ edit_field,
708
+ style = 'style="width:100%;height:100px"',
709
+ ) {
710
+ for (let i = 0; i < col_model.length; i++) {
711
+ if (col_model[i]["name"] === edit_field) {
712
+ col_model[i]["formatter"] = function (cell_val) {
713
+ const txt = "<textarea " + style + ">" + cell_val + "</textarea>";
714
+ return txt;
715
+ };
716
+ }
717
+ }
718
+ return col_model;
719
+ }
720
+
721
+ /**
722
+ * Get basic colModel data from raw data
723
+ @alias module:Jqgrid_utils
724
+ @param {array} - grid object
725
+ @param {array} - raw data object from loadComplete
726
+ @param {array} - list of columns to exclude (optional)
727
+ @param {array} - existing colModel (optional)
728
+ @returns {array} - col_model
729
+ @example
730
+ var jqu = new Jqgrid_utils();
731
+ ,loadComplete: async function(data)
732
+ {
733
+ let col_model = jQuery(this).jqGrid('getGridParam',"colModel");
734
+ const new_col_model= await update_col_model(this, data, ['id','cust_qty','waiting_supplier_orders','waiting_assemblies','pending_components','pending_customer_order',col_model);
735
+ jQuery(this).jqGrid('setGridParam',{colModel:new_col_model});
736
+ },
737
+ */
738
+ async get_col_model_from_data(obj, data, exclude = [], col_model = []) {
739
+ let cols = [];
740
+ for (let i in data) {
741
+ const keys = Object.keys(data[i]);
742
+ for (let ii in keys) {
743
+ const key = keys[ii];
744
+ cols.push(key);
745
+ }
746
+ }
747
+ cols = cols.filter((item, pos) => cols.indexOf(item) === pos);
748
+ let mcols = [];
749
+ for (let i in col_model) {
750
+ mcols.push(col_model[i]["name"]);
751
+ }
752
+
753
+ let diff = cols.filter((x) => !mcols.includes(x));
754
+ const _exclude = new Set(exclude);
755
+ diff = diff.filter((name) => {
756
+ return !_exclude.has(name);
757
+ });
758
+ diff.sort();
759
+
760
+ for (let x = 0; x < diff.length; x++) {
761
+ col_model.push({ name: diff[x], label: diff[x] });
762
+ }
763
+ //console.log(col_model);
764
+ return col_model;
765
+ }
766
+
767
+ /**
768
+ * Replace a Binaery 0 or 1 to other given value
769
+ @alias module:Jqgrid_utils
770
+ @param {string} - cell value
771
+ @param {string} - string replacement for 0
772
+ @param {string} - string replacement for 1
773
+ @example
774
+ var jqu = new Jqgrid_utils();
775
+ let _data = jqu.binery_replace(0,'zero','one');
776
+ or for column formatter
777
+ download_formatter:"var jqu = new Jqgrid_utils();jqu.binary_replace({0},'zero','one')"});
778
+ */
779
+ binary_replace(cell_value, a = "zero", b = "one") {
780
+ let value = a;
781
+ if (cell_value == 1 || cell_value == 0) {
782
+ if (cell_value == 1) {
783
+ value = b;
784
+ }
785
+ }
786
+ return value;
787
+ }
788
+
789
+ /**
790
+ * Convert a 112 date string to a DMY format with sepertaor - sync function
791
+ @alias module:Jqgrid_utils
792
+ @param {string} - date string
793
+ @param {string} - seperator used
794
+ @example
795
+ var jqu = new Jqgrid_utils();
796
+ let _data = jqu._date112_to_DMY('20220104','/');
797
+ console.log(_data);
798
+ */
799
+ _date112_to_DMY(cell_value, seperator = "/") {
800
+ let value = cell_value;
801
+ if (cell_value.length >= 8 && cell_value.indexOf(seperator) === -1) {
802
+ let a = [];
803
+ a.push(cell_value.substr(6, 2));
804
+ a.push(cell_value.substr(4, 2));
805
+ a.push(cell_value.substr(0, 4));
806
+ value = a.join(seperator);
807
+ }
808
+ return value;
809
+ }
810
+
811
+ /**
812
+ * Convert a 112 date to a DMY format with sepertaor
813
+ @alias module:Jqgrid_utils
814
+ @param {object} - col_model of the grid
815
+ @param {string} - name of the date 112 column what should get converted
816
+ @param {string} - seperator used
817
+ @example
818
+ var jqu = new Jqgrid_utils();
819
+ let _data = await jqu.date112_to_DMY(this,'field','/');
820
+ console.log(_data);
821
+ */
822
+ async date112_to_DMY(col_model, edit_field, seperator = "/") {
823
+ for (let i = 0; i < col_model.length; i++) {
824
+ if (col_model[i]["name"] === edit_field) {
825
+ col_model[i]["formatter"] = function (cell_value, o) {
826
+ if (cell_value) {
827
+ cell_value = cell_value.toString();
828
+ let value = cell_value;
829
+ if (
830
+ cell_value.length >= 8 &&
831
+ cell_value.indexOf(seperator) === -1
832
+ ) {
833
+ let a = [];
834
+ a.push(cell_value.substr(6, 2));
835
+ a.push(cell_value.substr(4, 2));
836
+ a.push(cell_value.substr(0, 4));
837
+ value = a.join(seperator);
838
+ }
839
+ return value;
840
+ } else {
841
+ return cell_value;
842
+ }
843
+ };
844
+ }
845
+ }
846
+ return col_model;
847
+ }
848
+
849
+ /**
850
+ * Add Formatter
851
+ @alias module:Jqgrid_utils
852
+ @param {array} - grid col_model
853
+ @param {string} - string columns names what will be formatted
854
+ @param {object} - formatter object like { formatter: "select", formatoptions: {value: "1:ok;0:fail", defaultValue: "1" }}
855
+ @example
856
+ var jqu = new Jqgrid_utils();
857
+ col_model = await jqu.add_formatter(col_model,'select',{ formatter: "select", formatoptions: {value: "1:ok;0:fail", defaultValue: "1" }})
858
+ */
859
+
860
+ async add_formatter(col_model, edit_field, formatter) {
861
+ for (let i = 0; i < col_model.length; i++) {
862
+ if (col_model[i]["name"] === edit_field) {
863
+ if (
864
+ formatter.hasOwnProperty("formatter") &&
865
+ formatter.hasOwnProperty("formatoptions")
866
+ ) {
867
+ col_model[i]["formatter"] = formatter["formatter"];
868
+ col_model[i]["formatoptions"] = formatter["formatoptions"];
869
+ col_model[i]["edittype"] = formatter["formatter"];
870
+ col_model[i]["editoptions"] = formatter["formatoptions"];
871
+ }
872
+ }
873
+ }
874
+ return col_model;
875
+ }
876
+
877
+ /**
878
+ * Natural Sort Column
879
+ @alias module:Jqgrid_utils
880
+ @param {array} - grid col_model
881
+ @param {string} - string columns names for natural sorting
882
+ @returns {array} - col_model
883
+ @example
884
+ var jqu = new Jqgrid_utils();
885
+ col_model = await jqu.natural_sort(col_model,'colunmename');
886
+ */
887
+
888
+ async natural_sort(col_model, column_name) {
889
+ for (let i = 0; i < col_model.length; i++) {
890
+ if (col_model[i]["name"] === column_name) {
891
+ col_model[i]["sortfunc"] = function (a, b, d) {
892
+ if (d === undefined) {
893
+ d = 1;
894
+ }
895
+ var re =
896
+ /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
897
+ sre = /(^[ ]*|[ ]*$)/g,
898
+ dre =
899
+ /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
900
+ hre = /^0x[0-9a-f]+$/i,
901
+ ore = /^0/,
902
+ i = function (s) {
903
+ return (self.insensitive && ("" + s).toLowerCase()) || "" + s;
904
+ },
905
+ // convert all to strings strip whitespace
906
+ x = i(a).replace(sre, "") || "",
907
+ y = i(b).replace(sre, "") || "",
908
+ // chunk/tokenize
909
+ xN = x
910
+ .replace(re, "\0$1\0")
911
+ .replace(/\0$/, "")
912
+ .replace(/^\0/, "")
913
+ .split("\0"),
914
+ yN = y
915
+ .replace(re, "\0$1\0")
916
+ .replace(/\0$/, "")
917
+ .replace(/^\0/, "")
918
+ .split("\0"),
919
+ // numeric, hex or date detection
920
+ xD =
921
+ parseInt(x.match(hre)) ||
922
+ (xN.length != 1 && x.match(dre) && Date.parse(x)),
923
+ yD =
924
+ parseInt(y.match(hre)) ||
925
+ (xD && y.match(dre) && Date.parse(y)) ||
926
+ null,
927
+ oFxNcL,
928
+ oFyNcL;
929
+ // first try and sort Hex codes or Dates
930
+ if (yD)
931
+ if (xD < yD) return -d;
932
+ else if (xD > yD) return d;
933
+ // natural sorting through split numeric strings and default strings
934
+ for (
935
+ var cLoc = 0, numS = Math.max(xN.length, yN.length);
936
+ cLoc < numS;
937
+ cLoc++
938
+ ) {
939
+ // find floats not starting with '0', string or 0 if not defined (Clint Priest)
940
+ oFxNcL =
941
+ (!(xN[cLoc] || "").match(ore) && parseFloat(xN[cLoc])) ||
942
+ xN[cLoc] ||
943
+ 0;
944
+ oFyNcL =
945
+ (!(yN[cLoc] || "").match(ore) && parseFloat(yN[cLoc])) ||
946
+ yN[cLoc] ||
947
+ 0;
948
+ // handle numeric vs string comparison - number < string - (Kyle Adams)
949
+ if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
950
+ return isNaN(oFxNcL) ? d : -d;
951
+ }
952
+ // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
953
+ else if (typeof oFxNcL !== typeof oFyNcL) {
954
+ oFxNcL += "";
955
+ oFyNcL += "";
956
+ }
957
+ if (oFxNcL < oFyNcL) return -d;
958
+ if (oFxNcL > oFyNcL) return d;
959
+ }
960
+ return 0;
961
+ };
962
+ }
963
+ }
964
+ return col_model;
965
+ }
966
+
967
+ /**
968
+ * Add HTML Formatter
969
+ @alias module:Jqgrid_utils
970
+ @param {array} - grid col_model
971
+ @param {string} - string columns names what will be converted to ok buttons
972
+ @param {string} - html tag code
973
+ @returns {array} - col_model
974
+ @example
975
+ var jqu = new Jqgrid_utils();
976
+ col_model = await jqu.add_html_formatter(col_model,'process',"<button tabindex='0' class='cellbtn' type='button'>Process</button>");
977
+ */
978
+
979
+ async add_html_formatter(col_model, edit_field, html) {
980
+ for (let i = 0; i < col_model.length; i++) {
981
+ if (col_model[i]["name"] === edit_field) {
982
+ col_model[i]["formatter"] = function (cell_val, o) {
983
+ return html;
984
+ };
985
+ }
986
+ }
987
+ return col_model;
988
+ }
989
+
990
+ /**
991
+ * Add an OK Button
992
+ @alias module:Jqgrid_utils
993
+ @param {array} - grid col_model
994
+ @param {array} - list of columns names what will be converted to ok buttons
995
+ @returns {array} - col_model
996
+ @example
997
+ var jqu = new Jqgrid_utils();
998
+ col_model = await jqu.add_ok_button(col_model, ['checked']);
999
+ */
1000
+
1001
+ async add_ok_button(col_model, fields) {
1002
+ let self = this;
1003
+ for (let i = 0; i < col_model.length; i++) {
1004
+ if (fields.indexOf(col_model[i]["name"]) > -1) {
1005
+ col_model[i]["formatter"] = function (cell_val) {
1006
+ if (cell_val != undefined) {
1007
+ return self.__cell_format(cell_val, "format_ok");
1008
+ } else {
1009
+ return "";
1010
+ }
1011
+ };
1012
+ }
1013
+ }
1014
+ return col_model;
1015
+ }
1016
+
1017
+ /**
1018
+ * Get the filled cell data
1019
+ @alias module:Jqgrid_utils
1020
+ @param {object} - the grid object or its name
1021
+ @param {array} - list of columns names what will be collected
1022
+ @returns {array} - table array
1023
+ @example
1024
+ var jqu = new Jqgrid_utils();
1025
+ col_model = await jqu.get_filled_cell_table_dat("#gridname","fieldname");
1026
+
1027
+ */
1028
+ async get_filled_cell_table_data(_grid, fields = []) {
1029
+ let d = jQuery(_grid).jqGrid("getGridParam", "data");
1030
+ let keys = fields;
1031
+ let _data = [];
1032
+ for (let i in d) {
1033
+ if (d[i].hasOwnProperty("id")) {
1034
+ let row = [d[i]["id"]];
1035
+ for (let x in keys) {
1036
+ if (d[i].hasOwnProperty(keys[x])) {
1037
+ row.push(d[i][keys[x]]);
1038
+ } else {
1039
+ row.push("");
1040
+ }
1041
+ }
1042
+ var f = row.filter(function (value, index, arr) {
1043
+ return value !== "";
1044
+ });
1045
+ if (Object.keys(f).length > 1) {
1046
+ _data.push(row);
1047
+ }
1048
+ }
1049
+ }
1050
+ return _data;
1051
+ }
1052
+
1053
+ /**
1054
+ * Get the filled cell data
1055
+ @alias module:Jqgrid_utils
1056
+ @param {object} - the grid object or its name
1057
+ @param {array} - list of columns names what will be collected
1058
+ @returns {object} - json object of the colleted fields
1059
+ @example
1060
+ var jqu = new Jqgrid_utils();
1061
+ let _data = await jqu.get_filled_cell_data(this,["P-","bulk","wholesale"]);
1062
+ */
1063
+
1064
+ async get_filled_cell_data(_grid, fields = []) {
1065
+ let d = jQuery(_grid).jqGrid("getGridParam", "data");
1066
+ let keys = fields;
1067
+ let _data = [];
1068
+ for (let i in d) {
1069
+ if (d[i].hasOwnProperty("id")) {
1070
+ let row = { id: d[i]["id"] };
1071
+ for (let x in keys) {
1072
+ if (d[i].hasOwnProperty(keys[x])) {
1073
+ if (d[i][keys[x]] != "") {
1074
+ row[keys[x]] = d[i][keys[x]];
1075
+ }
1076
+ }
1077
+ }
1078
+ if (Object.keys(row).length > 1) {
1079
+ _data.push(row);
1080
+ }
1081
+ }
1082
+ }
1083
+ return _data;
1084
+ }
1085
+
1086
+ /**
1087
+ * Add an URL from the data to a specific cell/column
1088
+ @alias module:Jqgrid_utils
1089
+ @param {object} - col_model of the grid
1090
+ @param {string} - name of the column what should get convert to the url
1091
+ @param {string} - the used url of the data
1092
+ @returns {object} https://foo.bar.com/av0_code/bar
1093
+ @example
1094
+ var jqu = new Jqgrid_utils();
1095
+ col_model = await jqu.set_link(col_model,'field_get_url','field_with_the_url','target="blank"');
1096
+ console.log(_data);
1097
+ */
1098
+ async set_link(col_model, edit_field, url, attr = "") {
1099
+ for (let i = 0; i < col_model.length; i++) {
1100
+ if (col_model[i]["name"] === edit_field) {
1101
+ col_model[i]["formatter"] = function (cell_val, o) {
1102
+ return (
1103
+ '<a class="gl" ' +
1104
+ attr +
1105
+ 'href="' +
1106
+ o.rowData[url] +
1107
+ '">' +
1108
+ cell_val +
1109
+ "</a>"
1110
+ );
1111
+ };
1112
+ }
1113
+ }
1114
+ return col_model;
1115
+ }
1116
+
1117
+ /**
1118
+ * Hide all columns execpt column
1119
+ * @alias module:Jqgrid_utils
1120
+ * @param {object} - col_model of the grid
1121
+ * @param {array} - array of names to not to hide
1122
+ * @returns {object} col_model
1123
+ * @example
1124
+ col_model = await jqu.hide_all_columns_except(col_model,['supplier','customer']);
1125
+ */
1126
+ async hide_all_columns_except(col_model, fields) {
1127
+ for (let i = 0; i < col_model.length; i++) {
1128
+ if (fields.indexOf(col_model[i]["name"]) > -1) {
1129
+ col_model[i]["hidden"] = false;
1130
+ } else {
1131
+ col_model[i]["hidden"] = true;
1132
+ }
1133
+ }
1134
+ return col_model;
1135
+ }
1136
+
1137
+ /**
1138
+ * Hide a col_model column before load the grid
1139
+ * @alias module:Jqgrid_utils
1140
+ * @param {object} - col_model of the grid
1141
+ * @param {string} - name of the column to hide
1142
+ * @returns {object} col_model
1143
+ * @example
1144
+ col_model = await jqu.hide_column(col_model,'wholesale');
1145
+ col_model = await jqu.hide_column(col_model,'wholesale_formula');
1146
+ */
1147
+ async hide_column(col_model, field) {
1148
+ for (let i = 0; i < col_model.length; i++) {
1149
+ if (col_model[i]["name"] === field) {
1150
+ col_model[i]["hidden"] = true;
1151
+ }
1152
+ }
1153
+ return col_model;
1154
+ }
1155
+
1156
+ /**
1157
+ @alias module:Jqgrid_utils
1158
+ @param {object} - gridobject;
1159
+ @param {object} - grid data (optional);
1160
+ @example
1161
+ var jqu = new Jqgrid_utils();
1162
+ loadComplete: function(){
1163
+ jqu.grid_set_caption(this);
1164
+ },
1165
+ */
1166
+
1167
+ s_grid_set_caption(_grid, data = []) {
1168
+ this.grid_set_captionn(_grid, (data = []));
1169
+ }
1170
+
1171
+ /**
1172
+ Adding the row count number to the caption
1173
+ @alias module:Jqgrid_utils
1174
+ @param {object} - gridobject;
1175
+ @param {object} - grid data (optional);
1176
+ @example
1177
+ var jqu = new Jqgrid_utils();
1178
+ loadComplete: function(){
1179
+ await jqu.grid_set_caption(this);
1180
+ },
1181
+ */
1182
+ async grid_set_caption(_grid, data = []) {
1183
+ if (_grid) {
1184
+ const grid = jQuery(_grid);
1185
+ let count = 0;
1186
+ if (data.length === 0) {
1187
+ count = grid.jqGrid("getGridParam", "records");
1188
+ } else {
1189
+ count = data.length;
1190
+ }
1191
+ let caption = grid.jqGrid("getGridParam", "caption");
1192
+ const reg = /\d.*x/;
1193
+ const new_caption = caption.replace(reg, "");
1194
+ grid.jqGrid("setCaption", new_caption + " " + count + "x");
1195
+ }
1196
+ }
1197
+
1198
+ /**
1199
+ @alias module:Jqgrid_utils
1200
+ @param {object} - the col_model of the grid
1201
+ @param {string} - the name of the page(optional)
1202
+ @param {object} - the grid objec(optional)
1203
+ @example
1204
+ col_model = await jqu.resize_saved_cell_width(col_model);
1205
+ */
1206
+ s_resize_saved_cell_width(col_model, page = false, grid = false) {
1207
+ this.grid_set_caption(col_model, page, grid);
1208
+ }
1209
+
1210
+ /**
1211
+ @alias module:Jqgrid_utils
1212
+ @param {object} - the col_model of the grid
1213
+ @param {string} - the name of the page(optional)
1214
+ @param {object} - the grid objec(optional)
1215
+ @example
1216
+ col_model = await jqu.resize_saved_cell_width(col_model);
1217
+ */
1218
+ async resize_saved_cell_width(col_model, page = false, grid = false) {
1219
+ let key = page ? page : this.page;
1220
+ key += grid ? "-" + grid + "-w-" : "-grid-w-";
1221
+ for (let x = 0; x <= col_model.length; x++) {
1222
+ if (col_model[x]) {
1223
+ if (col_model[x]["name"]) {
1224
+ const name = col_model[x]["name"];
1225
+ const width = localStorage.getItem(key + name);
1226
+ if (width) {
1227
+ col_model[x]["width"] = width;
1228
+ }
1229
+ }
1230
+ }
1231
+ }
1232
+ return col_model;
1233
+ }
1234
+
1235
+ /**
1236
+ @alias module:Jqgrid_utils
1237
+ @param {string} the width of the resized column
1238
+ @param {string} column number what get resized
1239
+ @param {string} not in use yet
1240
+ @example
1241
+ * var jqu = new Jqgrid_utils({page:'mypage'});
1242
+ * resizeStop: jqu.resize_cell,
1243
+ */
1244
+ resize_cell(width, index, _page = false) {
1245
+ const col_model = jQuery(this).jqGrid("getGridParam", "colModel");
1246
+ if (col_model[index]) {
1247
+ if (col_model[index]["name"]) {
1248
+ const name = col_model[index]["name"];
1249
+ const page = _page ? _page : localStorage.getItem("page");
1250
+ const grid = this.id;
1251
+ let key = page + "-" + grid + "-w-" + name;
1252
+ localStorage.setItem(key, width);
1253
+ const cat = localStorage.getItem(key);
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ /**
1259
+ * Upsert(insert or update) from the grid to an API
1260
+ @alias module:Jqgrid_utils
1261
+ @param {object} - row object
1262
+ @param {string} - url of the API
1263
+ @param {string} - data oject
1264
+ @returns {object} {update: 'ok'} or {update: 'failed'}
1265
+ @example
1266
+ var jqu = new Jqgrid_utils();
1267
+ afterSetRow: async function(row)
1268
+ {
1269
+ let r = await jqu.upsert_row(row, 'http://api.com',{'key':'value'});
1270
+ console.log(r);
1271
+ },
1272
+ */
1273
+ async upsert_row(row, url, req = {}) {
1274
+ if (row.rowid.startsWith("jqg")) {
1275
+ const r0 = await this.insert_row(row, url);
1276
+ return r0;
1277
+ } else {
1278
+ const r1 = await this.update_row(row, url);
1279
+ return r1;
1280
+ }
1281
+ }
1282
+
1283
+ /**
1284
+ * Insert from the grid to an API used by the upsert_row function
1285
+ @alias module:Jqgrid_utils
1286
+ @param {object} - row object
1287
+ @param {string} - URL of the API
1288
+ @returns {object} Object from the the API like {update: 'ok'} or {update: 'failed'}
1289
+ @example
1290
+ var jqu = new Jqgrid_utils();
1291
+ afterSetRow: async function(row)
1292
+ {
1293
+ let r = await jqu.insert_row(row, 'http://api.com');
1294
+ console.log(r);
1295
+ },
1296
+ */
1297
+ async insert_row(row, url) {
1298
+ let req = {};
1299
+ let ret = "";
1300
+ if (row.inputData.hasOwnProperty("id")) {
1301
+ req["_id"] = "id";
1302
+ req["_id_val"] = row.inputData["id"];
1303
+ for (let i in row.inputData) {
1304
+ req[i] = row.inputData[i];
1305
+ }
1306
+ delete req["id"];
1307
+ delete req["oper"];
1308
+ //console.log(req);
1309
+ ret = await this.put_json(url, JSON.stringify(req));
1310
+ }
1311
+ return ret;
1312
+ }
1313
+
1314
+ /**
1315
+ * Update from the grid to an API used by the upsert_row function
1316
+ @alias module:Jqgrid_utils
1317
+ @param {object} - row object
1318
+ @param {string} - url of the API
1319
+ @param {string} - data oject
1320
+ @returns {object} Object from the the API like {update: 'ok'} or {update: 'failed'}
1321
+ @example
1322
+ var jqu = new Jqgrid_utils();
1323
+ afterSetRow: async function(row)
1324
+ {
1325
+ let r = await jqu.update_row(row, 'http://api.com',{'key':value});
1326
+ console.log(r);
1327
+ },
1328
+ */
1329
+
1330
+ async update_row(row, url, req = {}) {
1331
+ let ret = "";
1332
+ {
1333
+ if (!req["_id"]) {
1334
+ req["_id"] = "id";
1335
+ }
1336
+ req["_id_val"] = row.inputData["id"];
1337
+ for (let i in row.inputData) {
1338
+ req[i] = row.inputData[i];
1339
+ }
1340
+ delete req["id"];
1341
+ delete req["oper"];
1342
+ ret = await this.post_json(url, JSON.stringify(req));
1343
+ }
1344
+ return ret;
1345
+ }
1346
+
1347
+ /**
1348
+ * Delete from the grid to an API
1349
+ @alias module:Jqgrid_utils
1350
+ @param {string} - row id
1351
+ @param {string} - url of the API
1352
+ @returns {object} @returns {object} Object from the the API like {delete: 'ok'} or {delete: 'failed'}
1353
+ @example
1354
+ var jqu = new Jqgrid_utils();
1355
+ afterDelRow: async function(row)
1356
+ {
1357
+ const r = await jqu.delete_row('id', 'http://api.com');
1358
+ console.log(r + ' : ' + row + ' - from API');
1359
+ },
1360
+ */
1361
+
1362
+ async delete_row(_id, url) {
1363
+ let ret = "";
1364
+ if (url.indexOf("?") > -1) {
1365
+ url += "&_id=" + encodeURIComponent(unescape(_id));
1366
+ } else {
1367
+ url += "?_id=" + encodeURIComponent(unescape(_id));
1368
+ }
1369
+
1370
+ ret = JSON.parse(await this.adelete_api(url));
1371
+ return ret["message"];
1372
+ }
1373
+
1374
+ /**
1375
+ * Async Delete request used by function delete_row
1376
+ @alias module:Jqgrid_utils
1377
+ @param {string} - url of the API
1378
+ @param {boalan} - header should be json type? default form type
1379
+ @returns {object} @returns {object} Object from the the API like {delete: 'ok'} or {delete: 'failed'}
1380
+ @example
1381
+ var jqu = new Jqgrid_utils();
1382
+ afterDelRow: async function(row)
1383
+ {
1384
+ ret = JSON.parse(await jqu.adelete_api(url));
1385
+ },
1386
+ */
1387
+
1388
+ async adelete_api(url, json = false) {
1389
+ let ctype = "application/x-www-form-urlencoded";
1390
+ let body = null;
1391
+ if (json) {
1392
+ ctype = "application/json;charset=UTF-8";
1393
+ body = json;
1394
+ }
1395
+ return new Promise((resolve, reject) => {
1396
+ let xhr = new XMLHttpRequest();
1397
+ xhr.open("DELETE", url);
1398
+ xhr.setRequestHeader("Content-type", ctype);
1399
+ xhr.onload = () => resolve(xhr.responseText);
1400
+ xhr.onerror = () => reject(xhr.statusText);
1401
+ xhr.send(body);
1402
+ });
1403
+ }
1404
+
1405
+ /**
1406
+ * Async Post request used by the update_row function
1407
+ @alias module:Jqgrid_utils
1408
+ @param {string} - url of the API
1409
+ @param {object} - json object
1410
+ @returns {object} @returns {object} Object from the the API like {update: 'ok'} or {update: 'failed'}
1411
+ @example
1412
+ var jqu = new Jqgrid_utils();
1413
+ ret = JSON.parse(await jqu.post_json(url,{'key':value,'key2':'value'}));
1414
+ */
1415
+
1416
+ async post_json(url, data) {
1417
+ return new Promise((resolve, reject) => {
1418
+ let xhr = new XMLHttpRequest();
1419
+ xhr.open("POST", url);
1420
+ xhr.setRequestHeader("Content-type", "application/json");
1421
+ xhr.onload = () => resolve(xhr.responseText);
1422
+ xhr.onerror = () => reject(xhr.statusText);
1423
+ xhr.send(data);
1424
+ });
1425
+ }
1426
+
1427
+ /**
1428
+ * Async Put request used by the insert_row function
1429
+ @alias module:Jqgrid_utils
1430
+ @param {string} - url of the API
1431
+ @param {object} - json object
1432
+ @returns {object} @returns {object} Object from the the API like {insert: 'ok'} or {insert: 'failed'}
1433
+ @example
1434
+ var jqu = new Jqgrid_utils();
1435
+ ret = JSON.parse(await jqu.put_json(url,{'key':value,'key2':'value2'}));
1436
+ */
1437
+ async put_json(url, data) {
1438
+ return new Promise((resolve, reject) => {
1439
+ let xhr = new XMLHttpRequest();
1440
+ xhr.open("PUT", url);
1441
+ xhr.setRequestHeader("Content-type", "application/json");
1442
+ xhr.onload = () => resolve(xhr.responseText);
1443
+ xhr.onerror = () => reject(xhr.statusText);
1444
+ xhr.send(data);
1445
+ });
1446
+ }
1447
+
1448
+ /**
1449
+ * Hide the del iconf rom the grid
1450
+ @alias module:Jqgrid_utils
1451
+ @example
1452
+ var jqu = new Jqgrid_utils();
1453
+ jqu.hide_del_icon();
1454
+ */
1455
+ s_hide_del_icon() {
1456
+ hide_del_icon();
1457
+ }
1458
+
1459
+ /**
1460
+ * Hide the del iconf rom the grid
1461
+ @alias module:Jqgrid_utils
1462
+ @example
1463
+ var jqu = new Jqgrid_utils();
1464
+ await jqu.hide_del_icon();
1465
+ */
1466
+ async hide_del_icon() {
1467
+ jQuery(".ui-inline-del").each(function (index) {
1468
+ jQuery(this).html("");
1469
+ });
1470
+ }
1471
+
1472
+ /**
1473
+ * Convert a cell into a link/url with data from another cell and spit the value by comma - CSV
1474
+ @alias module:Jqgrid_utils
1475
+ @param {object} - col_model of the grid
1476
+ @param {string} - URL string
1477
+ @param {string} - Column/Cell to use
1478
+ @param {string} - URL Attributes
1479
+ @param {object} - keys and fields value to use
1480
+ @param {object} - format info
1481
+ @param {string} - seperator of the cell value to split (default is comma)
1482
+ @example
1483
+ var jqu = new Jqgrid_utils();
1484
+ col_model = await jqu.add_link_details_csv(col_model, host + '/html/report.html' , 'tags','target="_blank"',{"tags":"tags"},',');
1485
+
1486
+ */
1487
+ async add_link_details_csv(
1488
+ col_model,
1489
+ url,
1490
+ edit_field,
1491
+ attr = "",
1492
+ keys,
1493
+ format,
1494
+ seperator = ",",
1495
+ ) {
1496
+ let self = this;
1497
+ if (url.indexOf("?") > -1) {
1498
+ url = url + "&";
1499
+ } else {
1500
+ url = url + "?";
1501
+ }
1502
+
1503
+ for (let i = 0; i < col_model.length; i++) {
1504
+ if (col_model[i]["name"] === edit_field) {
1505
+ col_model[i]["formatter"] = function (cell_val, obj) {
1506
+ let key_val = cell_val;
1507
+ const _cell_val = self.__cell_format(cell_val, format);
1508
+ const a = _cell_val.split(seperator);
1509
+ let cell_value = "";
1510
+ for (let x in a) {
1511
+ const x_value = a[x].trim();
1512
+ if (x_value) {
1513
+ if (typeof keys === "object") {
1514
+ let pref = "";
1515
+ for (let ii in keys) {
1516
+ let key = ii;
1517
+ let v = keys[ii];
1518
+ key_val = obj.rowData[v];
1519
+ if (key_val) {
1520
+ if (key.indexOf("=") !== -1) {
1521
+ pref =
1522
+ pref +
1523
+ "" +
1524
+ key +
1525
+ "" +
1526
+ encodeURIComponent(x_value) +
1527
+ "&";
1528
+ } else {
1529
+ pref =
1530
+ pref +
1531
+ "" +
1532
+ key +
1533
+ "=" +
1534
+ encodeURIComponent(x_value) +
1535
+ "&";
1536
+ }
1537
+ }
1538
+ }
1539
+ if (pref.slice(-1) === "&") {
1540
+ pref = pref.slice(0, -1);
1541
+ }
1542
+ cell_value +=
1543
+ "<a " +
1544
+ attr +
1545
+ 'href="' +
1546
+ url +
1547
+ pref +
1548
+ '"> ' +
1549
+ x_value +
1550
+ "</a>" +
1551
+ seperator +
1552
+ " ";
1553
+ }
1554
+ }
1555
+ cell_val = cell_value.trim();
1556
+ if (cell_val.slice(-1) === seperator) {
1557
+ //remove last seperator
1558
+ cell_val = cell_val.slice(0, -1);
1559
+ }
1560
+ }
1561
+
1562
+ if (cell_val) {
1563
+ return cell_val;
1564
+ } else {
1565
+ return _cell_val;
1566
+ }
1567
+ };
1568
+ }
1569
+ }
1570
+
1571
+ return col_model;
1572
+ }
1573
+
1574
+ /**
1575
+ * Compare 2 columns and give them a style class when they have different content
1576
+ * http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods
1577
+ @alias module:Jqgrid_utils
1578
+ @param {object} - grid object
1579
+ @param {string} - first column
1580
+ @param {string} - second column
1581
+ @param {string} - css class name
1582
+ @example
1583
+ loadComplete: async function()
1584
+ {
1585
+ await jqu.compare(this,'first_column','second_column','redlight');
1586
+ }
1587
+
1588
+ */
1589
+ async compare(obj, column1, column2, css_class) {
1590
+ const rows = jQuery(obj).jqGrid("getGridParam", "data");
1591
+ for (let i in rows) {
1592
+ if (rows[i][column1] != rows[i][column2]) {
1593
+ jQuery(obj).jqGrid("setCell", rows[i]["id"], column1, "", css_class);
1594
+ jQuery(obj).jqGrid("setCell", rows[i]["id"], column2, "", css_class);
1595
+ }
1596
+ }
1597
+ }
1598
+
1599
+ /**
1600
+ * Compare 2 columns for smaller and give them a style class
1601
+ * http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods
1602
+ @alias module:Jqgrid_utils
1603
+ @param {object} - grid object
1604
+ @param {string} - first column
1605
+ @param {string} - second column
1606
+ @param {string} - css class name
1607
+ @example
1608
+ loadComplete: async function()
1609
+ {
1610
+ await jqu.compare(this,'first_column','second_column','redlight');
1611
+ }
1612
+
1613
+ */
1614
+ async compare_smaller(obj, column1, column2, css_class) {
1615
+ const rows = jQuery(obj).jqGrid("getGridParam", "data");
1616
+ for (let i in rows) {
1617
+ if (rows[i][column1] < rows[i][column2]) {
1618
+ jQuery(obj).jqGrid("setCell", rows[i]["id"], column1, "", css_class);
1619
+ jQuery(obj).jqGrid("setCell", rows[i]["id"], column2, "", css_class);
1620
+ }
1621
+ }
1622
+ }
1623
+
1624
+ /**
1625
+ * Compare 2 columns for bigger and give them a style class
1626
+ * http://www.trirand.com/jqgridwiki/doku.php?id=wiki:methods
1627
+ @alias module:Jqgrid_utils
1628
+ @param {object} - grid object
1629
+ @param {string} - first column
1630
+ @param {string} - second column
1631
+ @param {string} - css class name
1632
+ @example
1633
+ loadComplete: async function()
1634
+ {
1635
+ await jqu.compare(this,'first_column','second_column','redlight');
1636
+ }
1637
+
1638
+ */
1639
+ async compare_bigger(obj, column1, column2, css_class) {
1640
+ const rows = jQuery(obj).jqGrid("getGridParam", "data");
1641
+ for (let i in rows) {
1642
+ if (rows[i][column1] > rows[i][column2]) {
1643
+ jQuery(obj).jqGrid("setCell", rows[i]["id"], column1, "", css_class);
1644
+ jQuery(obj).jqGrid("setCell", rows[i]["id"], column2, "", css_class);
1645
+ }
1646
+ }
1647
+ }
1648
+
1649
+ /**
1650
+ * Set styles to individual cells, what are defined in a dedicated column
1651
+ @alias module:Jqgrid_utils
1652
+ @param {object} - grid object
1653
+ @param {string} - name of the column what includes the style values what need to be in a strinify json format
1654
+ @example
1655
+ var jqu = new Jqgrid_utils();
1656
+ loadComplete: async function() {
1657
+ await jqu.set_styles(this);
1658
+ },
1659
+ */
1660
+ async set_styles(obj, style_column = "styles") {
1661
+ const rows = jQuery(obj).jqGrid("getGridParam", "data");
1662
+
1663
+ for (let i in rows) {
1664
+ if (rows[i][style_column]) {
1665
+ const styles = JSON.parse(rows[i][style_column]);
1666
+ for (let ii in styles) {
1667
+ const rowid = rows[i]["id"];
1668
+ const name = ii;
1669
+ if (rows[i].hasOwnProperty(name)) {
1670
+ jQuery(obj).jqGrid("setCell", rowid, name, "", styles[ii]);
1671
+ }
1672
+ }
1673
+ }
1674
+ }
1675
+ }
1676
+
1677
+ /**
1678
+ * Set a class to a row, what must be defined in a dedicated column called row.class
1679
+ * Once the grid is loaded, the functions adds extra class to the row element
1680
+ @alias module:Jqgrid_utils
1681
+ @param {object} - grid id like #grid
1682
+ @example
1683
+ var jqu = new Jqgrid_utils();
1684
+ loadComplete: async function() {
1685
+ await jqu.set_classes("#grid");
1686
+ },
1687
+ */
1688
+ async set_classes(grid_id, field) {
1689
+ const rows = jQuery(grid_id).getDataIDs();
1690
+ for (var i = 0; i < rows.length; i = i + 1) {
1691
+ const row = jQuery(grid_id).getRowData(rows[i]);
1692
+ var e = jQuery("#" + rows[i], jQuery(grid_id));
1693
+ e.removeClass("ui-widget-content");
1694
+ e.addClass(row.class);
1695
+ }
1696
+ }
1697
+
1698
+ /**
1699
+ * Convert a cell into a link/url with data from another cell
1700
+ @alias module:Jqgrid_utils
1701
+ @param {object} - col_model of the grid
1702
+ @param {string} - URL string
1703
+ @param {string} - Column/Cell to use
1704
+ @param {string} - URL Attributes
1705
+ @param {object} - keys and fields value to use
1706
+ @example
1707
+ var jqu = new Jqgrid_utils();
1708
+ col_model = await jqu.add_link_details(col_model,'http://foo.bar' , 'style','target="_blank"',{'key':'style'});
1709
+ col_model = await jqu.add_link_details(col_model, host + '/html/table_size.html' , 'database','target="_blank"',{"database":"database","server":"server"});
1710
+ */
1711
+ async add_link_details(col_model, url, edit_field, attr = "", keys, format) {
1712
+ let self = this;
1713
+ if (url.indexOf("?") > -1) {
1714
+ url = url + "&";
1715
+ } else {
1716
+ url = url + "?";
1717
+ }
1718
+
1719
+ for (let i = 0; i < col_model.length; i++) {
1720
+ if (col_model[i]["name"] === edit_field) {
1721
+ col_model[i]["formatter"] = function (cell_val, obj) {
1722
+ cell_val = String(cell_val);
1723
+ let key_val = "";
1724
+ if (cell_val) {
1725
+ key_val = cell_val;
1726
+ }
1727
+ let t = "";
1728
+ if (cell_val) {
1729
+ t = cell_val.toString();
1730
+ }
1731
+
1732
+ if (typeof keys === "object") {
1733
+ let pref = "";
1734
+ for (let ii in keys) {
1735
+ let key = ii;
1736
+ let v = keys[ii];
1737
+ key_val = obj.rowData[v];
1738
+ if (key_val) {
1739
+ if (key_val) {
1740
+ if (key.indexOf("=") !== -1) {
1741
+ pref =
1742
+ pref + "" + key + "" + encodeURIComponent(key_val) + "&";
1743
+ } else {
1744
+ pref =
1745
+ pref + "" + key + "=" + encodeURIComponent(key_val) + "&";
1746
+ }
1747
+ }
1748
+ }
1749
+ }
1750
+ if (pref) {
1751
+ if (pref.slice(-1) === "&") {
1752
+ pref = pref.slice(0, -1);
1753
+ }
1754
+ const _cell_val = self.__cell_format(cell_val, format);
1755
+
1756
+ if (t != "" && _cell_val && t) {
1757
+ cell_val =
1758
+ "<a " +
1759
+ attr +
1760
+ 'href="' +
1761
+ url +
1762
+ pref +
1763
+ '"> ' +
1764
+ _cell_val +
1765
+ "</a>";
1766
+ } else {
1767
+ cell_val = "";
1768
+ }
1769
+ }
1770
+ }
1771
+ if (t) {
1772
+ return cell_val;
1773
+ } else {
1774
+ return "";
1775
+ }
1776
+ };
1777
+ }
1778
+ }
1779
+
1780
+ return col_model;
1781
+ }
1782
+
1783
+ /**
1784
+ * Convert a cell into seperated based link/url like https://foo.bar.com/field/value/field/value
1785
+ @alias module:Jqgrid_utils
1786
+ @param {object} - col_model of the grid
1787
+ @param {string} - URL string
1788
+ @param {string} - Column/Cell to use
1789
+ @param {string} - URL Attributes
1790
+ @param {object} - keys and fields value to use
1791
+ @example
1792
+ var jqu = new Jqgrid_utils();
1793
+ col_model = await jqu.add_link_details_separator(col_model, url1 , 'style','target="_blank"',{"pricelist":"pricelist","style":"style"});
1794
+ col_model = await jqu.add_link_details_separator(col_model, 'https://foo.com' , 'target_column','target="_blank"',{"mykey":"myval"});
1795
+ */
1796
+ async add_link_details_separator(
1797
+ col_model,
1798
+ url,
1799
+ edit_field,
1800
+ attr = "",
1801
+ keys,
1802
+ format,
1803
+ ) {
1804
+ url = url + "/";
1805
+ let self = this;
1806
+ for (let i = 0; i < col_model.length; i++) {
1807
+ if (col_model[i]["name"] === edit_field) {
1808
+ col_model[i]["formatter"] = function (cell_val, obj) {
1809
+ let key_val = cell_val;
1810
+
1811
+ if (typeof keys === "object") {
1812
+ let pref = "";
1813
+ for (let ii in keys) {
1814
+ let key = ii;
1815
+ let v = keys[ii];
1816
+ key_val = obj.rowData[v];
1817
+ if (key_val) {
1818
+ if (key_val) {
1819
+ if (key != "") {
1820
+ pref += key + "" + "/" + encodeURIComponent(key_val) + "/";
1821
+ } else {
1822
+ pref += encodeURIComponent(key_val);
1823
+ }
1824
+ }
1825
+ }
1826
+ }
1827
+ if (pref) {
1828
+ if (pref.slice(-1) === "&" || pref.slice(-1) === "/") {
1829
+ pref = pref.slice(0, -1);
1830
+ }
1831
+ const _cell_val = self.__cell_format(cell_val, format);
1832
+ cell_val =
1833
+ "<a " +
1834
+ attr +
1835
+ 'href="' +
1836
+ url +
1837
+ pref +
1838
+ '"> ' +
1839
+ _cell_val +
1840
+ "</a>";
1841
+ }
1842
+ }
1843
+
1844
+ return cell_val;
1845
+ };
1846
+ }
1847
+ }
1848
+
1849
+ return col_model;
1850
+ }
1851
+
1852
+ /**
1853
+ * Convert a cell into seperated based link/url include parameter based url like https://foo.bar.com/field.html?k=v
1854
+ @alias module:Jqgrid_utils
1855
+ @param {object} - col_model of the grid
1856
+ @param {string} - URL string
1857
+ @param {array} - array of dict
1858
+ @param {string} - URL Attributes
1859
+ @example
1860
+ var jqu = new Jqgrid_utils();
1861
+ col_model = await jqu.add_link_separator(col_model, host + '/html' , 'style',[
1862
+ {
1863
+ 'field':'pricelist',
1864
+ 'extension':'.html',
1865
+ 'fields':{'style':'style'}
1866
+ }
1867
+ ]);
1868
+ //other example
1869
+ col_model = await jqu.add_link_separator(col_model, 'https://wiki.salamander-jewelry.net/index.php/grid_loss' , 'e',[{'field':'e'}],'target="_blank"');
1870
+
1871
+ */
1872
+ async add_link_separator(col_model, url, edit_field, fields, attr = "") {
1873
+ url = url + "/";
1874
+ let self = this;
1875
+ for (let i = 0; i < col_model.length; i++) {
1876
+ if (col_model[i]["name"] === edit_field) {
1877
+ col_model[i]["formatter"] = function (cell_val, obj) {
1878
+ let key_val = cell_val;
1879
+ let pref = "";
1880
+ for (let x in fields) {
1881
+ for (let xx in fields[x]) {
1882
+ if (xx === "field") {
1883
+ let field_value = obj.rowData[fields[x][xx]];
1884
+ pref += field_value;
1885
+ }
1886
+ if (xx === "extension") {
1887
+ pref += fields[x][xx];
1888
+ }
1889
+ if (xx === "fields") {
1890
+ pref += "?";
1891
+ for (let key in fields[x][xx]) {
1892
+ let val = obj.rowData[fields[x][xx][key]];
1893
+ pref = pref + "" + key + "=" + encodeURIComponent(val) + "&";
1894
+ }
1895
+ }
1896
+ }
1897
+ }
1898
+ if (pref) {
1899
+ if (pref.slice(-1) === "&" || pref.slice(-1) === "/") {
1900
+ pref = pref.slice(0, -1);
1901
+ }
1902
+ cell_val =
1903
+ "<a " + attr + 'href="' + url + pref + '"> ' + cell_val + "</a>";
1904
+ }
1905
+
1906
+ return cell_val;
1907
+ };
1908
+ }
1909
+ }
1910
+ return col_model;
1911
+ }
1912
+
1913
+ /**
1914
+ * Private Function
1915
+ @alias module:Jqgrid_utils
1916
+ */
1917
+ __cell_format(cell_value, format) {
1918
+ if (format == "format_ok") {
1919
+ if (cell_value == 0 || cell_value === "fail") {
1920
+ cell_value =
1921
+ '<i data-check="failed" class="fa fa-times-circle" aria-hidden="true" style="color:#ff0000;"></i>';
1922
+ } else {
1923
+ cell_value =
1924
+ '<i data-check="ok" class="fa fa-check-circle" aria-hidden="true" style="color:#008000;"></i>';
1925
+ }
1926
+ }
1927
+ return cell_value;
1928
+ }
1929
+
1930
+ /**
1931
+ @alias module:Jqgrid_utils
1932
+ @param {string} - row_id
1933
+ @param {string} - data id
1934
+ @param {string} - url to request
1935
+ @param {object} - col_model for the table
1936
+ @param {string} - Add to the caption of the subgrid
1937
+ @example
1938
+ subGrid: true,
1939
+ ,subGridRowExpanded: async function(_id, id) {
1940
+ let data_url2 = api + '/process_locations?f=data&process=';
1941
+ let col_model_url2 = api + '/process_locations?f=col_model';
1942
+ let col_model2 = JSON.parse(await vwu.aget_api(col_model_url2));
1943
+ await jqu.subgrid(_id, id, data_url2, col_model2,'Locations for Process');
1944
+
1945
+ let data_url = api + '/process_styles?f=data&process=';
1946
+ let col_model_url = api + '/process_styles?f=col_model';
1947
+ let col_model = JSON.parse(await vwu.aget_api(col_model_url));
1948
+ await jqu.subgrid(_id, id, data_url, col_model,'Styles for Process');
1949
+ },
1950
+
1951
+ or
1952
+
1953
+ subGrid: true,
1954
+ subGridRowExpanded: async function(_id, id) {
1955
+ let row_data = jQuery(this).jqGrid ('getRowData', id);
1956
+ let param={f:'data','style':row_data['style'],pricelist:'P-TENENGR1'};
1957
+ let data_url = api + '/order_ln';
1958
+ data_url = await add_parameters(data_url, param);
1959
+ let col_model_url2 = api + '/order_ln?f=col_model';
1960
+ let col_model2 = JSON.parse(await vwu.aget_api(col_model_url2));
1961
+ await jqu.subgrid(_id, false, data_url, col_model2,'Order Lines for ' + row_data['style']);
1962
+ },
1963
+
1964
+ */
1965
+ async subgrid(_id, id, url, col_model, caption = "") {
1966
+ caption = caption != "" ? caption + " " : "";
1967
+ if (id) {
1968
+ url += id;
1969
+ } else {
1970
+ id = "";
1971
+ }
1972
+ let $s1 = jQuery(
1973
+ "<table style='margin: 5px 0' class='" + _id + "_t'></table>",
1974
+ );
1975
+ $s1.appendTo("#" + jQuery.jgrid.jqID(_id));
1976
+ $s1.jqGrid({
1977
+ caption: caption + id,
1978
+ colModel: col_model,
1979
+ datatype: "json",
1980
+ url: url,
1981
+ gridview: true,
1982
+ rownumbers: true,
1983
+ autoencode: true,
1984
+ sortname: "c1",
1985
+ sortorder: "desc",
1986
+ });
1987
+ }
1988
+
1989
+ /**
1990
+ @alias module:Jqgrid_utils
1991
+ @param {object} - col_model for the grid
1992
+ @param {string} - field what include the image/picture href path like http://mypicture.png
1993
+ @param {int} - size of the picture
1994
+ @param {bolen} - image path should be a link
1995
+ @example
1996
+ col_model = await jqu.add_image(col_model, image_field, 60, false);
1997
+ */
1998
+ async add_image(col_model, edit_field, size, link = false) {
1999
+ if (size === undefined) {
2000
+ size = 60;
2001
+ }
2002
+ for (let i = 0; i < col_model.length; i++) {
2003
+ if (col_model[i]["name"] === edit_field) {
2004
+ col_model[i]["picture"] = true;
2005
+ col_model[i]["width"] = size;
2006
+ col_model[i]["height"] = size;
2007
+ col_model[i]["formatter"] = function (cell_val) {
2008
+ const cell_val2 = cell_val.toLowerCase();
2009
+
2010
+ if (
2011
+ cell_val2.startsWith("https://", 0) ||
2012
+ cell_val2.startsWith("http://", 0)
2013
+ ) {
2014
+ if (
2015
+ cell_val2.includes(".png") ||
2016
+ cell_val2.includes(".jpg") ||
2017
+ cell_val2.includes(".jpeg") ||
2018
+ cell_val2.includes(".gif") ||
2019
+ cell_val2.includes(".svg") ||
2020
+ cell_val2.includes(".svgz") ||
2021
+ cell_val2.includes(".webp")
2022
+ ) {
2023
+ if (link) {
2024
+ return (
2025
+ '<a target="blank" href="' +
2026
+ cell_val +
2027
+ '"><img src="' +
2028
+ cell_val +
2029
+ '" alt="my image" width="' +
2030
+ size +
2031
+ '" /></a>'
2032
+ );
2033
+ } else {
2034
+ return (
2035
+ '<img src="' +
2036
+ cell_val +
2037
+ '" alt="my image" width="' +
2038
+ size +
2039
+ '" />'
2040
+ );
2041
+ }
2042
+ }
2043
+ }
2044
+ return cell_val;
2045
+ };
2046
+ }
2047
+ }
2048
+ return col_model;
2049
+ }
2050
+
2051
+ /**
2052
+ * Add a filter to the website beside the grid
2053
+ @alias module:Jqgrid_utils
2054
+ @param {object} - grid object or grid string name
2055
+ @param {object} - the grid data object
2056
+ @param {object} - a dict with a array what should be filterd by the grid
2057
+ @param {string} - id name of the DOM oject where the filter should be appened
2058
+ @example
2059
+ var jqu = new Jqgrid_utils();
2060
+ var run_me_once = true;
2061
+ gridComplete: async function(){
2062
+ if(run_me_once)
2063
+ {
2064
+ await jqu.set_filter(this, data, {material:[],section:[]}, '#filter');
2065
+ run_me_once = false;
2066
+ }
2067
+ },
2068
+ */
2069
+ async set_filter(grid, data, fx, append_to = "#filter") {
2070
+ jQuery(grid).jqGrid("setGridParam", { fdata: data });
2071
+ let f = document.querySelector(append_to);
2072
+ for (const i in data) {
2073
+ for (let x in fx) {
2074
+ fx[x].push(data[i][x]);
2075
+ }
2076
+ }
2077
+
2078
+ for (let x in fx) {
2079
+ fx[x] = fx[x].filter((val, ind, arr) => arr.indexOf(val) === ind);
2080
+ fx[x].sort();
2081
+ }
2082
+
2083
+ for (let x in fx) {
2084
+ let ul = document.createElement("ul");
2085
+ let lh = document.createElement("lh");
2086
+ lh.innerHTML = x;
2087
+ ul.appendChild(lh);
2088
+ for (let i in fx[x]) {
2089
+ let li = document.createElement("li");
2090
+ let l = document.createElement("label");
2091
+ l.innerHTML = fx[x][i];
2092
+ let c = document.createElement("input");
2093
+ c.setAttribute("type", "checkbox");
2094
+ c.setAttribute("class", x);
2095
+ c.setAttribute("id", x + "_" + fx[x][i]);
2096
+ l.setAttribute("for", x + "_" + fx[x][i]);
2097
+ c.value = fx[x][i];
2098
+ c.onchange = async () => {
2099
+ await this._filter(grid, fx);
2100
+ };
2101
+ li.appendChild(l);
2102
+ li.appendChild(c);
2103
+ ul.appendChild(li);
2104
+ }
2105
+ f.appendChild(ul);
2106
+ }
2107
+ }
2108
+
2109
+ /**
2110
+ * private function of set_filter
2111
+ @alias module:Jqgrid_utils
2112
+ */
2113
+ async _filter(grid, fx) {
2114
+ let _data = [];
2115
+ let data = jQuery(grid).jqGrid("getGridParam", "fdata");
2116
+ let filter = [];
2117
+ for (let x in fx) {
2118
+ let m = document.querySelectorAll("." + x);
2119
+ filter[x] = [];
2120
+ for (let i in m) {
2121
+ if (m[i].checked) {
2122
+ filter[x].push(m[i].value);
2123
+ }
2124
+ }
2125
+ }
2126
+ for (let i in data) {
2127
+ let include = false;
2128
+ for (let x in fx) {
2129
+ if (filter[x].indexOf(data[i][x]) != -1) {
2130
+ include = true;
2131
+ }
2132
+ }
2133
+ if (include) {
2134
+ _data.push(data[i]);
2135
+ }
2136
+ }
2137
+ jQuery(grid).jqGrid("clearGridData");
2138
+ jQuery(grid).jqGrid("setGridParam", { data: _data });
2139
+ jQuery(grid).trigger("reloadGrid");
2140
+ }
2141
+ };
2142
+
2143
+ },{}]},{},[1])(1)
2144
+ });