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 createReactClass = global.p5VendorJs.createReactClass;
var h = global.p5VendorJs.React.createElement;
var ReactDOM = global.p5VendorJs.ReactDOM;
var swal = window.swal;
var globalRaportStore = global[STORE_NAME];
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 = '';
}
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(''+addedGroup['nazwa']+' ');
{ // 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(''+addedGroup['nazwa']+' ');
{ // 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 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 = $('
DODAJ WSZYSTKIE DO ANALIZY ');
btnAddAll.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addAllMatchesToReport);
$('#smad-filter-desc-kontrahenci').append(btnAddAll);
// var btnAddByReport = $('
DODAJ DO ANALIZY WG RAPORTU ');
// btnAddByReport.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addToReportByPreviousReport);
// $('#smad-filter-desc-kontrahenci').append(btnAddByReport);
var btnAddAllToGroup = $('
DODAJ WSZYSTKIE DO GRUPY ');
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 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 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('&')
filterFields = (filterFields.length > 0) ? '&' + filterFields : ''
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);
})*/
fetch(URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields, {
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 = $('
DODAJ WSZYSTKIE DO ANALIZY ')
btnAddAll.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addAllMatchesToReport);
$('#smad-filter-desc-pracownicy').append(btnAddAll);
// var btnAddByReport = $('
DODAJ DO ANALIZY WG RAPORTU ');
// btnAddByReport.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addToReportByPreviousReport);
// $('#smad-filter-desc-pracownicy').append(btnAddByReport);
var btnAddAllToGroup = $('
DODAJ WSZYSTKIE DO GRUPY ');
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 += '
' + row['NAZWA'] + ' ';
});
$("#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 += '
'+row['NAZWA']+' ';
});
$("#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,
})
}
// Pagination
var Pagination = {
code: '', // end show html paginations
clickPage: 1, // set default 1 page
// --------------------
// Utility
// --------------------
// initialize default data
Extend: function(data) {
data = data || {};
Pagination.url = data.url;
Pagination.id_pagination = data.id_pagination;
Pagination.type = data.type;
Pagination.limit = data.limit;
Pagination.total_items = data.total_items;
Pagination.size = data.size || 2;
Pagination.page = data.page || 1;
Pagination.step = data.step || 3;
},
// add pages by number (from [s] to [f])
Add: function(s, f) {
for (var i = s; i < f; i++) {
Pagination.code += '
' + i + ' ';
}
},
// add last page with separator
Last: function() {
Pagination.code += '
>> ';
},
// add first page with separator
First: function() {
Pagination.code += '
<< ';
},
// add last page with separator
Next: function() {
Pagination.code += '
> ';
},
// add first page with separator
Prev: function() {
Pagination.code += '
< ';
},
// --------------------
// Handlers
// --------------------
// change page
Click: function() {
clearSelectedCheckbox();
var selectPage = $("#pagination-"+Pagination.type.toLowerCase()+' .tblAjax__footer__toolbar__pagination').find('a.active').text();
Pagination.clickPage = +this.innerHTML || '';
if ( selectPage === NaN || selectPage > Pagination.size) { selectPage = 1; }
switch (this.innerHTML) {
case '>>': // last
Pagination.clickPage = Pagination.size;
break;
case '<<': // first
Pagination.clickPage = 1;
break;
case '<': // prev
Pagination.clickPage = parseInt(selectPage) - 1;
if (Pagination.clickPage < 1) {
Pagination.clickPage = 1;
}
break;
case '>': // next
Pagination.clickPage = parseInt(selectPage) + 1;
if (Pagination.clickPage > Pagination.size) {
Pagination.clickPage = Pagination.size;
}
break;
}
if ( Pagination.type === 'KONTRAHENCI' ) {
setItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page', Pagination.clickPage);
Pagination.page = urlFetchKontrahenci(Pagination.clickPage);
}
else if ( Pagination.type === 'PRACOWNICY' ){
setItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page', Pagination.clickPage);
Pagination.page = urlFetchPracownicy(Pagination.clickPage);
}
Pagination.Start();
},
// --------------------
// Script structure pagination
// --------------------
// binding pages
Bind: function() {
var a = Pagination.e.getElementsByTagName('a');
var currentPage = Pagination.clickPage || 1;
for (var i = 0; i < a.length; i++) {
if (+a[i].innerHTML === Pagination.page) a[i].className = 'btn btn-default active';
a[i].addEventListener('click', Pagination.Click, false);
}
},
// write pagination
Finish: function() {
Pagination.e.innerHTML = Pagination.code;
Pagination.code = '';
Pagination.Bind();
},
// find pagination type
Start: function() {
Pagination.code = '';
if ( Pagination.type === 'KONTRAHENCI' ) {
Pagination.code = '';
} else if ( Pagination.type === 'PRACOWNICY' ) {
Pagination.code = '';
}
Pagination.code += '