Bocian.php.view.js 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469
  1. var DBG = DBG || 0;
  2. var DBG1 = true;
  3. var CURRENT_DATE = CURRENT_DATE || '';
  4. if (!STORE_NAME) throw "Store name not defined";
  5. if (!global[STORE_NAME]) throw "Store not defined";
  6. if (!URL_TABLE_POWIAZANIA) throw "Brak URL_TABLE_POWIAZANIA";
  7. if (!BASE_URLS) throw "Brak BASE_URLS"
  8. var RECORD_MORE_FUNCTIONS_OPENED_NODE = null;
  9. if (!FIELD_LIST_PRACOWNICY) throw "Brak FIELD_LIST_PRACOWNICY"
  10. if (!FIELD_LIST_KONTRAHENCI) throw "Brak FIELD_LIST_KONTRAHENCI"
  11. var EXPORT_FIELDS_OD = EXPORT_FIELDS_OD || null;
  12. var EXPORT_FIELDS_DO = EXPORT_FIELDS_DO || null;
  13. var createReactClass = global.p5VendorJs.createReactClass;
  14. var h = global.p5VendorJs.React.createElement;
  15. var ReactDOM = global.p5VendorJs.ReactDOM;
  16. var swal = window.swal;
  17. var globalRaportStore = global[STORE_NAME];
  18. if (!p5UI__clickedOutsideElement) throw "Brak p5UI__clickedOutsideElement"
  19. if (!global.p5VendorJs.Unstated) throw "Brak Unstated"
  20. var Unstated = global.p5VendorJs.Unstated;
  21. var P5UI__BocianHeader = createReactClass({
  22. getStateFromStore: function () {
  23. var storeState = this.props.store.getState();
  24. return {
  25. totalOdPracownicy: storeState.totalOdPracownicy,
  26. totalOdPozostale: storeState.totalOdPozostale,
  27. totalDoKontrahenci: storeState.totalDoKontrahenci,
  28. totalDoPozostale: storeState.totalDoPozostale,
  29. depth: storeState.depth,
  30. onlyTargets: storeState.onlyTargets,
  31. title: storeState.title,
  32. };
  33. },
  34. getInitialState: function() {
  35. return this.getStateFromStore();
  36. },
  37. componentDidMount: function () {
  38. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  39. },
  40. componentWillUnmount: function () {
  41. this.unsubscribe()
  42. },
  43. storeUpdated: function () {
  44. DBG && console.log('DBG::P5UI__BocianHeader::storeUpdated ', this.getStateFromStore());
  45. this.setState(this.getStateFromStore())
  46. },
  47. addOdPozostale: function (event) {
  48. // window['createPracownikAjax'](event)
  49. window['addPozostaleOdDo'](event)
  50. },
  51. addDoPozostale: function (event) {
  52. // window['createKontrahentAjax'](event)
  53. window['addPozostaleOdDo'](event)
  54. },
  55. clearPozostaleOd: function (event) {
  56. this.props.store.dispatch({ type: 'CLEAR_POZOSTALE_OD' })
  57. },
  58. clearPozostaleDo: function (event) {
  59. this.props.store.dispatch({ type: 'CLEAR_POZOSTALE_DO' })
  60. },
  61. handleChangeDepth: function (event) {
  62. var store = this.props.store;
  63. var depth = event.target.value;
  64. store.dispatch({ type: 'SET_DEPTH', depth: depth })
  65. },
  66. handleChangeSetOnlyTargetsYes: function () {
  67. this.props.store.dispatch({ type: 'SET_ONLY_TARGETS', onlyTargets: true })
  68. },
  69. handleChangeSetOnlyTargetsNo: function () {
  70. this.props.store.dispatch({ type: 'SET_ONLY_TARGETS', onlyTargets: false })
  71. },
  72. handleChangeTitle: function (event) {
  73. this.props.store.dispatch({ type: 'SET_TITLE', title: event.target.value })
  74. },
  75. handleRaportSubmitForm: function (event) {
  76. event.preventDefault();
  77. var self_store = this.props.store;
  78. var idsPracownicy = getListFromLocalStorage('Bocian.biAuditForm.pracownicyIds');
  79. var idsKontrahenci = getListFromLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  80. var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD'));
  81. var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO'));
  82. var allOdLength = idsPracownicy.length + pozostaleOd.length;
  83. var allDoLength = idsKontrahenci.length + pozostaleDo.length;
  84. var depthValue = getItemLocalStorage('Bocian.biAuditForm.depth');
  85. var smadReaportTitle = getItemLocalStorage('Bocian.biAuditForm.smadReaportTitle');
  86. var analizaOnlyTargets = getItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets');
  87. if ( !smadReaportTitle ) {
  88. p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano tytułu raportu' });
  89. return;
  90. }
  91. if ( !depthValue ) {
  92. p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano wartości dla głębokości powiązań' });
  93. return;
  94. }
  95. if ( !analizaOnlyTargets ) {
  96. p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie podano wartości czy zwracać wyniki tylko z obiektami docelowymi' });
  97. return;
  98. }
  99. if ( !allOdLength ) {
  100. p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie wybrano pozycji OD do analizy (pracownicy lub pozostałe bazy)' });
  101. return;
  102. }
  103. if ( !allOdLength && !allDoLength ) {
  104. p5UI__notifyAjaxCallback({ type: 'error', msg: 'Nie wybrano pozycji do analizy' });
  105. return;
  106. }
  107. // TODO: analizaOnlyTargets = ( 'y' | 'n' ) - allDoLength should depend of analizaOnlyTargets?
  108. // if not choise 'pracownicy' or 'kontrahenci'
  109. if ( !allOdLength || !allDoLength ) {
  110. var messageConfirm = '';
  111. if ( !allDoLength ) {
  112. 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? ';
  113. }
  114. // show confirm window with message
  115. if (!confirm(messageConfirm)) return;
  116. }
  117. window.fetch(URL_GENERATE_BI_AUDIT_RAPORT_AJAX, {
  118. method: 'POST',
  119. headers: { 'Content-Type': 'application/json' },
  120. credentials: 'same-origin',
  121. body: JSON.stringify({
  122. pracownicyIds: idsPracownicy,
  123. kontrahenciIds: idsKontrahenci,
  124. pozostaleOd: pozostaleOd,
  125. pozostaleDo: pozostaleDo,
  126. depthValue: depthValue,
  127. smadReaportTitle: smadReaportTitle,
  128. analizaOnlyTargets: analizaOnlyTargets
  129. })
  130. })
  131. .then(function(response) {
  132. return response.text();
  133. })
  134. .then(function(responseText) {
  135. try {
  136. return JSON.parse(responseText);
  137. } catch (e) {
  138. throw responseText;
  139. }
  140. })
  141. .then(function(result) {
  142. if (result.type == 'success') {
  143. p5UI__notifyAjaxCallback(result);
  144. self_store.dispatch({ type: 'CLEAR_ALL' })
  145. updateTopCounters();
  146. $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
  147. $('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false);
  148. $('#count-selected-item-kontrahenci').text('0');
  149. $('#count-selected-item-pracownicy').text('0');
  150. $('.bottom--message-warning-critical-search').text('');
  151. swal({
  152. title: result.msg,
  153. html: '<a href="' + URL_TABLE_POWIAZANIA + '" title="przejdź do raportów" >Przejdź do raportów</a>',
  154. allowOutsideClick: false, // TODO: btn Anuluj na dole?
  155. showCloseButton: true,
  156. confirmButtonText: 'OK',
  157. });
  158. window.setTimeout(function () {
  159. console.warn("URL_TABLE_POWIAZANIA:", URL_TABLE_POWIAZANIA);
  160. }, 100);
  161. window.setTimeout(function () {
  162. window.location.href = URL_TABLE_POWIAZANIA;
  163. }, 6000);
  164. resolve(result.msg);
  165. } else {
  166. if (result.type && result.msg) p5UI__notifyAjaxCallback(result);
  167. reject(result.msg);
  168. }
  169. })
  170. .catch(function(error) {
  171. if(DBG) console.log('request failed', error);
  172. });
  173. },
  174. handleAddByLastReportClick: function (event) {
  175. swal({
  176. title: "dodaj do analizy wg raportu",
  177. input: 'radio',
  178. inputOptions: {
  179. 'pracownicy' : "Pracownicy",
  180. 'kontrahenci' : "Kontrahenci",
  181. // 'pracownicy_pozostale' : "Pracownicy (pozostałe)",
  182. // 'kontrahenci_pozostale' : "Kontrahenci (pozostałe)",
  183. },
  184. inputValidator: function (value) {
  185. return !value && 'Proszę wybrać typ danych';
  186. }
  187. }).then(function (data) {
  188. handleAddToReportByPreviousReport(data.value);
  189. })
  190. // TODO: like addToReportByPreviousReport but after select report, show counters for pracow., kontr., pozostale od and do with checkbox
  191. // swal({
  192. // title: "TODO: dodaj do analizy wg raportu",
  193. // })
  194. // TODO: https://github.com/sweetalert2/sweetalert2-react-content
  195. // - just pass React element to 'html' ?
  196. },
  197. renderClearPozostaleOdBtn: function () {
  198. return h('i', {
  199. title: "Wyczyść pozostałe",
  200. className: "glyphicon glyphicon-remove",
  201. style: { 'font-size': '14px', 'line-height': '21px', 'margin-left': '3px', 'vertical-align': 'middle', color: "#f00", opacity: "0.5", cursor: "pointer" },
  202. onClick: this.clearPozostaleOd, 'line-height': '20px'
  203. });
  204. },
  205. renderClearPozostaleDoBtn: function () {
  206. return h('i', {
  207. title: "Wyczyść pozostałe",
  208. className: "glyphicon glyphicon-remove",
  209. style: { 'font-size': '14px', 'line-height': '21px', 'margin-left': '3px', 'vertical-align': 'middle', color: "#f00", opacity: "0.5", cursor: "pointer" },
  210. onClick: this.clearPozostaleDo, 'line-height': '20px'
  211. });
  212. },
  213. renderSummaryList: function () {
  214. var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale;
  215. var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale;
  216. return h('ul', {}, [
  217. h('li', { style: { marginTop: "6px" } }, [
  218. h('span', {
  219. style: totalOd > 0 ? { color: "#d7142d" } : {}
  220. }, [
  221. " OD ",
  222. h('span', { className: "badge", style: totalOd > 0 ? { 'background-color': "#d7142d" } : {} }, totalOd),
  223. " : ",
  224. ]),
  225. h('a', { className: "btn btn-primary btn-xs", href: "#PRACOWNICY" }, [ // .bi-btn-primary
  226. " pracownicy ",
  227. h('span', { className: "badge" }, this.state.totalOdPracownicy),
  228. ]),
  229. h('i', { className: "glyphicon glyphicon-plus", style: { 'font-size': "14px", margin: "0 12px" } }),
  230. h('button', { className: "btn btn-primary btn-xs", onClick: this.addOdPozostale }, [ // .bi-btn-primary
  231. " pozostałe ",
  232. h('span', { className: "badge" }, this.state.totalOdPozostale),
  233. ]),
  234. (this.state.totalOdPozostale > 0) ? this.renderClearPozostaleOdBtn() : null,
  235. ]),
  236. h('li', { style: { marginTop: "6px" } }, [
  237. h('span', {
  238. style: totalDo > 0 ? { color: "#d7142d" } : {}
  239. }, [
  240. " DO ",
  241. h('span', { className: "badge", style: totalDo > 0 ? { 'background-color': "#d7142d" } : {} }, totalDo),
  242. " : ",
  243. ]),
  244. h('a', { className: "btn btn-primary btn-xs", href: "#KONTRAHENCI" }, [ // .bi-btn-primary
  245. " kontrahenci ",
  246. h('span', { className: "badge" }, this.state.totalDoKontrahenci),
  247. ]),
  248. h('i', { className: "glyphicon glyphicon-plus", style: { 'font-size': "14px", margin: "0 12px" } }),
  249. h('button', { className: "btn btn-primary btn-xs", onClick: this.addOdPozostale }, [ // .bi-btn-primary
  250. " pozostałe ",
  251. h('span', { className: "badge" }, this.state.totalDoPozostale),
  252. ]),
  253. (this.state.totalDoPozostale > 0) ? this.renderClearPozostaleDoBtn() : null,
  254. ]),
  255. ]);
  256. },
  257. renderRaportParamsForm: function () {
  258. var depth = parseInt(this.state.depth);
  259. var isDepthValid = ( !isNaN(depth) && depth >= 1 && depth <= 16 );
  260. var onlyTargets = this.state.onlyTargets;
  261. return h('div', {}, [
  262. h('div', { className: "row" + ( isDepthValid ? "" : " has-error" ), style: { 'margin-bottom': "12px" } }, [
  263. 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" } }, [
  264. "głębokość powiązań: ",
  265. ]),
  266. h('div', { className: "form-item col-md-5 col-lg-3" }, [
  267. h('input', { type: "number", className: "form-control", placeholder: "1-16", value: this.state.depth, onChange: this.handleChangeDepth, min: 1, max: 16 }),
  268. ]),
  269. ]),
  270. h('div', { className: "row", style: { 'margin-bottom': "12px" } }, [
  271. 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" } }, [
  272. "Czy zwracać wyniki tylko ze znalezionymi obiektami docelowymi (DO)? ",
  273. ]),
  274. h('div', { className: "form-item col-md-5 col-lg-3" }, [
  275. h('div', { className: "btn-group" }, [
  276. h('div', { className: "btn btn-default" + ( onlyTargets ? " active" : "" ), style: { padding: "6px 12px" }, onClick: this.handleChangeSetOnlyTargetsYes }, "TAK"),
  277. h('div', { className: "btn btn-default" + ( onlyTargets ? "" : " active" ), style: { padding: "6px 12px" }, onClick: this.handleChangeSetOnlyTargetsNo }, "NIE"),
  278. ]),
  279. ]),
  280. ]),
  281. h('div', { className: "row", style: { 'margin-bottom': "12px" } }, [
  282. h('div', { className: "form-item col-md-3 col-lg-3", style: { 'font-size': "14px", 'text-align': "right", 'padding-top': "5px", 'padding-bottom': "0" } }, [
  283. "Tytuł:",
  284. ]),
  285. h('div', { className: "form-item col-md-9 col-lg-9" }, [
  286. h('input', { type: "text", className: "form-control", placeholder: 'Raport bez tytułu z dnia ' + CURRENT_DATE, value: this.state.title, onChange: this.handleChangeTitle }),
  287. ]),
  288. ]),
  289. ]);
  290. },
  291. renderRaportFormSubmitBtn: function () {
  292. var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale;
  293. var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale;
  294. var isFormValid = (totalOd || totalDo);
  295. return h('div', { className: "row", style: { padding: "0", 'margin-bottom': "0", 'text-align': "right" } }, [
  296. h('div', { className: "form-item col-md-12 col-lg-12" }, [
  297. h('button', {
  298. type: "button",
  299. className: "btn btn-default" + ( isFormValid ? "" : " disabled" ),
  300. onClick: this.handleRaportSubmitForm,
  301. style: { padding: "18px 42px", 'font-size': "18px", 'font-weight': "900" }
  302. }, "GENERUJ RAPORT POWIĄZAŃ"),
  303. ]),
  304. ]);
  305. },
  306. renderAddMoreBtns: function () {
  307. return h('div', {
  308. style: { 'padding-top': 6, 'padding-bottom': 20 }
  309. }, [
  310. h('button', { className: "btn btn-success btn-xs", onClick: this.handleAddByLastReportClick }, "dodaj do analizy wg raportu"),
  311. ]);
  312. },
  313. render: function () {
  314. DBG && console.log('DBG::P5UI__BocianHeader::render ', { state: this.state });
  315. var totalOd = this.state.totalOdPracownicy + this.state.totalOdPozostale;
  316. var totalDo = this.state.totalDoKontrahenci + this.state.totalDoPozostale;
  317. var depth = this.state.depth;
  318. var errorMsg = (depth > 16) ? "Maksymalna głębokość powiązań to 16!" : "";
  319. var warningMsg = ( ( !totalOd || !totalDo ) && depth > 6 ) ? "Krytyczne wielkości danych do przeszukania. Optymalna głębokość szukania powiaząń to: 6" : "";
  320. return h('div', { className: "container-fluid", style: { backgroundColor: "#efefef" } }, [
  321. h('div', { style: { fontSize: '16px', fontWeight: "normal", color: "#777" } }, [
  322. h('div', { className: "row" }, [
  323. h('div', { className: "col-md-6" }, [
  324. h('h3', { style: { color: "#000" } }, [
  325. h('span', { style: { fontSize: "120%", color: "#d7142d" } }, "|"),
  326. " Tworzenie nowego raportu ",
  327. h('br'),
  328. h('small', {}, [
  329. "(Wybierz elementy do porównania: ",
  330. h('span', { style: { color: "#d7142d" } }, " OD "),
  331. h('i', { className: "glyphicon glyphicon-random", style: { padding: '0 3px', 'font-size': "80%", color: "#000" } }),
  332. h('span', { style: { color: "#d7142d" } }, " DO"),
  333. ")",
  334. ])
  335. ]),
  336. "Wybrano:",
  337. this.renderSummaryList(),
  338. this.renderAddMoreBtns(),
  339. ]),
  340. h('div', { className: "col-md-6", style: { 'padding-top': "20px", 'padding-bottom': "20px" } }, [
  341. this.renderRaportParamsForm(),
  342. this.renderRaportFormSubmitBtn(),
  343. ]),
  344. ]),
  345. h('div', { className: "row" }, [
  346. h('div', { className: "col-md-8 col-md-offset-2 col-xs-12" }, [
  347. errorMsg ? h('div', { className: "alert alert-danger" }, errorMsg) : null,
  348. warningMsg ? h('div', { className: "alert alert-warning" }, warningMsg) : null,
  349. ]),
  350. ]),
  351. ])
  352. ])
  353. }
  354. })
  355. function getSelectedListLocalStorageKey(from) { // from: ( OD | DO )
  356. switch (from) {
  357. case 'OD': return 'Bocian.biAuditForm.odFeatureKeys';
  358. case 'DO': return 'Bocian.biAuditForm.doFeatureKeys';
  359. default: throw "Not implemented from selected list '" + from + "' - expected 'OD' or 'DO'";
  360. }
  361. }
  362. function getListFromLocalStorage(key) {
  363. return JSON.parse( localStorage.getItem(key) || '[]' );
  364. }
  365. function getSignedIntFromLocalStorage(key, defaultValue) {
  366. return JSON.parse( localStorage.getItem(key) || defaultValue );
  367. }
  368. function getStringFromLocalStorage(key, defaultValue) {
  369. var value = localStorage.getItem(key);
  370. value = (value) ? JSON.parse(value) : '';
  371. return (value) ? value : defaultValue;
  372. }
  373. // function saveToSelectedListInLocalStorage(from, featureKey) {
  374. // DBG && console.log("DBG::saveToSelectedListInLocalStorage(from, featureKey)", {from, featureKey}, {added: getSelectedListFromLocalStorage(from).concat(featureKey)});
  375. // localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify(
  376. // getSelectedListFromLocalStorage(from).concat(featureKey)
  377. // ))
  378. // }
  379. // function removeFromSelectedListInLocalStorage(from, featureKey) {
  380. // DBG && console.log("DBG::removeFromSelectedListInLocalStorage(from, featureKey)", {from, featureKey});
  381. // localStorage.setItem(getSelectedListLocalStorageKey(from), JSON.stringify(
  382. // getSelectedListFromLocalStorage(from).filter(function (item) {
  383. // return ( item !== featureKey );
  384. // })
  385. // ))
  386. // }
  387. /* DATA FOR READ REAPORT */
  388. function urlFetchKontrahenciPowiazania() {
  389. // Documentation: https://github.com/github/fetch
  390. fetch(URL_FETCH_KONTRAHENCI_POWIAZANIA, {
  391. credentials: 'same-origin'
  392. })
  393. .then(function parseJSON(response) {
  394. return response.json()
  395. })
  396. .then(function(data) {
  397. var reaportItemsKontrahenciPowiazani = null;
  398. data.body.items.forEach (function(row) {
  399. reaportItemsKontrahenciPowiazani += '<tr><td><input type="checkbox" name="kontrID[]" value="'+row['ID']+'" /></td>'+
  400. '<td align="right">'+row["ID"]+'</td>';
  401. });
  402. $( "#body-reaport-kontrahenci-powiazani-tree" ).html(reaportItemsKontrahenciPowiazani);
  403. }).catch(function(error) {
  404. if(DBG) console.log('request failed', error)
  405. });
  406. }
  407. /* FORM DATA FOR GENERATAE REAPORT */
  408. /**
  409. * Załadowanie wybranej pozycji w select czy zwracać wyniki tylko z obiektami docelowymi onlyTarget
  410. */
  411. function loadCurrentOnlyTargetsSelect() {
  412. var analizaOnlyTargets = getItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets');
  413. $('#smad-select-target').val(analizaOnlyTargets).attr("selected", "selected");
  414. $('#smad-select-target-kontrahenci').val(analizaOnlyTargets).attr("selected", "selected");
  415. }
  416. /**
  417. * Załadowanie do storage informacji czy zwracać wyniki tylko z obiektami docelowymi
  418. */
  419. function updateLocalStorageBiAuditOnlyTargets(idSelect) {
  420. $(idSelect).change(function() {
  421. var newValue = $(idSelect).val();
  422. var responseValue = newValue;
  423. setItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets', responseValue);
  424. $('#smad-select-target').val(newValue).attr("selected", "selected");
  425. $('#smad-select-target-kontrahenci').val(newValue).attr("selected", "selected");
  426. // load in select selected option
  427. loadCurrentOnlyTargetsSelect();
  428. });
  429. }
  430. /**
  431. * Funkcja pozwala na wyświetlenie okienka importu
  432. */
  433. function showViewUploadFile( event, headerTitle, enumType, showCheckbox, csvFileExample ) {
  434. event.preventDefault();
  435. var enumType = enumType;
  436. if( csvFileExample !== undefined) { // przykład + instrukcja do pobrania
  437. csvFileExample = '<div><a href="'+csvFileExample+'" title="Pobierz przykład" download target="_balnk">Pobierz przykład</a></div>';
  438. }
  439. swal({
  440. title: 'Importuj plik csv',
  441. input: 'file',
  442. html: csvFileExample,
  443. inputAttributes: {
  444. 'accept': 'text/csv',
  445. 'aria-label': 'Upload csv file'
  446. },
  447. confirmButtonText: 'Importuj',
  448. preConfirm: function (file) {
  449. return new Promise(function (resolve, reject) {
  450. if (!file) {
  451. reject("Proszę wybrać plik csv");
  452. return
  453. }
  454. var input = document.querySelector('input[type="file"]');
  455. var data = new FormData()
  456. data.append('file', input.files[0])
  457. data.append('showCheckbox', showCheckbox);
  458. var responseParseFile = parseCsvFile( data, enumType );
  459. resolve('file imported')
  460. })
  461. },
  462. }).then(function (result) {
  463. if(DBG) console.log('result', result);
  464. }).catch(function (e) {
  465. if(DBG) console.log('catch: ', e);
  466. });
  467. }
  468. /**
  469. * Funkcja przekazuje dane z pliku csv do przeparsowania
  470. */
  471. function parseCsvFile( fileData, enumType ) {
  472. event.preventDefault();
  473. if(DBG) console.log( 'parseCsvFile fileData', fileData);
  474. fetch(URL_FORM_DATA_CSV_FILE_AJAX, {
  475. method: 'POST',
  476. credentials: 'same-origin',
  477. body: fileData
  478. })
  479. .then(function(response) {
  480. return response.json()
  481. }).then(function(json) {
  482. swal({
  483. title: 'Dane załadowane z pliku CSV',
  484. html: json.body.view,
  485. width: Math.round(window.innerWidth * 0.9),
  486. allowOutsideClick: false, // TODO: btn Anuluj na dole?
  487. showCloseButton: true,
  488. confirmButtonText: 'Zapisz',
  489. preConfirm: function (dataForm) {
  490. return new Promise(function (resolve, reject) {
  491. if (!dataForm) {
  492. reject("Formularz nie zawiera danych do zapisania");
  493. return
  494. }
  495. // zapisanie danych
  496. var responseSaveData = saveFormCsvFileAjaxAction(enumType);
  497. resolve('data save from form')
  498. })
  499. },
  500. }).then(function (result) {
  501. if(DBG) console.log('result', result)
  502. }).catch(function (e) {
  503. if(DBG) console.log('catch: ', e)
  504. });
  505. }).catch(function(ex) {
  506. if(DBG) console.log('parsing failed', ex);
  507. });
  508. }
  509. /**
  510. * Funkcja zapisuje dane z formularza do wgrania pliku csv
  511. */
  512. function saveFormCsvFileAjaxAction(enumType) {
  513. event.preventDefault();
  514. var formDataFrom = $("#formDataFromCsv").serialize();
  515. formDataFrom = formDataFrom.replace(/%5B/g,"[");
  516. formDataFrom = formDataFrom.replace(/%5D/g,"]");
  517. fetch(URL_SAVE_FORM_CSV_FILE_AJAX, {
  518. method: 'POST',
  519. credentials: 'same-origin',
  520. headers: {
  521. 'Content-Type': 'application/json'
  522. },
  523. body: JSON.stringify({
  524. formData: formDataFrom,
  525. enumType: enumType
  526. })
  527. })
  528. .then(function(response) {
  529. return response.json()
  530. }).then(function(json) {
  531. if(DBG) console.log('parsed json', json);
  532. if (response.type == 'success') {
  533. p5UI__notifyAjaxCallback(response.msg);
  534. }
  535. // return json;
  536. }).catch(function(ex) {
  537. if(DBG) console.log('parsing failed', ex);
  538. });
  539. }
  540. /**
  541. * Dodaj nowego pracownika
  542. */
  543. function createPracownikAjax(event) {
  544. event.preventDefault();
  545. swal({
  546. title: 'Dodaj osobę',
  547. showCancelButton: true,
  548. confirmButtonText: 'Zapisz',
  549. showLoaderOnConfirm: true,
  550. html:
  551. '<div class="form-group">'+
  552. '<input class="form-control required" id="personName" placeholder="Imię" >' +
  553. '<input class="form-control required" id="personSurname" placeholder="Nazwisko">'+
  554. '<input class="form-control required" id="personNip" placeholder="NIP">'+
  555. '<input class="form-control required" id="personPesel" placeholder="PESEL">'+
  556. '<input class="form-control required" id="personRegon" placeholder="REGON">'+
  557. '</div>',
  558. preConfirm: () => {
  559. return new Promise(function (resolve, reject) {
  560. // data from form
  561. var personName = $('#personName').val();
  562. var personSurname = $('#personSurname').val();
  563. var personNip = $('#personNip').val();
  564. var personPesel = $('#personPesel').val();
  565. var personRegon = $('#personRegon').val();
  566. //validate data from input
  567. if (!personName){
  568. reject('Proszę podać imię')
  569. return;
  570. }
  571. if (!personSurname){
  572. reject('Proszę podać nazwisko')
  573. return;
  574. }
  575. window.fetch(URL_CREATE_PRACOWNICY, {
  576. method: 'POST',
  577. header: {
  578. 'contentType': 'applications/json'
  579. },
  580. credentials: 'same-origin',
  581. body: JSON.stringify({
  582. 'personName': personName,
  583. 'personSurname': personSurname,
  584. 'personNip': personNip,
  585. 'personPesel': personPesel,
  586. 'personRegon': personRegon
  587. })
  588. })
  589. .then(function(response) {
  590. return response.text();
  591. })
  592. .then(function(responseText) {
  593. try {
  594. return JSON.parse(responseText);
  595. } catch (e) {
  596. throw responseText;
  597. }
  598. })
  599. .then(function(result) {
  600. if (result.type == 'success') {
  601. p5UI__notifyAjaxCallback(result);
  602. resolve(result.body);
  603. urlFetchPracownicy(1);
  604. }
  605. })
  606. .catch(function(error) {
  607. if(DBG) console.log('request failed', error);
  608. })
  609. })
  610. },
  611. allowOutsideClick: false
  612. }).then(function (createPerson) {
  613. if(DBG) console.log('dodanie osoby: ', createPerson);
  614. });
  615. }
  616. /**
  617. * Dodaj nowego kontrahenta
  618. */
  619. function createKontrahentAjax(event) {
  620. event.preventDefault();
  621. swal({
  622. title: 'Dodaj podmiot/kontrahenta',
  623. showCancelButton: true,
  624. confirmButtonText: 'Zapisz',
  625. showLoaderOnConfirm: true,
  626. html:
  627. '<div class="form-group">'+
  628. '<input class="form-control required" id="companyFullName" placeholder="Pelna nazwa" >' +
  629. '<input class="form-control required" id="companyShortName" placeholder="Skrócona nazwa\">'+
  630. '<input class="form-control required" id="companyNameGroup" placeholder="Nazwa grupy kapitałowej">'+
  631. '<input class="form-control required" id="companyKrs" placeholder="KRS">'+
  632. '<input class="form-control required" id="companyNip" placeholder="NIP">'+
  633. '<input class="form-control required" id="companyPesel" placeholder="PESEL">'+
  634. '<input class="form-control required" id="companyFax" placeholder="FAX">'+
  635. '<input class="form-control required" id="companyTelefon" placeholder="Telefon">'+
  636. '<input class="form-control required" id="companyMail" placeholder="Mail">'+
  637. '<input class="form-control required" id="companyStreet" placeholder="Ulica">'+
  638. '<input class="form-control required" id="companyNumberBuilding" placeholder="Numer budynku">'+
  639. '<input class="form-control required" id="companyNumberLocal" placeholder="Numer mieszkania /lokalu">'+
  640. '<input class="form-control required" id="companyPostCode" placeholder="Kod pocztowy">'+
  641. '<input class="form-control required" id="companyPlace" placeholder="Miejscowosc">'+
  642. '<input class="form-control required" id="companyCountry" placeholder="Kraj">'+
  643. '<input class="form-control required" id="companyTypeCompany" placeholder="Typ kontrahenta">'+
  644. '<input class="form-control required" id="companyTitleDocument" placeholder="Tytul dokumentu">'+
  645. '<input class="form-control required" id="companyDesc" placeholder="uwagi">'+
  646. '</div>',
  647. preConfirm: () => {
  648. return new Promise(function (resolve, reject) {
  649. // data from form
  650. var companyFullName = $('#companyFullName').val();
  651. var companyShortName = $('#companyShortName').val();
  652. var companyNameGroup = $('#companyNameGroup').val();
  653. var companyKrs = $('#companyKrs').val();
  654. var companyNip = $('#companyNip').val();
  655. var companyPesel = $('#companyPesel').val();
  656. var companyFax = $('#companyFax').val();
  657. var companyTelefon = $('#companyTelefon').val();
  658. var companyMail = $('#companyMail').val();
  659. var companyStreet = $('#companyStreet').val();
  660. var companyNumberBuilding = $('#companyNumberBuilding').val();
  661. var companyNumberLocal = $('#companyNumberLocal').val();
  662. var companyPostCode = $('#companyPostCode').val();
  663. var companyPlace = $('#companyPlace').val();
  664. var companyCountry = $('#companyCountry').val();
  665. var companyTypeCompany = $('#companyTypeCompany').val();
  666. var companyTitleDocument = $('#companyTitleDocument').val();
  667. var companyDesc = $('#companyDesc').val();
  668. //validate data from input
  669. if (!companyFullName){
  670. reject('Proszę podać pełną nazwę');
  671. return;
  672. }
  673. window.fetch(URL_CREATE_KONTRAHENCI, {
  674. method: 'POST',
  675. header: {
  676. 'contentType': 'applications/json'
  677. },
  678. credentials: 'same-origin',
  679. body: JSON.stringify({
  680. 'companyFullName': companyFullName,
  681. 'companyShortName': companyShortName,
  682. 'companyNameGroup': companyNameGroup,
  683. 'companyKrs': companyKrs,
  684. 'companyNip': companyNip,
  685. 'companyPesel': companyPesel,
  686. 'companyFax': companyFax,
  687. 'companyTelefon': companyTelefon,
  688. 'companyMail': companyMail,
  689. 'companyStreet': companyStreet,
  690. 'companyNumberBuilding': companyNumberBuilding,
  691. 'companyNumberLocal': companyNumberLocal,
  692. 'companyPostCode': companyPostCode,
  693. 'companyPlace': companyPlace,
  694. 'companyCountry': companyCountry,
  695. 'companyTypeCompany': companyTypeCompany,
  696. 'companyTitleDocument': companyTitleDocument,
  697. 'companyDesc': companyDesc
  698. })
  699. })
  700. .then(function(response) {
  701. return response.text();
  702. })
  703. .then(function(responseText) {
  704. try {
  705. return JSON.parse(responseText);
  706. } catch (e) {
  707. throw responseText;
  708. }
  709. })
  710. .then(function(result) {
  711. if (result.type == 'success') {
  712. p5UI__notifyAjaxCallback(result);
  713. resolve(result.body);
  714. urlFetchKontrahenci(1);
  715. }
  716. })
  717. .catch(function(error) {
  718. if(DBG) console.log('request failed', error);
  719. })
  720. })
  721. },
  722. allowOutsideClick: false
  723. }).then(function (createPerson) {
  724. if(DBG) console.log('dodanie podmiotu: ', createPerson);
  725. });
  726. }
  727. /**
  728. * Popup z opcja przeniesienia pracowników do innej grupy
  729. */
  730. function addPracownikToGroup(event) {
  731. event.preventDefault();
  732. var pracownicyIdsArray = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds');
  733. if (pracownicyIdsArray === null || !pracownicyIdsArray || !pracownicyIdsArray.length) {
  734. showTextListIdPracownikow = 'nie wybrano osób';
  735. } else {
  736. showTextListIdPracownikow = '' + pracownicyIdsArray.length + ' osób';
  737. }
  738. var arrayGroupOptions = [];
  739. var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups');
  740. // utworzenie tablicy Optionsów grupy
  741. listGroupStorage.map(function(item) {
  742. if (item.ID !== undefined) {
  743. arrayGroupOptions[item.ID] = item.NAZWA;
  744. }
  745. });
  746. swal({
  747. title: 'Dodaj do grupy',
  748. input: 'select',
  749. text: showTextListIdPracownikow,
  750. inputOptions: arrayGroupOptions,
  751. inputPlaceholder: 'Wybierz grupę',
  752. showCancelButton: true,
  753. confirmButtonText: 'Zapisz',
  754. showLoaderOnConfirm: true,
  755. preConfirm: function (idGroup) {
  756. if (!idGroup) {
  757. swal.showValidationError('Proszę wybrać nazwę grupy');
  758. return;
  759. }
  760. if (!pracownicyIdsArray || !pracownicyIdsArray.length) {
  761. swal.showValidationError('Proszę wybrać pracowników');
  762. return;
  763. }
  764. return new Promise(function (resolve, reject) {
  765. window.fetch(URL_ADD_PRACOWNICY_TO_GROUP, {
  766. method: 'POST',
  767. header: { 'contentType': 'applications/json' },
  768. credentials: 'same-origin',
  769. body: JSON.stringify({
  770. 'idGroup': idGroup,
  771. 'pracownicyIds': getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'),
  772. })
  773. })
  774. .then(function(response) {
  775. return response.text();
  776. })
  777. .then(function(responseText) {
  778. try {
  779. return JSON.parse(responseText);
  780. } catch (e) {
  781. throw responseText;
  782. }
  783. })
  784. .then(function(result) {
  785. if (result.type == 'success') {
  786. p5UI__notifyAjaxCallback(result);
  787. resolve(result.msg);
  788. } else {
  789. reject(result.msg);
  790. }
  791. })
  792. .catch(function(error) {
  793. if(DBG) console.warn('request failed', error);
  794. });
  795. })
  796. },
  797. allowOutsideClick: false
  798. }).then(function (value) {
  799. { // remove from selected
  800. setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', []);
  801. updateCountItemCheckedByType('pracownicy');
  802. $('form').find(':checkbox').prop('checked', false);
  803. }
  804. }).catch(function (e) {
  805. DBG && console.log('DBG: e', e)
  806. });
  807. }
  808. function addPracownikAllToGroup(event) {
  809. event.preventDefault();
  810. var showTextListIdPracownikow = 'wszystkich pracowników pasujących do kryteriów wyszukiwania';
  811. var arrayGroupOptions = [];
  812. var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups');
  813. // utworzenie tablicy Optionsów grupy
  814. listGroupStorage.map(function(item) {
  815. if (item.ID !== undefined) {
  816. arrayGroupOptions[item.ID] = item.NAZWA;
  817. }
  818. });
  819. swal({
  820. title: 'Dodaj do grupy',
  821. input: 'select',
  822. text: showTextListIdPracownikow,
  823. inputOptions: arrayGroupOptions,
  824. inputPlaceholder: 'Wybierz grupę',
  825. showCancelButton: true,
  826. confirmButtonText: 'Zapisz',
  827. showLoaderOnConfirm: true,
  828. preConfirm: function (idGroup) {
  829. return new Promise(function (resolve, reject) {
  830. if (!idGroup) {
  831. reject('Proszę wybrać nazwę grupy');
  832. return;
  833. }
  834. var filterFields = {}
  835. var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
  836. var fieldNameList = FIELD_LIST_PRACOWNICY
  837. fieldNameList.filter(function (fieldName) {
  838. if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"');
  839. return (frm[fieldName]) ? true : false
  840. }).map(function (fieldName) {
  841. return [ fieldName, frm[fieldName].value ]
  842. }).filter(function (filter) {
  843. return ( filter[1].length > 0 )
  844. }).map(function (filter) {
  845. filterFields[ filter[0] ] = filter[1]
  846. })
  847. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup');
  848. if (filterIdGroup) filterFields[ 'filterIdGroup' ] = filterIdGroup
  849. window.fetch(URL_ADD_PRACOWNICY_TO_GROUP, {
  850. method: 'POST',
  851. header: {
  852. 'contentType': 'applications/json'
  853. },
  854. credentials: 'same-origin',
  855. body: JSON.stringify({
  856. 'idGroup': idGroup,
  857. 'type': 'filter',
  858. 'filter': filterFields,
  859. })
  860. })
  861. .then(function(response) {
  862. return response.text();
  863. })
  864. .then(function(responseText) {
  865. try {
  866. return JSON.parse(responseText);
  867. } catch (e) {
  868. throw responseText;
  869. }
  870. })
  871. .then(function(result) {
  872. if (result.type == 'success') {
  873. p5UI__notifyAjaxCallback(result);
  874. resolve(result.msg);
  875. } else {
  876. reject(result.msg);
  877. }
  878. })
  879. .catch(function(error) {
  880. if(DBG) console.log('request failed', error);
  881. });
  882. })
  883. },
  884. allowOutsideClick: false
  885. }).then(function (groupPracownicyData) {
  886. //TODO: pIOTRKU CZY TU POWINIENEM COŚ JESZCZE OBSŁUŻYĆ
  887. });
  888. }
  889. /**
  890. * Popup z opcja przeniesienia kontrahentów do innej grupy
  891. */
  892. function addKontrahenciToGroup(event) {
  893. event.preventDefault();
  894. var kontrahenciIdsArray = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  895. if (kontrahenciIdsArray === null || !kontrahenciIdsArray || !kontrahenciIdsArray.length) {
  896. showTextListIdKontrahentow = 'nie wybrano kontrahentów';
  897. } else {
  898. showTextListIdKontrahentow = '' + kontrahenciIdsArray.length + ' podmiotów/kontrahentów';
  899. }
  900. var arrayGroupOptions = [];
  901. var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups');
  902. // utworzenie tablicy Optionsów grupy
  903. listGroupStorage.map(function(item) {
  904. if (item.ID !== undefined) {
  905. arrayGroupOptions[item.ID] = item.NAZWA;
  906. }
  907. });
  908. swal({
  909. title: 'Dodaj do grupy',
  910. input: 'select',
  911. text: showTextListIdKontrahentow,
  912. inputOptions: arrayGroupOptions,
  913. inputPlaceholder: 'Wybierz grupę',
  914. showCancelButton: true,
  915. confirmButtonText: 'Zapisz',
  916. showLoaderOnConfirm: true,
  917. preConfirm: function (idGroup) {
  918. if (!idGroup) {
  919. swal.showValidationError('Proszę wybrać nazwę grupy');
  920. return;
  921. }
  922. if (!kontrahenciIdsArray || !kontrahenciIdsArray.length) {
  923. swal.showValidationError('Proszę wybrać kontrahentów');
  924. return;
  925. }
  926. return new Promise(function (resolve, reject) {
  927. window.fetch(URL_ADD_KONTRAHENCI_TO_GROUP, {
  928. method: 'POST',
  929. header: { 'contentType': 'applications/json' },
  930. credentials: 'same-origin',
  931. body: JSON.stringify({
  932. 'idGroup': idGroup,
  933. 'kontrahenciIds': getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'),
  934. })
  935. })
  936. .then(function(response) {
  937. return response.text();
  938. })
  939. .then(function(responseText) {
  940. try {
  941. return JSON.parse(responseText);
  942. } catch (e) {
  943. throw responseText;
  944. }
  945. })
  946. .then(function(result) {
  947. if (result.type == 'success') {
  948. p5UI__notifyAjaxCallback(result);
  949. resolve(result.msg);
  950. } else {
  951. reject(result.msg);
  952. }
  953. })
  954. .catch(function(error) {
  955. if(DBG) console.warn('request failed', error);
  956. });
  957. })
  958. },
  959. allowOutsideClick: false
  960. }).then(function (value) {
  961. { // remove from selected
  962. setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', []);
  963. updateCountItemCheckedByType('kontrahenci');
  964. $('form').find(':checkbox').prop('checked', false);
  965. }
  966. }).catch(function (e) {
  967. DBG && console.log('DBG: e', e)
  968. });
  969. }
  970. function addKontrahenciAllToGroup(event) {
  971. event.preventDefault();
  972. var kontrahenciIdsArray = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  973. var showTextListIdKontrahentow = 'wszystkich podmotów/kontrahentów pasujących do kryteriów wyszukiwania';
  974. var arrayGroupOptions = [];
  975. var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups');
  976. // utworzenie tablicy Optionsów grupy
  977. listGroupStorage.map(function(item) {
  978. if (item.ID !== undefined) {
  979. arrayGroupOptions[item.ID] = item.NAZWA;
  980. }
  981. });
  982. swal({
  983. title: 'Dodaj do grupy',
  984. input: 'select',
  985. text: showTextListIdKontrahentow,
  986. inputOptions: arrayGroupOptions,
  987. inputPlaceholder: 'Wybierz grupę',
  988. showCancelButton: true,
  989. confirmButtonText: 'Zapisz',
  990. showLoaderOnConfirm: true,
  991. preConfirm: function (idGroup) {
  992. return new Promise(function (resolve, reject) {
  993. if (!idGroup) {
  994. reject('Proszę wybrać nazwę grupy');
  995. return;
  996. }
  997. var filterFields = {}
  998. var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
  999. var fieldNameList = FIELD_LIST_KONTRAHENCI
  1000. fieldNameList.filter(function (fieldName) {
  1001. if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
  1002. return (frm[fieldName]) ? true : false
  1003. }).map(function (fieldName) {
  1004. return [ fieldName, frm[fieldName].value ]
  1005. }).filter(function (filter) {
  1006. return ( filter[1].length > 0 )
  1007. }).map(function (filter) {
  1008. filterFields[ filter[0] ] = filter[1]
  1009. })
  1010. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup');
  1011. if (filterIdGroup) filterFields[ 'filterIdGroup' ] = filterIdGroup
  1012. window.fetch(URL_ADD_KONTRAHENCI_TO_GROUP, {
  1013. method: 'POST',
  1014. header: {
  1015. 'contentType': 'applications/json'
  1016. },
  1017. credentials: 'same-origin',
  1018. body: JSON.stringify({
  1019. 'idGroup': idGroup,
  1020. 'type': 'filter',
  1021. 'filter': filterFields,
  1022. })
  1023. })
  1024. .then(function(response) {
  1025. return response.text();
  1026. })
  1027. .then(function(responseText) {
  1028. try {
  1029. return JSON.parse(responseText);
  1030. } catch (e) {
  1031. throw responseText;
  1032. }
  1033. })
  1034. .then(function(result) {
  1035. $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
  1036. if (result.type == 'success') {
  1037. p5UI__notifyAjaxCallback(result);
  1038. resolve(result.msg);
  1039. } else {
  1040. reject(result.msg);
  1041. }
  1042. })
  1043. .catch(function(error) {
  1044. if(DBG) console.log('request failed', error);
  1045. });
  1046. })
  1047. },
  1048. allowOutsideClick: false
  1049. });
  1050. }
  1051. function removeKontrahenciFromGroup(event) {
  1052. event.preventDefault;
  1053. var kontrahenciIdsArray = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  1054. if (kontrahenciIdsArray === null || !kontrahenciIdsArray || !kontrahenciIdsArray.length) {
  1055. showTextListIdKontrahentow = 'nie wybrano kontrahentów';
  1056. } else {
  1057. showTextListIdKontrahentow = '' + kontrahenciIdsArray.length + ' podmiotów/kontrahentów';
  1058. }
  1059. var groupId = getItemLocalStorage("Bocian.biAuditForm.kontrahenci.filterIdGroup");
  1060. var removeTitle = "Czy chcesz usunąć z "
  1061. if (groupId === "0") {
  1062. removeTitle += "systemu";
  1063. } else {
  1064. var arrayGroupOptions = [];
  1065. var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups');
  1066. // utworzenie tablicy Optionsów grupy
  1067. listGroupStorage.map(function(item) {
  1068. if (item.ID !== undefined) {
  1069. arrayGroupOptions[item.ID] = item.NAZWA;
  1070. }
  1071. });
  1072. removeTitle += "grupy ";
  1073. removeTitle += arrayGroupOptions[groupId];
  1074. }
  1075. swal({
  1076. title: removeTitle,
  1077. text: showTextListIdKontrahentow,
  1078. showConfirmButton: true,
  1079. showCancelButton: true,
  1080. confirmButtonText: 'Usuń',
  1081. cancelButtonText: 'Anuluj',
  1082. showLoaderOnConfirm: true,
  1083. preConfirm: function () {
  1084. return new Promise(function (resolve, reject) {
  1085. if (!kontrahenciIdsArray || !kontrahenciIdsArray.length) {
  1086. reject('Wybierz kontrahentów');
  1087. return;
  1088. }
  1089. window.fetch(URL_REMOVE_KONTRAHENCI_FROM_GROUP, {
  1090. method: 'POST',
  1091. header: { 'contentType': 'applications/json' },
  1092. credentials: 'same-origin',
  1093. body: JSON.stringify({
  1094. 'idGroup': getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup'),
  1095. 'kontrahenciIds': getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds'),
  1096. })
  1097. })
  1098. .then(function(response) {
  1099. return response.text();
  1100. })
  1101. .then(function(responseText) {
  1102. try {
  1103. return JSON.parse(responseText);
  1104. } catch (e) {
  1105. throw responseText;
  1106. }
  1107. })
  1108. .then(function(result) {
  1109. result
  1110. if (result.type == 'success') {
  1111. p5UI__notifyAjaxCallback(result);
  1112. updateTopCounters();
  1113. $('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false);
  1114. resolve(result.msg);
  1115. } else {
  1116. reject(result.msg);
  1117. }
  1118. })
  1119. })
  1120. },
  1121. allowOutsideClick: false
  1122. }).then((result) => {
  1123. if (!result) return;
  1124. if (result.dismiss) return;
  1125. if (!result.value) return;
  1126. { // remove from selected
  1127. setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', []);
  1128. updateCountItemCheckedByType('kontrahenci');
  1129. $('#smad-table-KONTRAHENCI form').find(':checkbox').prop('checked', false);
  1130. }
  1131. urlFetchKontrahenci(1);
  1132. });
  1133. }
  1134. function removePracownikFromGroup(event){
  1135. event.preventDefault;
  1136. var pracownicyIdsArray = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds');
  1137. if (pracownicyIdsArray === null || !pracownicyIdsArray || !pracownicyIdsArray.length) {
  1138. showTextListIdPracownikow = 'nie wybrano osób';
  1139. } else {
  1140. showTextListIdPracownikow = '' + pracownicyIdsArray.length + ' osób';
  1141. }
  1142. var groupId = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup');
  1143. var removeTitle = "Czy chcesz usunąć z "
  1144. if (!groupId) {
  1145. removeTitle += "systemu";
  1146. } else {
  1147. var arrayGroupOptions = [];
  1148. var listGroupStorage = getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups');
  1149. // utworzenie tablicy Optionsów grupy
  1150. listGroupStorage.map(function(item) {
  1151. if (item.ID !== undefined) {
  1152. arrayGroupOptions[item.ID] = item.NAZWA;
  1153. }
  1154. });
  1155. removeTitle += "grupy ";
  1156. removeTitle += arrayGroupOptions[groupId];
  1157. }
  1158. swal({
  1159. title: removeTitle,
  1160. text: showTextListIdPracownikow,
  1161. showConfirmButton: true,
  1162. showCancelButton: true,
  1163. confirmButtonText: 'Usuń',
  1164. cancelButtonText: 'Anuluj',
  1165. showLoaderOnConfirm: true,
  1166. preConfirm: function () {
  1167. return new Promise(function (resolve, reject) {
  1168. if (!pracownicyIdsArray || !pracownicyIdsArray.length) {
  1169. reject('Wybierz osoby');
  1170. return;
  1171. }
  1172. window.fetch(URL_REMOVE_PRACOWNICY_FROM_GROUP, {
  1173. method: 'POST',
  1174. header: { 'contentType': 'applications/json' },
  1175. credentials: 'same-origin',
  1176. body: JSON.stringify({
  1177. 'idGroup': getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup'),
  1178. 'pracownicyIds': getItemLocalStorage('Bocian.biAuditForm.pracownicyIds'),
  1179. })
  1180. })
  1181. .then(function(response) {
  1182. return response.text();
  1183. })
  1184. .then(function(responseText) {
  1185. try {
  1186. return JSON.parse(responseText);
  1187. } catch (e) {
  1188. throw responseText;
  1189. }
  1190. })
  1191. .then(function(result) {
  1192. if (result.type == 'success') {
  1193. p5UI__notifyAjaxCallback(result);
  1194. updateTopCounters();
  1195. $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
  1196. resolve(result.msg);
  1197. } else {
  1198. reject(result.msg);
  1199. }
  1200. })
  1201. })
  1202. },
  1203. allowOutsideClick: false
  1204. }).then((result) => {
  1205. if (!result) return;
  1206. if (result.dismiss) return;
  1207. if (!result.value) return;
  1208. { // remove from selected
  1209. setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', []);
  1210. updateCountItemCheckedByType('pracownicy');
  1211. $('#smad-table-PRACOWNICY form').find(':checkbox').prop('checked', false);
  1212. }
  1213. urlFetchPracownicy(1);
  1214. });
  1215. }
  1216. function createGroupKontrahenci(event) {
  1217. event.preventDefault();
  1218. swal({
  1219. title: 'Utwórz grupę',
  1220. input: 'text',
  1221. showCancelButton: true,
  1222. confirmButtonText: 'Zapisz',
  1223. showLoaderOnConfirm: true,
  1224. preConfirm: function (NAZWA) {
  1225. return new Promise(function (resolve, reject) {
  1226. if (!NAZWA) {
  1227. reject('Proszę podać nazwę grupy');
  1228. return;
  1229. }
  1230. window.fetch(URL_CREATE_PRACOWNICY_GROUP, {
  1231. method: 'POST',
  1232. header: { 'contentType': 'applications/json' },
  1233. credentials: 'same-origin',
  1234. body: JSON.stringify({
  1235. 'NAZWA': NAZWA
  1236. })
  1237. })
  1238. .then(function(response) {
  1239. return response.text();
  1240. })
  1241. .then(function(responseText) {
  1242. try {
  1243. return JSON.parse(responseText);
  1244. } catch (e) {
  1245. throw responseText;
  1246. }
  1247. })
  1248. .then(function(result) {
  1249. if (result.type == 'success') {
  1250. p5UI__notifyAjaxCallback(result);
  1251. resolve(result.body);
  1252. } else {
  1253. reject("Proszę podać inną nazwę grupy");
  1254. }
  1255. })
  1256. .catch(function(error) {
  1257. if(DBG) console.log('request failed', error);
  1258. })
  1259. })
  1260. },
  1261. allowOutsideClick: false
  1262. }).then(function (result) {
  1263. if (!result) return;
  1264. if (result.dismiss) return;
  1265. if (!result.value) return;
  1266. // NOTE: swal has input, so resolver object from preConfirm is in { value: resolvedObject }
  1267. var addedGroup = result.value;
  1268. if (addedGroup.id && addedGroup.nazwa) {
  1269. $('#group-kontrahenci').append('<button class="btn btn-default" title="'+addedGroup['nazwa']+'" data-group-filter="'+addedGroup['id']+'">'+addedGroup['nazwa']+'</button>');
  1270. { // add group to local storage
  1271. setItemLocalStorage(
  1272. 'Bocian.biAuditForm.kontrahenci.groups',
  1273. [].concat(
  1274. getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups') || [],
  1275. [ { 'ID': addedGroup.id, 'NAZWA': addedGroup.nazwa } ]
  1276. )
  1277. );
  1278. }
  1279. }
  1280. //TODO: aktualizacja fitrów na widoku -> SPrawdzić co dostaniemy w odpowiedzi po dodaniu filtra grupy
  1281. });
  1282. }
  1283. function createGroupPracownicy(event) {
  1284. event.preventDefault();
  1285. swal({
  1286. title: 'Utwórz grupę',
  1287. input: 'text',
  1288. showCancelButton: true,
  1289. confirmButtonText: 'Zapisz',
  1290. showLoaderOnConfirm: true,
  1291. preConfirm: function (NAZWA) {
  1292. return new Promise(function (resolve, reject) {
  1293. if (!NAZWA) {
  1294. reject('Proszę podać nazwę grupy');
  1295. return;
  1296. }
  1297. window.fetch(URL_CREATE_PRACOWNICY_GROUP, {
  1298. method: 'POST',
  1299. header: { 'contentType': 'applications/json' },
  1300. credentials: 'same-origin',
  1301. body: JSON.stringify({
  1302. 'NAZWA': NAZWA
  1303. })
  1304. })
  1305. .then(function(response) {
  1306. return response.text();
  1307. })
  1308. .then(function(responseText) {
  1309. try {
  1310. return JSON.parse(responseText);
  1311. } catch (e) {
  1312. throw responseText;
  1313. }
  1314. })
  1315. .then(function(result) {
  1316. console.warn('DBG group added? result', result)
  1317. if (result.type == 'success') {
  1318. p5UI__notifyAjaxCallback(result);
  1319. resolve(result.body);
  1320. } else {
  1321. reject("Proszę podać inną nazwę grupy");
  1322. }
  1323. })
  1324. .catch(function(error) {
  1325. if(DBG) console.log('request failed', error);
  1326. })
  1327. })
  1328. },
  1329. allowOutsideClick: false
  1330. }).then(function (result) {
  1331. if (!result) return;
  1332. if (result.dismiss) return;
  1333. if (!result.value) return;
  1334. // NOTE: swal has input, so resolver object from preConfirm is in { value: resolvedObject }
  1335. var addedGroup = result.value;
  1336. if (addedGroup.id && addedGroup.nazwa) {
  1337. $('#group-pracownicy').append('<button class="btn btn-default" title="'+addedGroup['nazwa']+'" data-group-filter="'+addedGroup['id']+'">'+addedGroup['nazwa']+'</button>');
  1338. { // add group to local storage
  1339. setItemLocalStorage(
  1340. 'Bocian.biAuditForm.pracownicy.groups',
  1341. [].concat(
  1342. getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups') || [],
  1343. [ { 'ID': addedGroup.id, 'NAZWA': addedGroup.nazwa } ]
  1344. )
  1345. );
  1346. }
  1347. }
  1348. //TODO: aktualizacja fitrów na widoku -> SPrawdzić co dostaniemy w odpowiedzi po dodaniu filtra grupy
  1349. });
  1350. }
  1351. /**
  1352. * Function for load view Form pracownicy/kontrahenci
  1353. */
  1354. function rootChangeForm() {
  1355. //todo: do przeniesienia
  1356. urlFetchKontrahenciPowiazania();
  1357. var valueUrl = global.location.hash;
  1358. switch (valueUrl) {
  1359. case '#KONTRAHENCI':
  1360. $( ".container-bi_audit_form_kontrahenci_raport" ).html( VIEW_KONTRAHENCI );
  1361. urlFetchKontrahenci(1);
  1362. fetchGroupKontrahenci();
  1363. $( ".container-bi_audit_form_pracownicy_raport" ).hide();
  1364. $( ".container-bi_audit_form_kontrahenci_raport" ).show();
  1365. $(".container-bi-audit_form_operacyjna_baza_zgloszen").hide();
  1366. //parseGraph();
  1367. break;
  1368. case '#PRACOWNICY':
  1369. $( ".container-bi_audit_form_pracownicy_raport" ).html( VIEW_PRACOWNICY );
  1370. urlFetchPracownicy(1);
  1371. fetchGroupPracownicy();
  1372. $( ".container-bi_audit_form_kontrahenci_raport" ).hide();
  1373. $( ".container-bi_audit_form_pracownicy_raport" ).show();
  1374. $(".container-bi-audit_form_operacyjna_baza_zgloszen").hide();
  1375. break;
  1376. case '#OPERACYJNA_BAZA_ZGLOSZEN':
  1377. $( ".container-bi_audit_form_operacyjna_baza_zgloszen" ).html( OPERACYJNA_BAZA_ZGLOSZEN );
  1378. // urlFetchPracownicy(1);
  1379. // fetchGroupPracownicy();
  1380. $( ".container-bi_audit_form_kontrahenci_raport" ).hide();
  1381. $( ".container-bi_audit_form_pracownicy_raport" ).hide();
  1382. $(".container-bi-audit_form_operacyjna_baza_zgloszen").show();
  1383. break;
  1384. // case '#REAPORT':
  1385. // $( ".container-bi_audit_form_raport_data" ).html( VIEW_TREE_REAPORT );
  1386. // urlFetchKontrahenciPowiazania();
  1387. // $( ".container-bi_audit_form_kontrahenci_raport" ).hide();
  1388. // $( ".container-bi_audit_form_pracownicy_raport" ).hide();
  1389. // $( ".container-bi_audit_form_raport_data" ).show();
  1390. // break;
  1391. default:
  1392. $( ".container-bi_audit_form_pracownicy_raport" ).html( VIEW_PRACOWNICY );
  1393. urlFetchPracownicy(1);
  1394. fetchGroupPracownicy();
  1395. $( ".container-bi_audit_form_kontrahenci_raport" ).hide();
  1396. $( ".container-training" ).hide();
  1397. $( ".container-about" ).hide();
  1398. $( ".container-bi_audit_form_pracownicy_raport" ).show();
  1399. break;
  1400. }
  1401. // aktualizacja select option czy zwracać wyniki tylko z obiektami docelowymi
  1402. updateLocalStorageBiAuditOnlyTargets('#smad-select-target');
  1403. updateLocalStorageBiAuditOnlyTargets('#smad-select-target-kontrahenci');
  1404. // load in select selected option BI_analiza_onlyTargets
  1405. loadCurrentOnlyTargetsSelect();
  1406. }
  1407. function getAddressData(objectValue) {
  1408. var objectValue = objectValue || [];
  1409. var listData = '';
  1410. if (!objectValue) {
  1411. return true;
  1412. }
  1413. objectValue.forEach (function(item) {
  1414. if (item['kodPocztowy']) { listData += '<div>kod pocztowy: ' + item['kodPocztowy'] + '<div>'; }
  1415. if (item['miejscowosc']) { listData += '<div>miejscowość: ' + item['miejscowosc'] + '<div>'; }
  1416. if (item['nrBudynku']) { listData += '<div>nr budynku: ' + item['nrBudynku'] + '<div>'; }
  1417. if (item['nrLokalu']) { listData += '<div>nr lokalu: ' + item['nrLokalu'] + '<div>'; }
  1418. if (item['typAdresu']) { listData += '<div>typ adresu: ' + item['typAdresu'] + '<div>'; }
  1419. if (item['ulica']) { listData += '<div>ulica: ' + item['ulica'] + '<div>'; }
  1420. listData += '<div>------<div>';
  1421. });
  1422. return listData;
  1423. }
  1424. /**
  1425. * Get name name group
  1426. */
  1427. function getNameGroupById(store, filterIdGroup) {
  1428. var NAZWA = '';
  1429. if (!store || filterIdGroup === 0 ) {
  1430. NAZWA = 'Wszyscy';
  1431. } else {
  1432. $(store).each(function() {
  1433. if ( parseInt(filterIdGroup) === parseInt(this.ID) ) {
  1434. NAZWA = this.NAZWA;
  1435. }
  1436. });
  1437. }
  1438. return NAZWA;
  1439. }
  1440. function getSearchParamsKontrahenci(page) {
  1441. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup');
  1442. var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
  1443. var fieldNameList = FIELD_LIST_KONTRAHENCI
  1444. var filterFields = fieldNameList.filter(function (fieldName) {
  1445. if (!frm[fieldName] && DBG) console.log('Err missing field: "' + fieldName + '"')
  1446. return (frm[fieldName]) ? true : false
  1447. }).map(function (fieldName) {
  1448. return [fieldName, frm[fieldName].value]
  1449. }).filter(function (filter) {
  1450. return (filter[1].length > 0)
  1451. }).map(function (filter) {
  1452. return '' + filter[0] + '=' + filter[1]
  1453. }).join('&')
  1454. return {
  1455. page: page,
  1456. filterIdGroup: filterIdGroup,
  1457. filterFields: (filterFields.length > 0) ? filterFields : null,
  1458. };
  1459. }
  1460. function getUrlFetchKontrahenci(page) {
  1461. // return URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields;
  1462. var searchParams = getSearchParamsKontrahenci(page);
  1463. return [
  1464. URL_FETCH_KONTRAHENCI,
  1465. 'page=' + searchParams.page,
  1466. 'filterIdGroup=' + searchParams.filterIdGroup,
  1467. searchParams.filterFields,
  1468. ].filter(Boolean).join('&');
  1469. }
  1470. function urlFetchKontrahenci(page) {
  1471. hideMoreRecordFunctionsPopover()
  1472. var page = page || getItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page');
  1473. selectPage('KONTRAHENCI', page);
  1474. if ( page === 1) {
  1475. setItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page', 1);
  1476. }
  1477. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup');
  1478. var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
  1479. var fieldNameList = FIELD_LIST_KONTRAHENCI
  1480. var filterFields = fieldNameList.map(function (fieldName) {
  1481. return [ fieldName, frm[fieldName].value ]
  1482. }).filter(function (filter) {
  1483. return ( filter[1].length > 0 )
  1484. }).map(function (filter) {
  1485. return '' + filter[0] + '=' + filter[1]
  1486. }).join('&')
  1487. filterFields = (filterFields.length > 0) ? '&' + filterFields : ''
  1488. fetch(URL_FETCH_KONTRAHENCI + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields, {
  1489. credentials: 'same-origin'
  1490. })
  1491. .then(function parseJSON(response) {
  1492. return response.json()
  1493. var filterIdGroup = filterIdGroup || getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup');
  1494. })
  1495. .then(function(data) {
  1496. var listItemsKontrahenci = null;
  1497. data.body.items.forEach (function(row) {
  1498. listItemsKontrahenci += '<tr><td style="white-space:nowrap">' +
  1499. '<input style="vertical-align:top" type="checkbox" name="kontrID[]" value="'+row['ID']+'" />' +
  1500. '<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>' +
  1501. '</td>' +
  1502. '<td align="right">'+row["ID"]+'</td>'+
  1503. '<td align="right">' + ( row["Nazwa_grupy_kapitalowej"] || '' ) + '</td>' +
  1504. '<td align="right">' + ( row["Pelna_nazwa_kontrahenta"] || '' ) + '</td>' +
  1505. '<td align="right">' + ( row["Numer_kontrahenta"] || '' ) + '</td>' +
  1506. '<td align="right">' + ( row["Skrocona_Nazwa_Kontrahenta"] || '' ) + '</td>' +
  1507. '<td align="right">' + ( row["Typ_kontrahenta"] || '' ) + '</td>' +
  1508. '<td align="right">' + ( row["NIP"] || '' ) + '</td>' +
  1509. '<td align="right">' + ( row["KRS"] || '' ) + '</td>' +
  1510. '<td align="right">' + ( row["REGON"] || '' ) + '</td>' +
  1511. '<td align="right">' + ( row["PESEL"] || '' ) + '</td>' +
  1512. '<td align="right">' + ( row["Forma_prawna_dzialalnosci"] || '' ) + '</td>' +
  1513. '<td align="right">' + ( row["Ulica"] || '' ) + '</td>' +
  1514. '<td align="right">' + ( row["Numer_budynku"] || '' ) + '</td>' +
  1515. '<td align="right">' + ( row["Numer_mieszkania_lokalu"] || '' ) + '</td>' +
  1516. '<td align="right">' + ( row["Miejscowosc"] || '' ) + '</td>' +
  1517. '<td align="right">' + ( row["Kod_pocztowy"] || '' ) + '</td>' +
  1518. '<td align="right">' + ( row["Kraj"] || '' ) + '</td>' +
  1519. '<td align="right">' + ( row["Telefon"] || '' ) + '</td>' +
  1520. '<td align="right">' + ( row["Fax"] || '' ) + '</td>' +
  1521. '<td align="right">' + ( row["Mail"] || '' ) + '</td>' +
  1522. '<td align="right">' + ( row["A_ADM_COMPANY"] || '' ) + '</td>' +
  1523. '<td align="right">' + ( row["A_CLASSIFIED"] || '' ) + '</td>' +
  1524. '<td align="right">' + ( row["Dodano"] || '' ) + '</td>' +
  1525. '<td align="right">' + ( row["Podmiot_dominujacy"] || '' ) + '</td>' +
  1526. '<td align="right">' + ( row["Tytul_dokumentu"] || '' ) + '</td>' +
  1527. '<td align="right">' + ( row["ownCompany"] || '' ) + '</td>' +
  1528. '<td align="right">' + ( row["uwagi"] || '' ) + '</td></tr>';
  1529. });
  1530. if (data.body.pagination !== undefined) {
  1531. Pagination.Init(document.getElementById('pagination-kontrahenci'), {
  1532. url: BASE_URLS+'index.php?_route=UrlAction_Bocian#KONTRAHENCI',
  1533. id_pagination: 'pagination-kontrahenci',
  1534. type: 'KONTRAHENCI',
  1535. limit: data.body.pagination.limit,
  1536. total_items: data.body.pagination.total_items, // pages size
  1537. size: data.body.pagination.size, // pages size
  1538. page: page, // selected page
  1539. step: 1 // pages before and after current
  1540. });
  1541. var paginationShowNextCount = 1;
  1542. if ( parseInt(data.body.pagination.current) !== 1) {
  1543. paginationShowNextCount = parseInt(data.body.pagination.limit) * (parseInt(data.body.pagination.current) - 1 ) + 1;
  1544. }
  1545. $('#paginationShowNextCount-KONTRAHENCI').text(paginationShowNextCount);
  1546. $('#smad-filter-desc-kontrahenci').text(data.body.pagination.total_items);
  1547. if (data.body.pagination.total_items > 0) {
  1548. var btnAddAll = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO ANALIZY</button>');
  1549. btnAddAll.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addAllMatchesToReport);
  1550. $('#smad-filter-desc-kontrahenci').append(btnAddAll);
  1551. // var btnAddByReport = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ DO ANALIZY WG RAPORTU</button>');
  1552. // btnAddByReport.on('click', { type: 'kontrahenci', pagination: data.body.pagination }, addToReportByPreviousReport);
  1553. // $('#smad-filter-desc-kontrahenci').append(btnAddByReport);
  1554. var btnAddAllToGroup = $('<button class="btn btn-info" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</button>');
  1555. btnAddAllToGroup.on('click', addKontrahenciAllToGroup);
  1556. $('#smad-filter-desc-kontrahenci').append(btnAddAllToGroup);
  1557. }
  1558. }
  1559. var groupSelectData = getNameGroupById(getItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups'), filterIdGroup);
  1560. $('#smad-filter-head-title-kontrahenci').text(groupSelectData);
  1561. if(DBG) console.log('kontrahenci groupSelectData: ', groupSelectData);
  1562. $( "#body-kontrahenci" ).html(listItemsKontrahenci);
  1563. checkAll('KONTRAHENCI');
  1564. catchEventCheckbox('KONTRAHENCI');
  1565. checkedChoiseItems('KONTRAHENCI', getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds') );
  1566. // $( ".container-bi_audit_raport" ).append( data.body.view );
  1567. if(DBG) console.log('request succeeded with JSON responseKontrahenci', data)
  1568. updateTopCounters();
  1569. }).catch(function(error) {
  1570. if(DBG) console.log('request failed', error);
  1571. })
  1572. }
  1573. function getSearchParamsPracownicy(page) {
  1574. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup');
  1575. var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
  1576. var fieldNameList = FIELD_LIST_PRACOWNICY
  1577. var filterFields = fieldNameList.filter(function (fieldName) {
  1578. if (!frm[fieldName] && DBG) console.log('Err missing field: "' + fieldName + '"')
  1579. return (frm[fieldName]) ? true : false
  1580. }).map(function (fieldName) {
  1581. return [fieldName, frm[fieldName].value]
  1582. }).filter(function (filter) {
  1583. return (filter[1].length > 0)
  1584. }).map(function (filter) {
  1585. return '' + filter[0] + '=' + filter[1]
  1586. }).join('&')
  1587. return {
  1588. page: page,
  1589. filterIdGroup: filterIdGroup,
  1590. filterFields: (filterFields.length > 0) ? filterFields : null,
  1591. };
  1592. }
  1593. function getUrlFetchPracownicy(page) {
  1594. // return URL_FETCH_PRACOWNICY + '&page=' + page + '&filterIdGroup=' + filterIdGroup + filterFields;
  1595. var searchParams = getSearchParamsPracownicy(page);
  1596. return [
  1597. URL_FETCH_PRACOWNICY,
  1598. 'page=' + searchParams.page,
  1599. 'filterIdGroup=' + searchParams.filterIdGroup,
  1600. searchParams.filterFields,
  1601. ].filter(Boolean).join('&');
  1602. }
  1603. function urlFetchPracownicy(page) {
  1604. hideMoreRecordFunctionsPopover()
  1605. var page = page || getItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page');
  1606. if ( page === 1) {
  1607. setItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page', 1);
  1608. }
  1609. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup');
  1610. selectPage('PRACOWNICY', page);
  1611. // var paginationLimit = 20;
  1612. /*p5WFS_GetFeature('default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
  1613. Object.assign({
  1614. sortBy: 'ID+D',
  1615. maxFeatures: paginationLimit,
  1616. startIndex: (page - 1) * paginationLimit,
  1617. // TODO: backRefNS, backRefPK, backRefField - TODO: from groups
  1618. // resolve: 'all',
  1619. // resolveDepth: 2
  1620. 'ogc:Filter': '<wfs:Query>' + '\n' + [
  1621. '*',
  1622. 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*',
  1623. [
  1624. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  1625. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
  1626. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object',
  1627. 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI'
  1628. ].join('/')
  1629. ].map(function (fieldName) {
  1630. return '<wfs:PropertyName>' + fieldName + '</wfs:PropertyName>';
  1631. }).join('\n') + '\n' + '</wfs:Query>'
  1632. }, (filterIdGroup > 0)
  1633. ? {
  1634. backRefNS: 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
  1635. backRefPK: filterIdGroup,
  1636. backRefField: 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
  1637. }
  1638. : {}
  1639. )
  1640. ).then(function (items) {
  1641. if(DBG)console.log('p5WFS_GetFeature: items: ', items);
  1642. }).catch(function (err) {
  1643. if(DBG)console.log('p5WFS_GetFeature: err: ', err);
  1644. })*/
  1645. var fetchUrl = getUrlFetchPracownicy(page);
  1646. DBG && console.log('DBG: fetch ', { fetchUrl });
  1647. fetch(fetchUrl, {
  1648. credentials: 'same-origin'
  1649. })
  1650. .then(function parseJSON(response) {
  1651. return response.json()
  1652. })
  1653. .then(function(data) {
  1654. var addresPerson = '';
  1655. var listItemsPracownik = null;
  1656. if(DBG) console.log('urlFetchPracownicy', data.body.items);
  1657. data.body.items.forEach (function(row) {
  1658. if (row["default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy"]) {
  1659. addresPerson = getAddressData(row["default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy"]);
  1660. }
  1661. listItemsPracownik += '<tr><td style="white-space:nowrap">' +
  1662. '<input style="vertical-align:top" type="checkbox" name="prID[]" value="'+row['ID']+'" />' +
  1663. '<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>' +
  1664. '</td>' +
  1665. '<td align="right">'+row["ID"]+'</td>' +
  1666. '<td align="right">' + ( row["imiona"] || '' ) + '</td>' +
  1667. '<td align="right">' + ( row["nazwisko"] || '' ) + '</td>' +
  1668. '<td align="right">' + ( row["nip"] || '' ) + '</td>' +
  1669. '<td align="right">' + ( row["pesel"] || '' ) + '</td>' +
  1670. '<td align="right">' + ( row["regon"] || '' ) + '</td>' +
  1671. '<td align="right">' + ( row["source"] || '' ) + '</td>' +
  1672. '<td align="right">' + ( row["jednostka_organizacyjna"] || '' ) + '</td>' +
  1673. '<td align="right">' + ( row["A_STATUS"] || '' ) + '</td>' +
  1674. '<td align="right">' + ( row["A_STATUS_INFO"] || '' ) + '</td>' +
  1675. '<td align="right">' + ( row["L_APPOITMENT_USER"] || '' ) + '</td>' +
  1676. '<td align="right">'+ addresPerson +'</td></tr>';
  1677. });
  1678. if (data.body.pagination.size) {
  1679. Pagination.Init(document.getElementById('pagination-pracownicy'), {
  1680. url: BASE_URLS+'index.php?_route=UrlAction_Bocian#PRACOWNICY',
  1681. id_pagination: 'pagination-pracownicy',
  1682. type: 'PRACOWNICY',
  1683. limit: data.body.pagination.limit,
  1684. total_items: data.body.pagination.total_items, // pages size
  1685. size: data.body.pagination.size, // pages size
  1686. page: data.body.pagination.current, // selected page
  1687. step: 1 // pages before and after current
  1688. });
  1689. var paginationShowNextCount = 1;
  1690. if ( parseInt(data.body.pagination.current) !== 1) {
  1691. paginationShowNextCount = parseInt(data.body.pagination.limit) * (parseInt(data.body.pagination.current) - 1 ) + 1;
  1692. }
  1693. $('#paginationShowNextCount-PRACOWNICY').text(paginationShowNextCount);
  1694. $('#smad-filter-desc-pracownicy').text(data.body.pagination.total_items);
  1695. if (data.body.pagination.total_items > 0) {
  1696. var btnAddAll = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO ANALIZY</button>')
  1697. btnAddAll.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addAllMatchesToReport);
  1698. $('#smad-filter-desc-pracownicy').append(btnAddAll);
  1699. // var btnAddByReport = $('<button class="btn btn-primary" style="padding:1px 5px; margin-left:12px">DODAJ DO ANALIZY WG RAPORTU</button>');
  1700. // btnAddByReport.on('click', { type: 'pracownicy', pagination: data.body.pagination }, addToReportByPreviousReport);
  1701. // $('#smad-filter-desc-pracownicy').append(btnAddByReport);
  1702. var btnAddAllToGroup = $('<button class="btn btn-info" style="padding:1px 5px; margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</button>');
  1703. btnAddAllToGroup.on('click', addPracownikAllToGroup);
  1704. $('#smad-filter-desc-kontrahenci').append(btnAddAllToGroup);
  1705. }
  1706. }
  1707. // wyświetlenie wybranej grupy w naglówku nad tabela
  1708. var groupSelectData = getNameGroupById(getItemLocalStorage('Bocian.biAuditForm.pracownicy.groups'), filterIdGroup);
  1709. $('#smad-filter-head-title-pracownicy').text(groupSelectData);
  1710. // zaladaowanie listy pracowników
  1711. $( "#body-pracownicy" ).html( listItemsPracownik);
  1712. checkAll('PRACOWNICY');
  1713. catchEventCheckbox('PRACOWNICY');
  1714. checkedChoiseItems('PRACOWNICY', getItemLocalStorage('Bocian.biAuditForm.pracownicyIds') );
  1715. updateTopCounters();
  1716. }).catch(function(error) {
  1717. if(DBG) console.log('request failed', error)
  1718. })
  1719. }
  1720. function selectPage(type, nrPage) {
  1721. var type = type.toLowerCase();
  1722. $('#pagination-' + type + ' ul li a').each(function(index, value){
  1723. if (this.text === nrPage) {
  1724. $(this).addClass('active');
  1725. } else {
  1726. $(this).removeClass('active');
  1727. }
  1728. });
  1729. }
  1730. function checkAll(type) {
  1731. $('#checkAll-' + type).change(function() {
  1732. var valueCheckbox = null;
  1733. var checkboxes = $('form').find(':checkbox');
  1734. if($(this).prop('checked')) {
  1735. checkboxes.prop('checked', true);
  1736. //valueCheckbox = checkboxes.prop("checked");
  1737. var allValsChecked = [];
  1738. var checkedValues = $('#smad-table-' + type + ' input:checkbox:checked').map(function() {
  1739. if (this.value !== 'on') {
  1740. allValsChecked.push(parseInt(this.value));
  1741. }
  1742. }).get();
  1743. updateListIdBiAuditReaport(type, allValsChecked);
  1744. } else {
  1745. checkboxes.prop('checked', false);
  1746. var allValsUnChecked = [];
  1747. var checkedValues = $('#smad-table-' + type + ' input:checkbox:not(:checked)').map(function() {
  1748. if (this.value !== 'on') {
  1749. allValsUnChecked.push(parseInt(this.value));
  1750. }
  1751. }).get();
  1752. deleteListIdBiAuditReaport(type, allValsUnChecked);
  1753. }
  1754. // update count selected IDs
  1755. updateCountItemCheckedByType(type.toLowerCase());
  1756. });
  1757. }
  1758. /**
  1759. * Select again checkbox before selected item chekbox from storage (pracownicy/kontrahenci)
  1760. */
  1761. function checkedChoiseItems(type, store) {
  1762. updateCountItemCheckedByType(type.toLowerCase());
  1763. var idElement = 'smad-table-' + type;
  1764. // if id element exist
  1765. if (document.getElementById(idElement)) {
  1766. // if not checked
  1767. if (!store) {
  1768. return false;
  1769. }
  1770. // checked again if user selected Item (pracownicy/kontrahent)
  1771. for (i = 0; i < store.length; i++) {
  1772. $('#body-'+type.toLowerCase() +' input[type=checkbox] ').map(function(k, v) {
  1773. if ( store[i] === parseInt(this.value) ){
  1774. $(this).prop('checked', true);
  1775. }
  1776. }).get();
  1777. }
  1778. }
  1779. $('#smad-table-' + type + ' input[type=checkbox]').on( 'load', function() {
  1780. var itemsCHecked = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds');
  1781. getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  1782. if (itemsCHecked.lenght === 0 ) {
  1783. return;
  1784. }
  1785. var valueCheckbox = null;
  1786. var checkboxes = $('form').find(':checkbox');
  1787. if($(this).prop('checked')) {
  1788. checkboxes.prop('checked', true);
  1789. var allValsChecked = [];
  1790. var checkedValues = $('#smad-table-' + type + ' input:checkbox:checked').map(function() {
  1791. if (this.value !== 'on') {
  1792. allValsChecked.push(parseInt(this.value));
  1793. }
  1794. }).get();
  1795. updateListIdBiAuditReaport(type, allValsChecked);
  1796. } else {
  1797. checkboxes.prop('checked', false);
  1798. var allValsUnChecked = [];
  1799. var checkedValues = $('#smad-table-' + type + ' input:checkbox:not(:checked)').map(function() {
  1800. if (this.value !== 'on') {
  1801. allValsUnChecked.push(parseInt(this.value));
  1802. }
  1803. }).get();
  1804. deleteListIdBiAuditReaport(type, allValsUnChecked);
  1805. }
  1806. });
  1807. }
  1808. function catchEventCheckbox(type) {
  1809. $('#smad-table-' + type + ' input[type="checkbox"]').on('change', function() {
  1810. if($(this).is(":checked")) {
  1811. var allValsChecked = [];
  1812. if (this.value !== 'on') {
  1813. allValsChecked.push(parseInt(this.value));
  1814. }
  1815. updateListIdBiAuditReaport(type, allValsChecked);
  1816. } else {
  1817. var allValsUnChecke = [];
  1818. if (this.value !== 'on') {
  1819. allValsUnChecke.push(parseInt(this.value));
  1820. }
  1821. deleteListIdBiAuditReaport(type, allValsUnChecke);
  1822. }
  1823. // update count selected IDs
  1824. updateCountItemCheckedByType(type.toLowerCase());
  1825. });
  1826. }
  1827. function clearSelectedCheckbox() {
  1828. $('#checkAll-PRACOWNICY').prop('checked', false)
  1829. $('#checkAll-KONTRAHENCI').prop('checked', false)
  1830. }
  1831. function updateListIdBiAuditReaport(type, valueArray) {
  1832. var currentStoragePracownicyIds = [];
  1833. var updateListPracownicyIds = null;
  1834. var currentStorageKontrahenciIds = [];
  1835. var updateListKontrahenciIds = null;
  1836. if ( type == 'PRACOWNICY') {
  1837. currentStoragePracownicyIds = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds');
  1838. if(currentStoragePracownicyIds !== null) {
  1839. updateListPracownicyIds = [...new Set([...currentStoragePracownicyIds ,...valueArray])];
  1840. }
  1841. else {
  1842. updateListPracownicyIds = valueArray;
  1843. }
  1844. setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', updateListPracownicyIds);
  1845. }
  1846. if ( type == 'KONTRAHENCI') {
  1847. currentStorageKontrahenciIds = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  1848. if(currentStorageKontrahenciIds !== null) {
  1849. updateListKontrahenciIds = [...new Set([...currentStorageKontrahenciIds ,...valueArray])];
  1850. }
  1851. else {
  1852. updateListKontrahenciIds = valueArray;
  1853. }
  1854. setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', updateListKontrahenciIds);
  1855. }
  1856. }
  1857. function deleteListIdBiAuditReaport(type, valueArray) {
  1858. if ( type == 'PRACOWNICY') {
  1859. deleteItemLocalStorage('Bocian.biAuditForm.pracownicyIds', valueArray);
  1860. }
  1861. if ( type == 'KONTRAHENCI') {
  1862. deleteItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', valueArray);
  1863. }
  1864. }
  1865. function fetchGroupPracownicy() {
  1866. fetch(URL_FETCH_GROUP_PRACOWNICY, {
  1867. credentials: 'same-origin'
  1868. })
  1869. .then(function parseJSON(response) {
  1870. return response.json()
  1871. })
  1872. .then(function(data) {
  1873. setItemLocalStorage('Bocian.biAuditForm.pracownicy.groups', data.body.itmesGroupPracownicy);
  1874. if (data.body.itmesGroupPracownicy === null) {
  1875. return;
  1876. }
  1877. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup');
  1878. var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth');
  1879. setItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup', filterIdGroup);
  1880. setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue);
  1881. var groupsPracownicy = '';
  1882. var activeButton = '';
  1883. data.body.itmesGroupPracownicy.forEach (function(row) {
  1884. activeButton = '';
  1885. if ( filterIdGroup === parseInt(row['ID']) ) {
  1886. activeButton = 'active';
  1887. $('#group-pracownicy button.active').removeClass('active');
  1888. }
  1889. groupsPracownicy += '<button class="btn btn-default '+activeButton+'" title="' + row['NAZWA'] + '" data-group-filter="' + row['ID'] + '">' + row['NAZWA'] + '</button>';
  1890. });
  1891. $("#group-pracownicy").append(groupsPracownicy);
  1892. updateCountItemCheckedByType('pracownicy');
  1893. detectChoiseFilter();
  1894. }).catch(function(error) {
  1895. if(DBG) console.log('request failed', error)
  1896. });
  1897. }
  1898. function fetchGroupKontrahenci() {
  1899. fetch(URL_FETCH_GROUP_KONTRAHENCI, {
  1900. credentials: 'same-origin'
  1901. })
  1902. .then(function parseJSON(response) {
  1903. return response.json()
  1904. })
  1905. .then(function(data) {
  1906. setItemLocalStorage('Bocian.biAuditForm.kontrahenci.groups', data.body.itemsGroupKontrahenci);
  1907. if (data.body.itemsGroupKontrahenci === null) {
  1908. return;
  1909. }
  1910. var filterIdGroup = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup');
  1911. var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth');
  1912. setItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup', filterIdGroup);
  1913. setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue);
  1914. var groupsKontrahenci = '';
  1915. var activeButton = '';
  1916. data.body.itemsGroupKontrahenci.forEach (function(row) {
  1917. activeButton = '';
  1918. if ( filterIdGroup === parseInt(row['ID']) ) {
  1919. activeButton = 'active';
  1920. $('#group-kontrahenci button.active').removeClass('active');
  1921. }
  1922. groupsKontrahenci += '<button class="btn btn-default '+activeButton+'" title="'+row['NAZWA']+'" data-group-filter="'+row['ID']+'">'+row['NAZWA']+'</button>';
  1923. });
  1924. $("#group-kontrahenci").append(groupsKontrahenci);
  1925. updateCountItemCheckedByType('kontrahenci');
  1926. detectChoiseFilter();
  1927. }).catch(function(error) {
  1928. if(DBG) console.log('request failed', error)
  1929. });
  1930. }
  1931. function detectChoiseFilter() {
  1932. $('#group-kontrahenci').on('click', 'button', function(evt) {
  1933. $('#group-kontrahenci button.active').removeClass('active');
  1934. $(this).addClass('active');
  1935. // pobranie id grupy kliknietego buttonu
  1936. var filterIdGroup = $(this).attr("data-group-filter");
  1937. // aktaulna wartość zagłebienia
  1938. var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth');
  1939. // czy zwracać wyniki tylko z obiektami docelowymi
  1940. var analizaOnlyTargets = getItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets');
  1941. // ustawienie ostaniej wartości zagłebienia przed resete
  1942. setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue);
  1943. // czy zwracać wyniki tylko z obiektami docelowymi
  1944. setItemLocalStorage('Bocian.biAuditForm.analizaOnlyTargets', analizaOnlyTargets);
  1945. // ustawić id grupy do sesyjnej
  1946. setItemLocalStorage('Bocian.biAuditForm.kontrahenci.filterIdGroup', parseInt(filterIdGroup));
  1947. // wywylac funckje pobrania danych
  1948. urlFetchKontrahenci(1);
  1949. });
  1950. $('#group-pracownicy').on('click', 'button', function(e) {
  1951. e.preventDefault();
  1952. $('#group-pracownicy button.active').removeClass('active');
  1953. $(this).addClass('active');
  1954. // pobranie id grupy kliknietego buttonu
  1955. var filterIdGroup = $(this).attr("data-group-filter");
  1956. // aktaulna wartość zagłebienia
  1957. var currentDepthValue = getItemLocalStorage('Bocian.biAuditForm.depth');
  1958. // ustawienie ostaniej wartości zagłebienia przed resete
  1959. setItemLocalStorage('Bocian.biAuditForm.depth', currentDepthValue);
  1960. // ustawić id grupy do sesyjnej
  1961. setItemLocalStorage('Bocian.biAuditForm.pracownicy.filterIdGroup', parseInt(filterIdGroup));
  1962. // wywylac funckje pobrania danych
  1963. urlFetchPracownicy(1);
  1964. });
  1965. }
  1966. // Local storage
  1967. function setItemLocalStorage(key, array) {
  1968. localStorage.setItem(key, JSON.stringify(array));
  1969. }
  1970. function getItemLocalStorage(key) {
  1971. var retrievedData = localStorage.getItem(key);
  1972. var response = JSON.parse(retrievedData);
  1973. return response;
  1974. }
  1975. function deleteItemLocalStorage(key, itemsArray) {
  1976. var currentStorageArray = getItemLocalStorage(key);
  1977. var newStorageArray = removeItemArrayInArray(currentStorageArray, itemsArray);
  1978. setItemLocalStorage(key, newStorageArray);
  1979. }
  1980. /**
  1981. * arr - array
  1982. * item - search item
  1983. */
  1984. function removeItemInArray(arr, item) {
  1985. for(var i = arr.length; i--;) {
  1986. if(arr[i] === item) {
  1987. arr.splice(i, 1);
  1988. }
  1989. }
  1990. return arr;
  1991. }
  1992. /**
  1993. * arr - array
  1994. * item - array list items
  1995. */
  1996. function removeItemArrayInArray(arr, itemsArray) {
  1997. for(var i = arr.length; i--;) {
  1998. for(var j = itemsArray.length; j--;) {
  1999. if(arr[i] === itemsArray[j]) {
  2000. arr.splice(i, 1);
  2001. }
  2002. }
  2003. }
  2004. return arr;
  2005. }
  2006. /**
  2007. * Cleart list local storage by type
  2008. * typeNameLocalStorage - name (praconwicy/kontrahenci)
  2009. */
  2010. function clearListLocalStorageByType(typeNameLocalStorage) {
  2011. if (typeNameLocalStorage === 'pracownicy') {
  2012. setItemLocalStorage('Bocian.biAuditForm.pracownicyIds', []);
  2013. }
  2014. if (typeNameLocalStorage === 'kontrahenci') {
  2015. setItemLocalStorage('Bocian.biAuditForm.kontrahenciIds', []);
  2016. }
  2017. // update count selected item
  2018. updateCountItemCheckedByType(typeNameLocalStorage);
  2019. // unchecked checkbox
  2020. $('#smad-table-'+typeNameLocalStorage.toUpperCase()+' form').find(':checkbox').prop('checked', false);
  2021. }
  2022. /**
  2023. * Update count selected pracowniyc/kontrahenci
  2024. */
  2025. function updateCountItemCheckedByType(typeNameLocalStorage) {
  2026. var countId = 0;
  2027. updateTopCounters();
  2028. if (typeNameLocalStorage === 'pracownicy') {
  2029. var countPracownicy = getItemLocalStorage('Bocian.biAuditForm.pracownicyIds');
  2030. if (countPracownicy === null || countPracownicy === undefined) {
  2031. return countId;
  2032. }
  2033. countId = Object.keys(countPracownicy).length;
  2034. $('#count-selected-item-pracownicy').text(countId);
  2035. }
  2036. if (typeNameLocalStorage === 'kontrahenci') {
  2037. var countKontrahenci = getItemLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  2038. if (countKontrahenci === null || countKontrahenci === undefined) {
  2039. return countId;
  2040. }
  2041. countId = Object.keys(countKontrahenci).length;
  2042. $('#count-selected-item-kontrahenci').text(countId);
  2043. }
  2044. return countId;
  2045. }
  2046. function updateTopCounters() {
  2047. var idsPracownicy = getListFromLocalStorage('Bocian.biAuditForm.pracownicyIds');
  2048. var idsKontrahenci = getListFromLocalStorage('Bocian.biAuditForm.kontrahenciIds');
  2049. var pozostaleOd = getListFromLocalStorage(getSelectedListLocalStorageKey('OD'));
  2050. var pozostaleDo = getListFromLocalStorage(getSelectedListLocalStorageKey('DO'));
  2051. var allOdLength = idsPracownicy.length + pozostaleOd.length;
  2052. var allDoLength = idsKontrahenci.length + pozostaleDo.length;
  2053. var depthValue = getItemLocalStorage('Bocian.biAuditForm.depth');
  2054. if (globalRaportStore) globalRaportStore.dispatch({
  2055. type: 'UPDATE',
  2056. totalOdPracownicy: idsPracownicy.length,
  2057. totalDoKontrahenci: idsKontrahenci.length,
  2058. })
  2059. }
  2060. var P5UI__Bocian__ExportFieldSelectOverlay = createReactClass({
  2061. handleChange: function (fieldName) {
  2062. DBG && console.log('DBG:P5UI__Bocian__ExportFieldSelectOverlay:handleChange', { fieldName })
  2063. this.props.handleToggle(fieldName);
  2064. },
  2065. setRef: function (reactComponent) {
  2066. this._rootNode = reactComponent;
  2067. },
  2068. componentWillMount: function () { // TODO: mv to div at the end of body, then position div by event.target.offsetTop / offsetLeft
  2069. this._closeDropdownIfClickedOutside = function (event) {
  2070. if (DBG) console.log("P5UI__Bocian__ExportFieldSelectOverlay::_closeDropdownIfClickedOutside idHtmlPopover:", { 'this__rootNode': this._rootNode })
  2071. if (!this._rootNode) return;
  2072. var isClickedOutside = p5UI__clickedOutsideElement(this._rootNode, event)
  2073. if (isClickedOutside) {
  2074. this._unbindCloseDropdownIfClickedOutside();
  2075. this.props.handleClose();
  2076. }
  2077. }.bind(this);
  2078. this._bindCloseDropdownIfClickedOutside = function () {
  2079. if (DBG) console.log("P5UI__Bocian__ExportFieldSelectOverlay::_bindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
  2080. if (!document.addEventListener && document.attachEvent) {
  2081. document.attachEvent('onclick', this._closeDropdownIfClickedOutside);
  2082. } else {
  2083. document.addEventListener('click', this._closeDropdownIfClickedOutside);
  2084. }
  2085. }.bind(this);
  2086. this._unbindCloseDropdownIfClickedOutside = function () {
  2087. if (DBG) console.log("P5UI__Bocian__ExportFieldSelectOverlay::_unbindCloseDropdownIfClickedOutside", this._closeDropdownIfClickedOutside)
  2088. if (!document.removeEventListener && document.detachEvent) {
  2089. document.detachEvent('onclick', this._closeDropdownIfClickedOutside);
  2090. } else {
  2091. document.removeEventListener('click', this._closeDropdownIfClickedOutside);
  2092. }
  2093. }.bind(this);
  2094. },
  2095. componentDidMount: function () {
  2096. this._bindCloseDropdownIfClickedOutside();
  2097. },
  2098. renderExportField: function (field) {
  2099. // <li><input checked="" type="checkbox" title="ID" value="ID">&nbsp;Nr</li>
  2100. var self = this;
  2101. var fieldName = field.name;
  2102. var label = field.label;
  2103. var isChecked = this.props.exportFieldsStore.state.selected.has(fieldName);
  2104. return h('li', {}, [
  2105. h('label', { style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
  2106. h('input', {
  2107. checked: isChecked,
  2108. type: "checkbox",
  2109. title: fieldName,
  2110. value: fieldName,
  2111. onChange: function () {
  2112. self.handleChange(fieldName);
  2113. }
  2114. }),
  2115. " ",
  2116. label.replace(/_/g, ' ')
  2117. ])
  2118. ]);
  2119. },
  2120. handleExportToHTML: function (event) {
  2121. event.preventDefault();
  2122. this.openExportWindow('html');
  2123. },
  2124. handleExportToCSV: function (event) {
  2125. event.preventDefault();
  2126. this.openExportWindow('csv');
  2127. },
  2128. handleExportToLatin2CSV: function (event) {
  2129. event.preventDefault();
  2130. this.openExportWindow('csv_cp1250');
  2131. },
  2132. handleExportToXLS: function (event) {
  2133. event.preventDefault();
  2134. this.openExportWindow('xls');
  2135. },
  2136. handleExportToXLSX: function (event) {
  2137. event.preventDefault();
  2138. this.openExportWindow('xlsx');
  2139. },
  2140. openExportWindow: function (format) {
  2141. var selected = this.props.exportFieldsStore.state.selected;
  2142. DBG && console.log('DBG:P5UI__Bocian__ExportFieldSelectOverlay:openExportWindow', { format: format, selected: selected })
  2143. var exportUrl = [ 'index.php?_route=ViewTableAjax&_task=export&namespace=' + this.props.namespace,
  2144. 'format=' + format,
  2145. 'flds=' + Array.from(selected).join(','),
  2146. 'sortCol=' + (this.props.sortCol || ''),
  2147. 'sortDir=' + (this.props.sortDir ? "desc" : "asc"),
  2148. this.props.queryFilter
  2149. ].join('&');
  2150. var win = window.open(exportUrl, '_blank');
  2151. win.focus();
  2152. },
  2153. // if (!exportFields.length) {
  2154. // alert('Nie wybrano żadnych pól do eksportu.');
  2155. // e.preventDefault();
  2156. // return false;
  2157. // }
  2158. // var limit = 10000;
  2159. // if (!_data.total || _data.total <= 0) {
  2160. // alert('Brak rekordów do eksportu.');
  2161. // e.preventDefault();
  2162. // return false;
  2163. // }
  2164. // if (_data.total > limit) {
  2165. // if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  2166. // e.preventDefault();
  2167. // return false;
  2168. // }
  2169. // }
  2170. renderExportToHTML: function () {
  2171. return h('li', {}, [
  2172. h('a', { href: "#", onClick: this.handleExportToHTML, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
  2173. h('i', { className: "glyphicon glyphicon-share" }),
  2174. " Export do HTML"
  2175. ])
  2176. ]);
  2177. },
  2178. renderExportToCSV: function () {
  2179. return h('li', {}, [
  2180. h('a', { href: "#", onClick: this.handleExportToCSV, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
  2181. h('i', { className: "glyphicon glyphicon-share" }),
  2182. " Export do CSV"
  2183. ])
  2184. ]);
  2185. },
  2186. renderExportToLatin2CSV: function () {
  2187. return h('li', {}, [
  2188. h('a', {
  2189. href: "#", onClick: this.handleExportToLatin2CSV,
  2190. style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" },
  2191. title: "Export do pliku CSV w kodowaniu Windows-1250",
  2192. }, [
  2193. h('i', { className: "glyphicon glyphicon-share" }),
  2194. " Export do CSV (Windows-1250)"
  2195. ])
  2196. ]);
  2197. },
  2198. renderExportToXLS: function () {
  2199. return h('li', {}, [
  2200. h('a', { href: "#", onClick: this.handleExportToXLS, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
  2201. h('i', { className: "glyphicon glyphicon-share" }),
  2202. " Export do XLS"
  2203. ])
  2204. ]);
  2205. },
  2206. renderExportToXLSX: function () {
  2207. return h('li', {}, [
  2208. h('a', { href: "#", onClick: this.handleExportToXLSX, style: { 'font-size': "small", 'font-weight': "normal", 'margin-bottom': "0" } }, [
  2209. h('i', { className: "glyphicon glyphicon-share" }),
  2210. " Export do XLSX"
  2211. ])
  2212. ]);
  2213. },
  2214. render: function () {
  2215. if (!this.props.exportFields) console.warn('DBG: missing this.props.exportFields', { 'this.props': this.props });
  2216. if (!this.props.exportFields) return null;
  2217. return h('ul', {
  2218. ref: this.setRef,
  2219. className: "dropdown-menu",
  2220. style: {
  2221. height: "250px",
  2222. 'min-width': "300px",
  2223. 'padding': "5px 20px 5px 8px",
  2224. overflow: "auto",
  2225. display: "block",
  2226. position: "absolute",
  2227. left: this.props.offsetLeft,
  2228. top: this.props.offsetTop - 250,
  2229. margin: 0,
  2230. // height: 250px;
  2231. // this.props.btnBBox
  2232. },
  2233. }, this.props.exportFields.map(this.renderExportField).concat([
  2234. this.renderExportToHTML(),
  2235. this.renderExportToCSV(),
  2236. this.renderExportToLatin2CSV(),
  2237. this.renderExportToXLS(),
  2238. this.renderExportToXLSX(),
  2239. ]));
  2240. }
  2241. });
  2242. var _Containers__ExportFields = {}; // namespace => Unstated Container
  2243. var _Containers__get = function (namespace, initialSelected) {
  2244. if (_Containers__ExportFields[namespace]) return _Containers__ExportFields[namespace];
  2245. var selected = new Set();
  2246. if (initialSelected) initialSelected.forEach(function (field) {
  2247. selected.add(field.name);
  2248. })
  2249. _Containers__ExportFields[namespace] = global.p5VendorJs.createUnstatedContainer({
  2250. state: {
  2251. namespace: namespace,
  2252. selected: selected,
  2253. },
  2254. toggleField(fieldName) {
  2255. var selected = this.state.selected;
  2256. selected.has(fieldName) ? selected.delete(fieldName) : selected.add(fieldName)
  2257. this.setState({ selected: selected });
  2258. },
  2259. selectField(fieldName) {
  2260. var selected = this.state.selected;
  2261. selected.add(fieldName)
  2262. this.setState({ selected: selected });
  2263. },
  2264. unselectField(fieldName) {
  2265. var selected = this.state.selected;
  2266. selected.delete(fieldName)
  2267. this.setState({ selected: selected });
  2268. },
  2269. });
  2270. // namespace = 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY';
  2271. // namespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI';
  2272. return _Containers__ExportFields[namespace];
  2273. }
  2274. var P5UI__Bocian__ExportTable = createReactClass({ // @props: { namespace, exportFields }
  2275. _node: null,
  2276. getInitialState: function () {
  2277. return {
  2278. isOpen: false,
  2279. };
  2280. },
  2281. handleToggleDropdown: function (event) {
  2282. var offsetLeft = 0;
  2283. var offsetTop = 0;
  2284. this.removePopup();
  2285. if (!this.state.isOpen) {
  2286. var btnBBox = ("BUTTON" !== event.target.nodeName) ? event.target.parentNode.getBoundingClientRect() : event.target.getBoundingClientRect();
  2287. offsetLeft = btnBBox.left;
  2288. offsetTop = window.pageYOffset + btnBBox.y;
  2289. this._node = document.createElement('div');
  2290. this._node.setAttribute('data-p5class', "P5UI__Bocian__ExportTable");
  2291. this._node.position = "absolute";
  2292. this._node.left = "0";
  2293. this._node.top = "0";
  2294. this._node.height = "100%";
  2295. this._node.backgroundColor = "#00000050";
  2296. this._node.width = "100%";
  2297. var handleClose = this.handleClose.bind(this);
  2298. var exportFields = this.props.exportFields;
  2299. var exportFieldsContainer = _Containers__get(this.props.namespace, this.props.exportFields);
  2300. document.body.appendChild(this._node);
  2301. var self__props = this.props;
  2302. ReactDOM.render(
  2303. h(Unstated.Provider, {}, [
  2304. h(Unstated.Subscribe, { to: [ exportFieldsContainer ] },
  2305. function (exportFieldsCont) {
  2306. DBG && console.log('DBG:exportFieldsCont', { exportFieldsCont })
  2307. return h(P5UI__Bocian__ExportFieldSelectOverlay, Object.assign({}, self__props, {
  2308. exportFields: exportFields,
  2309. btnBBox: btnBBox,
  2310. exportFieldsStore: exportFieldsCont,
  2311. handleToggle: exportFieldsCont.toggleField.bind(exportFieldsCont),
  2312. handleClose: handleClose,
  2313. offsetLeft: offsetLeft,
  2314. offsetTop: offsetTop,
  2315. }));
  2316. }
  2317. )
  2318. ]),
  2319. this._node
  2320. );
  2321. }
  2322. this.setState({ isOpen: !this.state.isOpen });
  2323. },
  2324. removePopup: function () {
  2325. if (this._node && 1 === this._node.nodeType) {
  2326. document.body.removeChild(this._node);
  2327. }
  2328. this._node = null;
  2329. },
  2330. handleClose: function () {
  2331. this.removePopup();
  2332. this.setState({ isOpen: false });
  2333. },
  2334. render: function () {
  2335. // Pagination.code += '<div class="btn-group dropup pagesize" style="margin-left:40px">' +
  2336. // <button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;<span class="caret"></span></button>
  2337. // <ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">
  2338. // <li><input checked="" type="checkbox" title="ID" value="ID">&nbsp;Nr</li>
  2339. // <li><input checked="" type="checkbox" title="A_STATUS" value="A_STATUS">&nbsp;Status</li>
  2340. // ...
  2341. // <li><input checked="" type="checkbox" title="TV_DVBC_EPG_CHANNEL_NUMBER" value="TV_DVBC_EPG_CHANNEL_NUMBER">&nbsp;TV: Nr kanału w EPG</li>
  2342. // <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a></li>
  2343. // <li><a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a></li>
  2344. // <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>
  2345. // </ul></div>';
  2346. return h('div', {
  2347. className: "btn-group", // className: "btn-group dropup pagesize" + " open",
  2348. }, [
  2349. h('button', {
  2350. className: "btn btn-sm btn-default", // className: "btn btn-sm btn-default dropdown-toggle", // 'data-toggle': "dropdown",
  2351. onClick: this.handleToggleDropdown
  2352. }, [
  2353. "Export ",
  2354. h('span', { className: "caret" }),
  2355. ]),
  2356. // h('ul', {
  2357. // className: "dropdown-menu",
  2358. // style: {
  2359. // 'max-height': "250px",
  2360. // 'min-width': "300px",
  2361. // 'padding': "5px 20px 5px 8px",
  2362. // overflow: "auto",
  2363. // }
  2364. // }, this.props.exportFields.map(this.renderExportField))
  2365. ]);
  2366. // @from TableAjax:
  2367. // if (priv.options.exportFields && priv.options.exportFields.length) {
  2368. // node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  2369. // var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  2370. // var span = $('<span class="caret"></span>').appendTo(btn);
  2371. // var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
  2372. // $.each(_data.cols, function (col, props) {
  2373. // if (-1 !== priv.options.exportFields.indexOf(col)) {
  2374. // var li = $('<li></li>').appendTo(ul);
  2375. // $(p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>', [(_exportFieldsSelect[col]) ? 'checked' : '', col, props.friendly || col])).appendTo(li);
  2376. // li.on('click', 'input', priv.exportFieldChanged);
  2377. // }
  2378. // });
  2379. // var li = $('<li></li>').appendTo(ul);
  2380. // $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  2381. // li.on('click', 'a', priv.exportToHTML);
  2382. // var li = $('<li></li>').appendTo(ul);
  2383. // $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  2384. // li.on('click', 'a', priv.exportToCSV);
  2385. // var li = $('<li></li>').appendTo(ul);
  2386. // $('<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);
  2387. // li.on('click', 'a', priv.exportToCSVWinCP1250);
  2388. // } else {
  2389. // node = $('<span class="' + nodeClass + '"></span>');
  2390. // }
  2391. }
  2392. });
  2393. // Pagination
  2394. var Pagination = {
  2395. code: '', // end show html paginations
  2396. clickPage: 1, // set default 1 page
  2397. // --------------------
  2398. // Utility
  2399. // --------------------
  2400. // initialize default data
  2401. Extend: function(data) {
  2402. data = data || {};
  2403. Pagination.url = data.url;
  2404. Pagination.id_pagination = data.id_pagination;
  2405. Pagination.type = data.type;
  2406. Pagination.limit = data.limit;
  2407. Pagination.total_items = data.total_items;
  2408. Pagination.size = data.size || 2;
  2409. Pagination.page = data.page || 1;
  2410. Pagination.step = data.step || 3;
  2411. },
  2412. // add pages by number (from [s] to [f])
  2413. Add: function(s, f) {
  2414. for (var i = s; i < f; i++) {
  2415. Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">' + i + '</a></li>';
  2416. }
  2417. },
  2418. // add last page with separator
  2419. Last: function() {
  2420. Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">>></a></li>';
  2421. },
  2422. // add first page with separator
  2423. First: function() {
  2424. Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default"><<</a></li>';
  2425. },
  2426. // add last page with separator
  2427. Next: function() {
  2428. Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default">></a></li>';
  2429. },
  2430. // add first page with separator
  2431. Prev: function() {
  2432. Pagination.code += '<li><a href="' + Pagination.url + '" class="btn btn-default"><</a></li>';
  2433. },
  2434. // --------------------
  2435. // Handlers
  2436. // --------------------
  2437. // change page
  2438. Click: function() {
  2439. clearSelectedCheckbox();
  2440. var selectPage = $("#pagination-"+Pagination.type.toLowerCase()+' .tblAjax__footer__toolbar__pagination').find('a.active').text();
  2441. Pagination.clickPage = +this.innerHTML || '';
  2442. if ( selectPage === NaN || selectPage > Pagination.size) { selectPage = 1; }
  2443. switch (this.innerHTML) {
  2444. case '&gt;&gt;': // last
  2445. Pagination.clickPage = Pagination.size;
  2446. break;
  2447. case '&lt;&lt;': // first
  2448. Pagination.clickPage = 1;
  2449. break;
  2450. case '&lt;': // prev
  2451. Pagination.clickPage = parseInt(selectPage) - 1;
  2452. if (Pagination.clickPage < 1) {
  2453. Pagination.clickPage = 1;
  2454. }
  2455. break;
  2456. case '&gt;': // next
  2457. Pagination.clickPage = parseInt(selectPage) + 1;
  2458. if (Pagination.clickPage > Pagination.size) {
  2459. Pagination.clickPage = Pagination.size;
  2460. }
  2461. break;
  2462. }
  2463. if ( Pagination.type === 'KONTRAHENCI' ) {
  2464. setItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page', Pagination.clickPage);
  2465. Pagination.page = urlFetchKontrahenci(Pagination.clickPage);
  2466. }
  2467. else if ( Pagination.type === 'PRACOWNICY' ){
  2468. setItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page', Pagination.clickPage);
  2469. Pagination.page = urlFetchPracownicy(Pagination.clickPage);
  2470. }
  2471. Pagination.Start();
  2472. },
  2473. // --------------------
  2474. // Script structure pagination
  2475. // --------------------
  2476. // binding pages
  2477. Bind: function() {
  2478. var a = Pagination.e.getElementsByTagName('a');
  2479. // var currentPage = Pagination.clickPage || 1;
  2480. for (var i = 0; i < a.length; i++) {
  2481. if (+a[i].innerHTML === Pagination.page) a[i].className = 'btn btn-default active';
  2482. a[i].addEventListener('click', Pagination.Click, false);
  2483. }
  2484. },
  2485. ExportWidget: function() {
  2486. var exportWidgetId = 'p5__exportWidget__' + Pagination.type;
  2487. Pagination.code += '<div id="' + exportWidgetId + '" class="btn-group dropup pagesize" style="margin-left:40px"></div>';
  2488. },
  2489. getSearchQueryFilter: function () { // @return url query filter by namespace
  2490. switch (Pagination.type) {
  2491. case 'PRACOWNICY': {
  2492. var searchParams = getSearchParamsPracownicy();
  2493. return [
  2494. searchParams.filterFields,
  2495. (searchParams.filterIdGroup) ? 'filterIdGroup=' + searchParams.filterIdGroup : null, // TODO: backRef search
  2496. ].filter(Boolean).join('&')
  2497. }
  2498. case 'KONTRAHENCI': {
  2499. var searchParams = getSearchParamsKontrahenci();
  2500. return [
  2501. searchParams.filterFields,
  2502. (searchParams.filterIdGroup) ? 'filterIdGroup=' + searchParams.filterIdGroup : null, // TODO: backRef search
  2503. ].filter(Boolean).join('&')
  2504. }
  2505. default: return '';
  2506. }
  2507. },
  2508. CreateExportWidget: function() {
  2509. var exportFields = null;
  2510. var namespace = '';
  2511. if (Pagination.type === 'PRACOWNICY') {
  2512. exportFields = EXPORT_FIELDS_OD;
  2513. namespace = 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY';
  2514. } else if (Pagination.type === 'KONTRAHENCI') {
  2515. exportFields = EXPORT_FIELDS_DO;
  2516. namespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI';
  2517. }
  2518. DBG && console.log('DBG:EXPORT_FIELDS...', { EXPORT_FIELDS_OD, EXPORT_FIELDS_DO, exportFields });
  2519. if (!exportFields || (exportFields && !exportFields.length)) return;
  2520. var exportWidgetId = 'p5__exportWidget__' + Pagination.type;
  2521. var node = document.getElementById(exportWidgetId);
  2522. DBG && console.log('node: ', { node });
  2523. if (!node) return;
  2524. var sortCol = 'ID';
  2525. var sortDir = 'desc';
  2526. var queryFilter = Pagination.getSearchQueryFilter();
  2527. ReactDOM.render(
  2528. h(P5UI__Bocian__ExportTable, {
  2529. namespace: namespace,
  2530. exportFields: exportFields,
  2531. sortCol: sortCol,
  2532. sortDir: sortDir,
  2533. queryFilter: queryFilter,
  2534. }),
  2535. node
  2536. );
  2537. },
  2538. Finish: function() {
  2539. Pagination.e.innerHTML = Pagination.code;
  2540. Pagination.Bind();
  2541. Pagination.CreateExportWidget();
  2542. },
  2543. // find pagination type
  2544. Start: function() {
  2545. Pagination.code = '';
  2546. if ( Pagination.type === 'KONTRAHENCI' ) {
  2547. 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>';
  2548. } else if ( Pagination.type === 'PRACOWNICY' ) {
  2549. 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>';
  2550. }
  2551. 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">';
  2552. Pagination.First();
  2553. Pagination.Prev();
  2554. if ( Pagination.type === 'KONTRAHENCI' ) {
  2555. Pagination.page = getItemLocalStorage('Bocian.biAuditForm.kontrahenci.pagination.page') || 1;
  2556. }
  2557. else if ( Pagination.type === 'PRACOWNICY' ) {
  2558. Pagination.page = getItemLocalStorage('Bocian.biAuditForm.pracownicy.pagination.page') || 1;
  2559. }
  2560. if ( Pagination.page > Pagination.size ) {
  2561. Pagination.page = 1;
  2562. }
  2563. if (Pagination.size < Pagination.step * 2 + 6) {
  2564. Pagination.Add(1, Pagination.size + 1);
  2565. }
  2566. else if (Pagination.page < Pagination.step * 2 + 1) {
  2567. Pagination.Add(1, Pagination.step * 2 + 4);
  2568. }
  2569. else if (Pagination.page > Pagination.size - Pagination.step * 2) {
  2570. Pagination.Add(Pagination.size - Pagination.step * 2 - 2, Pagination.size + 1);
  2571. }
  2572. else {
  2573. Pagination.Add(Pagination.page - Pagination.step, Pagination.page + Pagination.step + 1);
  2574. }
  2575. Pagination.Next();
  2576. Pagination.Last();
  2577. Pagination.code += '</ul></nav>';
  2578. Pagination.ExportWidget();
  2579. Pagination.Finish();
  2580. },
  2581. // --------------------
  2582. // Initialization
  2583. // --------------------
  2584. // binding buttons
  2585. Buttons: function(e) {
  2586. var nav = e.getElementsByTagName('a');
  2587. },
  2588. // create skeleton
  2589. Create: function(element) {
  2590. var html = [
  2591. '<div></div>' // pagination container
  2592. ];
  2593. element.innerHTML = html.join('');
  2594. Pagination.e = element.getElementsByTagName('div')[0];
  2595. Pagination.Buttons(element);
  2596. },
  2597. // init
  2598. Init: function(element, options) {
  2599. Pagination.Extend(options);
  2600. Pagination.Create(element);
  2601. Pagination.Start();
  2602. }
  2603. };
  2604. function todo__fetchRaport(id) {
  2605. /* p5WFS_GetFeature('default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', {
  2606. primaryKey: id,
  2607. resolve: 'all',
  2608. resolveDepth: 3,
  2609. }).then(function (features) {
  2610. if(DBG) console.log('features', features)
  2611. }).catch(function (e) {
  2612. if(DBG) console.warn(e)
  2613. p5UI__notifyAjaxCallback({ type: 'error', msg: e })
  2614. })*/
  2615. }
  2616. function removeFiltersPracownicy(event, btnNode) {
  2617. event.preventDefault()
  2618. var fieldNameList = FIELD_LIST_PRACOWNICY
  2619. fieldNameList.forEach(function (fieldName) {
  2620. btnNode.form[fieldName].value = ''
  2621. })
  2622. urlFetchPracownicy(1)
  2623. }
  2624. function removeFiltersKontrahenci(event, btnNode) {
  2625. event.preventDefault()
  2626. var fieldNameList = FIELD_LIST_KONTRAHENCI
  2627. fieldNameList.forEach(function (fieldName) {
  2628. btnNode.form[fieldName].value = ''
  2629. })
  2630. urlFetchKontrahenci(1)
  2631. }
  2632. function onChangeFiltersPracownicy(event, inputNode) {
  2633. urlFetchPracownicy(1)
  2634. }
  2635. function onKeypressFiltersPracownicy(event, inputNode) {
  2636. if ("Enter" === event.key) {
  2637. event.stopPropagation()
  2638. event.preventDefault()
  2639. urlFetchPracownicy(1)
  2640. return false
  2641. }
  2642. }
  2643. function onChangeFiltersKontrahenci(event, inputNode) {
  2644. urlFetchKontrahenci(1)
  2645. }
  2646. function onKeypressFiltersKontrahenci(event, inputNode) {
  2647. if ("Enter" === event.key) {
  2648. event.stopPropagation()
  2649. event.preventDefault()
  2650. urlFetchKontrahenci(1)
  2651. return false
  2652. }
  2653. }
  2654. function loadMoreRecordFunctions(event, node, rowPK, namespace) {
  2655. var _node = node
  2656. var _rowPK = rowPK
  2657. var toShow = true
  2658. if (RECORD_MORE_FUNCTIONS_OPENED_NODE) {
  2659. if (RECORD_MORE_FUNCTIONS_OPENED_NODE === node) toShow = false
  2660. if (RECORD_MORE_FUNCTIONS_OPENED_NODE !== node) {
  2661. jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
  2662. }
  2663. }
  2664. RECORD_MORE_FUNCTIONS_OPENED_NODE = node
  2665. // jQuery(node).popover({
  2666. // container: 'body',
  2667. // placement: 'right',
  2668. // trigger: 'click',
  2669. // template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
  2670. // '<div class="arrow"></div>' +
  2671. // '<div style="display:block;position:relative;">' +
  2672. // '<div class="popover-title">' +
  2673. // '</div>' +
  2674. // '<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">&times;</button>' +
  2675. // '</div>' +
  2676. // '<div class="popover-content"></div>' +
  2677. // '</div>' +
  2678. // '',
  2679. // html: true,
  2680. // })
  2681. // jQuery(node).popover('show')
  2682. global.fetch(BASE_URLS + 'index.php?_route=ViewTableAjax&namespace=' + namespace + '&_task=moreFunctionsCellAjax&ID=' + rowPK, {
  2683. credentials: 'same-origin'
  2684. }).then(function (response) {
  2685. return response.json()
  2686. }).then(function (json) {
  2687. var funcListWrap = $('<div></div>')
  2688. var funcListNode = $('<ul class="list-unstyled popoverRowFunctions"></ul>').appendTo(funcListWrap)
  2689. if (_node === RECORD_MORE_FUNCTIONS_OPENED_NODE) {
  2690. if (json && 'success' === json.type && json.rowFunctions && json.rowFunctions.length > 0) {
  2691. json.rowFunctions.forEach(function(funObj) {
  2692. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, _rowPK, {ico: true, label: true});
  2693. var funcItemNode = jQuery('<li></li>')
  2694. funcItemNode.append(funcNode)
  2695. funcListNode.append(funcItemNode)
  2696. });
  2697. }
  2698. }
  2699. // jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
  2700. jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover({
  2701. container: 'body',
  2702. placement: 'right',
  2703. trigger: 'click',
  2704. template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
  2705. '<div class="arrow"></div>' +
  2706. '<div style="display:block;position:relative;">' +
  2707. '<div class="popover-title">' +
  2708. '</div>' +
  2709. '<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">&times;</button>' +
  2710. '</div>' +
  2711. '<div class="popover-content"></div>' +
  2712. '</div>' +
  2713. '',
  2714. html: true,
  2715. content: funcListWrap.html(),
  2716. })
  2717. jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('show')
  2718. }).catch(function (err) {
  2719. if(DBG) console.log('err', err);
  2720. })
  2721. }
  2722. var p5UI_TableAjax_generateFunctionNode = function(funObj, rowPK, props) {
  2723. var defaultsProps = {
  2724. ico: true,
  2725. label: false
  2726. },
  2727. props = jQuery.extend({}, defaultsProps, props);
  2728. funcNode = $('<a href="#" style="margin:0 2px;"></a>')
  2729. ;
  2730. if ('href' in funObj) funcNode.attr('href', p5Utils__format(funObj.href, [rowPK]));
  2731. if (props.ico) {
  2732. if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
  2733. }
  2734. if ('onclick' in funObj) funcNode.attr('onclick', p5Utils__format(funObj.onclick, [rowPK]));
  2735. if ('title' in funObj) funcNode.attr('title', funObj.title);
  2736. if ('target' in funObj) funcNode.attr('target', funObj.target);
  2737. if (props.label) {
  2738. if ('label' in funObj) {
  2739. funcNode.append(' ' + funObj.label);
  2740. } else if ('title' in funObj) {
  2741. funcNode.append(' ' + funObj.title);
  2742. }
  2743. }
  2744. return funcNode;
  2745. };
  2746. global.p5UI_TableAjax_generateFunctionNode = p5UI_TableAjax_generateFunctionNode
  2747. function addAllMatchesToReport(event) {
  2748. switch (event.data.type) {
  2749. case 'kontrahenci': break; // OK
  2750. case 'pracownicy': break; // OK
  2751. default: throw "Wrong type";
  2752. }
  2753. var postData = {}
  2754. if ('filter_idGroup' in event.data.pagination && event.data.pagination['filter_idGroup']) postData['filter_idGroup'] = event.data.pagination['filter_idGroup']
  2755. Object.keys(event.data.pagination).filter(function (key) {
  2756. return ('f_' === key.substr(0, 2))
  2757. }).forEach(function (filterKey) {
  2758. var value = event.data.pagination[filterKey]
  2759. postData[filterKey] = value
  2760. })
  2761. var thisButton = $(this)
  2762. thisButton.attr('disabled', true)
  2763. thisButton.text( thisButton.text() + '...' )
  2764. if ('pracownicy' === event.data.type) {
  2765. p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie pracowników..." })
  2766. var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
  2767. var fieldNameList = FIELD_LIST_PRACOWNICY
  2768. fieldNameList.filter(function (fieldName) {
  2769. if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
  2770. return (frm[fieldName]) ? true : false
  2771. }).map(function (fieldName) {
  2772. return [ fieldName, frm[fieldName].value ]
  2773. }).filter(function (filter) {
  2774. return ( filter[1].length > 0 )
  2775. }).forEach(function (filter) {
  2776. postData[ filter[0] ] = filter[1];
  2777. })
  2778. global.fetch(URL_FETCH_PRACOWNICY_IDS_AJAX, {
  2779. credentials: 'same-origin',
  2780. method: 'POST',
  2781. headers: { 'Content-Type': 'application/json' },
  2782. body: JSON.stringify(postData)
  2783. })
  2784. .then(function __parseJSON(response) {
  2785. return response.json()
  2786. })
  2787. .then(function (json) {
  2788. if ('success' === json.type && json.body && json.body.ids) {
  2789. updateListIdBiAuditReaport('PRACOWNICY', json.body.ids.map(function (id) {
  2790. return parseInt(id)
  2791. }))
  2792. // jQuery('#body-pracownicy').find('input[name="prID[]"]').attr('checked', true)
  2793. jQuery('#body-pracownicy').find('input[name="prID[]"]').each(function (idx, inputNode) {
  2794. inputNode.checked = true;
  2795. })
  2796. thisButton.attr('disabled', false)
  2797. var txt = thisButton.text()
  2798. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2799. updateCountItemCheckedByType('pracownicy');
  2800. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" pracowników" })
  2801. }
  2802. })
  2803. .catch(function (e) {
  2804. p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
  2805. thisButton.attr('disabled', false)
  2806. var txt = thisButton.text()
  2807. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2808. })
  2809. }
  2810. if ('kontrahenci' === event.data.type) {
  2811. p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie podmiotów/kontrahentów..." })
  2812. var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
  2813. var fieldNameList = FIELD_LIST_KONTRAHENCI
  2814. fieldNameList.filter(function (fieldName) {
  2815. if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
  2816. return (frm[fieldName]) ? true : false
  2817. }).map(function (fieldName) {
  2818. return [ fieldName, frm[fieldName].value ]
  2819. }).filter(function (filter) {
  2820. return ( filter[1].length > 0 )
  2821. }).forEach(function (filter) {
  2822. postData[ filter[0] ] = filter[1];
  2823. })
  2824. global.fetch(URL_FETCH_KONTRAHENCI_IDS_AJAX, {
  2825. credentials: 'same-origin',
  2826. method: 'POST',
  2827. headers: { 'Content-Type': 'application/json' },
  2828. body: JSON.stringify(postData)
  2829. })
  2830. .then(function __parseJSON(response) {
  2831. return response.json()
  2832. })
  2833. .then(function (json) {
  2834. if ('success' === json.type && json.body && json.body.ids) {
  2835. updateListIdBiAuditReaport('KONTRAHENCI', json.body.ids.map(function (id) {
  2836. return parseInt(id)
  2837. }))
  2838. // jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').attr('checked', true); // Not working
  2839. jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').each(function (idx, inputNode) {
  2840. inputNode.checked = true;
  2841. })
  2842. thisButton.attr('disabled', false);
  2843. var txt = thisButton.text()
  2844. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2845. updateCountItemCheckedByType('kontrahenci');
  2846. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" kontrahentów" })
  2847. }
  2848. })
  2849. .catch(function (e) {
  2850. p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
  2851. thisButton.attr('disabled', false)
  2852. var txt = thisButton.text()
  2853. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2854. });
  2855. }
  2856. }
  2857. function mock_error__fetchLastReports(id) {
  2858. return new Promise(function (resolve) {
  2859. throw "Wystąpił błąd, spróbuj ponownie później"
  2860. })
  2861. }
  2862. function mock__fetchLastReports(id) {
  2863. return new Promise(function (resolve) {
  2864. 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"}]}}';
  2865. var json = JSON.parse(fakeResponse);
  2866. var items = json.body.items;
  2867. console.log('items', items)
  2868. setTimeout(function () {
  2869. console.log('resolve items', items)
  2870. resolve(items);
  2871. }, 500);
  2872. });
  2873. }
  2874. function fetchLastReports(id) {
  2875. return global.fetch(URL_FETCH_LAST_REPORTS_AJAX, {
  2876. credentials: 'same-origin',
  2877. method: 'POST',
  2878. headers: { 'Content-Type': 'application/json' },
  2879. body: JSON.stringify({ id: id })
  2880. })
  2881. .then(function __parseJSON(response) {
  2882. return response.json()
  2883. })
  2884. .then(function (json) {
  2885. if ('success' === json.type && json.body && json.body.items) {
  2886. if (!json.body.items.length) throw "Brak danych"
  2887. return json.body.items;
  2888. }
  2889. throw "Wystąpił błąd, spróbuj ponownie później.";
  2890. })
  2891. }
  2892. function fetchPracownicyIdsByReport(id) {
  2893. return global.fetch(URL_FETCH_PRACOWNICY_IDS_BY_REPORT_AJAX, {
  2894. credentials: 'same-origin',
  2895. method: 'POST',
  2896. headers: { 'Content-Type': 'application/json' },
  2897. body: JSON.stringify({ id: id })
  2898. })
  2899. .then(function __parseJSON(response) {
  2900. return response.json()
  2901. })
  2902. .then(function (json) {
  2903. if ('success' === json.type && json.body && json.body.ids) {
  2904. if (!json.body.ids.length) throw "Brak danych"
  2905. return json.body.ids;
  2906. }
  2907. throw "Wystąpił błąd, spróbuj ponownie później.";
  2908. })
  2909. }
  2910. function fetchKontrahenciIdsByReport(id) {
  2911. return global.fetch(URL_FETCH_KONTRAHENCI_IDS_BY_REPORT_AJAX, {
  2912. credentials: 'same-origin',
  2913. method: 'POST',
  2914. headers: { 'Content-Type': 'application/json' },
  2915. body: JSON.stringify({ id: id })
  2916. })
  2917. .then(function __parseJSON(response) {
  2918. return response.json()
  2919. })
  2920. .then(function (json) {
  2921. if ('success' === json.type && json.body && json.body.ids) {
  2922. if (!json.body.ids.length) throw "Brak danych"
  2923. return json.body.ids;
  2924. }
  2925. throw "Wystąpił błąd, spróbuj ponownie później.";
  2926. })
  2927. }
  2928. function addToReportByPreviousReport(event) {
  2929. var pageType = (event.data.type) ? event.data.type : '';
  2930. handleAddToReportByPreviousReport(pageType);
  2931. }
  2932. function handleAddToReportByPreviousReport(pageType) {
  2933. switch (pageType) {
  2934. case 'pracownicy': break; // OK
  2935. case 'kontrahenci': break; // OK
  2936. default: throw "Wrong type";
  2937. }
  2938. var thisButton = $(this)
  2939. thisButton.attr('disabled', true)
  2940. thisButton.text( thisButton.text() + '...' )
  2941. function this__enableButton() {
  2942. thisButton.attr('disabled', false)
  2943. var txt = thisButton.text()
  2944. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2945. }
  2946. var lastReportOptions = new Promise(function (resolve) {
  2947. fetchLastReports() // TODO: TEST remote `mock__`
  2948. .then(function (items) {
  2949. var options = {};
  2950. items.forEach(function (item) {
  2951. var label = "Nr " + item.id + ": " + item.adnotacje + " ";
  2952. var total = 0;
  2953. switch (pageType) {
  2954. case 'pracownicy': total = parseInt(item.totalPracownicy); break;
  2955. case 'kontrahenci': total = parseInt(item.totalKontrahenci); break;
  2956. }
  2957. label += ( total > 0 ? "(" + total + ")" : "brak");
  2958. options['raport-'+item.id] = label;
  2959. });
  2960. resolve(options);
  2961. })
  2962. .catch(function (e) {
  2963. swal.showValidationError(''+e)
  2964. swal.hideLoading();
  2965. resolve();
  2966. })
  2967. });
  2968. swal({
  2969. title: "Dodaj " + ('pracownicy' === pageType ? "praconików" : "kontrahentów") + " do analizy",
  2970. showCancelButton: true,
  2971. cancelButtonText: "Anuluj",
  2972. showConfirmButton: true,
  2973. confirmButtonText: "Wybierz",
  2974. focusCancel: true,
  2975. width: 600,
  2976. input: 'select',
  2977. inputOptions: lastReportOptions,
  2978. inputClass: "form-control input-lg",
  2979. preConfirm: function (selected) {
  2980. var id = parseInt(selected.substr('raport-'.length));
  2981. swal.showLoading();
  2982. if ('pracownicy' === pageType) {
  2983. return new Promise(function (resolve) {
  2984. fetchPracownicyIdsByReport(id)
  2985. .then(function (ids) {
  2986. updateListIdBiAuditReaport('PRACOWNICY', ids.map(function (id) {
  2987. return parseInt(id)
  2988. }))
  2989. ids.forEach(function (id) {
  2990. jQuery('#body-pracownicy').find('input[name="prID[]"][value="'+id+'"]').each(function (idx, inputNode) {
  2991. inputNode.checked = true;
  2992. })
  2993. })
  2994. updateCountItemCheckedByType('pracownicy');
  2995. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" pracowników" })
  2996. resolve();
  2997. })
  2998. .catch(function (e) {
  2999. swal.showValidationError(''+e)
  3000. swal.hideLoading();
  3001. resolve();
  3002. });
  3003. });
  3004. } else if ('kontrahenci' === pageType) {
  3005. return new Promise(function (resolve) {
  3006. fetchKontrahenciIdsByReport(id)
  3007. .then(function (ids) {
  3008. updateListIdBiAuditReaport('KONTRAHENCI', ids.map(function (id) {
  3009. return parseInt(id)
  3010. }))
  3011. ids.forEach(function (id) {
  3012. jQuery('#body-kontrahenci').find('input[name="kontrID[]"][value="'+id+'"]').each(function (idx, inputNode) {
  3013. inputNode.checked = true;
  3014. })
  3015. })
  3016. updateCountItemCheckedByType('kontrahenci');
  3017. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" kontrahentów" })
  3018. resolve();
  3019. })
  3020. .catch(function (e) {
  3021. swal.showValidationError(''+e)
  3022. swal.hideLoading();
  3023. resolve();
  3024. });
  3025. });
  3026. } else return true;
  3027. },
  3028. // inputValidator: (value) => {
  3029. // return !value && 'Proszę wybrać raport'
  3030. // }
  3031. // html: '<p>Ostatnie raporty:</p>' + '<ul id="' + uniqHtmlId + '"></ul></p>',
  3032. }).then(function (selected) {
  3033. this__enableButton();
  3034. }).catch(function (e) {
  3035. this__enableButton();
  3036. })
  3037. }
  3038. $(document).ready(function(){
  3039. DBG && console.warn('DBG:: SET window[STORE_NAME]', { store: window[STORE_NAME], STORE_NAME: STORE_NAME, globalRaportStore })
  3040. ReactDOM.render(
  3041. h(P5UI__BocianHeader, {
  3042. store: globalRaportStore
  3043. }),
  3044. document.getElementById('bi_audit_header')
  3045. );
  3046. rootChangeForm();
  3047. updateTopCounters();
  3048. var unsubscribe = globalRaportStore.subscribe(function () {
  3049. // TODO: fetch data from globalRaportStore.getState()
  3050. // var defaultState = global[STORE_NAME + '__defaults']();
  3051. })
  3052. $(window).on('hashchange', function() {
  3053. DBG && console.warn("$(window).on('hashchange', ...")
  3054. rootChangeForm();
  3055. updateTopCounters();
  3056. hideMoreRecordFunctionsPopover()
  3057. });
  3058. });
  3059. global.hideMoreRecordFunctionsPopover = function() {
  3060. if (RECORD_MORE_FUNCTIONS_OPENED_NODE) jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
  3061. }
  3062. global.pracownicyLoadMoreRecordFunctions = function(event, node, rowPK) {
  3063. return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY")
  3064. }
  3065. global.kontrahenciLoadMoreRecordFunctions = function(event, node, rowPK) {
  3066. return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI")
  3067. }
  3068. global.removeFiltersPracownicy = removeFiltersPracownicy;
  3069. global.removeFiltersKontrahenci = removeFiltersKontrahenci;
  3070. global.onChangeFiltersPracownicy = onChangeFiltersPracownicy;
  3071. global.onKeypressFiltersPracownicy = onKeypressFiltersPracownicy;
  3072. global.onChangeFiltersKontrahenci = onChangeFiltersKontrahenci;
  3073. global.onKeypressFiltersKontrahenci = onKeypressFiltersKontrahenci;
  3074. global.checkAll = checkAll;
  3075. global.checkedChoiseItems = checkedChoiseItems;
  3076. global.catchEventCheckbox = catchEventCheckbox;
  3077. global.clearSelectedCheckbox = clearSelectedCheckbox;
  3078. global.getNameGroupById = getNameGroupById;
  3079. global.createGroupPracownicy = createGroupPracownicy;
  3080. global.createGroupKontrahenci = createGroupKontrahenci;
  3081. global.selectPage = selectPage;
  3082. global.detectChoiseFilter = detectChoiseFilter;
  3083. global.updateListIdBiAuditReaport = updateListIdBiAuditReaport;
  3084. global.deleteListIdBiAuditReaport = deleteListIdBiAuditReaport;
  3085. global.urlFetchPracownicy = urlFetchPracownicy;
  3086. global.urlFetchKontrahenci = urlFetchKontrahenci;
  3087. global.getAddressData = getAddressData;
  3088. global.Pagination = Pagination;
  3089. global.todo__fetchRaport = todo__fetchRaport;
  3090. global.setItemLocalStorage = setItemLocalStorage;
  3091. global.getItemLocalStorage = getItemLocalStorage;
  3092. global.deleteItemLocalStorage = deleteItemLocalStorage;
  3093. global.removeItemInArray = removeItemInArray;
  3094. global.removeItemArrayInArray = removeItemArrayInArray;
  3095. global.addPracownikToGroup = addPracownikToGroup;
  3096. global.addPracownikAllToGroup = addPracownikAllToGroup;
  3097. global.addKontrahenciToGroup = addKontrahenciToGroup;
  3098. global.addKontrahenciAllToGroup = addKontrahenciAllToGroup;
  3099. global.createPracownikAjax = createPracownikAjax;
  3100. global.createKontrahentAjax = createKontrahentAjax;
  3101. global.removePracownikFromGroup = removePracownikFromGroup;
  3102. global.removeKontrahenciFromGroup = removeKontrahenciFromGroup;
  3103. global.showViewUploadFile = showViewUploadFile;
  3104. global.parseCsvFile = parseCsvFile;
  3105. global.clearListLocalStorageByType = clearListLocalStorageByType;
  3106. // message
  3107. global.messageCriticalSearchData = 'Krytyczne wielkości danych do przeszukania. Optymalna wartość głębokość szukania powiaząń to: 6';