Bocian.php.view.js 100 KB

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