if(typeof Product==='undefined'){ class Product extends DataModel{ /* * Constructor */ constructor (data,options) { super(data,options) if(typeof this.contact ==="undefined"){ this.contact=[]; } console.log('Product constructor called'); }; }; window.Product=Product; } window.ProductAdmin=function (options,ProductItem) { /* * Variables accessible * in the class */ let Opts = { token: null, containerCssSelector: '.containerProduct', container:null, resultContainerSelector:'.containerProduct .containerResult', resultContainer:null, testMode: false, filters:{ Product:{}, }, URL: { getDataTableContent: '', index: '', show: '', edit: '', create: '', store: '', update: '', destroy: '', attachFile: '', detachFile: '', }, dataTable: { orderDirective: [1, 'asc'], }, onAfterInitViewDetails: function () { } }; let Product = {}; let root = this; let contactPopupWorkflow = 'new'; let dataTable=null; /* * Constructor */ this.construct = function (options, ProductItem) { console.log('ProductAdmin constructor called'); $.extend(Opts, options); if (!ProductItem) { console.log('Product letre kellet hozni '); if (!APP.Product) { APP.Product = new window.Product(); } root.Product = APP.Product; } }; this.getOpts = function () { return Opts; } this.datatableRowActionButtonClick=function (event){ debug('datatableRowActionButtonClick'); let node=$(event[0].currentTarget); let row=$(dataTableCSSSelector).DataTable().row(node.parents('tr')); let rowData=row.data(); let actionName='datatableRowAction'+node.data('buttontype').capitalize(); if (typeof root[actionName] === "function") { return root[actionName](rowData,node) } } this.datatableRowActionEdit=function (rowData,node) { console.log('datatableRowActionEdit Called'); //Opts.onAfterInitViewDetails=root.autofillDetails; let ajaxUrl=Opts.URL.edit.replace('%id%',rowData.id); APP.loadMainContent(ajaxUrl,root.initViewDetails); console.log('datatableRowActionEdit End'); } this.initViewListOld = function (options={}) { debug('listview inicialization'); dataTableCSSSelector=Opts.containerCssSelector+' .dataTable'; // let colNum=$(dataTableCSSSelector+' thead th').length; //buttons insert position need APP.setOpts({ datatableRowActionButtonClickCallBack:root.datatableRowActionButtonClick, }) let orderDirective=Opts.dataTable.orderDirective; if(typeof options['orderDirective']!='undefined'){ orderDirective=options['orderDirective']; } $(dataTableCSSSelector).DataTable( { language: { url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json' }, //"ajax": "{{asset('exapmle2.json')}}", "ajax": Opts.URL.getDataTableContent, serverSide: true, "columnDefs": [ { "targets": colNum-1, orderable: false, "render": function ( data, type, row ) { let buttons=APP.datatableAddRowEditButton(0,arguments); return buttons; }, }, { "targets": 1, "render": function ( data, type, row ) { return type === "sort" ? data.latinise() : data; }, }, //{ "visible": false, "targets": [ 0 ] } ], buttons:{ buttons: [ 'excel','pdf', { extend: 'print', //text: 'Print current page', 'title': 'title custom text', 'messageTop': 'Message On Top', autoPrint: true }, ] }, "columns": [ { "data": "id"}, { "data": "name" }, { "data": "hooreycaId" }, {"data": "productGroup"}, {"data": "supplierName"}, { "data": "price" }, { "data": "created_at" }, null, ], "order": orderDirective, "stateSave": true, "drawCallback": function( settings ) { APP.datatableAddRowAction(dataTableCSSSelector); } } ); debug('listview end'); } this.initViewList=function (options={}) { debug('initViewSearch inicialization 1'); root.container.find('select.supplierSelect, select.profitCenterSelect, select.productGroupSelect, select.producerSelect, select.hooreycaNamesSelect, select.specialOfferSelect').select2(); root.container.find('select.productSelect').select2({ placeholder: '...', allowClear: true, ajax: { url: Opts.URL.getProductSearch, dataType: 'json', data: function(params) { return { term: params.term || '', page: params.page || 1, supplierId: root.container.find('select.supplierSelect').val(), } }, cache: true } }); root.container.find('.datePickerFrom, .datePickerTo').datepicker({ dateFormat: 'yy-mm-dd', onSelect: function (dateText,obj) { debug(this); debug(obj.input); /* root.container.find('.selectedDateText').text(dateText); $('.deliveryDatePlace').text(dateText.replaceAll('-', '.') + '.'); root.container.find(' input[name="deliveryDate"]').val(dateText); */ //root.changePriceListProfitCenterParameter(null,$(obj.input)); }, }); root.container.find('.datePickerClick').click(function(){ debug($(this).data('action')); root.container.find('input[name="'+$(this).data('action')+'"]').datepicker('show'); }); let button=root.container.find('.FormSendButton'); button.off('click'); button.on('click',function (){ debug ('FormSendButton click'); root.loadingResultContainer(); root.requestProducts(); }); root.setVisibleFilters('Product'); if (root.loadFiltersFromLocalStorage()) { root.loadingResultContainer(); root.requestProducts(); } debug('initViewSearch end'); } this.loadingResultContainer=function (){ debug('clearResultContainer'); debug(root.resultContainer); root.hideResultContainer(); root.container.find('.containerLoading').show(); /* let template=root.container.find('template[data-name="loading"]').html() root.resultContainer.html(template); */ } this.hideResultContainer=function (){ debug('hide containerResult'); debug(root.resultContainer); root.resultContainer.hide(); } this.showResultContainer=function (){ root.container.find('.containerLoading').hide(); root.resultContainer.show(); } this.init=function (options,ProductItem){ console.log('ProductAdmin init'); $.extend(Opts, options); if(Opts.testMode){ return root.testMode(); } if(ProductItem){ root.Product=ProductItem } root.dataTable=null; root.container=$(Opts.containerCssSelector); root.resultContainer=$(Opts.resultContainerSelector); root.initViewList(); } this.initViewDetails=function (options,ProductItem){ debug('**call initViewDetails '); let CSSSelectorForm=Opts.containerCssSelector+' .productForm'; if(root.Product.picture){ console.log('*****//////////////////****************'); console.log(root.Product.picture); console.log(CSSSelectorForm); let picUrl=root.Product.picture.PublicUrl+'/'+root.Product.picture.filename; console.log(picUrl); console.log($(CSSSelectorForm+' img.imageProduct')); $(CSSSelectorForm+' img.imageProduct').attr('src',picUrl); } if(root.Product.specification){ console.log('*****//////////////////****************'); console.log(root.Product.specification); let docUrl=root.Product.specification.PublicUrl+'/'+root.Product.specification.filename; root.addAttachment(root.Product.specification); } let FormSaveButton=$(CSSSelectorForm+' button.FormSaveButton'); FormSaveButton.off('click'); FormSaveButton.on('click',root.clickSaveButton); } this.addAttachment=function (attachmentData){ console.log(attachmentData); let CSSSelectorForm=Opts.containerCssSelector+' .productForm'; //root.Supplier.attachment.push(attachmentData); //attachmentData.rowNum=root.Supplier.attachment.length; attachmentData.rowNum=1; let dateStr=new Date(attachmentData.updated_at); dateStr=dateStr.toLocaleString('hu-HU', {}); attachmentData.date=dateStr; attachmentData.link=attachmentData.PublicUrl+'/'+attachmentData.filename; let template=$('template[data-name="productAttachmentTableRow"]').html() let render=Mustache.render(template,attachmentData); $(CSSSelectorForm+' .attachmentTable tbody').append(render); //root.bindContactClickAction(); Toast.enableTimers(false); Toast.create({ title: "Fájl hozzáadva!", message: attachmentData.original_filename+" fájl hozzáadva", status: TOAST_STATUS.SUCCESS, timeout: 5000 }); } this.setVisibleFilters=function (type){ console.log('setVisibleFilters'); console.log(Opts.filters[type]); console.log(root.container); $(root.container).find('div[class*="filter"]').hide() for (const typeIndex in Opts.filters[type]) { const typeName=Opts.filters[type][typeIndex]; debug(typeName); console.log($(root.container).find('.filter_'+typeName)); $(root.container).find('.filter_'+typeName).show(); } } this.c=function (CSSSelectorForm){ console.log('c called'); console.log(CSSSelectorForm); console.log(root.container); console.log(root.container.find('form')); console.log(root.container.find(CSSSelectorForm)); } this.formDataToDataObjectAPICall = function (CSSSelectorForm) { console.log(CSSSelectorForm); console.log(root.container); console.log(root.container.find(CSSSelectorForm)); console.log(root.container.find('form')); console.log(root.container.find('form'+CSSSelectorForm)[0]); //return; let ajaxData = new FormData(root.container.find('form'+CSSSelectorForm)[0]); $.each(ajaxData.getAll('supplier'), function (key, value) { ajaxData.append('suppliers[]', value); }) ajaxData.delete('supplier'); $.each(ajaxData.getAll('profitCenter'), function (key, value) { ajaxData.append('profitCenters[]', value); }) ajaxData.delete('profitCenter'); $.each(ajaxData.getAll('productGroup'), function (key, value) { ajaxData.append('productGroups[]', value); }) ajaxData.delete('productGroup'); $.each(ajaxData.getAll('product'), function (key, value) { ajaxData.append('products[]', value); }) ajaxData.delete('product'); $.each(ajaxData.getAll('producer'), function (key, value) { ajaxData.append('producers[]', value); }) ajaxData.delete('producer'); $.each(ajaxData.getAll('hooreycaName'), function (key, value) { ajaxData.append('hooreycaNames[]', value); }) ajaxData.delete('hooreycaName'); //ajaxData.append('_token', root.container.find('input[name=_token]').val()); /* $(CSSSelectorForm + ' input[data-inputmask]').each(function () { let indexKey = $(this).attr('name'); if (ajaxData.get(indexKey)) { ajaxData.set(indexKey, ajaxData.get(indexKey).replace(/[_ ]+$/g, "")); } }); */ return ajaxData; } this.getAjaxDataJson=function(){ let ajaxData=root.formDataToDataObjectAPICall('.ProductListForm'); console.log('======================'); for (let pair of ajaxData.entries()) { console.log(pair[0]+ ', ' + pair[1]); } let object = {}; ajaxData.forEach((value, key) => { // Reflect.has in favor of: object.hasOwnProperty(key) if(!Reflect.has(object, key)){ object[key] = value; return; } if(!Array.isArray(object[key])){ object[key] = [object[key]]; } object[key].push(value); }); let ajaxDataJson = JSON.stringify(object); return ajaxDataJson; } this.requestProducts=function () { let ajaxUrl=Opts.URL.getDataTableContent; let ajaxMethod='GET'; //token formdataba! debug(ajaxUrl); ajaxDataJson=root.getAjaxDataJson(); console.log(ajaxDataJson); // Save filters to localStorage let form = root.container.find('form.ProductListForm'); if (form.length > 0) { let formData = new FormData(form[0]); let filterData = {}; formData.forEach((value, key) => { if(!Reflect.has(filterData, key)){ filterData[key] = value; return; } if(!Array.isArray(filterData[key])){ filterData[key] = [filterData[key]]; } filterData[key].push(value); }); localStorage.setItem('product_admin_filters', JSON.stringify(filterData)); } dataTableCSSSelector=Opts.containerCssSelector+' .dataTable'; // console.log(dataTableCSSSelector ); let colNum=$(dataTableCSSSelector+' thead th').length; //buttons insert position need APP.setOpts({ datatableRowActionButtonClickCallBack:root.datatableRowActionButtonClick, }) let orderDirective=Opts.dataTable.orderDirective; /* if(typeof options['orderDirective']!='undefined'){ orderDirective=options['orderDirective']; } */ if(!root.dataTable){ console.log('XXXXXXXXXXXXXXXXXXXX Nincs Datatable'); root.dataTable= $(dataTableCSSSelector).DataTable( { language: { url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json' }, //"ajax": "{{asset('exapmle2.json')}}", "ajax":{ url: Opts.URL.getDataTableContent, data: function (d) { console.log('---******----'); console.log(APP.ProductAdmin.getAjaxDataJson()); return $.extend({}, d, { ajaxData: APP.ProductAdmin.getAjaxDataJson }); }, type: ajaxMethod /* data: ajaxData, */ } , serverSide: true, "columnDefs": [ { "targets": colNum-1, orderable: false, "render": function ( data, type, row ) { let buttons=APP.datatableAddRowEditButton(0,arguments); return buttons; }, }, { "targets": 1, "render": function ( data, type, row ) { return type === "sort" ? data.latinise() : data; }, }, //{ "visible": false, "targets": [ 0 ] } ], buttons:{ buttons: [ 'excel','pdf', { extend: 'print', //text: 'Print current page', 'title': 'title custom text', 'messageTop': 'Message On Top', autoPrint: true }, ] }, "columns": [ { "data": "id"}, { "data": "name" }, { "data": "hooreycaId" }, {"data": "productGroup"}, {"data": "supplierName"}, { "data": "price" }, { "data": "created_at" }, null, ], "order": orderDirective, "stateSave": true, "drawCallback": function( settings ) { APP.datatableAddRowAction(dataTableCSSSelector); root.showResultContainer(); console.log('drawCallback'); } } ); }else{ console.log('XXXXXXXXXXXXXXXXXXXX van Datatable'); //root.dataTable.ajax.reload(); root.dataTable.draw(); } } this.loadFiltersFromLocalStorage = function() { let filters = localStorage.getItem('product_admin_filters'); if (filters) { let filterData = JSON.parse(filters); let form = root.container.find('form.ProductListForm'); if (form.length === 0) return false; for (let key in filterData) { let value = filterData[key]; let fields = form.find('[name="' + key + '"]'); if (fields.length) { if (fields.is('select')) { fields.val(value).trigger('change'); } else if (fields.is(':checkbox') || fields.is(':radio')) { fields.each(function() { if (Array.isArray(value)) { $(this).prop('checked', value.includes($(this).val())); } else { $(this).prop('checked', $(this).val() == value); } }); } else { fields.val(value); } } } return true; } return false; } this.processResponse=function () { } this.clickSaveButton=function (event) { debug('Save clicked'); let CSSSelectorForm=Opts.containerCssSelector+' .productForm'; event.preventDefault(); if ($(CSSSelectorForm)[0].checkValidity() === false) { console.log('validaton false'); event.stopPropagation(); return; } else { console.log('validaton ok'); //do your ajax submition here } let ajaxData=root.formDataToDataObjectAPICall('.productForm'); let ajaxUrl=Opts.URL.store; let ajaxMethod="POST"; if(root.Product.id){ ajaxUrl=Opts.URL.update.replace('%id%',root.Product.id); //ajaxMethod="PUT"; //ajaxData=new FormData($(CSSSelectorForm)[0]); ajaxData.append('_method','PUT'); } debug(ajaxMethod); debug(ajaxData); $.ajax({ url:ajaxUrl, data:ajaxData, type:ajaxMethod, contentType:false, processData: false, headers: { //'X-CSRF-TOKEN': $('input[name="_token"]').val() 'X-CSRF-TOKEN': Opts.token }, success:function (data){ debug(data); if(data.success==true){ //Opts.onAfterInitViewDetails=root.autofillDetails; Opts.dataTable.orderDirective=[0, 'desc']; Toast.create({ title: "Sikeres rögzítés!", message: ajaxData.get('name')+" nevű termék elmentve", status: TOAST_STATUS.SUCCESS, timeout: 5000 }); // APP.loadMainContent(Opts.URL.index+'?init=0',root.initViewList); } } }); } }