1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469 |
- 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: '<a href="' + URL_TABLE_POWIAZANIA + '" title="przejdź do raportów" >Przejdź do raportów</a>',
- 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 += '<tr><td><input type="checkbox" name="kontrID[]" value="'+row['ID']+'" /></td>'+
- '<td align="right">'+row["ID"]+'</td>';
- });
- $( "#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 = '<div><a href="'+csvFileExample+'" title="Pobierz przykład" download target="_balnk">Pobierz przykład</a></div>';
- }
- 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:
- '<div class="form-group">'+
- '<input class="form-control required" id="personName" placeholder="Imię" >' +
- '<input class="form-control required" id="personSurname" placeholder="Nazwisko">'+
- '<input class="form-control required" id="personNip" placeholder="NIP">'+
- '<input class="form-control required" id="personPesel" placeholder="PESEL">'+
- '<input class="form-control required" id="personRegon" placeholder="REGON">'+
- '</div>',
- 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:
- '<div class="form-group">'+
- '<input class="form-control required" id="companyFullName" placeholder="Pelna nazwa" >' +
- '<input class="form-control required" id="companyShortName" placeholder="Skrócona nazwa\">'+
- '<input class="form-control required" id="companyNameGroup" placeholder="Nazwa grupy kapitałowej">'+
- '<input class="form-control required" id="companyKrs" placeholder="KRS">'+
- '<input class="form-control required" id="companyNip" placeholder="NIP">'+
- '<input class="form-control required" id="companyPesel" placeholder="PESEL">'+
- '<input class="form-control required" id="companyFax" placeholder="FAX">'+
- '<input class="form-control required" id="companyTelefon" placeholder="Telefon">'+
- '<input class="form-control required" id="companyMail" placeholder="Mail">'+
- '<input class="form-control required" id="companyStreet" placeholder="Ulica">'+
- '<input class="form-control required" id="companyNumberBuilding" placeholder="Numer budynku">'+
- '<input class="form-control required" id="companyNumberLocal" placeholder="Numer mieszkania /lokalu">'+
- '<input class="form-control required" id="companyPostCode" placeholder="Kod pocztowy">'+
- '<input class="form-control required" id="companyPlace" placeholder="Miejscowosc">'+
- '<input class="form-control required" id="companyCountry" placeholder="Kraj">'+
- '<input class="form-control required" id="companyTypeCompany" placeholder="Typ kontrahenta">'+
- '<input class="form-control required" id="companyTitleDocument" placeholder="Tytul dokumentu">'+
- '<input class="form-control required" id="companyDesc" placeholder="uwagi">'+
- '</div>',
- 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('<button class="btn btn-default" title="'+addedGroup['nazwa']+'" data-group-filter="'+addedGroup['id']+'">'+addedGroup['nazwa']+'</button>');
- { // 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('<button class="btn btn-default" title="'+addedGroup['nazwa']+'" data-group-filter="'+addedGroup['id']+'">'+addedGroup['nazwa']+'</button>');
- { // 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 += '<div>kod pocztowy: ' + item['kodPocztowy'] + '<div>'; }
- if (item['miejscowosc']) { listData += '<div>miejscowość: ' + item['miejscowosc'] + '<div>'; }
- if (item['nrBudynku']) { listData += '<div>nr budynku: ' + item['nrBudynku'] + '<div>'; }
- if (item['nrLokalu']) { listData += '<div>nr lokalu: ' + item['nrLokalu'] + '<div>'; }
- if (item['typAdresu']) { listData += '<div>typ adresu: ' + item['typAdresu'] + '<div>'; }
- if (item['ulica']) { listData += '<div>ulica: ' + item['ulica'] + '<div>'; }
- listData += '<div>------<div>';
- });
- 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 += '<tr><td style="white-space:nowrap">' +
- '<input style="vertical-align:top" type="checkbox" name="kontrID[]" value="'+row['ID']+'" />' +
- '<i onClick="kontrahenciLoadMoreRecordFunctions(event, this, '+row['ID']+')" style="margin-left:6px; cursor:pointer; color:#333" class="glyphicon glyphicon-menu-hamburger" title="Więcej funkcji dla rekordu nr ' + row['ID'] + '"></i>' +
- '</td>' +
- '<td align="right">'+row["ID"]+'</td>'+
- '<td align="right">' + ( row["Nazwa_grupy_kapitalowej"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Pelna_nazwa_kontrahenta"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Numer_kontrahenta"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Skrocona_Nazwa_Kontrahenta"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Typ_kontrahenta"] || '' ) + '</td>' +
- '<td align="right">' + ( row["NIP"] || '' ) + '</td>' +
- '<td align="right">' + ( row["KRS"] || '' ) + '</td>' +
- '<td align="right">' + ( row["REGON"] || '' ) + '</td>' +
- '<td align="right">' + ( row["PESEL"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Forma_prawna_dzialalnosci"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Ulica"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Numer_budynku"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Numer_mieszkania_lokalu"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Miejscowosc"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Kod_pocztowy"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Kraj"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Telefon"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Fax"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Mail"] || '' ) + '</td>' +
- '<td align="right">' + ( row["A_ADM_COMPANY"] || '' ) + '</td>' +
- '<td align="right">' + ( row["A_CLASSIFIED"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Dodano"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Podmiot_dominujacy"] || '' ) + '</td>' +
- '<td align="right">' + ( row["Tytul_dokumentu"] || '' ) + '</td>' +
- '<td align="right">' + ( row["ownCompany"] || '' ) + '</td>' +
- '<td align="right">' + ( row["uwagi"] || '' ) + '</td></tr>';
- });
- 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 = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO ANALIZY</button>');
- btnAddAll.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addAllMatchesToReport);
- $('#smad-filter-desc-kontrahenci').append(btnAddAll);
- // var btnAddByReport = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ DO ANALIZY WG RAPORTU</button>');
- // btnAddByReport.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addToReportByPreviousReport);
- // $('#smad-filter-desc-kontrahenci').append(btnAddByReport);
- var btnAddAllToGroup = $('<button class="btn btn-info" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</button>');
- 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': '<wfs:Query>' + '\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 '<wfs:PropertyName>' + fieldName + '</wfs:PropertyName>';
- }).join('\n') + '\n' + '</wfs:Query>'
- }, (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 += '<tr><td style="white-space:nowrap">' +
- '<input style="vertical-align:top" type="checkbox" name="prID[]" value="'+row['ID']+'" />' +
- '<i onClick="pracownicyLoadMoreRecordFunctions(event, this, '+row['ID']+')" style="margin-left:6px; cursor:pointer; color:#333" class="glyphicon glyphicon-menu-hamburger" title="Więcej funkcji dla rekordu nr ' + row['ID'] + '"></i>' +
- '</td>' +
- '<td align="right">'+row["ID"]+'</td>' +
- '<td align="right">' + ( row["imiona"] || '' ) + '</td>' +
- '<td align="right">' + ( row["nazwisko"] || '' ) + '</td>' +
- '<td align="right">' + ( row["nip"] || '' ) + '</td>' +
- '<td align="right">' + ( row["pesel"] || '' ) + '</td>' +
- '<td align="right">' + ( row["regon"] || '' ) + '</td>' +
- '<td align="right">' + ( row["source"] || '' ) + '</td>' +
- '<td align="right">' + ( row["jednostka_organizacyjna"] || '' ) + '</td>' +
- '<td align="right">' + ( row["A_STATUS"] || '' ) + '</td>' +
- '<td align="right">' + ( row["A_STATUS_INFO"] || '' ) + '</td>' +
- '<td align="right">' + ( row["L_APPOITMENT_USER"] || '' ) + '</td>' +
- '<td align="right">'+ addresPerson +'</td></tr>';
- });
- 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 = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO ANALIZY</button>')
- btnAddAll.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addAllMatchesToReport);
- $('#smad-filter-desc-pracownicy').append(btnAddAll);
- // var btnAddByReport = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ DO ANALIZY WG RAPORTU</button>');
- // btnAddByReport.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addToReportByPreviousReport);
- // $('#smad-filter-desc-pracownicy').append(btnAddByReport);
- var btnAddAllToGroup = $('<button class="btn btn-info" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</button>');
- 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 += '<button class="btn btn-default '+activeButton+'" title="' + row['NAZWA'] + '" data-group-filter="' + row['ID'] + '">' + row['NAZWA'] + '</button>';
- });
- $("#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 += '<button class="btn btn-default '+activeButton+'" title="'+row['NAZWA']+'" data-group-filter="'+row['ID']+'">'+row['NAZWA']+'</button>';
- });
- $("#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) {
- // <li><input checked="" type="checkbox" title="ID" value="ID"> Nr</li>
- 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 += '<div class="btn-group dropup pagesize" style="margin-left:40px">' +
- // <button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export <span class="caret"></span></button>
- // <ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">
- // <li><input checked="" type="checkbox" title="ID" value="ID"> Nr</li>
- // <li><input checked="" type="checkbox" title="A_STATUS" value="A_STATUS"> Status</li>
- // ...
- // <li><input checked="" type="checkbox" title="TV_DVBC_EPG_CHANNEL_NUMBER" value="TV_DVBC_EPG_CHANNEL_NUMBER"> TV: Nr kanału w EPG</li>
- // <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a></li>
- // <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a></li>
- // <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export do pliku CSV w kodowaniu Windows-1250"></i>Export do CSV (Windows-1250)</a></li>
- // </ul></div>';
- 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 = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
- // var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export </button>').appendTo(node);
- // var span = $('<span class="caret"></span>').appendTo(btn);
- // var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
- // $.each(_data.cols, function (col, props) {
- // if (-1 !== priv.options.exportFields.indexOf(col)) {
- // var li = $('<li></li>').appendTo(ul);
- // $(p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" > {2}</input>', [(_exportFieldsSelect[col]) ? 'checked' : '', col, props.friendly || col])).appendTo(li);
- // li.on('click', 'input', priv.exportFieldChanged);
- // }
- // });
- // var li = $('<li></li>').appendTo(ul);
- // $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
- // li.on('click', 'a', priv.exportToHTML);
- // var li = $('<li></li>').appendTo(ul);
- // $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
- // li.on('click', 'a', priv.exportToCSV);
- // var li = $('<li></li>').appendTo(ul);
- // $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export do pliku CSV w kodowaniu Windows-1250"></i>Export do CSV (Windows-1250)</a>').appendTo(li);
- // li.on('click', 'a', priv.exportToCSVWinCP1250);
- // } else {
- // node = $('<span class="' + nodeClass + '"></span>');
- // }
- }
- });
- // 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 += '<li><a href="' + Pagination.url + '" class="btn btn-default">' + i + '</a></li>';
- }
- },
- // add last page with separator
- Last: function() {
- Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">>></a></li>';
- },
- // add first page with separator
- First: function() {
- Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default"><<</a></li>';
- },
- // add last page with separator
- Next: function() {
- Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">></a></li>';
- },
- // add first page with separator
- Prev: function() {
- Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default"><</a></li>';
- },
- // --------------------
- // 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);
- }
- },
- ExportWidget: function() {
- var exportWidgetId = 'p5__exportWidget__' + Pagination.type;
- Pagination.code += '<div id="' + exportWidgetId + '" class="btn-group dropup pagesize" style="margin-left:40px"></div>';
- },
- getSearchQueryFilter: function () { // @return url query filter by namespace
- switch (Pagination.type) {
- case 'PRACOWNICY': {
- var searchParams = getSearchParamsPracownicy();
- return [
- searchParams.filterFields,
- (searchParams.filterIdGroup) ? 'filterIdGroup=' + searchParams.filterIdGroup : null, // TODO: backRef search
- ].filter(Boolean).join('&')
- }
- case 'KONTRAHENCI': {
- var searchParams = getSearchParamsKontrahenci();
- return [
- searchParams.filterFields,
- (searchParams.filterIdGroup) ? 'filterIdGroup=' + searchParams.filterIdGroup : null, // TODO: backRef search
- ].filter(Boolean).join('&')
- }
- default: return '';
- }
- },
- CreateExportWidget: function() {
- var exportFields = null;
- var namespace = '';
- if (Pagination.type === 'PRACOWNICY') {
- exportFields = EXPORT_FIELDS_OD;
- namespace = 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY';
- } else if (Pagination.type === 'KONTRAHENCI') {
- exportFields = EXPORT_FIELDS_DO;
- namespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI';
- }
- DBG && console.log('DBG:EXPORT_FIELDS...', { EXPORT_FIELDS_OD, EXPORT_FIELDS_DO, exportFields });
- if (!exportFields || (exportFields && !exportFields.length)) return;
- var exportWidgetId = 'p5__exportWidget__' + Pagination.type;
- var node = document.getElementById(exportWidgetId);
- DBG && console.log('node: ', { node });
- if (!node) return;
- var sortCol = 'ID';
- var sortDir = 'desc';
- var queryFilter = Pagination.getSearchQueryFilter();
- ReactDOM.render(
- h(P5UI__Bocian__ExportTable, {
- namespace: namespace,
- exportFields: exportFields,
- sortCol: sortCol,
- sortDir: sortDir,
- queryFilter: queryFilter,
- }),
- node
- );
- },
- Finish: function() {
- Pagination.e.innerHTML = Pagination.code;
- Pagination.Bind();
- Pagination.CreateExportWidget();
- },
- // find pagination type
- Start: function() {
- Pagination.code = '';
- if ( Pagination.type === 'KONTRAHENCI' ) {
- Pagination.code += '<div class="foot-info tblAjax__footer__toolbar__info footer_pagination_menu_items"><p>Wiersze od <span id="paginationShowNextCount-KONTRAHENCI"></span> do ' + Pagination.total_items + ' z ' + Pagination.total_items + '</p></div>';
- } else if ( Pagination.type === 'PRACOWNICY' ) {
- Pagination.code += '<div class="foot-info tblAjax__footer__toolbar__info footer_pagination_menu_items"><p>Wiersze od <span id="paginationShowNextCount-PRACOWNICY"></span> do ' + Pagination.total_items + ' z ' + Pagination.total_items + '</p></div>';
- }
- Pagination.code += '<nav aria-label="Page navigation" class="footer_pagination_menu_items"><ul class="btn-group tblAjax__footer__toolbar__pagination smad-pagination" style="margin-bottom:0">';
- Pagination.First();
- Pagination.Prev();
- if ( Pagination.type === 'KONTRAHENCI' ) {
- Pagination.page = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page') || 1;
- }
- else if ( Pagination.type === 'PRACOWNICY' ) {
- Pagination.page = getItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page') || 1;
- }
- if ( Pagination.page > Pagination.size ) {
- Pagination.page = 1;
- }
- if (Pagination.size < Pagination.step * 2 + 6) {
- Pagination.Add(1, Pagination.size + 1);
- }
- else if (Pagination.page < Pagination.step * 2 + 1) {
- Pagination.Add(1, Pagination.step * 2 + 4);
- }
- else if (Pagination.page > Pagination.size - Pagination.step * 2) {
- Pagination.Add(Pagination.size - Pagination.step * 2 - 2, Pagination.size + 1);
- }
- else {
- Pagination.Add(Pagination.page - Pagination.step, Pagination.page + Pagination.step + 1);
- }
- Pagination.Next();
- Pagination.Last();
- Pagination.code += '</ul></nav>';
- Pagination.ExportWidget();
- Pagination.Finish();
- },
- // --------------------
- // Initialization
- // --------------------
- // binding buttons
- Buttons: function(e) {
- var nav = e.getElementsByTagName('a');
- },
- // create skeleton
- Create: function(element) {
- var html = [
- '<div></div>' // pagination container
- ];
- element.innerHTML = html.join('');
- Pagination.e = element.getElementsByTagName('div')[0];
- Pagination.Buttons(element);
- },
- // init
- Init: function(element, options) {
- Pagination.Extend(options);
- Pagination.Create(element);
- Pagination.Start();
- }
- };
- function todo__fetchRaport(id) {
- /* p5WFS_GetFeature('default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', {
- primaryKey: id,
- resolve: 'all',
- resolveDepth: 3,
- }).then(function (features) {
- if(DBG) console.log('features', features)
- }).catch(function (e) {
- if(DBG) console.warn(e)
- p5UI__notifyAjaxCallback({ type: 'error', msg: e })
- })*/
- }
- function removeFiltersPracownicy(event, btnNode) {
- event.preventDefault()
- var fieldNameList = FIELD_LIST_PRACOWNICY
- fieldNameList.forEach(function (fieldName) {
- btnNode.form[fieldName].value = ''
- })
- urlFetchPracownicy(1)
- }
- function removeFiltersKontrahenci(event, btnNode) {
- event.preventDefault()
- var fieldNameList = FIELD_LIST_KONTRAHENCI
- fieldNameList.forEach(function (fieldName) {
- btnNode.form[fieldName].value = ''
- })
- urlFetchKontrahenci(1)
- }
- function onChangeFiltersPracownicy(event, inputNode) {
- urlFetchPracownicy(1)
- }
- function onKeypressFiltersPracownicy(event, inputNode) {
- if ("Enter" === event.key) {
- event.stopPropagation()
- event.preventDefault()
- urlFetchPracownicy(1)
- return false
- }
- }
- function onChangeFiltersKontrahenci(event, inputNode) {
- urlFetchKontrahenci(1)
- }
- function onKeypressFiltersKontrahenci(event, inputNode) {
- if ("Enter" === event.key) {
- event.stopPropagation()
- event.preventDefault()
- urlFetchKontrahenci(1)
- return false
- }
- }
- function loadMoreRecordFunctions(event, node, rowPK, namespace) {
- var _node = node
- var _rowPK = rowPK
- var toShow = true
- if (RECORD_MORE_FUNCTIONS_OPENED_NODE) {
- if (RECORD_MORE_FUNCTIONS_OPENED_NODE === node) toShow = false
- if (RECORD_MORE_FUNCTIONS_OPENED_NODE !== node) {
- jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
- }
- }
- RECORD_MORE_FUNCTIONS_OPENED_NODE = node
- // jQuery(node).popover({
- // container: 'body',
- // placement: 'right',
- // trigger: 'click',
- // template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
- // '<div class="arrow"></div>' +
- // '<div style="display:block;position:relative;">' +
- // '<div class="popover-title">' +
- // '</div>' +
- // '<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">×</button>' +
- // '</div>' +
- // '<div class="popover-content"></div>' +
- // '</div>' +
- // '',
- // html: true,
- // })
- // jQuery(node).popover('show')
- global.fetch(BASE_URLS + 'index.php?_route=ViewTableAjax&namespace=' + namespace + '&_task=moreFunctionsCellAjax&ID=' + rowPK, {
- credentials: 'same-origin'
- }).then(function (response) {
- return response.json()
- }).then(function (json) {
- var funcListWrap = $('<div></div>')
- var funcListNode = $('<ul class="list-unstyled popoverRowFunctions"></ul>').appendTo(funcListWrap)
- if (_node === RECORD_MORE_FUNCTIONS_OPENED_NODE) {
- if (json && 'success' === json.type && json.rowFunctions && json.rowFunctions.length > 0) {
- json.rowFunctions.forEach(function(funObj) {
- var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, _rowPK, {ico: true, label: true});
- var funcItemNode = jQuery('<li></li>')
- funcItemNode.append(funcNode)
- funcListNode.append(funcItemNode)
- });
- }
- }
- // jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
- jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover({
- container: 'body',
- placement: 'right',
- trigger: 'click',
- template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
- '<div class="arrow"></div>' +
- '<div style="display:block;position:relative;">' +
- '<div class="popover-title">' +
- '</div>' +
- '<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">×</button>' +
- '</div>' +
- '<div class="popover-content"></div>' +
- '</div>' +
- '',
- html: true,
- content: funcListWrap.html(),
- })
- jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('show')
- }).catch(function (err) {
- if(DBG) console.log('err', err);
- })
- }
- var p5UI_TableAjax_generateFunctionNode = function(funObj, rowPK, props) {
- var defaultsProps = {
- ico: true,
- label: false
- },
- props = jQuery.extend({}, defaultsProps, props);
- funcNode = $('<a href="#" style="margin:0 2px;"></a>')
- ;
- if ('href' in funObj) funcNode.attr('href', p5Utils__format(funObj.href, [rowPK]));
- if (props.ico) {
- if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
- }
- if ('onclick' in funObj) funcNode.attr('onclick', p5Utils__format(funObj.onclick, [rowPK]));
- if ('title' in funObj) funcNode.attr('title', funObj.title);
- if ('target' in funObj) funcNode.attr('target', funObj.target);
- if (props.label) {
- if ('label' in funObj) {
- funcNode.append(' ' + funObj.label);
- } else if ('title' in funObj) {
- funcNode.append(' ' + funObj.title);
- }
- }
- return funcNode;
- };
- global.p5UI_TableAjax_generateFunctionNode = p5UI_TableAjax_generateFunctionNode
- function addAllMatchesToReport(event) {
- switch (event.data.type) {
- case 'kontrahenci': break; // OK
- case 'pracownicy': break; // OK
- default: throw "Wrong type";
- }
- var postData = {}
- if ('filter_idGroup' in event.data.pagination && event.data.pagination['filter_idGroup']) postData['filter_idGroup'] = event.data.pagination['filter_idGroup']
- Object.keys(event.data.pagination).filter(function (key) {
- return ('f_' === key.substr(0, 2))
- }).forEach(function (filterKey) {
- var value = event.data.pagination[filterKey]
- postData[filterKey] = value
- })
- var thisButton = $(this)
- thisButton.attr('disabled', true)
- thisButton.text( thisButton.text() + '...' )
- if ('pracownicy' === event.data.type) {
- p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie pracowników..." })
- 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 )
- }).forEach(function (filter) {
- postData[ filter[0] ] = filter[1];
- })
- global.fetch(URL_FETCH_PRACOWNICY_IDS_AJAX, {
- credentials: 'same-origin',
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(postData)
- })
- .then(function __parseJSON(response) {
- return response.json()
- })
- .then(function (json) {
- if ('success' === json.type && json.body && json.body.ids) {
- updateListIdBiAuditReaport('PRACOWNICY', json.body.ids.map(function (id) {
- return parseInt(id)
- }))
- // jQuery('#body-pracownicy').find('input[name="prID[]"]').attr('checked', true)
- jQuery('#body-pracownicy').find('input[name="prID[]"]').each(function (idx, inputNode) {
- inputNode.checked = true;
- })
- thisButton.attr('disabled', false)
- var txt = thisButton.text()
- thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
- updateCountItemCheckedByType('pracownicy');
- p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" pracowników" })
- }
- })
- .catch(function (e) {
- p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
- thisButton.attr('disabled', false)
- var txt = thisButton.text()
- thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
- })
- }
- if ('kontrahenci' === event.data.type) {
- p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie podmiotów/kontrahentów..." })
- 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 )
- }).forEach(function (filter) {
- postData[ filter[0] ] = filter[1];
- })
- global.fetch(URL_FETCH_KONTRAHENCI_IDS_AJAX, {
- credentials: 'same-origin',
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(postData)
- })
- .then(function __parseJSON(response) {
- return response.json()
- })
- .then(function (json) {
- if ('success' === json.type && json.body && json.body.ids) {
- updateListIdBiAuditReaport('KONTRAHENCI', json.body.ids.map(function (id) {
- return parseInt(id)
- }))
- // jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').attr('checked', true); // Not working
- jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').each(function (idx, inputNode) {
- inputNode.checked = true;
- })
- thisButton.attr('disabled', false);
- var txt = thisButton.text()
- thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
- updateCountItemCheckedByType('kontrahenci');
- p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" kontrahentów" })
- }
- })
- .catch(function (e) {
- p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
- thisButton.attr('disabled', false)
- var txt = thisButton.text()
- thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
- });
- }
- }
- function mock_error__fetchLastReports(id) {
- return new Promise(function (resolve) {
- throw "Wystąpił błąd, spróbuj ponownie później"
- })
- }
- function mock__fetchLastReports(id) {
- return new Promise(function (resolve) {
- var fakeResponse = '{"type":"success","msg":"ostatnie raporty","body":{"items":[{"id":"103","adnotacje":"raport pani x","totalPracownicy":"1","totalKontrahenci":"2"},{"id":"102","adnotacje":"test","totalPracownicy":"1","totalKontrahenci":"1"},{"id":"101","adnotacje":"Zuranski test all 7","totalPracownicy":"1","totalKontrahenci":"9307"},{"id":"100","adnotacje":"kike all 4","totalPracownicy":"5","totalKontrahenci":"9305"},{"id":"99","adnotacje":"test pracownik z KRS bez celu 3","totalPracownicy":"1","totalKontrahenci":"9305"}]}}';
- var json = JSON.parse(fakeResponse);
- var items = json.body.items;
- console.log('items', items)
- setTimeout(function () {
- console.log('resolve items', items)
- resolve(items);
- }, 500);
- });
- }
- function fetchLastReports(id) {
- return global.fetch(URL_FETCH_LAST_REPORTS_AJAX, {
- credentials: 'same-origin',
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: id })
- })
- .then(function __parseJSON(response) {
- return response.json()
- })
- .then(function (json) {
- if ('success' === json.type && json.body && json.body.items) {
- if (!json.body.items.length) throw "Brak danych"
- return json.body.items;
- }
- throw "Wystąpił błąd, spróbuj ponownie później.";
- })
- }
- function fetchPracownicyIdsByReport(id) {
- return global.fetch(URL_FETCH_PRACOWNICY_IDS_BY_REPORT_AJAX, {
- credentials: 'same-origin',
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: id })
- })
- .then(function __parseJSON(response) {
- return response.json()
- })
- .then(function (json) {
- if ('success' === json.type && json.body && json.body.ids) {
- if (!json.body.ids.length) throw "Brak danych"
- return json.body.ids;
- }
- throw "Wystąpił błąd, spróbuj ponownie później.";
- })
- }
- function fetchKontrahenciIdsByReport(id) {
- return global.fetch(URL_FETCH_KONTRAHENCI_IDS_BY_REPORT_AJAX, {
- credentials: 'same-origin',
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id: id })
- })
- .then(function __parseJSON(response) {
- return response.json()
- })
- .then(function (json) {
- if ('success' === json.type && json.body && json.body.ids) {
- if (!json.body.ids.length) throw "Brak danych"
- return json.body.ids;
- }
- throw "Wystąpił błąd, spróbuj ponownie później.";
- })
- }
- function addToReportByPreviousReport(event) {
- var pageType = (event.data.type) ? event.data.type : '';
- handleAddToReportByPreviousReport(pageType);
- }
- function handleAddToReportByPreviousReport(pageType) {
- switch (pageType) {
- case 'pracownicy': break; // OK
- case 'kontrahenci': break; // OK
- default: throw "Wrong type";
- }
- var thisButton = $(this)
- thisButton.attr('disabled', true)
- thisButton.text( thisButton.text() + '...' )
- function this__enableButton() {
- thisButton.attr('disabled', false)
- var txt = thisButton.text()
- thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
- }
- var lastReportOptions = new Promise(function (resolve) {
- fetchLastReports() // TODO: TEST remote `mock__`
- .then(function (items) {
- var options = {};
- items.forEach(function (item) {
- var label = "Nr " + item.id + ": " + item.adnotacje + " ";
- var total = 0;
- switch (pageType) {
- case 'pracownicy': total = parseInt(item.totalPracownicy); break;
- case 'kontrahenci': total = parseInt(item.totalKontrahenci); break;
- }
- label += ( total > 0 ? "(" + total + ")" : "brak");
- options['raport-'+item.id] = label;
- });
- resolve(options);
- })
- .catch(function (e) {
- swal.showValidationError(''+e)
- swal.hideLoading();
- resolve();
- })
- });
- swal({
- title: "Dodaj " + ('pracownicy' === pageType ? "praconików" : "kontrahentów") + " do analizy",
- showCancelButton: true,
- cancelButtonText: "Anuluj",
- showConfirmButton: true,
- confirmButtonText: "Wybierz",
- focusCancel: true,
- width: 600,
- input: 'select',
- inputOptions: lastReportOptions,
- inputClass: "form-control input-lg",
- preConfirm: function (selected) {
- var id = parseInt(selected.substr('raport-'.length));
- swal.showLoading();
- if ('pracownicy' === pageType) {
- return new Promise(function (resolve) {
- fetchPracownicyIdsByReport(id)
- .then(function (ids) {
- updateListIdBiAuditReaport('PRACOWNICY', ids.map(function (id) {
- return parseInt(id)
- }))
- ids.forEach(function (id) {
- jQuery('#body-pracownicy').find('input[name="prID[]"][value="'+id+'"]').each(function (idx, inputNode) {
- inputNode.checked = true;
- })
- })
- updateCountItemCheckedByType('pracownicy');
- p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" pracowników" })
- resolve();
- })
- .catch(function (e) {
- swal.showValidationError(''+e)
- swal.hideLoading();
- resolve();
- });
- });
- } else if ('kontrahenci' === pageType) {
- return new Promise(function (resolve) {
- fetchKontrahenciIdsByReport(id)
- .then(function (ids) {
- updateListIdBiAuditReaport('KONTRAHENCI', ids.map(function (id) {
- return parseInt(id)
- }))
- ids.forEach(function (id) {
- jQuery('#body-kontrahenci').find('input[name="kontrID[]"][value="'+id+'"]').each(function (idx, inputNode) {
- inputNode.checked = true;
- })
- })
- updateCountItemCheckedByType('kontrahenci');
- p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" kontrahentów" })
- resolve();
- })
- .catch(function (e) {
- swal.showValidationError(''+e)
- swal.hideLoading();
- resolve();
- });
- });
- } else return true;
- },
- // inputValidator: (value) => {
- // return !value && 'Proszę wybrać raport'
- // }
- // html: '<p>Ostatnie raporty:</p>' + '<ul id="' + uniqHtmlId + '"></ul></p>',
- }).then(function (selected) {
- this__enableButton();
- }).catch(function (e) {
- this__enableButton();
- })
- }
- $(document).ready(function(){
- DBG && console.warn('DBG:: SET window[STORE_NAME]', { store: window[STORE_NAME], STORE_NAME: STORE_NAME, globalRaportStore })
- ReactDOM.render(
- h(P5UI__BocianHeader, {
- store: globalRaportStore
- }),
- document.getElementById('bi_audit_header')
- );
- rootChangeForm();
- updateTopCounters();
- var unsubscribe = globalRaportStore.subscribe(function () {
- // TODO: fetch data from globalRaportStore.getState()
- // var defaultState = global[STORE_NAME + '__defaults']();
- })
- $(window).on('hashchange', function() {
- DBG && console.warn("$(window).on('hashchange', ...")
- rootChangeForm();
- updateTopCounters();
- hideMoreRecordFunctionsPopover()
- });
- });
- global.hideMoreRecordFunctionsPopover = function() {
- if (RECORD_MORE_FUNCTIONS_OPENED_NODE) jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
- }
- global.pracownicyLoadMoreRecordFunctions = function(event, node, rowPK) {
- return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY")
- }
- global.kontrahenciLoadMoreRecordFunctions = function(event, node, rowPK) {
- return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI")
- }
- global.removeFiltersPracownicy = removeFiltersPracownicy;
- global.removeFiltersKontrahenci = removeFiltersKontrahenci;
- global.onChangeFiltersPracownicy = onChangeFiltersPracownicy;
- global.onKeypressFiltersPracownicy = onKeypressFiltersPracownicy;
- global.onChangeFiltersKontrahenci = onChangeFiltersKontrahenci;
- global.onKeypressFiltersKontrahenci = onKeypressFiltersKontrahenci;
- global.checkAll = checkAll;
- global.checkedChoiseItems = checkedChoiseItems;
- global.catchEventCheckbox = catchEventCheckbox;
- global.clearSelectedCheckbox = clearSelectedCheckbox;
- global.getNameGroupById = getNameGroupById;
- global.createGroupPracownicy = createGroupPracownicy;
- global.createGroupKontrahenci = createGroupKontrahenci;
- global.selectPage = selectPage;
- global.detectChoiseFilter = detectChoiseFilter;
- global.updateListIdBiAuditReaport = updateListIdBiAuditReaport;
- global.deleteListIdBiAuditReaport = deleteListIdBiAuditReaport;
- global.urlFetchPracownicy = urlFetchPracownicy;
- global.urlFetchKontrahenci = urlFetchKontrahenci;
- global.getAddressData = getAddressData;
- global.Pagination = Pagination;
- global.todo__fetchRaport = todo__fetchRaport;
- global.setItemLocalStorage = setItemLocalStorage;
- global.getItemLocalStorage = getItemLocalStorage;
- global.deleteItemLocalStorage = deleteItemLocalStorage;
- global.removeItemInArray = removeItemInArray;
- global.removeItemArrayInArray = removeItemArrayInArray;
- global.addPracownikToGroup = addPracownikToGroup;
- global.addPracownikAllToGroup = addPracownikAllToGroup;
- global.addKontrahenciToGroup = addKontrahenciToGroup;
- global.addKontrahenciAllToGroup = addKontrahenciAllToGroup;
- global.createPracownikAjax = createPracownikAjax;
- global.createKontrahentAjax = createKontrahentAjax;
- global.removePracownikFromGroup = removePracownikFromGroup;
- global.removeKontrahenciFromGroup = removeKontrahenciFromGroup;
- global.showViewUploadFile = showViewUploadFile;
- global.parseCsvFile = parseCsvFile;
- global.clearListLocalStorageByType = clearListLocalStorageByType;
- // message
- global.messageCriticalSearchData = 'Krytyczne wielkości danych do przeszukania. Optymalna wartość głębokość szukania powiaząń to: 6';
|