Bocian.php.view.js 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563
  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=ExportTableAjax&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. if (_node === RECORD_MORE_FUNCTIONS_OPENED_NODE) {
  2689. if (json && 'success' === json.type && json.rowFunctions && json.rowFunctions.length > 0) {
  2690. var popoverContent = generateViewMoreRecordFunctions(json.rowFunctions, namespace, _rowPK);
  2691. popoverContent.appendTo(funcListWrap);
  2692. }
  2693. }
  2694. // jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
  2695. jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover({
  2696. container: 'body',
  2697. placement: 'right',
  2698. trigger: 'click',
  2699. template: '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">' +
  2700. '<div class="arrow"></div>' +
  2701. '<div style="display:block;position:relative;">' +
  2702. '<div class="popover-title">' +
  2703. '</div>' +
  2704. '<button type="button" class="close" onclick="return hideMoreRecordFunctionsPopover();" style="position:absolute;right:8px;top:6px;">&times;</button>' +
  2705. '</div>' +
  2706. '<div class="popover-content"></div>' +
  2707. '</div>' +
  2708. '',
  2709. html: true,
  2710. content: funcListWrap.html(),
  2711. })
  2712. jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('show')
  2713. }).catch(function (err) {
  2714. if(DBG) console.log('err', err);
  2715. })
  2716. }
  2717. function generateViewMoreRecordFunctions(rowFunctions, namespace, rowPK) {
  2718. var popoverContent;
  2719. var funcNodesToUpdate = [];
  2720. if (!rowFunctions.length) {
  2721. popoverContent = $('<p class="text-muted">Brak dodatkowych funkcji</p>');
  2722. } else if (3 === namespace.split('/').length) { // if namesapce is AntAcl [ and has ref fields or back ref ]
  2723. popoverContent = $('<ul class="list-unstyled"></ul>');
  2724. var rowFunctionsByType = rowFunctions.reduce(function (ret, funObj) {
  2725. if (
  2726. 'Powiązania od ' === funObj.label.substr(0, 'Powiązania od '.length)
  2727. || 'Powiązania do ' === funObj.label.substr(0, 'Powiązania do '.length)
  2728. ) {
  2729. if (funObj.total > 0) {
  2730. ret.refConnections.push(funObj);
  2731. } else {
  2732. ret.refEmptyConnections.push(funObj);
  2733. }
  2734. } else {
  2735. ret.others.push(funObj);
  2736. }
  2737. return ret;
  2738. // href: "https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS/BI_audit_KRS&childRefNS=default_db/BI_audit_KRS/BI_audit_KRS&childRefPK=2068689"
  2739. // ico: "glyphicon glyphicon-random"
  2740. // label: "Powiązania od 'KRS' <span class="badge">0</span>"
  2741. // title: "Powiązania od 'Audyt / KRS' (0)"
  2742. }, { refConnections: [], refEmptyConnections: [], others: [] });
  2743. rowFunctionsByType.others.forEach(function (funObj) {
  2744. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true });
  2745. if (funObj.id) {
  2746. funcNodesToUpdate.push({ id: funObj.id, node: funcNode });
  2747. } else {
  2748. var funcItemNode = $('<li></li>').appendTo(popoverContent);
  2749. funcItemNode.append(funcNode);
  2750. }
  2751. });
  2752. if (!rowFunctionsByType.refConnections.length) {
  2753. $('<li>Brak powiązań</li>').appendTo(popoverContent);
  2754. } else {
  2755. var refConnItemNode = $('<li style="margin-top:10px"><i class="glyphicon glyphicon-random"></i> <b>Powiązania</b></li>').appendTo(popoverContent);
  2756. {
  2757. var funObj = {
  2758. // ico: 'glyphicon glyphicon-random',
  2759. label: 'przeglądaj',
  2760. title: "Przeglądaj powiązania",
  2761. href: 'index.php?_route=RefGraph&namespace=' + namespace + '&primaryKey=' + rowPK,
  2762. // onclick: function (e) { // TODO: open in
  2763. // console.log('TODO: przeglądaj powiązania')
  2764. // }
  2765. }
  2766. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true })
  2767. refConnItemNode.append(" - ");
  2768. refConnItemNode.append(funcNode);
  2769. }
  2770. var refConnFuncList = $('<ul class="list-unstyled" style="margin-left:20px"></ul>').appendTo(refConnItemNode);
  2771. rowFunctionsByType.refConnections.forEach(function (funObj) {
  2772. var refFunObj = Object.assign({}, funObj, {
  2773. // ico: null,
  2774. label: funObj.label.substr('Powiązania '.length),
  2775. });
  2776. var funcNode = p5UI_TableAjax_generateFunctionNode(refFunObj, rowPK, { ico: true, label: true });
  2777. var funcItemNode = $('<li></li>').appendTo(refConnFuncList);
  2778. funcItemNode.append(funcNode);
  2779. })
  2780. }
  2781. if (rowFunctionsByType.refEmptyConnections.length) {
  2782. var refConnItemNode = $('<li style="margin-top:10px; opacity:0.7"></li>').appendTo(popoverContent);
  2783. var emptyRefsDetailsNode = $('<details></details>').appendTo(refConnItemNode);
  2784. // $('<summary><i class="glyphicon glyphicon-random"></i> Pozostałe powiązania</summary>').appendTo(emptyRefsDetailsNode);
  2785. $('<summary style="cursor:pointer">Pozostałe powiązania ...</summary>').appendTo(emptyRefsDetailsNode);
  2786. var refConnFuncList = $('<ul class="list-unstyled" style="margin-left:20px"></ul>').appendTo(emptyRefsDetailsNode);
  2787. rowFunctionsByType.refEmptyConnections.forEach(function (funObj) {
  2788. var refFunObj = Object.assign({}, funObj, {
  2789. // ico: null,
  2790. label: funObj.label.substr('Powiązania '.length),
  2791. });
  2792. var funcNode = p5UI_TableAjax_generateFunctionNode(refFunObj, rowPK, { ico: true, label: true });
  2793. var funcItemNode = $('<li></li>').appendTo(refConnFuncList);
  2794. funcItemNode.append(funcNode);
  2795. })
  2796. }
  2797. } else {
  2798. popoverContent = $('<ul class="list-unstyled"></ul>');
  2799. rowFunctions.forEach(function (funObj) {
  2800. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true });
  2801. if (funObj.id) {
  2802. funcNodesToUpdate.push({ id: funObj.id, node: funcNode });
  2803. } else {
  2804. var funcItemNode = $('<li></li>').appendTo(popoverContent);
  2805. funcItemNode.append(funcNode);
  2806. }
  2807. });
  2808. }
  2809. return popoverContent;
  2810. }
  2811. function p5UI_TableAjax_generateFunctionNode(funObj, rowPK, props) {
  2812. if (!rowPK) throw "Missing primaryKey in p5UI_TableAjax_generateFunctionNode";
  2813. var defaultsProps = {
  2814. ico: true,
  2815. label: false
  2816. };
  2817. var props = jQuery.extend({}, defaultsProps, props);
  2818. var funcNode = $('<a href="#" style="margin:0 2px;"></a>');
  2819. if ('href' in funObj) funcNode.attr('href', p5Utils__format(funObj.href, [rowPK]));
  2820. if (props.ico) {
  2821. if ('ico' in funObj) funcNode.append('<span class="' + funObj.ico + '"></span>');
  2822. }
  2823. if ('onclick' in funObj) funcNode.attr('onclick', p5Utils__format(funObj.onclick, [rowPK]));
  2824. if ('title' in funObj) funcNode.attr('title', funObj.title);
  2825. if ('target' in funObj) funcNode.attr('target', funObj.target);
  2826. if (props.label) {
  2827. if ('label' in funObj) {
  2828. funcNode.append(' ' + funObj.label);
  2829. } else if ('title' in funObj) {
  2830. funcNode.append(' ' + funObj.title);
  2831. }
  2832. }
  2833. return funcNode;
  2834. };
  2835. global.p5UI_TableAjax_generateFunctionNode = p5UI_TableAjax_generateFunctionNode
  2836. function addAllMatchesToReport(event) {
  2837. switch (event.data.type) {
  2838. case 'kontrahenci': break; // OK
  2839. case 'pracownicy': break; // OK
  2840. default: throw "Wrong type";
  2841. }
  2842. var postData = {}
  2843. if ('filter_idGroup' in event.data.pagination && event.data.pagination['filter_idGroup']) postData['filter_idGroup'] = event.data.pagination['filter_idGroup']
  2844. Object.keys(event.data.pagination).filter(function (key) {
  2845. return ('f_' === key.substr(0, 2))
  2846. }).forEach(function (filterKey) {
  2847. var value = event.data.pagination[filterKey]
  2848. postData[filterKey] = value
  2849. })
  2850. var thisButton = $(this)
  2851. thisButton.attr('disabled', true)
  2852. thisButton.text( thisButton.text() + '...' )
  2853. if ('pracownicy' === event.data.type) {
  2854. p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie pracowników..." })
  2855. var frm = document.getElementById('filtersFieldRemoveBtn-PRACOWNICY').form
  2856. var fieldNameList = FIELD_LIST_PRACOWNICY
  2857. fieldNameList.filter(function (fieldName) {
  2858. if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
  2859. return (frm[fieldName]) ? true : false
  2860. }).map(function (fieldName) {
  2861. return [ fieldName, frm[fieldName].value ]
  2862. }).filter(function (filter) {
  2863. return ( filter[1].length > 0 )
  2864. }).forEach(function (filter) {
  2865. postData[ filter[0] ] = filter[1];
  2866. })
  2867. global.fetch(URL_FETCH_PRACOWNICY_IDS_AJAX, {
  2868. credentials: 'same-origin',
  2869. method: 'POST',
  2870. headers: { 'Content-Type': 'application/json' },
  2871. body: JSON.stringify(postData)
  2872. })
  2873. .then(function __parseJSON(response) {
  2874. return response.json()
  2875. })
  2876. .then(function (json) {
  2877. if ('success' === json.type && json.body && json.body.ids) {
  2878. updateListIdBiAuditReaport('PRACOWNICY', json.body.ids.map(function (id) {
  2879. return parseInt(id)
  2880. }))
  2881. // jQuery('#body-pracownicy').find('input[name="prID[]"]').attr('checked', true)
  2882. jQuery('#body-pracownicy').find('input[name="prID[]"]').each(function (idx, inputNode) {
  2883. inputNode.checked = true;
  2884. })
  2885. thisButton.attr('disabled', false)
  2886. var txt = thisButton.text()
  2887. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2888. updateCountItemCheckedByType('pracownicy');
  2889. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" pracowników" })
  2890. }
  2891. })
  2892. .catch(function (e) {
  2893. p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
  2894. thisButton.attr('disabled', false)
  2895. var txt = thisButton.text()
  2896. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2897. })
  2898. }
  2899. if ('kontrahenci' === event.data.type) {
  2900. p5UI__notifyAjaxCallback({ type: 'info', msg: "Pobieranie podmiotów/kontrahentów..." })
  2901. var frm = document.getElementById('filtersFieldRemoveBtn-KONTRAHENCI').form
  2902. var fieldNameList = FIELD_LIST_KONTRAHENCI
  2903. fieldNameList.filter(function (fieldName) {
  2904. if (!frm[fieldName] && DBG) console.log('Err missing field: "'+fieldName+'"')
  2905. return (frm[fieldName]) ? true : false
  2906. }).map(function (fieldName) {
  2907. return [ fieldName, frm[fieldName].value ]
  2908. }).filter(function (filter) {
  2909. return ( filter[1].length > 0 )
  2910. }).forEach(function (filter) {
  2911. postData[ filter[0] ] = filter[1];
  2912. })
  2913. global.fetch(URL_FETCH_KONTRAHENCI_IDS_AJAX, {
  2914. credentials: 'same-origin',
  2915. method: 'POST',
  2916. headers: { 'Content-Type': 'application/json' },
  2917. body: JSON.stringify(postData)
  2918. })
  2919. .then(function __parseJSON(response) {
  2920. return response.json()
  2921. })
  2922. .then(function (json) {
  2923. if ('success' === json.type && json.body && json.body.ids) {
  2924. updateListIdBiAuditReaport('KONTRAHENCI', json.body.ids.map(function (id) {
  2925. return parseInt(id)
  2926. }))
  2927. // jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').attr('checked', true); // Not working
  2928. jQuery('#body-kontrahenci').find('input[name="kontrID[]"]').each(function (idx, inputNode) {
  2929. inputNode.checked = true;
  2930. })
  2931. thisButton.attr('disabled', false);
  2932. var txt = thisButton.text()
  2933. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2934. updateCountItemCheckedByType('kontrahenci');
  2935. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+json.body.ids.length+" kontrahentów" })
  2936. }
  2937. })
  2938. .catch(function (e) {
  2939. p5UI__notifyAjaxCallback({ type: 'error', msg: '' + e })
  2940. thisButton.attr('disabled', false)
  2941. var txt = thisButton.text()
  2942. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  2943. });
  2944. }
  2945. }
  2946. function mock_error__fetchLastReports(id) {
  2947. return new Promise(function (resolve) {
  2948. throw "Wystąpił błąd, spróbuj ponownie później"
  2949. })
  2950. }
  2951. function mock__fetchLastReports(id) {
  2952. return new Promise(function (resolve) {
  2953. 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"}]}}';
  2954. var json = JSON.parse(fakeResponse);
  2955. var items = json.body.items;
  2956. console.log('items', items)
  2957. setTimeout(function () {
  2958. console.log('resolve items', items)
  2959. resolve(items);
  2960. }, 500);
  2961. });
  2962. }
  2963. function fetchLastReports(id) {
  2964. return global.fetch(URL_FETCH_LAST_REPORTS_AJAX, {
  2965. credentials: 'same-origin',
  2966. method: 'POST',
  2967. headers: { 'Content-Type': 'application/json' },
  2968. body: JSON.stringify({ id: id })
  2969. })
  2970. .then(function __parseJSON(response) {
  2971. return response.json()
  2972. })
  2973. .then(function (json) {
  2974. if ('success' === json.type && json.body && json.body.items) {
  2975. if (!json.body.items.length) throw "Brak danych"
  2976. return json.body.items;
  2977. }
  2978. throw "Wystąpił błąd, spróbuj ponownie później.";
  2979. })
  2980. }
  2981. function fetchPracownicyIdsByReport(id) {
  2982. return global.fetch(URL_FETCH_PRACOWNICY_IDS_BY_REPORT_AJAX, {
  2983. credentials: 'same-origin',
  2984. method: 'POST',
  2985. headers: { 'Content-Type': 'application/json' },
  2986. body: JSON.stringify({ id: id })
  2987. })
  2988. .then(function __parseJSON(response) {
  2989. return response.json()
  2990. })
  2991. .then(function (json) {
  2992. if ('success' === json.type && json.body && json.body.ids) {
  2993. if (!json.body.ids.length) throw "Brak danych"
  2994. return json.body.ids;
  2995. }
  2996. throw "Wystąpił błąd, spróbuj ponownie później.";
  2997. })
  2998. }
  2999. function fetchKontrahenciIdsByReport(id) {
  3000. return global.fetch(URL_FETCH_KONTRAHENCI_IDS_BY_REPORT_AJAX, {
  3001. credentials: 'same-origin',
  3002. method: 'POST',
  3003. headers: { 'Content-Type': 'application/json' },
  3004. body: JSON.stringify({ id: id })
  3005. })
  3006. .then(function __parseJSON(response) {
  3007. return response.json()
  3008. })
  3009. .then(function (json) {
  3010. if ('success' === json.type && json.body && json.body.ids) {
  3011. if (!json.body.ids.length) throw "Brak danych"
  3012. return json.body.ids;
  3013. }
  3014. throw "Wystąpił błąd, spróbuj ponownie później.";
  3015. })
  3016. }
  3017. function addToReportByPreviousReport(event) {
  3018. var pageType = (event.data.type) ? event.data.type : '';
  3019. handleAddToReportByPreviousReport(pageType);
  3020. }
  3021. function handleAddToReportByPreviousReport(pageType) {
  3022. switch (pageType) {
  3023. case 'pracownicy': break; // OK
  3024. case 'kontrahenci': break; // OK
  3025. default: throw "Wrong type";
  3026. }
  3027. var thisButton = $(this)
  3028. thisButton.attr('disabled', true)
  3029. thisButton.text( thisButton.text() + '...' )
  3030. function this__enableButton() {
  3031. thisButton.attr('disabled', false)
  3032. var txt = thisButton.text()
  3033. thisButton.text( '...' === txt.substr(-3) ? txt.substr(0, txt.length - 3) : txt )
  3034. }
  3035. var lastReportOptions = new Promise(function (resolve) {
  3036. fetchLastReports() // TODO: TEST remote `mock__`
  3037. .then(function (items) {
  3038. var options = {};
  3039. items.forEach(function (item) {
  3040. var label = "Nr " + item.id + ": " + item.adnotacje + " ";
  3041. var total = 0;
  3042. switch (pageType) {
  3043. case 'pracownicy': total = parseInt(item.totalPracownicy); break;
  3044. case 'kontrahenci': total = parseInt(item.totalKontrahenci); break;
  3045. }
  3046. label += ( total > 0 ? "(" + total + ")" : "brak");
  3047. options['raport-'+item.id] = label;
  3048. });
  3049. resolve(options);
  3050. })
  3051. .catch(function (e) {
  3052. swal.showValidationError(''+e)
  3053. swal.hideLoading();
  3054. resolve();
  3055. })
  3056. });
  3057. swal({
  3058. title: "Dodaj " + ('pracownicy' === pageType ? "praconików" : "kontrahentów") + " do analizy",
  3059. showCancelButton: true,
  3060. cancelButtonText: "Anuluj",
  3061. showConfirmButton: true,
  3062. confirmButtonText: "Wybierz",
  3063. focusCancel: true,
  3064. width: 600,
  3065. input: 'select',
  3066. inputOptions: lastReportOptions,
  3067. inputClass: "form-control input-lg",
  3068. preConfirm: function (selected) {
  3069. var id = parseInt(selected.substr('raport-'.length));
  3070. swal.showLoading();
  3071. if ('pracownicy' === pageType) {
  3072. return new Promise(function (resolve) {
  3073. fetchPracownicyIdsByReport(id)
  3074. .then(function (ids) {
  3075. updateListIdBiAuditReaport('PRACOWNICY', ids.map(function (id) {
  3076. return parseInt(id)
  3077. }))
  3078. ids.forEach(function (id) {
  3079. jQuery('#body-pracownicy').find('input[name="prID[]"][value="'+id+'"]').each(function (idx, inputNode) {
  3080. inputNode.checked = true;
  3081. })
  3082. })
  3083. updateCountItemCheckedByType('pracownicy');
  3084. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" pracowników" })
  3085. resolve();
  3086. })
  3087. .catch(function (e) {
  3088. swal.showValidationError(''+e)
  3089. swal.hideLoading();
  3090. resolve();
  3091. });
  3092. });
  3093. } else if ('kontrahenci' === pageType) {
  3094. return new Promise(function (resolve) {
  3095. fetchKontrahenciIdsByReport(id)
  3096. .then(function (ids) {
  3097. updateListIdBiAuditReaport('KONTRAHENCI', ids.map(function (id) {
  3098. return parseInt(id)
  3099. }))
  3100. ids.forEach(function (id) {
  3101. jQuery('#body-kontrahenci').find('input[name="kontrID[]"][value="'+id+'"]').each(function (idx, inputNode) {
  3102. inputNode.checked = true;
  3103. })
  3104. })
  3105. updateCountItemCheckedByType('kontrahenci');
  3106. p5UI__notifyAjaxCallback({ type: 'success', msg: "Dodano "+ids.length+" kontrahentów" })
  3107. resolve();
  3108. })
  3109. .catch(function (e) {
  3110. swal.showValidationError(''+e)
  3111. swal.hideLoading();
  3112. resolve();
  3113. });
  3114. });
  3115. } else return true;
  3116. },
  3117. // inputValidator: (value) => {
  3118. // return !value && 'Proszę wybrać raport'
  3119. // }
  3120. // html: '<p>Ostatnie raporty:</p>' + '<ul id="' + uniqHtmlId + '"></ul></p>',
  3121. }).then(function (selected) {
  3122. this__enableButton();
  3123. }).catch(function (e) {
  3124. this__enableButton();
  3125. })
  3126. }
  3127. $(document).ready(function(){
  3128. DBG && console.warn('DBG:: SET window[STORE_NAME]', { store: window[STORE_NAME], STORE_NAME: STORE_NAME, globalRaportStore })
  3129. ReactDOM.render(
  3130. h(P5UI__BocianHeader, {
  3131. store: globalRaportStore
  3132. }),
  3133. document.getElementById('bi_audit_header')
  3134. );
  3135. rootChangeForm();
  3136. updateTopCounters();
  3137. var unsubscribe = globalRaportStore.subscribe(function () {
  3138. // TODO: fetch data from globalRaportStore.getState()
  3139. // var defaultState = global[STORE_NAME + '__defaults']();
  3140. })
  3141. $(window).on('hashchange', function() {
  3142. DBG && console.warn("$(window).on('hashchange', ...")
  3143. rootChangeForm();
  3144. updateTopCounters();
  3145. hideMoreRecordFunctionsPopover()
  3146. });
  3147. });
  3148. global.hideMoreRecordFunctionsPopover = function() {
  3149. if (RECORD_MORE_FUNCTIONS_OPENED_NODE) jQuery(RECORD_MORE_FUNCTIONS_OPENED_NODE).popover('destroy')
  3150. }
  3151. global.pracownicyLoadMoreRecordFunctions = function(event, node, rowPK) {
  3152. return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY")
  3153. }
  3154. global.kontrahenciLoadMoreRecordFunctions = function(event, node, rowPK) {
  3155. return loadMoreRecordFunctions(event, node, rowPK, "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI")
  3156. }
  3157. global.removeFiltersPracownicy = removeFiltersPracownicy;
  3158. global.removeFiltersKontrahenci = removeFiltersKontrahenci;
  3159. global.onChangeFiltersPracownicy = onChangeFiltersPracownicy;
  3160. global.onKeypressFiltersPracownicy = onKeypressFiltersPracownicy;
  3161. global.onChangeFiltersKontrahenci = onChangeFiltersKontrahenci;
  3162. global.onKeypressFiltersKontrahenci = onKeypressFiltersKontrahenci;
  3163. global.checkAll = checkAll;
  3164. global.checkedChoiseItems = checkedChoiseItems;
  3165. global.catchEventCheckbox = catchEventCheckbox;
  3166. global.clearSelectedCheckbox = clearSelectedCheckbox;
  3167. global.getNameGroupById = getNameGroupById;
  3168. global.createGroupPracownicy = createGroupPracownicy;
  3169. global.createGroupKontrahenci = createGroupKontrahenci;
  3170. global.selectPage = selectPage;
  3171. global.detectChoiseFilter = detectChoiseFilter;
  3172. global.updateListIdBiAuditReaport = updateListIdBiAuditReaport;
  3173. global.deleteListIdBiAuditReaport = deleteListIdBiAuditReaport;
  3174. global.urlFetchPracownicy = urlFetchPracownicy;
  3175. global.urlFetchKontrahenci = urlFetchKontrahenci;
  3176. global.getAddressData = getAddressData;
  3177. global.Pagination = Pagination;
  3178. global.todo__fetchRaport = todo__fetchRaport;
  3179. global.setItemLocalStorage = setItemLocalStorage;
  3180. global.getItemLocalStorage = getItemLocalStorage;
  3181. global.deleteItemLocalStorage = deleteItemLocalStorage;
  3182. global.removeItemInArray = removeItemInArray;
  3183. global.removeItemArrayInArray = removeItemArrayInArray;
  3184. global.addPracownikToGroup = addPracownikToGroup;
  3185. global.addPracownikAllToGroup = addPracownikAllToGroup;
  3186. global.addKontrahenciToGroup = addKontrahenciToGroup;
  3187. global.addKontrahenciAllToGroup = addKontrahenciAllToGroup;
  3188. global.createPracownikAjax = createPracownikAjax;
  3189. global.createKontrahentAjax = createKontrahentAjax;
  3190. global.removePracownikFromGroup = removePracownikFromGroup;
  3191. global.removeKontrahenciFromGroup = removeKontrahenciFromGroup;
  3192. global.showViewUploadFile = showViewUploadFile;
  3193. global.parseCsvFile = parseCsvFile;
  3194. global.clearListLocalStorageByType = clearListLocalStorageByType;
  3195. // message
  3196. global.messageCriticalSearchData = 'Krytyczne wielkości danych do przeszukania. Optymalna wartość głębokość szukania powiaząń to: 6';