var DBG = DBG || 0; var DBG1 = true; var CURRENT_DATE = CURRENT_DATE || ''; if (!STORE_NAME) throw "Store name not defined"; if (!global[STORE_NAME]) throw "Store not defined"; if (!URL_TABLE_POWIAZANIA) throw "Brak URL_TABLE_POWIAZANIA"; if (!BASE_URLS) throw "Brak BASE_URLS" var RECORD_MORE_FUNCTIONS_OPENED_NODE = null; if (!FIELD_LIST_PRACOWNICY) throw "Brak FIELD_LIST_PRACOWNICY" if (!FIELD_LIST_KONTRAHENCI) throw "Brak FIELD_LIST_KONTRAHENCI" var EXPORT_FIELDS_OD = EXPORT_FIELDS_OD || null; var EXPORT_FIELDS_DO = EXPORT_FIELDS_DO || null; var createReactClass = global.p5VendorJs.createReactClass; var h = global.p5VendorJs.React.createElement; var ReactDOM = global.p5VendorJs.ReactDOM; var swal = window.swal; var globalRaportStore = global[STORE_NAME]; if (!p5UI__clickedOutsideElement) throw "Brak p5UI__clickedOutsideElement" if (!global.p5VendorJs.Unstated) throw "Brak Unstated" var Unstated = global.p5VendorJs.Unstated; var P5UI__BocianHeader = createReactClass({ getStateFromStore: function () { var storeState = this.props.store.getState(); return { totalOdPracownicy: storeState.totalOdPracownicy, totalOdPozostale: storeState.totalOdPozostale, totalDoKontrahenci: storeState.totalDoKontrahenci, totalDoPozostale: storeState.totalDoPozostale, depth: storeState.depth, onlyTargets: storeState.onlyTargets, title: storeState.title, }; }, getInitialState: function() { return this.getStateFromStore(); }, componentDidMount: function () { this.unsubscribe = this.props.store.subscribe(this.storeUpdated) }, componentWillUnmount: function () { this.unsubscribe() }, storeUpdated: function () { DBG && console.log('DBG::P5UI__BocianHeader::storeUpdated ', this.getStateFromStore()); this.setState(this.getStateFromStore()) }, addOdPozostale: function (event) { // window['createPracownikAjax'](event) window['addPozostaleOdDo'](event) }, addDoPozostale: function (event) { // window['createKontrahentAjax'](event) window['addPozostaleOdDo'](event) }, clearPozostaleOd: function (event) { this.props.store.dispatch({ type: 'CLEAR_POZOSTALE_OD' }) }, clearPozostaleDo: function (event) { this.props.store.dispatch({ type: 'CLEAR_POZOSTALE_DO' }) }, handleChangeDepth: function (event) { var store = this.props.store; var depth = event.target.value; store.dispatch({ type: 'SET_DEPTH', depth: depth }) }, handleChangeSetOnlyTargetsYes: function () { this.props.store.dispatch({ type: 'SET_ONLY_TARGETS', onlyTargets: true }) }, handleChangeSetOnlyTargetsNo: function () { this.props.store.dispatch({ type: 'SET_ONLY_TARGETS', onlyTargets: false }) }, handleChangeTitle: function (event) { this.props.store.dispatch({ type: 'SET_TITLE', title: event.target.value }) }, handleRaportSubmitForm: function (event) { event.preventDefault(); var self_store = this.props.store; var idsPracownicy = getListFromLocalStorage('Bocian.biAuditForm.pracownicyIds'); var idsKontrahenci = getListFromLocalStorage('Bocian.biAuditForm.kontrahenciIds'); var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD')); var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO')); var allOdLength = idsPracownicy.length + pozostaleOd.length; var allDoLength = idsKontrahenci.length + pozostaleDo.length; var depthValue = getItemLocalStorage('Bocian.biAuditForm.depth'); var smadReaportTitle = getItemLocalStorage('Bocian.biAuditForm.smadReaportTitle'); var analizaOnlyTargets = getItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets'); if ( !smadReaportTitle ) { p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano tytułu raportu' }); return; } if ( !depthValue ) { p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano wartości dla głębokości powiązań' }); return; } if ( !analizaOnlyTargets ) { p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano wartości czy zwracać wyniki tylko z obiektami docelowymi' }); return; } if ( !allOdLength ) { p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie wybrano pozycji OD do analizy (pracownicy lub pozostałe bazy)' }); return; } if ( !allOdLength && !allDoLength ) { p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie wybrano pozycji do analizy' }); return; } // TODO: analizaOnlyTargets = ( 'y' | 'n' ) - allDoLength should depend of analizaOnlyTargets? // if not choise 'pracownicy' or 'kontrahenci' if ( !allOdLength || !allDoLength ) { var messageConfirm = ''; if ( !allDoLength ) { messageConfirm = 'Nie wybrano podmiotów/kontrahentów! Czas przygotowania raportu może wydłużyć się ze względu na sprawdzenie powiązania ze wszystkimi podmiotami/kontrahentami w systemie. Czy jesteś pewny? '; } // show confirm window with message if (!confirm(messageConfirm)) return; } window.fetch(URL_GENERATE_BI_AUDIT_RAPORT_AJAX, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ pracownicyIds: idsPracownicy, kontrahenciIds: idsKontrahenci, pozostaleOd: pozostaleOd, pozostaleDo: pozostaleDo, depthValue: depthValue, smadReaportTitle: smadReaportTitle, analizaOnlyTargets: analizaOnlyTargets }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); self_store.dispatch({ type: 'CLEAR_ALL' }) updateTopCounters(); $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false); $('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false); $('#count-selected-item-kontrahenci').text('0'); $('#count-selected-item-pracownicy').text('0'); $('.bottom--message-warning-critical-search').text(''); swal({ title: result.msg, html: 'Przejdź do raportów', allowOutsideClick: false, // TODO: btn Anuluj na dole? showCloseButton: true, confirmButtonText: 'OK', }); window.setTimeout(function () { console.warn("URL_TABLE_POWIAZANIA:", URL_TABLE_POWIAZANIA); }, 100); window.setTimeout(function () { window.location.href = URL_TABLE_POWIAZANIA; }, 6000); resolve(result.msg); } else { if (result.type && result.msg) p5UI__notifyAjaxCallback(result); reject(result.msg); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }); }, handleAddByLastReportClick: function (event) { swal({ title: "dodaj do analizy wg raportu", input: 'radio', inputOptions: { 'pracownicy' : "Pracownicy", 'kontrahenci' : "Kontrahenci", // 'pracownicy_pozostale' : "Pracownicy (pozostałe)", // 'kontrahenci_pozostale' : "Kontrahenci (pozostałe)", }, inputValidator: function (value) { return !value && 'Proszę wybrać typ danych'; } }).then(function (data) { handleAddToReportByPreviousReport(data.value); }) // TODO: like addToReportByPreviousReport but after select report, show counters for pracow., kontr., pozostale od and do with checkbox // swal({ // title: "TODO: dodaj do analizy wg raportu", // }) // TODO: https://github.com/sweetalert2/sweetalert2-react-content // - just pass React element to 'html' ? }, renderClearPozostaleOdBtn: function () { return h('i', { title: "Wyczyść pozostałe", className: "glyphicon glyphicon-remove", style: { 'font-size': '14px', 'line-height': '21px', 'margin-left': '3px', 'vertical-align': 'middle', color: "#f00", opacity: "0.5", cursor: "pointer" }, onClick: this.clearPozostaleOd, 'line-height': '20px' }); }, renderClearPozostaleDoBtn: function () { return h('i', { title: "Wyczyść pozostałe", className: "glyphicon glyphicon-remove", style: { 'font-size': '14px', 'line-height': '21px', 'margin-left': '3px', 'vertical-align': 'middle', color: "#f00", opacity: "0.5", cursor: "pointer" }, onClick: this.clearPozostaleDo, 'line-height': '20px' }); }, renderSummaryList: function () { var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale; var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale; return h('ul', {}, [ h('li', { style: { marginTop: "6px" } }, [ h('span', { style: totalOd > 0 ? { color: "#d7142d" } : {} }, [ " OD ", h('span', { className: "badge", style: totalOd > 0 ? { 'background-color': "#d7142d" } : {} }, totalOd), " : ", ]), h('a', { className: "btn btn-primary btn-xs", href: "#PRACOWNICY" }, [ // .bi-btn-primary " pracownicy ", h('span', { className: "badge" }, this.state.totalOdPracownicy), ]), h('i', { className: "glyphicon glyphicon-plus", style: { 'font-size': "14px", margin: "0 12px" } }), h('button', { className: "btn btn-primary btn-xs", onClick: this.addOdPozostale }, [ // .bi-btn-primary " pozostałe ", h('span', { className: "badge" }, this.state.totalOdPozostale), ]), (this.state.totalOdPozostale > 0) ? this.renderClearPozostaleOdBtn() : null, ]), h('li', { style: { marginTop: "6px" } }, [ h('span', { style: totalDo > 0 ? { color: "#d7142d" } : {} }, [ " DO ", h('span', { className: "badge", style: totalDo > 0 ? { 'background-color': "#d7142d" } : {} }, totalDo), " : ", ]), h('a', { className: "btn btn-primary btn-xs", href: "#KONTRAHENCI" }, [ // .bi-btn-primary " kontrahenci ", h('span', { className: "badge" }, this.state.totalDoKontrahenci), ]), h('i', { className: "glyphicon glyphicon-plus", style: { 'font-size': "14px", margin: "0 12px" } }), h('button', { className: "btn btn-primary btn-xs", onClick: this.addOdPozostale }, [ // .bi-btn-primary " pozostałe ", h('span', { className: "badge" }, this.state.totalDoPozostale), ]), (this.state.totalDoPozostale > 0) ? this.renderClearPozostaleDoBtn() : null, ]), ]); }, renderRaportParamsForm: function () { var depth = parseInt(this.state.depth); var isDepthValid = ( !isNaN(depth) && depth >= 1 && depth <= 16 ); var onlyTargets = this.state.onlyTargets; return h('div', {}, [ h('div', { className: "row" + ( isDepthValid ? "" : " has-error" ), style: { 'margin-bottom': "12px" } }, [ h('div', { className: "form-item col-md-7 col-lg-9 smad-heder-title", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [ "głębokość powiązań: ", ]), h('div', { className: "form-item col-md-5 col-lg-3" }, [ h('input', { type: "number", className: "form-control", placeholder: "1-16", value: this.state.depth, onChange: this.handleChangeDepth, min: 1, max: 16 }), ]), ]), h('div', { className: "row", style: { 'margin-bottom': "12px" } }, [ h('div', { className: "form-item col-md-7 col-lg-9 smad-heder-title", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [ "Czy zwracać wyniki tylko ze znalezionymi obiektami docelowymi (DO)? ", ]), h('div', { className: "form-item col-md-5 col-lg-3" }, [ h('div', { className: "btn-group" }, [ h('div', { className: "btn btn-default" + ( onlyTargets ? " active" : "" ), style: { padding: "6px 12px" }, onClick: this.handleChangeSetOnlyTargetsYes }, "TAK"), h('div', { className: "btn btn-default" + ( onlyTargets ? "" : " active" ), style: { padding: "6px 12px" }, onClick: this.handleChangeSetOnlyTargetsNo }, "NIE"), ]), ]), ]), h('div', { className: "row", style: { 'margin-bottom': "12px" } }, [ h('div', { className: "form-item col-md-3 col-lg-3", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [ "Tytuł:", ]), h('div', { className: "form-item col-md-9 col-lg-9" }, [ h('input', { type: "text", className: "form-control", placeholder: 'Raport bez tytułu z dnia ' + CURRENT_DATE, value: this.state.title, onChange: this.handleChangeTitle }), ]), ]), ]); }, renderRaportFormSubmitBtn: function () { var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale; var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale; var isFormValid = (totalOd || totalDo); return h('div', { className: "row", style: { padding: "0", 'margin-bottom': "0", 'text-align': "right" } }, [ h('div', { className: "form-item col-md-12 col-lg-12" }, [ h('button', { type: "button", className: "btn btn-default" + ( isFormValid ? "" : " disabled" ), onClick: this.handleRaportSubmitForm, style: { padding: "18px 42px", 'font-size': "18px", 'font-weight': "900" } }, "GENERUJ RAPORT POWIĄZAŃ"), ]), ]); }, renderAddMoreBtns: function () { return h('div', { style: { 'padding-top': 6, 'padding-bottom': 20 } }, [ h('button', { className: "btn btn-success btn-xs", onClick: this.handleAddByLastReportClick }, "dodaj do analizy wg raportu"), ]); }, render: function () { DBG && console.log('DBG::P5UI__BocianHeader::render ', { state: this.state }); var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale; var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale; var depth = this.state.depth; var errorMsg = (depth > 16) ? "Maksymalna głębokość powiązań to 16!" : ""; var warningMsg = ( ( !totalOd || !totalDo ) && depth > 6 ) ? "Krytyczne wielkości danych do przeszukania. Optymalna głębokość szukania powiaząń to: 6" : ""; return h('div', { className: "container-fluid", style: { backgroundColor: "#efefef" } }, [ h('div', { style: { fontSize: '16px', fontWeight: "normal", color: "#777" } }, [ h('div', { className: "row" }, [ h('div', { className: "col-md-6" }, [ h('h3', { style: { color: "#000" } }, [ h('span', { style: { fontSize: "120%", color: "#d7142d" } }, "|"), " Tworzenie nowego raportu ", h('br'), h('small', {}, [ "(Wybierz elementy do porównania: ", h('span', { style: { color: "#d7142d" } }, " OD "), h('i', { className: "glyphicon glyphicon-random", style: { padding: '0 3px', 'font-size': "80%", color: "#000" } }), h('span', { style: { color: "#d7142d" } }, " DO"), ")", ]) ]), "Wybrano:", this.renderSummaryList(), this.renderAddMoreBtns(), ]), h('div', { className: "col-md-6", style: { 'padding-top': "20px", 'padding-bottom': "20px" } }, [ this.renderRaportParamsForm(), this.renderRaportFormSubmitBtn(), ]), ]), h('div', { className: "row" }, [ h('div', { className: "col-md-8 col-md-offset-2 col-xs-12" }, [ errorMsg ? h('div', { className: "alert alert-danger" }, errorMsg) : null, warningMsg ? h('div', { className: "alert alert-warning" }, warningMsg) : null, ]), ]), ]) ]) } }) function getSelectedListLocalStorageKey(from) { // from: ( OD | DO ) switch (from) { case 'OD': return 'Bocian.biAuditForm.odFeatureKeys'; case 'DO': return 'Bocian.biAuditForm.doFeatureKeys'; default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'"; } } function getListFromLocalStorage(key) { return JSON.parse( localStorage.getItem(key) || '[]' ); } function getSignedIntFromLocalStorage(key, defaultValue) { return JSON.parse( localStorage.getItem(key) || defaultValue ); } function getStringFromLocalStorage(key, defaultValue) { var value = localStorage.getItem(key); value = (value) ? JSON.parse(value) : ''; return (value) ? value : defaultValue; } // function saveToSelectedListInLocalStorage(from, featureKey) { // DBG && console.log("DBG::saveToSelectedListInLocalStorage(from, featureKey)", {from, featureKey}, {added: getSelectedListFromLocalStorage(from).concat(featureKey)}); // localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify( // getSelectedListFromLocalStorage(from).concat(featureKey) // )) // } // function removeFromSelectedListInLocalStorage(from, featureKey) { // DBG && console.log("DBG::removeFromSelectedListInLocalStorage(from, featureKey)", {from, featureKey}); // localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify( // getSelectedListFromLocalStorage(from).filter(function (item) { // return ( item !== featureKey ); // }) // )) // } /* DATA FOR READ REAPORT */ function urlFetchKontrahenciPowiazania() { // Documentation: https://github.com/github/fetch fetch(URL_FETCH_KONTRAHENCI_POWIAZANIA, { credentials: 'same-origin' }) .then(function parseJSON(response) { return response.json() }) .then(function(data) { var reaportItemsKontrahenciPowiazani = null; data.body.items.forEach (function(row) { reaportItemsKontrahenciPowiazani += ''+ ''+row["ID"]+''; }); $( "#body-reaport-kontrahenci-powiazani-tree" ).html(reaportItemsKontrahenciPowiazani); }).catch(function(error) { if(DBG) console.log('request failed', error) }); } /* FORM DATA FOR GENERATAE REAPORT */ /** * Załadowanie wybranej pozycji w select czy zwracać wyniki tylko z obiektami docelowymi onlyTarget */ function loadCurrentOnlyTargetsSelect() { var analizaOnlyTargets = getItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets'); $('#smad-select-target').val(analizaOnlyTargets).attr("selected", "selected"); $('#smad-select-target-kontrahenci').val(analizaOnlyTargets).attr("selected", "selected"); } /** * Załadowanie do storage informacji czy zwracać wyniki tylko z obiektami docelowymi */ function updateLocalStorageBiAuditOnlyTargets(idSelect) { $(idSelect).change(function() { var newValue = $(idSelect).val(); var responseValue = newValue; setItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets', responseValue); $('#smad-select-target').val(newValue).attr("selected", "selected"); $('#smad-select-target-kontrahenci').val(newValue).attr("selected", "selected"); // load in select selected option loadCurrentOnlyTargetsSelect(); }); } /** * Funkcja pozwala na wyświetlenie okienka importu */ function showViewUploadFile( event, headerTitle, enumType, showCheckbox, csvFileExample ) { event.preventDefault(); var enumType = enumType; if( csvFileExample !== undefined) { // przykład + instrukcja do pobrania csvFileExample = '
Pobierz przykład
'; } swal({ title: 'Importuj plik csv', input: 'file', html: csvFileExample, inputAttributes: { 'accept': 'text/csv', 'aria-label': 'Upload csv file' }, confirmButtonText: 'Importuj', preConfirm: function (file) { return new Promise(function (resolve, reject) { if (!file) { reject("Proszę wybrać plik csv"); return } var input = document.querySelector('input[type="file"]'); var data = new FormData() data.append('file', input.files[0]) data.append('showCheckbox', showCheckbox); var responseParseFile = parseCsvFile( data, enumType ); resolve('file imported') }) }, }).then(function (result) { if(DBG) console.log('result', result); }).catch(function (e) { if(DBG) console.log('catch: ', e); }); } /** * Funkcja przekazuje dane z pliku csv do przeparsowania */ function parseCsvFile( fileData, enumType ) { event.preventDefault(); if(DBG) console.log( 'parseCsvFile fileData', fileData); fetch(URL_FORM_DATA_CSV_FILE_AJAX, { method: 'POST', credentials: 'same-origin', body: fileData }) .then(function(response) { return response.json() }).then(function(json) { swal({ title: 'Dane załadowane z pliku CSV', html: json.body.view, width: Math.round(window.innerWidth * 0.9), allowOutsideClick: false, // TODO: btn Anuluj na dole? showCloseButton: true, confirmButtonText: 'Zapisz', preConfirm: function (dataForm) { return new Promise(function (resolve, reject) { if (!dataForm) { reject("Formularz nie zawiera danych do zapisania"); return } // zapisanie danych var responseSaveData = saveFormCsvFileAjaxAction(enumType); resolve('data save from form') }) }, }).then(function (result) { if(DBG) console.log('result', result) }).catch(function (e) { if(DBG) console.log('catch: ', e) }); }).catch(function(ex) { if(DBG) console.log('parsing failed', ex); }); } /** * Funkcja zapisuje dane z formularza do wgrania pliku csv */ function saveFormCsvFileAjaxAction(enumType) { event.preventDefault(); var formDataFrom = $("#formDataFromCsv").serialize(); formDataFrom = formDataFrom.replace(/%5B/g,"["); formDataFrom = formDataFrom.replace(/%5D/g,"]"); fetch(URL_SAVE_FORM_CSV_FILE_AJAX, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ formData: formDataFrom, enumType: enumType }) }) .then(function(response) { return response.json() }).then(function(json) { if(DBG) console.log('parsed json', json); if (response.type == 'success') { p5UI__notifyAjaxCallback(response.msg); } // return json; }).catch(function(ex) { if(DBG) console.log('parsing failed', ex); }); } /** * Dodaj nowego pracownika */ function createPracownikAjax(event) { event.preventDefault(); swal({ title: 'Dodaj osobę', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, html: '
'+ '' + ''+ ''+ ''+ ''+ '
', preConfirm: () => { return new Promise(function (resolve, reject) { // data from form var personName = $('#personName').val(); var personSurname = $('#personSurname').val(); var personNip = $('#personNip').val(); var personPesel = $('#personPesel').val(); var personRegon = $('#personRegon').val(); //validate data from input if (!personName){ reject('Proszę podać imię') return; } if (!personSurname){ reject('Proszę podać nazwisko') return; } window.fetch(URL_CREATE_PRACOWNICY, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'personName': personName, 'personSurname': personSurname, 'personNip': personNip, 'personPesel': personPesel, 'personRegon': personRegon }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.body); urlFetchPracownicy(1); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }) }) }, allowOutsideClick: false }).then(function (createPerson) { if(DBG) console.log('dodanie osoby: ', createPerson); }); } /** * Dodaj nowego kontrahenta */ function createKontrahentAjax(event) { event.preventDefault(); swal({ title: 'Dodaj podmiot/kontrahenta', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, html: '
'+ '' + ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ ''+ '
', preConfirm: () => { return new Promise(function (resolve, reject) { // data from form var companyFullName = $('#companyFullName').val(); var companyShortName = $('#companyShortName').val(); var companyNameGroup = $('#companyNameGroup').val(); var companyKrs = $('#companyKrs').val(); var companyNip = $('#companyNip').val(); var companyPesel = $('#companyPesel').val(); var companyFax = $('#companyFax').val(); var companyTelefon = $('#companyTelefon').val(); var companyMail = $('#companyMail').val(); var companyStreet = $('#companyStreet').val(); var companyNumberBuilding = $('#companyNumberBuilding').val(); var companyNumberLocal = $('#companyNumberLocal').val(); var companyPostCode = $('#companyPostCode').val(); var companyPlace = $('#companyPlace').val(); var companyCountry = $('#companyCountry').val(); var companyTypeCompany = $('#companyTypeCompany').val(); var companyTitleDocument = $('#companyTitleDocument').val(); var companyDesc = $('#companyDesc').val(); //validate data from input if (!companyFullName){ reject('Proszę podać pełną nazwę'); return; } window.fetch(URL_CREATE_KONTRAHENCI, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'companyFullName': companyFullName, 'companyShortName': companyShortName, 'companyNameGroup': companyNameGroup, 'companyKrs': companyKrs, 'companyNip': companyNip, 'companyPesel': companyPesel, 'companyFax': companyFax, 'companyTelefon': companyTelefon, 'companyMail': companyMail, 'companyStreet': companyStreet, 'companyNumberBuilding': companyNumberBuilding, 'companyNumberLocal': companyNumberLocal, 'companyPostCode': companyPostCode, 'companyPlace': companyPlace, 'companyCountry': companyCountry, 'companyTypeCompany': companyTypeCompany, 'companyTitleDocument': companyTitleDocument, 'companyDesc': companyDesc }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.body); urlFetchKontrahenci(1); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }) }) }, allowOutsideClick: false }).then(function (createPerson) { if(DBG) console.log('dodanie podmiotu: ', createPerson); }); } /** * Popup z opcja przeniesienia pracowników do innej grupy */ function addPracownikToGroup(event) { event.preventDefault(); var pracownicyIdsArray = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'); if (pracownicyIdsArray === null || !pracownicyIdsArray || !pracownicyIdsArray.length) { showTextListIdPracownikow = 'nie wybrano osób'; } else { showTextListIdPracownikow = '' + pracownicyIdsArray.length + ' osób'; } var arrayGroupOptions = []; var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups'); // utworzenie tablicy Optionsów grupy listGroupStorage.map(function(item) { if (item.ID !== undefined) { arrayGroupOptions[item.ID] = item.NAZWA; } }); swal({ title: 'Dodaj do grupy', input: 'select', text: showTextListIdPracownikow, inputOptions: arrayGroupOptions, inputPlaceholder: 'Wybierz grupę', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, preConfirm: function (idGroup) { if (!idGroup) { swal.showValidationError('Proszę wybrać nazwę grupy'); return; } if (!pracownicyIdsArray || !pracownicyIdsArray.length) { swal.showValidationError('Proszę wybrać pracowników'); return; } return new Promise(function (resolve, reject) { window.fetch(URL_ADD_PRACOWNICY_TO_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'idGroup': idGroup, 'pracownicyIds': getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'), }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.msg); } else { reject(result.msg); } }) .catch(function(error) { if(DBG) console.warn('request failed', error); }); }) }, allowOutsideClick: false }).then(function (value) { { // remove from selected setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', []); updateCountItemCheckedByType('pracownicy'); $('form').find(':checkbox').prop('checked', false); } }).catch(function (e) { DBG && console.log('DBG: e', e) }); } function addPracownikAllToGroup(event) { event.preventDefault(); var showTextListIdPracownikow = 'wszystkich pracowników pasujących do kryteriów wyszukiwania'; var arrayGroupOptions = []; var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups'); // utworzenie tablicy Optionsów grupy listGroupStorage.map(function(item) { if (item.ID !== undefined) { arrayGroupOptions[item.ID] = item.NAZWA; } }); swal({ title: 'Dodaj do grupy', input: 'select', text: showTextListIdPracownikow, inputOptions: arrayGroupOptions, inputPlaceholder: 'Wybierz grupę', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, preConfirm: function (idGroup) { return new Promise(function (resolve, reject) { if (!idGroup) { reject('Proszę wybrać nazwę grupy'); return; } var filterFields = {} var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form var fieldNameList = FIELD_LIST_PRACOWNICY fieldNameList.filter(function (fieldName) { if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"'); return (frm[fieldName]) ? true : false }).map(function (fieldName) { return [ fieldName, frm[fieldName].value ] }).filter(function (filter) { return ( filter[1].length > 0 ) }).map(function (filter) { filterFields[ filter[0] ] = filter[1] }) var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'); if (filterIdGroup) filterFields[ 'filterIdGroup' ] = filterIdGroup window.fetch(URL_ADD_PRACOWNICY_TO_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'idGroup': idGroup, 'type': 'filter', 'filter': filterFields, }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.msg); } else { reject(result.msg); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }); }) }, allowOutsideClick: false }).then(function (groupPracownicyData) { //TODO: pIOTRKU CZY TU POWINIENEM COŚ JESZCZE OBSŁUŻYĆ }); } /** * Popup z opcja przeniesienia kontrahentów do innej grupy */ function addKontrahenciToGroup(event) { event.preventDefault(); var kontrahenciIdsArray = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'); if (kontrahenciIdsArray === null || !kontrahenciIdsArray || !kontrahenciIdsArray.length) { showTextListIdKontrahentow = 'nie wybrano kontrahentów'; } else { showTextListIdKontrahentow = '' + kontrahenciIdsArray.length + ' podmiotów/kontrahentów'; } var arrayGroupOptions = []; var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups'); // utworzenie tablicy Optionsów grupy listGroupStorage.map(function(item) { if (item.ID !== undefined) { arrayGroupOptions[item.ID] = item.NAZWA; } }); swal({ title: 'Dodaj do grupy', input: 'select', text: showTextListIdKontrahentow, inputOptions: arrayGroupOptions, inputPlaceholder: 'Wybierz grupę', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, preConfirm: function (idGroup) { if (!idGroup) { swal.showValidationError('Proszę wybrać nazwę grupy'); return; } if (!kontrahenciIdsArray || !kontrahenciIdsArray.length) { swal.showValidationError('Proszę wybrać kontrahentów'); return; } return new Promise(function (resolve, reject) { window.fetch(URL_ADD_KONTRAHENCI_TO_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'idGroup': idGroup, 'kontrahenciIds': getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'), }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.msg); } else { reject(result.msg); } }) .catch(function(error) { if(DBG) console.warn('request failed', error); }); }) }, allowOutsideClick: false }).then(function (value) { { // remove from selected setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', []); updateCountItemCheckedByType('kontrahenci'); $('form').find(':checkbox').prop('checked', false); } }).catch(function (e) { DBG && console.log('DBG: e', e) }); } function addKontrahenciAllToGroup(event) { event.preventDefault(); var kontrahenciIdsArray = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'); var showTextListIdKontrahentow = 'wszystkich podmotów/kontrahentów pasujących do kryteriów wyszukiwania'; var arrayGroupOptions = []; var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups'); // utworzenie tablicy Optionsów grupy listGroupStorage.map(function(item) { if (item.ID !== undefined) { arrayGroupOptions[item.ID] = item.NAZWA; } }); swal({ title: 'Dodaj do grupy', input: 'select', text: showTextListIdKontrahentow, inputOptions: arrayGroupOptions, inputPlaceholder: 'Wybierz grupę', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, preConfirm: function (idGroup) { return new Promise(function (resolve, reject) { if (!idGroup) { reject('Proszę wybrać nazwę grupy'); return; } var filterFields = {} var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form var fieldNameList = FIELD_LIST_KONTRAHENCI fieldNameList.filter(function (fieldName) { if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"') return (frm[fieldName]) ? true : false }).map(function (fieldName) { return [ fieldName, frm[fieldName].value ] }).filter(function (filter) { return ( filter[1].length > 0 ) }).map(function (filter) { filterFields[ filter[0] ] = filter[1] }) var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'); if (filterIdGroup) filterFields[ 'filterIdGroup' ] = filterIdGroup window.fetch(URL_ADD_KONTRAHENCI_TO_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'idGroup': idGroup, 'type': 'filter', 'filter': filterFields, }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false); if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.msg); } else { reject(result.msg); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }); }) }, allowOutsideClick: false }); } function removeKontrahenciFromGroup(event) { event.preventDefault; var kontrahenciIdsArray = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'); if (kontrahenciIdsArray === null || !kontrahenciIdsArray || !kontrahenciIdsArray.length) { showTextListIdKontrahentow = 'nie wybrano kontrahentów'; } else { showTextListIdKontrahentow = '' + kontrahenciIdsArray.length + ' podmiotów/kontrahentów'; } var groupId = getItemLocalStorage("Bocian.biAuditForm.kontrahenci.filterIdGroup"); var removeTitle = "Czy chcesz usunąć z " if (groupId === "0") { removeTitle += "systemu"; } else { var arrayGroupOptions = []; var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups'); // utworzenie tablicy Optionsów grupy listGroupStorage.map(function(item) { if (item.ID !== undefined) { arrayGroupOptions[item.ID] = item.NAZWA; } }); removeTitle += "grupy "; removeTitle += arrayGroupOptions[groupId]; } swal({ title: removeTitle, text: showTextListIdKontrahentow, showConfirmButton: true, showCancelButton: true, confirmButtonText: 'Usuń', cancelButtonText: 'Anuluj', showLoaderOnConfirm: true, preConfirm: function () { return new Promise(function (resolve, reject) { if (!kontrahenciIdsArray || !kontrahenciIdsArray.length) { reject('Wybierz kontrahentów'); return; } window.fetch(URL_REMOVE_KONTRAHENCI_FROM_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'idGroup': getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'), 'kontrahenciIds': getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'), }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { result if (result.type == 'success') { p5UI__notifyAjaxCallback(result); updateTopCounters(); $('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false); resolve(result.msg); } else { reject(result.msg); } }) }) }, allowOutsideClick: false }).then((result) => { if (!result) return; if (result.dismiss) return; if (!result.value) return; { // remove from selected setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', []); updateCountItemCheckedByType('kontrahenci'); $('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false); } urlFetchKontrahenci(1); }); } function removePracownikFromGroup(event){ event.preventDefault; var pracownicyIdsArray = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'); if (pracownicyIdsArray === null || !pracownicyIdsArray || !pracownicyIdsArray.length) { showTextListIdPracownikow = 'nie wybrano osób'; } else { showTextListIdPracownikow = '' + pracownicyIdsArray.length + ' osób'; } var groupId = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'); var removeTitle = "Czy chcesz usunąć z " if (!groupId) { removeTitle += "systemu"; } else { var arrayGroupOptions = []; var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups'); // utworzenie tablicy Optionsów grupy listGroupStorage.map(function(item) { if (item.ID !== undefined) { arrayGroupOptions[item.ID] = item.NAZWA; } }); removeTitle += "grupy "; removeTitle += arrayGroupOptions[groupId]; } swal({ title: removeTitle, text: showTextListIdPracownikow, showConfirmButton: true, showCancelButton: true, confirmButtonText: 'Usuń', cancelButtonText: 'Anuluj', showLoaderOnConfirm: true, preConfirm: function () { return new Promise(function (resolve, reject) { if (!pracownicyIdsArray || !pracownicyIdsArray.length) { reject('Wybierz osoby'); return; } window.fetch(URL_REMOVE_PRACOWNICY_FROM_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'idGroup': getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'), 'pracownicyIds': getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'), }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); updateTopCounters(); $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false); resolve(result.msg); } else { reject(result.msg); } }) }) }, allowOutsideClick: false }).then((result) => { if (!result) return; if (result.dismiss) return; if (!result.value) return; { // remove from selected setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', []); updateCountItemCheckedByType('pracownicy'); $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false); } urlFetchPracownicy(1); }); } function createGroupKontrahenci(event) { event.preventDefault(); swal({ title: 'Utwórz grupę', input: 'text', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, preConfirm: function (NAZWA) { return new Promise(function (resolve, reject) { if (!NAZWA) { reject('Proszę podać nazwę grupy'); return; } window.fetch(URL_CREATE_PRACOWNICY_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'NAZWA': NAZWA }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.body); } else { reject("Proszę podać inną nazwę grupy"); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }) }) }, allowOutsideClick: false }).then(function (result) { if (!result) return; if (result.dismiss) return; if (!result.value) return; // NOTE: swal has input, so resolver object from preConfirm is in { value: resolvedObject } var addedGroup = result.value; if (addedGroup.id && addedGroup.nazwa) { $('#group-kontrahenci').append(''); { // add group to local storage setItemLocalStorage( 'Bocian.biAuditForm.kontrahenci.groups', [].concat( getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups') || [], [ { 'ID': addedGroup.id, 'NAZWA': addedGroup.nazwa } ] ) ); } } //TODO: aktualizacja fitrów na widoku -> SPrawdzić co dostaniemy w odpowiedzi po dodaniu filtra grupy }); } function createGroupPracownicy(event) { event.preventDefault(); swal({ title: 'Utwórz grupę', input: 'text', showCancelButton: true, confirmButtonText: 'Zapisz', showLoaderOnConfirm: true, preConfirm: function (NAZWA) { return new Promise(function (resolve, reject) { if (!NAZWA) { reject('Proszę podać nazwę grupy'); return; } window.fetch(URL_CREATE_PRACOWNICY_GROUP, { method: 'POST', header: { 'contentType': 'applications/json' }, credentials: 'same-origin', body: JSON.stringify({ 'NAZWA': NAZWA }) }) .then(function(response) { return response.text(); }) .then(function(responseText) { try { return JSON.parse(responseText); } catch (e) { throw responseText; } }) .then(function(result) { console.warn('DBG group added? result', result) if (result.type == 'success') { p5UI__notifyAjaxCallback(result); resolve(result.body); } else { reject("Proszę podać inną nazwę grupy"); } }) .catch(function(error) { if(DBG) console.log('request failed', error); }) }) }, allowOutsideClick: false }).then(function (result) { if (!result) return; if (result.dismiss) return; if (!result.value) return; // NOTE: swal has input, so resolver object from preConfirm is in { value: resolvedObject } var addedGroup = result.value; if (addedGroup.id && addedGroup.nazwa) { $('#group-pracownicy').append(''); { // add group to local storage setItemLocalStorage( 'Bocian.biAuditForm.pracownicy.groups', [].concat( getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups') || [], [ { 'ID': addedGroup.id, 'NAZWA': addedGroup.nazwa } ] ) ); } } //TODO: aktualizacja fitrów na widoku -> SPrawdzić co dostaniemy w odpowiedzi po dodaniu filtra grupy }); } /** * Function for load view Form pracownicy/kontrahenci */ function rootChangeForm() { //todo: do przeniesienia urlFetchKontrahenciPowiazania(); var valueUrl = global.location.hash; switch (valueUrl) { case '#KONTRAHENCI': $( ".container-bi_audit_form_kontrahenci_raport" ).html( VIEW_KONTRAHENCI ); urlFetchKontrahenci(1); fetchGroupKontrahenci(); $( ".container-bi_audit_form_pracownicy_raport" ).hide(); $( ".container-bi_audit_form_kontrahenci_raport" ).show(); $(".container-bi-audit_form_operacyjna_baza_zgloszen").hide(); //parseGraph(); break; case '#PRACOWNICY': $( ".container-bi_audit_form_pracownicy_raport" ).html( VIEW_PRACOWNICY ); urlFetchPracownicy(1); fetchGroupPracownicy(); $( ".container-bi_audit_form_kontrahenci_raport" ).hide(); $( ".container-bi_audit_form_pracownicy_raport" ).show(); $(".container-bi-audit_form_operacyjna_baza_zgloszen").hide(); break; case '#OPERACYJNA_BAZA_ZGLOSZEN': $( ".container-bi_audit_form_operacyjna_baza_zgloszen" ).html( OPERACYJNA_BAZA_ZGLOSZEN ); // urlFetchPracownicy(1); // fetchGroupPracownicy(); $( ".container-bi_audit_form_kontrahenci_raport" ).hide(); $( ".container-bi_audit_form_pracownicy_raport" ).hide(); $(".container-bi-audit_form_operacyjna_baza_zgloszen").show(); break; // case '#REAPORT': // $( ".container-bi_audit_form_raport_data" ).html( VIEW_TREE_REAPORT ); // urlFetchKontrahenciPowiazania(); // $( ".container-bi_audit_form_kontrahenci_raport" ).hide(); // $( ".container-bi_audit_form_pracownicy_raport" ).hide(); // $( ".container-bi_audit_form_raport_data" ).show(); // break; default: $( ".container-bi_audit_form_pracownicy_raport" ).html( VIEW_PRACOWNICY ); urlFetchPracownicy(1); fetchGroupPracownicy(); $( ".container-bi_audit_form_kontrahenci_raport" ).hide(); $( ".container-training" ).hide(); $( ".container-about" ).hide(); $( ".container-bi_audit_form_pracownicy_raport" ).show(); break; } // aktualizacja select option czy zwracać wyniki tylko z obiektami docelowymi updateLocalStorageBiAuditOnlyTargets('#smad-select-target'); updateLocalStorageBiAuditOnlyTargets('#smad-select-target-kontrahenci'); // load in select selected option BI_analiza_onlyTargets loadCurrentOnlyTargetsSelect(); } function getAddressData(objectValue) { var objectValue = objectValue || []; var listData = ''; if (!objectValue) { return true; } objectValue.forEach (function(item) { if (item['kodPocztowy']) { listData += '
kod pocztowy: ' + item['kodPocztowy'] + '
'; } if (item['miejscowosc']) { listData += '
miejscowość: ' + item['miejscowosc'] + '
'; } if (item['nrBudynku']) { listData += '
nr budynku: ' + item['nrBudynku'] + '
'; } if (item['nrLokalu']) { listData += '
nr lokalu: ' + item['nrLokalu'] + '
'; } if (item['typAdresu']) { listData += '
typ adresu: ' + item['typAdresu'] + '
'; } if (item['ulica']) { listData += '
ulica: ' + item['ulica'] + '
'; } listData += '
------
'; }); return listData; } /** * Get name name group */ function getNameGroupById(store, filterIdGroup) { var NAZWA = ''; if (!store || filterIdGroup === 0 ) { NAZWA = 'Wszyscy'; } else { $(store).each(function() { if ( parseInt(filterIdGroup) === parseInt(this.ID) ) { NAZWA = this.NAZWA; } }); } return NAZWA; } function getSearchParamsKontrahenci(page) { var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'); var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form var fieldNameList = FIELD_LIST_KONTRAHENCI var filterFields = fieldNameList.filter(function (fieldName) { if (!frm[fieldName] && DBG) console.log('Err missing field: "' + fieldName + '"') return (frm[fieldName]) ? true : false }).map(function (fieldName) { return [fieldName, frm[fieldName].value] }).filter(function (filter) { return (filter[1].length > 0) }).map(function (filter) { return '' + filter[0] + '=' + filter[1] }).join('&') return { page: page, filterIdGroup: filterIdGroup, filterFields: (filterFields.length > 0) ? filterFields : null, }; } function getUrlFetchKontrahenci(page) { // return URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields; var searchParams = getSearchParamsKontrahenci(page); return [ URL_FETCH_KONTRAHENCI, 'page=' + searchParams.page, 'filterIdGroup=' + searchParams.filterIdGroup, searchParams.filterFields, ].filter(Boolean).join('&'); } function urlFetchKontrahenci(page) { hideMoreRecordFunctionsPopover() var page = page || getItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page'); selectPage('KONTRAHENCI', page); if ( page === 1) { setItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page', 1); } var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'); var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form var fieldNameList = FIELD_LIST_KONTRAHENCI var filterFields = fieldNameList.map(function (fieldName) { return [ fieldName, frm[fieldName].value ] }).filter(function (filter) { return ( filter[1].length > 0 ) }).map(function (filter) { return '' + filter[0] + '=' + filter[1] }).join('&') filterFields = (filterFields.length > 0) ? '&' + filterFields : '' fetch(URL_FETCH_KONTRAHENCI + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields, { credentials: 'same-origin' }) .then(function parseJSON(response) { return response.json() var filterIdGroup = filterIdGroup || getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'); }) .then(function(data) { var listItemsKontrahenci = null; data.body.items.forEach (function(row) { listItemsKontrahenci += '' + '' + '' + '' + ''+row["ID"]+''+ '' + ( row["Nazwa_grupy_kapitalowej"] || '' ) + '' + '' + ( row["Pelna_nazwa_kontrahenta"] || '' ) + '' + '' + ( row["Numer_kontrahenta"] || '' ) + '' + '' + ( row["Skrocona_Nazwa_Kontrahenta"] || '' ) + '' + '' + ( row["Typ_kontrahenta"] || '' ) + '' + '' + ( row["NIP"] || '' ) + '' + '' + ( row["KRS"] || '' ) + '' + '' + ( row["REGON"] || '' ) + '' + '' + ( row["PESEL"] || '' ) + '' + '' + ( row["Forma_prawna_dzialalnosci"] || '' ) + '' + '' + ( row["Ulica"] || '' ) + '' + '' + ( row["Numer_budynku"] || '' ) + '' + '' + ( row["Numer_mieszkania_lokalu"] || '' ) + '' + '' + ( row["Miejscowosc"] || '' ) + '' + '' + ( row["Kod_pocztowy"] || '' ) + '' + '' + ( row["Kraj"] || '' ) + '' + '' + ( row["Telefon"] || '' ) + '' + '' + ( row["Fax"] || '' ) + '' + '' + ( row["Mail"] || '' ) + '' + '' + ( row["A_ADM_COMPANY"] || '' ) + '' + '' + ( row["A_CLASSIFIED"] || '' ) + '' + '' + ( row["Dodano"] || '' ) + '' + '' + ( row["Podmiot_dominujacy"] || '' ) + '' + '' + ( row["Tytul_dokumentu"] || '' ) + '' + '' + ( row["ownCompany"] || '' ) + '' + '' + ( row["uwagi"] || '' ) + ''; }); if (data.body.pagination !== undefined) { Pagination.Init(document.getElementById('pagination-kontrahenci'), { url: BASE_URLS+'index.php?_route=UrlAction_Bocian#KONTRAHENCI', id_pagination: 'pagination-kontrahenci', type: 'KONTRAHENCI', limit: data.body.pagination.limit, total_items: data.body.pagination.total_items, // pages size size: data.body.pagination.size, // pages size page: page, // selected page step: 1 // pages before and after current }); var paginationShowNextCount = 1; if ( parseInt(data.body.pagination.current) !== 1) { paginationShowNextCount = parseInt(data.body.pagination.limit) * (parseInt(data.body.pagination.current) - 1 ) + 1; } $('#paginationShowNextCount-KONTRAHENCI').text(paginationShowNextCount); $('#smad-filter-desc-kontrahenci').text(data.body.pagination.total_items); if (data.body.pagination.total_items > 0) { var btnAddAll = $(''); btnAddAll.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addAllMatchesToReport); $('#smad-filter-desc-kontrahenci').append(btnAddAll); // var btnAddByReport = $(''); // btnAddByReport.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addToReportByPreviousReport); // $('#smad-filter-desc-kontrahenci').append(btnAddByReport); var btnAddAllToGroup = $(''); btnAddAllToGroup.on('click', addKontrahenciAllToGroup); $('#smad-filter-desc-kontrahenci').append(btnAddAllToGroup); } } var groupSelectData = getNameGroupById(getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups'), filterIdGroup); $('#smad-filter-head-title-kontrahenci').text(groupSelectData); if(DBG) console.log('kontrahenci groupSelectData: ', groupSelectData); $( "#body-kontrahenci" ).html(listItemsKontrahenci); checkAll('KONTRAHENCI'); catchEventCheckbox('KONTRAHENCI'); checkedChoiseItems('KONTRAHENCI', getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds') ); // $( ".container-bi_audit_raport" ).append( data.body.view ); if(DBG) console.log('request succeeded with JSON responseKontrahenci', data) updateTopCounters(); }).catch(function(error) { if(DBG) console.log('request failed', error); }) } function getSearchParamsPracownicy(page) { var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'); var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form var fieldNameList = FIELD_LIST_PRACOWNICY var filterFields = fieldNameList.filter(function (fieldName) { if (!frm[fieldName] && DBG) console.log('Err missing field: "' + fieldName + '"') return (frm[fieldName]) ? true : false }).map(function (fieldName) { return [fieldName, frm[fieldName].value] }).filter(function (filter) { return (filter[1].length > 0) }).map(function (filter) { return '' + filter[0] + '=' + filter[1] }).join('&') return { page: page, filterIdGroup: filterIdGroup, filterFields: (filterFields.length > 0) ? filterFields : null, }; } function getUrlFetchPracownicy(page) { // return URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields; var searchParams = getSearchParamsPracownicy(page); return [ URL_FETCH_PRACOWNICY, 'page=' + searchParams.page, 'filterIdGroup=' + searchParams.filterIdGroup, searchParams.filterFields, ].filter(Boolean).join('&'); } function urlFetchPracownicy(page) { hideMoreRecordFunctionsPopover() var page = page || getItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page'); if ( page === 1) { setItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page', 1); } var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'); selectPage('PRACOWNICY', page); // var paginationLimit = 20; /*p5WFS_GetFeature('default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY', Object.assign({ sortBy: 'ID+D', maxFeatures: paginationLimit, startIndex: (page - 1) * paginationLimit, // TODO: backRefNS, backRefPK, backRefField - TODO: from groups // resolve: 'all', // resolveDepth: 2 'ogc:Filter': '' + '\n' + [ '*', 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*', [ 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI' ].join('/') ].map(function (fieldName) { return '' + fieldName + ''; }).join('\n') + '\n' + '' }, (filterIdGroup > 0) ? { backRefNS: 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group', backRefPK: filterIdGroup, backRefField: 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY', } : {} ) ).then(function (items) { if(DBG)console.log('p5WFS_GetFeature: items: ', items); }).catch(function (err) { if(DBG)console.log('p5WFS_GetFeature: err: ', err); })*/ var fetchUrl = getUrlFetchPracownicy(page); DBG && console.log('DBG: fetch ', { fetchUrl }); fetch(fetchUrl, { credentials: 'same-origin' }) .then(function parseJSON(response) { return response.json() }) .then(function(data) { var addresPerson = ''; var listItemsPracownik = null; if(DBG) console.log('urlFetchPracownicy', data.body.items); data.body.items.forEach (function(row) { if (row["default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy"]) { addresPerson = getAddressData(row["default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy"]); } listItemsPracownik += '' + '' + '' + '' + ''+row["ID"]+'' + '' + ( row["imiona"] || '' ) + '' + '' + ( row["nazwisko"] || '' ) + '' + '' + ( row["nip"] || '' ) + '' + '' + ( row["pesel"] || '' ) + '' + '' + ( row["regon"] || '' ) + '' + '' + ( row["source"] || '' ) + '' + '' + ( row["jednostka_organizacyjna"] || '' ) + '' + '' + ( row["A_STATUS"] || '' ) + '' + '' + ( row["A_STATUS_INFO"] || '' ) + '' + '' + ( row["L_APPOITMENT_USER"] || '' ) + '' + ''+ addresPerson +''; }); if (data.body.pagination.size) { Pagination.Init(document.getElementById('pagination-pracownicy'), { url: BASE_URLS+'index.php?_route=UrlAction_Bocian#PRACOWNICY', id_pagination: 'pagination-pracownicy', type: 'PRACOWNICY', limit: data.body.pagination.limit, total_items: data.body.pagination.total_items, // pages size size: data.body.pagination.size, // pages size page: data.body.pagination.current, // selected page step: 1 // pages before and after current }); var paginationShowNextCount = 1; if ( parseInt(data.body.pagination.current) !== 1) { paginationShowNextCount = parseInt(data.body.pagination.limit) * (parseInt(data.body.pagination.current) - 1 ) + 1; } $('#paginationShowNextCount-PRACOWNICY').text(paginationShowNextCount); $('#smad-filter-desc-pracownicy').text(data.body.pagination.total_items); if (data.body.pagination.total_items > 0) { var btnAddAll = $('') btnAddAll.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addAllMatchesToReport); $('#smad-filter-desc-pracownicy').append(btnAddAll); // var btnAddByReport = $(''); // btnAddByReport.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addToReportByPreviousReport); // $('#smad-filter-desc-pracownicy').append(btnAddByReport); var btnAddAllToGroup = $(''); btnAddAllToGroup.on('click', addPracownikAllToGroup); $('#smad-filter-desc-kontrahenci').append(btnAddAllToGroup); } } // wyświetlenie wybranej grupy w naglówku nad tabela var groupSelectData = getNameGroupById(getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups'), filterIdGroup); $('#smad-filter-head-title-pracownicy').text(groupSelectData); // zaladaowanie listy pracowników $( "#body-pracownicy" ).html( listItemsPracownik); checkAll('PRACOWNICY'); catchEventCheckbox('PRACOWNICY'); checkedChoiseItems('PRACOWNICY', getItemLocalStorage('Bocian.biAuditForm.pracownicyIds') ); updateTopCounters(); }).catch(function(error) { if(DBG) console.log('request failed', error) }) } function selectPage(type, nrPage) { var type = type.toLowerCase(); $('#pagination-' + type + ' ul li a').each(function(index, value){ if (this.text === nrPage) { $(this).addClass('active'); } else { $(this).removeClass('active'); } }); } function checkAll(type) { $('#checkAll-' + type).change(function() { var valueCheckbox = null; var checkboxes = $('form').find(':checkbox'); if($(this).prop('checked')) { checkboxes.prop('checked', true); //valueCheckbox = checkboxes.prop("checked"); var allValsChecked = []; var checkedValues = $('#smad-table-' + type + ' input:checkbox:checked').map(function() { if (this.value !== 'on') { allValsChecked.push(parseInt(this.value)); } }).get(); updateListIdBiAuditReaport(type, allValsChecked); } else { checkboxes.prop('checked', false); var allValsUnChecked = []; var checkedValues = $('#smad-table-' + type + ' input:checkbox:not(:checked)').map(function() { if (this.value !== 'on') { allValsUnChecked.push(parseInt(this.value)); } }).get(); deleteListIdBiAuditReaport(type, allValsUnChecked); } // update count selected IDs updateCountItemCheckedByType(type.toLowerCase()); }); } /** * Select again checkbox before selected item chekbox from storage (pracownicy/kontrahenci) */ function checkedChoiseItems(type, store) { updateCountItemCheckedByType(type.toLowerCase()); var idElement = 'smad-table-' + type; // if id element exist if (document.getElementById(idElement)) { // if not checked if (!store) { return false; } // checked again if user selected Item (pracownicy/kontrahent) for (i = 0; i < store.length; i++) { $('#body-'+type.toLowerCase() +' input[type=checkbox] ').map(function(k, v) { if ( store[i] === parseInt(this.value) ){ $(this).prop('checked', true); } }).get(); } } $('#smad-table-' + type + ' input[type=checkbox]').on( 'load', function() { var itemsCHecked = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'); getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'); if (itemsCHecked.lenght === 0 ) { return; } var valueCheckbox = null; var checkboxes = $('form').find(':checkbox'); if($(this).prop('checked')) { checkboxes.prop('checked', true); var allValsChecked = []; var checkedValues = $('#smad-table-' + type + ' input:checkbox:checked').map(function() { if (this.value !== 'on') { allValsChecked.push(parseInt(this.value)); } }).get(); updateListIdBiAuditReaport(type, allValsChecked); } else { checkboxes.prop('checked', false); var allValsUnChecked = []; var checkedValues = $('#smad-table-' + type + ' input:checkbox:not(:checked)').map(function() { if (this.value !== 'on') { allValsUnChecked.push(parseInt(this.value)); } }).get(); deleteListIdBiAuditReaport(type, allValsUnChecked); } }); } function catchEventCheckbox(type) { $('#smad-table-' + type + ' input[type="checkbox"]').on('change', function() { if($(this).is(":checked")) { var allValsChecked = []; if (this.value !== 'on') { allValsChecked.push(parseInt(this.value)); } updateListIdBiAuditReaport(type, allValsChecked); } else { var allValsUnChecke = []; if (this.value !== 'on') { allValsUnChecke.push(parseInt(this.value)); } deleteListIdBiAuditReaport(type, allValsUnChecke); } // update count selected IDs updateCountItemCheckedByType(type.toLowerCase()); }); } function clearSelectedCheckbox() { $('#checkAll-PRACOWNICY').prop('checked', false) $('#checkAll-KONTRAHENCI').prop('checked', false) } function updateListIdBiAuditReaport(type, valueArray) { var currentStoragePracownicyIds = []; var updateListPracownicyIds = null; var currentStorageKontrahenciIds = []; var updateListKontrahenciIds = null; if ( type == 'PRACOWNICY') { currentStoragePracownicyIds = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'); if(currentStoragePracownicyIds !== null) { updateListPracownicyIds = [...new Set([...currentStoragePracownicyIds ,...valueArray])]; } else { updateListPracownicyIds = valueArray; } setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', updateListPracownicyIds); } if ( type == 'KONTRAHENCI') { currentStorageKontrahenciIds = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'); if(currentStorageKontrahenciIds !== null) { updateListKontrahenciIds = [...new Set([...currentStorageKontrahenciIds ,...valueArray])]; } else { updateListKontrahenciIds = valueArray; } setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', updateListKontrahenciIds); } } function deleteListIdBiAuditReaport(type, valueArray) { if ( type == 'PRACOWNICY') { deleteItemLocalStorage('Bocian.biAuditForm.pracownicyIds', valueArray); } if ( type == 'KONTRAHENCI') { deleteItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', valueArray); } } function fetchGroupPracownicy() { fetch(URL_FETCH_GROUP_PRACOWNICY, { credentials: 'same-origin' }) .then(function parseJSON(response) { return response.json() }) .then(function(data) { setItemLocalStorage('Bocian.biAuditForm.pracownicy.groups', data.body.itmesGroupPracownicy); if (data.body.itmesGroupPracownicy === null) { return; } var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'); var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth'); setItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup', filterIdGroup); setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue); var groupsPracownicy = ''; var activeButton = ''; data.body.itmesGroupPracownicy.forEach (function(row) { activeButton = ''; if ( filterIdGroup === parseInt(row['ID']) ) { activeButton = 'active'; $('#group-pracownicy button.active').removeClass('active'); } groupsPracownicy += ''; }); $("#group-pracownicy").append(groupsPracownicy); updateCountItemCheckedByType('pracownicy'); detectChoiseFilter(); }).catch(function(error) { if(DBG) console.log('request failed', error) }); } function fetchGroupKontrahenci() { fetch(URL_FETCH_GROUP_KONTRAHENCI, { credentials: 'same-origin' }) .then(function parseJSON(response) { return response.json() }) .then(function(data) { setItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups', data.body.itemsGroupKontrahenci); if (data.body.itemsGroupKontrahenci === null) { return; } var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'); var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth'); setItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup', filterIdGroup); setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue); var groupsKontrahenci = ''; var activeButton = ''; data.body.itemsGroupKontrahenci.forEach (function(row) { activeButton = ''; if ( filterIdGroup === parseInt(row['ID']) ) { activeButton = 'active'; $('#group-kontrahenci button.active').removeClass('active'); } groupsKontrahenci += ''; }); $("#group-kontrahenci").append(groupsKontrahenci); updateCountItemCheckedByType('kontrahenci'); detectChoiseFilter(); }).catch(function(error) { if(DBG) console.log('request failed', error) }); } function detectChoiseFilter() { $('#group-kontrahenci').on('click', 'button', function(evt) { $('#group-kontrahenci button.active').removeClass('active'); $(this).addClass('active'); // pobranie id grupy kliknietego buttonu var filterIdGroup = $(this).attr("data-group-filter"); // aktaulna wartość zagłebienia var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth'); // czy zwracać wyniki tylko z obiektami docelowymi var analizaOnlyTargets = getItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets'); // ustawienie ostaniej wartości zagłebienia przed resete setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue); // czy zwracać wyniki tylko z obiektami docelowymi setItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets', analizaOnlyTargets); // ustawić id grupy do sesyjnej setItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup', parseInt(filterIdGroup)); // wywylac funckje pobrania danych urlFetchKontrahenci(1); }); $('#group-pracownicy').on('click', 'button', function(e) { e.preventDefault(); $('#group-pracownicy button.active').removeClass('active'); $(this).addClass('active'); // pobranie id grupy kliknietego buttonu var filterIdGroup = $(this).attr("data-group-filter"); // aktaulna wartość zagłebienia var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth'); // ustawienie ostaniej wartości zagłebienia przed resete setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue); // ustawić id grupy do sesyjnej setItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup', parseInt(filterIdGroup)); // wywylac funckje pobrania danych urlFetchPracownicy(1); }); } // Local storage function setItemLocalStorage(key, array) { localStorage.setItem(key, JSON.stringify(array)); } function getItemLocalStorage(key) { var retrievedData = localStorage.getItem(key); var response = JSON.parse(retrievedData); return response; } function deleteItemLocalStorage(key, itemsArray) { var currentStorageArray = getItemLocalStorage(key); var newStorageArray = removeItemArrayInArray(currentStorageArray, itemsArray); setItemLocalStorage(key, newStorageArray); } /** * arr - array * item - search item */ function removeItemInArray(arr, item) { for(var i = arr.length; i--;) { if(arr[i] === item) { arr.splice(i, 1); } } return arr; } /** * arr - array * item - array list items */ function removeItemArrayInArray(arr, itemsArray) { for(var i = arr.length; i--;) { for(var j = itemsArray.length; j--;) { if(arr[i] === itemsArray[j]) { arr.splice(i, 1); } } } return arr; } /** * Cleart list local storage by type * typeNameLocalStorage - name (praconwicy/kontrahenci) */ function clearListLocalStorageByType(typeNameLocalStorage) { if (typeNameLocalStorage === 'pracownicy') { setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', []); } if (typeNameLocalStorage === 'kontrahenci') { setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', []); } // update count selected item updateCountItemCheckedByType(typeNameLocalStorage); // unchecked checkbox $('#smad-table-'+typeNameLocalStorage.toUpperCase()+' form').find(':checkbox').prop('checked', false); } /** * Update count selected pracowniyc/kontrahenci */ function updateCountItemCheckedByType(typeNameLocalStorage) { var countId = 0; updateTopCounters(); if (typeNameLocalStorage === 'pracownicy') { var countPracownicy = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'); if (countPracownicy === null || countPracownicy === undefined) { return countId; } countId = Object.keys(countPracownicy).length; $('#count-selected-item-pracownicy').text(countId); } if (typeNameLocalStorage === 'kontrahenci') { var countKontrahenci = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'); if (countKontrahenci === null || countKontrahenci === undefined) { return countId; } countId = Object.keys(countKontrahenci).length; $('#count-selected-item-kontrahenci').text(countId); } return countId; } function updateTopCounters() { var idsPracownicy = getListFromLocalStorage('Bocian.biAuditForm.pracownicyIds'); var idsKontrahenci = getListFromLocalStorage('Bocian.biAuditForm.kontrahenciIds'); var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD')); var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO')); var allOdLength = idsPracownicy.length + pozostaleOd.length; var allDoLength = idsKontrahenci.length + pozostaleDo.length; var depthValue = getItemLocalStorage('Bocian.biAuditForm.depth'); if (globalRaportStore) globalRaportStore.dispatch({ type: 'UPDATE', totalOdPracownicy: idsPracownicy.length, totalDoKontrahenci: idsKontrahenci.length, }) } var P5UI__Bocian__ExportFieldSelectOverlay = createReactClass({ handleChange: function (fieldName) { DBG && console.log('DBG:P5UI__Bocian__ExportFieldSelectOverlay:handleChange', { fieldName }) this.props.handleToggle(fieldName); }, setRef: function (reactComponent) { this._rootNode = reactComponent; }, componentWillMount: function () { // TODO: mv to div at the end of body, then position div by event.target.offsetTop / offsetLeft this._closeDropdownIfClickedOutside = function (event) { if (DBG) console.log("P5UI__Bocian__ExportFieldSelectOverlay::_closeDropdownIfClickedOutside idHtmlPopover:", { 'this__rootNode': this._rootNode }) if (!this._rootNode) return; var isClickedOutside = p5UI__clickedOutsideElement(this._rootNode, event) if (isClickedOutside) { this._unbindCloseDropdownIfClickedOutside(); this.props.handleClose(); } }.bind(this); this._bindCloseDropdownIfClickedOutside = function () { if (DBG) console.log("P5UI__Bocian__ExportFieldSelectOverlay::_bindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside) if (!document.addEventListener && document.attachEvent) { document.attachEvent('onclick', this._closeDropdownIfClickedOutside); } else { document.addEventListener('click', this._closeDropdownIfClickedOutside); } }.bind(this); this._unbindCloseDropdownIfClickedOutside = function () { if (DBG) console.log("P5UI__Bocian__ExportFieldSelectOverlay::_unbindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside) if (!document.removeEventListener && document.detachEvent) { document.detachEvent('onclick', this._closeDropdownIfClickedOutside); } else { document.removeEventListener('click', this._closeDropdownIfClickedOutside); } }.bind(this); }, componentDidMount: function () { this._bindCloseDropdownIfClickedOutside(); }, renderExportField: function (field) { //
  •  Nr
  • var self = this; var fieldName = field.name; var label = field.label; var isChecked = this.props.exportFieldsStore.state.selected.has(fieldName); return h('li', {}, [ h('label', { style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [ h('input', { checked: isChecked, type: "checkbox", title: fieldName, value: fieldName, onChange: function () { self.handleChange(fieldName); } }), " ", label.replace(/_/g, ' ') ]) ]); }, handleExportToHTML: function (event) { event.preventDefault(); this.openExportWindow('html'); }, handleExportToCSV: function (event) { event.preventDefault(); this.openExportWindow('csv'); }, handleExportToLatin2CSV: function (event) { event.preventDefault(); this.openExportWindow('csv_cp1250'); }, handleExportToXLS: function (event) { event.preventDefault(); this.openExportWindow('xls'); }, handleExportToXLSX: function (event) { event.preventDefault(); this.openExportWindow('xlsx'); }, openExportWindow: function (format) { var selected = this.props.exportFieldsStore.state.selected; DBG && console.log('DBG:P5UI__Bocian__ExportFieldSelectOverlay:openExportWindow', { format: format, selected: selected }) var exportUrl = [ 'index.php?_route=ViewTableAjax&_task=export&namespace=' + this.props.namespace, 'format=' + format, 'flds=' + Array.from(selected).join(','), 'sortCol=' + (this.props.sortCol || ''), 'sortDir=' + (this.props.sortDir ? "desc" : "asc"), this.props.queryFilter ].join('&'); var win = window.open(exportUrl, '_blank'); win.focus(); }, // if (!exportFields.length) { // alert('Nie wybrano żadnych pól do eksportu.'); // e.preventDefault(); // return false; // } // var limit = 10000; // if (!_data.total || _data.total <= 0) { // alert('Brak rekordów do eksportu.'); // e.preventDefault(); // return false; // } // if (_data.total > limit) { // if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) { // e.preventDefault(); // return false; // } // } renderExportToHTML: function () { return h('li', {}, [ h('a', { href: "#", onClick: this.handleExportToHTML, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [ h('i', { className: "glyphicon glyphicon-share" }), " Export do HTML" ]) ]); }, renderExportToCSV: function () { return h('li', {}, [ h('a', { href: "#", onClick: this.handleExportToCSV, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [ h('i', { className: "glyphicon glyphicon-share" }), " Export do CSV" ]) ]); }, renderExportToLatin2CSV: function () { return h('li', {}, [ h('a', { href: "#", onClick: this.handleExportToLatin2CSV, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" }, title: "Export do pliku CSV w kodowaniu Windows-1250", }, [ h('i', { className: "glyphicon glyphicon-share" }), " Export do CSV (Windows-1250)" ]) ]); }, renderExportToXLS: function () { return h('li', {}, [ h('a', { href: "#", onClick: this.handleExportToXLS, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [ h('i', { className: "glyphicon glyphicon-share" }), " Export do XLS" ]) ]); }, renderExportToXLSX: function () { return h('li', {}, [ h('a', { href: "#", onClick: this.handleExportToXLSX, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [ h('i', { className: "glyphicon glyphicon-share" }), " Export do XLSX" ]) ]); }, render: function () { if (!this.props.exportFields) console.warn('DBG: missing this.props.exportFields', { 'this.props': this.props }); if (!this.props.exportFields) return null; return h('ul', { ref: this.setRef, className: "dropdown-menu", style: { height: "250px", 'min-width': "300px", 'padding': "5px 20px 5px 8px", overflow: "auto", display: "block", position: "absolute", left: this.props.offsetLeft, top: this.props.offsetTop - 250, margin: 0, // height: 250px; // this.props.btnBBox }, }, this.props.exportFields.map(this.renderExportField).concat([ this.renderExportToHTML(), this.renderExportToCSV(), this.renderExportToLatin2CSV(), this.renderExportToXLS(), this.renderExportToXLSX(), ])); } }); var _Containers__ExportFields = {}; // namespace => Unstated Container var _Containers__get = function (namespace, initialSelected) { if (_Containers__ExportFields[namespace]) return _Containers__ExportFields[namespace]; var selected = new Set(); if (initialSelected) initialSelected.forEach(function (field) { selected.add(field.name); }) _Containers__ExportFields[namespace] = global.p5VendorJs.createUnstatedContainer({ state: { namespace: namespace, selected: selected, }, toggleField(fieldName) { var selected = this.state.selected; selected.has(fieldName) ? selected.delete(fieldName) : selected.add(fieldName) this.setState({ selected: selected }); }, selectField(fieldName) { var selected = this.state.selected; selected.add(fieldName) this.setState({ selected: selected }); }, unselectField(fieldName) { var selected = this.state.selected; selected.delete(fieldName) this.setState({ selected: selected }); }, }); // namespace = 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY'; // namespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI'; return _Containers__ExportFields[namespace]; } var P5UI__Bocian__ExportTable = createReactClass({ // @props: { namespace, exportFields } _node: null, getInitialState: function () { return { isOpen: false, }; }, handleToggleDropdown: function (event) { var offsetLeft = 0; var offsetTop = 0; this.removePopup(); if (!this.state.isOpen) { var btnBBox = ("BUTTON" !== event.target.nodeName) ? event.target.parentNode.getBoundingClientRect() : event.target.getBoundingClientRect(); offsetLeft = btnBBox.left; offsetTop = window.pageYOffset + btnBBox.y; this._node = document.createElement('div'); this._node.setAttribute('data-p5class', "P5UI__Bocian__ExportTable"); this._node.position = "absolute"; this._node.left = "0"; this._node.top = "0"; this._node.height = "100%"; this._node.backgroundColor = "#00000050"; this._node.width = "100%"; var handleClose = this.handleClose.bind(this); var exportFields = this.props.exportFields; var exportFieldsContainer = _Containers__get(this.props.namespace, this.props.exportFields); document.body.appendChild(this._node); var self__props = this.props; ReactDOM.render( h(Unstated.Provider, {}, [ h(Unstated.Subscribe, { to: [ exportFieldsContainer ] }, function (exportFieldsCont) { DBG && console.log('DBG:exportFieldsCont', { exportFieldsCont }) return h(P5UI__Bocian__ExportFieldSelectOverlay, Object.assign({}, self__props, { exportFields: exportFields, btnBBox: btnBBox, exportFieldsStore: exportFieldsCont, handleToggle: exportFieldsCont.toggleField.bind(exportFieldsCont), handleClose: handleClose, offsetLeft: offsetLeft, offsetTop: offsetTop, })); } ) ]), this._node ); } this.setState({ isOpen: !this.state.isOpen }); }, removePopup: function () { if (this._node && 1 === this._node.nodeType) { document.body.removeChild(this._node); } this._node = null; }, handleClose: function () { this.removePopup(); this.setState({ isOpen: false }); }, render: function () { // Pagination.code += '
    ' + // //
    '; return h('div', { className: "btn-group", // className: "btn-group dropup pagesize" + " open", }, [ h('button', { className: "btn btn-sm btn-default", // className: "btn btn-sm btn-default dropdown-toggle", // 'data-toggle': "dropdown", onClick: this.handleToggleDropdown }, [ "Export ", h('span', { className: "caret" }), ]), // h('ul', { // className: "dropdown-menu", // style: { // 'max-height': "250px", // 'min-width': "300px", // 'padding': "5px 20px 5px 8px", // overflow: "auto", // } // }, this.props.exportFields.map(this.renderExportField)) ]); // @from TableAjax: // if (priv.options.exportFields && priv.options.exportFields.length) { // node = $('
    '); // var btn = $('').appendTo(node); // var span = $('').appendTo(btn); // var ul = $('