BiAuditGenerate.php 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577
  1. <?php
  2. //TODO optimal - akcja aby doruzcic do pracownikow do analizy jakas spolke z kontekstu przegladania KRS - zapytanie przyklad:
  3. // insert ignore into BI_audit_ENERGA_PRACOWNICY (imiona, nazwisko, pesel, source )
  4. // select p.imiona, p.nazwisko, p.pesel, 'ENSO_STORA/zadanie' from `BI_audit_KRS_person` as p
  5. // right join `CRM__#REF_TABLE__12` as r on r.`REMOTE_PRIMARY_KEY`=p.ID
  6. // right join BI_audit_KRS as k on k.ID=r.`PRIMARY_KEY`
  7. // where k.`nazwa` like '%Stora%enso%';
  8. //serwisowy skrypt jest tutaj pod nazwa xyz.
  9. //TODO mozliwosc przerwania przetwarzania
  10. Lib::loadClass('RouteBase');
  11. Lib::loadClass('FoldersConfig');
  12. Lib::loadClass('FileUploader');
  13. Lib::loadClass('ProcesHelper');
  14. Lib::loadClass('SchemaFactory');
  15. Lib::loadClass('Core_AclHelper');
  16. Lib::loadClass('Core_AclSimpleSchemaBase');
  17. class Route_UrlAction_BiAuditGenerate extends RouteBase {
  18. private $powiazanie = null;
  19. private $SOURCE = null;
  20. private $REFERER;
  21. private $POWIAZANIA_ID = null;
  22. public function handleAuth() {
  23. if (!User::logged()) {
  24. User::authByRequest();
  25. }
  26. }
  27. private static function getDirectory($table, $id) {
  28. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  29. $record = new stdClass;
  30. $record->ID = $id;
  31. $uploader = new FileUploader($table.'_COLUMN', $record);
  32. $errMsg = "";
  33. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  34. $uploader->findFolder();
  35. return $uploader->getDestLocalPath(true);
  36. }
  37. private static function getUrl($table, $id) {
  38. $folderConf = FoldersConfig::getAll($table.'_COLUMN');
  39. $record = new stdClass;
  40. $record->ID = $id;
  41. $uploader = new FileUploader($table.'_COLUMN', $record);
  42. $errMsg = "";
  43. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  44. return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
  45. }
  46. private static function getMainDirectory() {
  47. $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
  48. if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
  49. return $folderConf['mount_point'];
  50. }
  51. private static function parseNipRegon($string) {
  52. $nip = null; $regon = null;
  53. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  54. if (!empty($matches[2])) $nip = trim($matches[2]);
  55. if ($nip && !V::isNip($nip)) $nip = null;
  56. preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
  57. if (!empty($matches[2])) $regon = trim($matches[2]);
  58. if ($regon && !V::isRegon($regon)) $regon = null;
  59. return [$nip, $regon];
  60. }
  61. private function initializePowiazaniaForm() {
  62. ?>
  63. <div class="container" style="margin-top:20px">
  64. <form class="form-horizontal" method="post">
  65. <legend>
  66. Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
  67. <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
  68. </legend>
  69. <div class="form-group">
  70. <div class="col-sm-12">
  71. <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
  72. <table class="table table-bordered table-hover table-striped" height=5>
  73. <thead>
  74. <tr style="text-align:center; background-color:lightgray">
  75. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  76. <td width=1>ID</td>
  77. <td>Imiona</td>
  78. <td>Nazwisko</td>
  79. <td>Pesel</td>
  80. <td>NIP</td>
  81. <td>Regon</td>
  82. <td>source</td>
  83. </tr>
  84. </thead>
  85. <tbody>
  86. <?php
  87. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
  88. $queryFeatures = $acl->buildQuery(['limit' => 0]);
  89. $pracownicy = $queryFeatures->getItems();
  90. foreach ($pracownicy as $pracownik) {
  91. ?>
  92. <tr>
  93. <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
  94. <td align="right"><?=$pracownik['ID']?></td>
  95. <td><?=$pracownik['imiona']?></td>
  96. <td><?=$pracownik['nazwisko']?></td>
  97. <td><?=$pracownik['pesel']?></td>
  98. <td><?=$pracownik['nip']?></td>
  99. <td><?=$pracownik['regon']?></td>
  100. <td><?=$pracownik['source']?></td>
  101. </tr>
  102. <?php
  103. }
  104. ?>
  105. </tbody>
  106. </table>
  107. </div>
  108. </div>
  109. <!-- <div class="form-group">
  110. <label class="col-sm-2 control-label">
  111. Odśwież cache
  112. </label>
  113. <div class="col-sm-2">
  114. <select name="reloadCache" class="form-control">
  115. <option value="No" selected>Nie</option>
  116. <!-#- <option value="Part">Częściowe</option>-#->
  117. <option value="Full">Pełne</option>
  118. </select>
  119. </div>
  120. </div>
  121. <div class="form-group">
  122. <div class="col-sm-offset-2 col-sm-10">
  123. <!-#- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-#->
  124. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  125. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  126. </div>
  127. </div>-->
  128. <div class="form-group">
  129. <div class="col-sm-12">
  130. <div class="containter" style="text-align:center">
  131. <button type="submit" class="btn btn-primary" name="action" value="initialize">Generuj</button>
  132. <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
  133. </div>
  134. </div>
  135. </div>
  136. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  137. </form>
  138. </div>
  139. <script language="JavaScript">
  140. <!--
  141. function toggleAll(source) {
  142. checkboxes = document.getElementsByName('prID[]');
  143. for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
  144. }
  145. function toggle(source) {
  146. checkboxes = document.getElementsByName('prID[]');
  147. all = true;
  148. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
  149. source.form['checkAll'].checked = all;
  150. }
  151. -->
  152. </script>
  153. <?php
  154. }
  155. private function initializePowiazaniaSave() {
  156. $prID = V::get('prID', array(), $_POST);
  157. if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
  158. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
  159. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  160. $kontrahenci = $queryFeatures->getItems();
  161. $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
  162. $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
  163. $requestedPersons = $queryFeatures->getItems();
  164. if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
  165. $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
  166. $reloadCache = V::get('reloadCache', 'No', $_POST);
  167. $reloadCacheAvailable = ['Full', 'Part', 'No'];
  168. if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
  169. $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
  170. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
  171. $result = DB::getPDO()->fetchValue($query);
  172. if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
  173. elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
  174. else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
  175. if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
  176. $powiazanieID = $this->powiazanie['ID'];
  177. } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
  178. if (count($prID) != 1) throw new Exception("Błąd formularza!");
  179. if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
  180. if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  181. if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
  182. if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
  183. $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
  184. $result = DB::getPDO()->fetchFirst($query);
  185. if (!$result) throw new Exception("Błąd formularza!");
  186. $sqlInsert = [
  187. 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
  188. 'A_STATUS' => 'NORMAL',
  189. 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
  190. 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
  191. 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
  192. 'FILE_STATUS' => 'NONE',
  193. 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
  194. 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
  195. 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
  196. 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
  197. 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
  198. ];
  199. $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
  200. if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
  201. else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  202. }
  203. $sqlUpdate['ID'] = $powiazanieID;
  204. self::truncatePowiazaniaFromDB($powiazanieID);
  205. $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
  206. foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
  207. $refPowiazaniaToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  208. foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
  209. $refPowiazaniaToKwRequestedPreson = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_KW_requested_person', true);
  210. foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
  211. $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
  212. if ($affected) {
  213. if ($this->powiazanie) {
  214. SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
  215. ?>
  216. <div class="container" style="text-align:center">
  217. <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
  218. </div>
  219. <?php
  220. }
  221. } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
  222. }
  223. private function initializePowiazania() {
  224. switch (V::get('action', '', $_POST)) {
  225. case "initialize":
  226. $this->initializePowiazaniaSave();
  227. break;
  228. default:
  229. $this->initializePowiazaniaForm();
  230. }
  231. }
  232. private function showPowiazania() {
  233. // echo "Statystyki znalezionych powiązań [TODO]";
  234. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  235. $url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
  236. $reports = [
  237. 'pdf' => [
  238. 'files' => glob("{$dir}/relations*.pdf"),
  239. 'label' => 'Raporty PDF:<br/>&nbsp;',
  240. 'button' => 'Pokaż raport PDF',
  241. 'regex' => "/^relations(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.pdf$/",
  242. 'parentDir' => false,
  243. ],
  244. 'html' => [
  245. 'files' => glob("{$dir}/html*/relations-{$this->powiazanie['ID']}*.html"),
  246. 'label' => 'Raporty HTML<br/>do przeglądania:',
  247. 'button' => 'Pokaż raport HTML',
  248. 'regex' => "/^relations-({$this->powiazanie['ID']})_([[:digit:]]+)\.html$/",
  249. 'parentDir' => true,
  250. ],
  251. 'htmlZip' => [
  252. 'files' => glob("{$dir}/html*.zip"),
  253. 'label' => 'Raporty HTML<br/>do pobrania:',
  254. 'button' => 'Pobież raport HTML',
  255. 'regex' => "/^html(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.zip$/",
  256. 'parentDir' => false,
  257. ],
  258. ];
  259. ?>
  260. <div class="container" style="margin-top:20px">
  261. <legend>
  262. Wygenerowany raport nr <?=$this->powiazanie['ID']?>
  263. </legend>
  264. <div class="form-group" style="text-align: center;">
  265. <?php
  266. array_walk($reports, function ($report) use ($url) {
  267. echo "<div class=\"col-sm-2\"><h4>{$report['label']}</h4>";
  268. $hrefs = array_filter(array_map(function ($path) use ($url, $report) {
  269. if (!is_file($path)) return false;
  270. $file = basename($path);
  271. if (preg_match($report['regex'], $file, $matches)) $i = " (" . ltrim($matches[2], '0') . ")";
  272. else $i = '';
  273. if ($report['parentDir']) $file = basename(dirname($path)) . "/" . $file;
  274. return "<a href=\"{$url}/{$file}\" target=\"_blank\" class=\"btn btn-primary\">{$report['button']}{$i}</a>";
  275. }, $report['files']));
  276. if ($hrefs) echo implode('<br/><br/>', $hrefs);
  277. else echo "<h5>Nie znaleziono</h5>";
  278. echo "</div>\n";
  279. });
  280. ?>
  281. </div>
  282. <div class="form-group">
  283. <div class="col-sm-12">
  284. <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  285. </div>
  286. </div>
  287. </div>
  288. <?php
  289. }
  290. private function showPowiazaniaList() {
  291. switch (V::get('action', '', $_POST)) {
  292. case "initialize":
  293. $this->initializePowiazaniaSave();
  294. break;
  295. }
  296. $this->showPowiazaniaListForm();
  297. }
  298. private function showPowiazaniaListForm() {
  299. if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
  300. elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
  301. $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
  302. $pracownik = DB::getPDO()->fetchFirst($query);
  303. if (!$pracownik) throw new Exception("Błąd danych");
  304. ?>
  305. <div class="container" style="margin-top:20px">
  306. <legend>
  307. Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
  308. <span class="pull-right"># <?=$pracownik['ID']?></span>
  309. </legend>
  310. <div class="form-group">
  311. <div class="col-sm-12">
  312. <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
  313. <table class="table table-bordered table-hover table-striped" height=5>
  314. <thead>
  315. <tr style="text-align:center; background-color:lightgray">
  316. <td width=1>ID</td>
  317. <td>Adnotacje</td>
  318. <td>Minimalna głębokość analizy</td>
  319. <td>Maksymalna głębokość analizy</td>
  320. <td>Powiązania tylko do celów</td>
  321. <td>Status raportu</td>
  322. <td>Status raportu - informacje</td>
  323. <td>Indywidualny raport</td>
  324. <td width=1></td>
  325. </tr>
  326. </thead>
  327. <tbody>
  328. <?php
  329. $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
  330. $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
  331. from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  332. join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
  333. where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
  334. $result = DB::getPDO()->fetchAll($query);
  335. if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
  336. else {
  337. foreach ($result as $row) {
  338. $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
  339. $count = DB::getPDO()->fetchValue($query);
  340. ?>
  341. <tr>
  342. <td align="right"><?=$row['ID']?></td>
  343. <td><?=$row['L_APPOITMENT_INFO']?></td>
  344. <td><?=$row['BI_analiza_minDepth']?></td>
  345. <td><?=$row['BI_analiza_maxDepth']?></td>
  346. <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
  347. <td><?=$row['FILE_STATUS']?></td>
  348. <td><?=$row['FILE_STATUS_info']?></td>
  349. <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
  350. <td><?=UI::hButtonPost("Pokaż w tabeli", ['class' => 'btn-info btn-xs', 'action' => "index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA&ff_ID={$row['ID']}", 'data' > ['f_ID' => $row['ID']]])?></td>
  351. </tr>
  352. <?php
  353. }
  354. }
  355. ?>
  356. </tbody>
  357. </table>
  358. </div>
  359. </div>
  360. <div class="form-group">
  361. <div class="col-sm-12">
  362. <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
  363. </div>
  364. </div>
  365. <form class="form-horizontal" method="post">
  366. <div class="form-group">
  367. <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
  368. <div class="col-sm-1">
  369. <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
  370. </div>
  371. </div>
  372. <div class="form-group">
  373. <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
  374. <div class="col-sm-1">
  375. <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
  376. </div>
  377. </div>
  378. <div class="form-group">
  379. <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
  380. <div class="col-sm-1">
  381. <select name="onlyTargets" class="form-control">
  382. <option value="Y" selected>Tak</option>
  383. <option value="N">Nie</option>
  384. </select>
  385. </div>
  386. </div>
  387. <div class="form-group">
  388. <label class="col-sm-4 control-label">Adnotacje</label>
  389. <div class="col-sm-4">
  390. <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
  391. </div>
  392. </div>
  393. <!-- <div class="form-group">
  394. <label class="col-sm-4 control-label">
  395. Odśwież cache
  396. </label>
  397. <div class="col-sm-2">
  398. <select name="reloadCache" class="form-control">
  399. <option value="No" selected>Nie</option>
  400. <!-#- <option value="Part">Częściowe</option>-#->
  401. <option value="Full">Pełne</option>
  402. </select>
  403. </div>
  404. </div>
  405. <div class="form-group">
  406. <div class="col-sm-offset-4 col-sm-8">
  407. <!-#- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-#->
  408. Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
  409. Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
  410. </div>
  411. </div>-->
  412. <div class="form-group">
  413. <div class="col-sm-12">
  414. <div class="containter" style="text-align:center">
  415. <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
  416. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  417. </div>
  418. </div>
  419. </div>
  420. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  421. <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>">
  422. </form>
  423. </div>
  424. <script language="JavaScript">
  425. <!--
  426. function validate() {
  427. result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
  428. if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
  429. return result;
  430. }
  431. -->
  432. </script>
  433. <?php
  434. }
  435. private function powiazania() {
  436. try {
  437. if (!$this->SOURCE) throw new Exception("Błąd danych");
  438. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  439. switch ($this->SOURCE['TABLE']) {
  440. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  441. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  442. if (!$powiazania) throw new Exception("Błąd danych");
  443. $this->powiazanie = $powiazania[0];
  444. switch ($this->powiazanie['FILE_STATUS']) {
  445. case "NONE":
  446. $this->initializePowiazania();
  447. break;
  448. case "GENERATED":
  449. $this->showPowiazania();
  450. break;
  451. default: throw new Exception("Błędny status rekordu");
  452. }
  453. break;
  454. case "BI_audit_ENERGA_PRACOWNICY":
  455. $this->showPowiazaniaList();
  456. break;
  457. case "BI_audit_KRS":
  458. case "BI_audit_MSIG":
  459. $this->importToPracownicySearch($this->SOURCE['ID']);
  460. break;
  461. case "BI_audit_KRS_person":
  462. $this->showKrsForKrsPerson();
  463. break;
  464. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  465. }
  466. } catch (Exception $e) {
  467. SE_Layout::alert('danger',$e->getMessage());
  468. $_SESSION['REFERER'] = $this->REFERER;
  469. ?>
  470. <div class="container" style="text-align:center">
  471. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  472. </div>
  473. <?php
  474. }
  475. }
  476. private function importToPracownicy() {
  477. $action = V::get('action', '', $_POST);
  478. switch ($action) {
  479. case "search":
  480. $this->importToPracownicySearch();
  481. break;
  482. default: $this->importToPracownicyForm();
  483. }
  484. }
  485. private $tableDesc = ['BI_audit_KRS' => 'KRS', 'BI_audit_MSIG' => 'MSiG'];
  486. private function importToPracownicyForm() {
  487. $TABLE = $this->SOURCE['TABLE'];
  488. $DESC = $this->tableDesc[$TABLE];
  489. ?>
  490. <div class="container" style="margin-top:20px">
  491. <legend>
  492. Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
  493. </legend>
  494. <div class="form-group">
  495. <div class="col-sm-12">
  496. <h4>Znajdź podmiot</h4>
  497. </div>
  498. </div>
  499. <form class="form-horizontal" method="post">
  500. <div class="form-group">
  501. <label class="col-sm-1 control-label">Nazwa</label>
  502. <div class="col-sm-4">
  503. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  504. </div>
  505. </div>
  506. <div class="form-group">
  507. <label class="col-sm-1 control-label">KRS</label>
  508. <div class="col-sm-2">
  509. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  510. </div>
  511. </div>
  512. <div class="form-group">
  513. <label class="col-sm-1 control-label">NIP</label>
  514. <div class="col-sm-2">
  515. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  516. </div>
  517. </div>
  518. <div class="form-group">
  519. <label class="col-sm-1 control-label">Regon</label>
  520. <div class="col-sm-2">
  521. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  522. </div>
  523. </div>
  524. <div class="form-group">
  525. <div class="col-sm-offset-1 col-sm-11">
  526. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  527. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  528. </div>
  529. </div>
  530. </form>
  531. </div>
  532. <?php
  533. }
  534. private function importToPracownicySearch($krsId = null) {
  535. $TABLE = $this->SOURCE['TABLE'];
  536. $DESC = $this->tableDesc[$TABLE];
  537. $formItems = [
  538. "nazwa" => 'like',
  539. "krs" => '=',
  540. "nip" => '=',
  541. "regon" => '=',
  542. ];
  543. try {
  544. $subaction = V::get('subaction', '', $_POST);
  545. switch ($subaction) {
  546. case "listPerson":
  547. $krsId = V::get('krsId', 0, $_POST, int);
  548. break;
  549. case "addPersonToPracownicy":
  550. $krsId = V::get('krsId', 0, $_POST, int);
  551. $personId = V::get('personId', [], $_POST);
  552. if (!$personId) throw new Exception("Błąd formularza");
  553. $query = "insert into BI_audit_ENERGA_PRACOWNICY (source, imiona, nazwisko, pesel) select 'KRS', imiona, nazwisko, pesel from {$TABLE}_person where ID in (" . implode(", ", $personId) . ")";
  554. DB::getPDO()->query($query);
  555. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  556. break;
  557. case "addToKontrahenci":
  558. $krsId = V::get('krsId', 0, $_POST, int);
  559. if (!$krsId) throw new Exception("Błąd formularza");
  560. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join {$TABLE} krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  561. $kontrahentExists = DB::getPDO()->fetchValue($query);
  562. if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
  563. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (Tytul_dokumentu, Pelna_nazwa_kontrahenta, REGON, NIP, KRS) select 'ZaImportowano z {$DESC}', nazwa, regon, nip, krs from {$TABLE} where ID = ".$krsId." ";
  564. DB::getPDO()->query($query);
  565. SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
  566. break;
  567. }
  568. if ($krsId) {
  569. $where = ["ID = '{$krsId}'"];
  570. } else {
  571. $form = [];
  572. foreach ($formItems as $item => $type) {
  573. if ($param = V::get($item, '', $_POST)) {
  574. if ($type == 'like') $param = "%{$param}%";
  575. $form[$item] = DB::getPDO()->quote($param);
  576. }
  577. }
  578. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  579. $where = [];
  580. foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
  581. }
  582. } catch (Exception $e) {
  583. SE_Layout::alert('danger', $e->getMessage());
  584. $this->importToPracownicyForm();
  585. return;
  586. }
  587. $query = "select * from `{$TABLE}` where " . implode(" and ", $where) . "order by ID limit 1001";
  588. $result = DB::getPDO()->fetchAll($query);
  589. if (count($result) == 1001) {
  590. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  591. $this->importToPracownicyForm();
  592. return;
  593. } elseif (count($result) == 1) {
  594. $krsId = $result[0]['ID'];
  595. }
  596. ?>
  597. <div class="container" style="margin-top:20px">
  598. <form method="post">
  599. <legend>
  600. Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
  601. </legend>
  602. <div class="form-group">
  603. <div class="col-sm-12">
  604. <h4>Znalezione podmioty:</h4>
  605. </div>
  606. </div>
  607. <div class="form-group">
  608. <div class="col-sm-12">
  609. <table class="table table-bordered table-hover table-striped" height=5>
  610. <thead>
  611. <tr style="text-align:center; background-color:lightgray">
  612. <td width=1>Lp.</td>
  613. <td>Nazwa</td>
  614. <td>Adres</td>
  615. <td>KRS</td>
  616. <td>NIP</td>
  617. <td>Regon</td>
  618. <?php
  619. if (count($result) > 1) {
  620. ?>
  621. <td width=1>Wybierz</td>
  622. <?php
  623. }
  624. ?>
  625. </tr>
  626. </thead>
  627. <tbody>
  628. <?php
  629. if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
  630. else {
  631. $lp = 1;
  632. foreach ($result as $row) {
  633. $adres = $row['A_miejscowosc'];
  634. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  635. if ($row['A_nrDomu']) {
  636. $adres .= " {$row['A_nrDomu']}";
  637. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  638. }
  639. ?>
  640. <tr>
  641. <td align="right"><?=$lp++?></td>
  642. <td><?=htmlspecialchars($row['nazwa'])?></td>
  643. <td><?=htmlspecialchars($adres)?></td>
  644. <td><?=$row['krs']?></td>
  645. <td><?=$row['nip']?></td>
  646. <td><?=$row['regon']?></td>
  647. <?php
  648. if (count($result) > 1) {
  649. ?>
  650. <td align="center">
  651. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  652. </td>
  653. <?php
  654. }
  655. ?>
  656. </tr>
  657. <?php
  658. }
  659. }
  660. ?>
  661. </tbody>
  662. </table>
  663. </div>
  664. </div>
  665. <?php
  666. if (count($result) > 1) {
  667. ?>
  668. <div class="form-group">
  669. <div class="col-sm-12">
  670. <?php
  671. foreach (array_keys($formItems) as $item) {
  672. ?>
  673. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  674. <?php
  675. }
  676. ?>
  677. <input type="hidden" name="back" value="search"/>
  678. <div class="containter" style="text-align:center">
  679. <button type="submit" class="btn btn-primary" name="subaction" value="listPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
  680. <a href="" class="btn btn-default">Powrót</a>
  681. </div>
  682. </div>
  683. </div>
  684. <?php
  685. } elseif ($krsId) {
  686. ?>
  687. <div class="form-group">
  688. <div class="col-sm-12">
  689. <h4>Znalezione osoby:</h4>
  690. </div>
  691. </div>
  692. <div class="form-group">
  693. <div class="col-sm-12">
  694. <table class="table table-bordered table-hover table-striped" height=5>
  695. <thead>
  696. <tr style="text-align:center; background-color:lightgray">
  697. <td width=1>Lp.</td>
  698. <td>Nazwisko</td>
  699. <td>Imiona</td>
  700. <td>Pesel</td>
  701. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  702. </tr>
  703. </thead>
  704. <tbody>
  705. <?php
  706. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI kh join {$TABLE} krs on (kh.NIP = krs.nip or kh.REGON = krs.regon or kh.KRS = krs.krs) where krs.ID = '{$krsId}'";
  707. $kontrahentExists = DB::getPDO()->fetchValue($query);
  708. $refToPerson = BiAuditRefTables::getRefTable($TABLE, "{$TABLE}_person", true);
  709. $query = "select person.*, pracownicy.ID as pracownicyId from `{$refToPerson}` ref join `{$TABLE}_person` person on ref.REMOTE_PRIMARY_KEY = person.ID left join BI_audit_ENERGA_PRACOWNICY pracownicy on person.pesel = pracownicy.pesel where ref.PRIMARY_KEY = '{$krsId}'";
  710. $result = DB::getPDO()->fetchAll($query);
  711. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  712. else {
  713. $lp = 1;
  714. foreach ($result as $row) {
  715. ?>
  716. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  717. <td align="right"><?=$lp++?></td>
  718. <td><?=$row['nazwisko']?></td>
  719. <td><?=$row['imiona']?></td>
  720. <td><?=$row['pesel']?></td>
  721. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  722. </tr>
  723. <?php
  724. }
  725. }
  726. ?>
  727. </tbody>
  728. </table>
  729. </div>
  730. </div>
  731. <!-- <div class="form-group">
  732. <div class="col-sm-12">
  733. <label class="col-sm-4 control-label">Opis/źródło</label>
  734. <div class="col-sm-4">
  735. <input type="text" class="form-control" name="source" placeholder="KRS"/>
  736. </div>
  737. </div>
  738. </div>-->
  739. <div class="form-group">
  740. <div class="col-sm-12" style="text-align: center;">
  741. <button type="submit" class="btn btn-primary" name="subaction" value="addToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
  742. <button type="submit" class="btn btn-primary" name="subaction" value="addPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  743. <input type="hidden" name="krsId" value="<?=$krsId?>"/>
  744. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  745. <?php
  746. if (V::get('back', '', $_POST) == 'search') {
  747. foreach (array_keys($formItems) as $item) {
  748. ?>
  749. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  750. <?php
  751. }
  752. ?>
  753. <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
  754. <?php
  755. } else {
  756. ?>
  757. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  758. <?php
  759. }
  760. ?>
  761. </div>
  762. </div>
  763. <?php
  764. }
  765. ?>
  766. <input type="hidden" name="action" value="search">
  767. </form>
  768. </div>
  769. <script language="JavaScript">
  770. <!--
  771. function toggleAll(source) {
  772. checkboxes = document.getElementsByName('personId[]');
  773. checked = false;
  774. for(var i=0, n=checkboxes.length;i<n;i++) {
  775. if (!checkboxes[i].disabled) {
  776. checkboxes[i].checked = source.checked;
  777. checked = true;
  778. }
  779. }
  780. if (source.checked && (!checked)) source.checked = false;
  781. }
  782. function toggle(source) {
  783. checkboxes = document.getElementsByName('personId[]');
  784. all = true;
  785. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  786. source.form['checkAll'].checked = all;
  787. }
  788. function validatePerson(source) {
  789. checkboxes = document.getElementsByName('personId[]');
  790. checked = false;
  791. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  792. if (!checked) alert('Nie wybrano żadnej osoby!');
  793. return checked;
  794. }
  795. function validateCompany(source) {
  796. radios = document.getElementsByName('krsId');
  797. checked = false;
  798. for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
  799. if (!checked) alert('Nie wybrano żadnej firmy!');
  800. return checked;
  801. }
  802. -->
  803. </script>
  804. <?php
  805. }
  806. private function showKrsForKrsPerson() {
  807. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  808. $result = DB::getPDO()->fetchFirst($query);
  809. ?>
  810. <div class="container" style="margin-top:20px">
  811. <legend>
  812. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  813. </legend>
  814. <div class="form-group">
  815. <div class="col-sm-12">
  816. <table class="table table-bordered table-hover table-striped" height=5>
  817. <thead>
  818. <tr style="text-align:center; background-color:lightgray">
  819. <td width=1>Lp.</td>
  820. <td>Nazwa</td>
  821. <td>Adres</td>
  822. <td>KRS</td>
  823. <td>NIP</td>
  824. <td>Regon</td>
  825. <td width=1></td>
  826. </tr>
  827. </thead>
  828. <tbody>
  829. <?php
  830. $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
  831. $query = "select krs.* from `{$refKrsToKrsPerson}` ref join BI_audit_KRS krs on ref.PRIMARY_KEY = krs.ID where ref.REMOTE_PRIMARY_KEY = '{$this->SOURCE['ID']}'";
  832. $result = DB::getPDO()->fetchAll($query);
  833. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  834. else {
  835. $lp = 1;
  836. foreach ($result as $row) {
  837. $adres = $row['A_miejscowosc'];
  838. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  839. if ($row['A_nrDomu']) {
  840. $adres .= " {$row['A_nrDomu']}";
  841. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  842. }
  843. ?>
  844. <tr>
  845. <td align="right"><?=$lp++?></td>
  846. <td><?=htmlspecialchars($row['nazwa'])?></td>
  847. <td><?=htmlspecialchars($adres)?></td>
  848. <td><?=$row['krs']?></td>
  849. <td><?=$row['nip']?></td>
  850. <td><?=$row['regon']?></td>
  851. <td><?=UI::hButtonPost("Pokaż w tabeli", ['class' => 'btn-info btn-xs', 'action' => "index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS/BI_audit_KRS&ff_ID={$row['ID']}", 'data' > ['f_ID' => $row['ID']]])?></td>
  852. </tr>
  853. <?php
  854. }
  855. }
  856. ?>
  857. </tbody>
  858. </table>
  859. </div>
  860. </div>
  861. <div class="form-group">
  862. <div class="col-sm-12">
  863. <div class="containter" style="text-align:center">
  864. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  865. </div>
  866. </div>
  867. </div>
  868. </div>
  869. <?php
  870. }
  871. private function clearTable_do() {
  872. try {
  873. $wynik = V::get('wynik', 0, $_POST, 'int');
  874. $ctrl = @gzuncompress(@base64_decode(V::get('_BiAuditGenerate_ctrl', '', $_SESSION)));
  875. unset($_SESSION['_BiAuditGenerate_ctrl']);
  876. $deleteFiles = (V::get('deleteFiles', '', $_POST) === 'on');
  877. $deletedDirs = 0; $deletedFiles = 0;
  878. if (!($ctrl)) throw new Exception('Błąd parametru');
  879. if (!($wynik == $ctrl)) {
  880. SE_Layout::alert('warning', 'Podano błędny wynik działania');
  881. $this->clearTable_form();
  882. return;
  883. }
  884. $refs = []; $backRefs = []; $tables = []; $queries = [];
  885. switch ($this->SOURCE['TABLE']) {
  886. case "BI_audit_ENERGA_PRACOWNICY":
  887. $refs[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
  888. $tables[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
  889. $queries[] = "update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'";
  890. break;
  891. case "BI_audit_ENERGA_PRACOWNICY_import":
  892. break;
  893. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  894. $backRefs[] = 'BI_audit_ENERGA_RUM_UMOWY';
  895. $backRefs[] = 'BI_audit_ENERGA_FAKTURY';
  896. $queries[] = "update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING'";
  897. break;
  898. case "BI_audit_ENERGA_RUM_UMOWY":
  899. $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  900. break;
  901. case "BI_audit_ENERGA_FAKTURY":
  902. $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  903. break;
  904. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  905. $query = "select ID from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  906. $result = DB::getPDO()->fetchAll($query);
  907. foreach ($result as $row) {
  908. if ($deleteFiles) {
  909. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  910. if (!file_exists($dir)) continue;
  911. $deleted = V::deleteWholeDirectory($dir, true, false);
  912. $deletedDirs += count($deleted['dirs']);
  913. $deletedFiles += count($deleted['files']);
  914. }
  915. self::deleteResultsFromDB($row['ID']);
  916. self::truncatePowiazaniaFromDB($row['ID']);
  917. }
  918. break;
  919. default: throw new Exception('Błąd parametru');
  920. }
  921. $tables[] = $this->SOURCE['TABLE'];
  922. foreach ($refs as $ref) $tables[] = BiAuditRefTables::getRefTable($this->SOURCE['TABLE'], $ref, true);
  923. foreach ($backRefs as $backRef) $tables[] = BiAuditRefTables::getRefTable($backRef, $this->SOURCE['TABLE'], true);
  924. foreach ($tables as $table) $queries[] = "delete from `{$table}`";
  925. foreach ($queries as $query) DB::getPDO()->query($query);
  926. ?>
  927. <div style="text-align: center;">
  928. <h2>Pomyślnie wyczyszczono tabelę <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>.</h2>
  929. <?php
  930. if ($deleteFiles && ($deletedDirs || $deletedFiles)):
  931. ?>
  932. <h4>Ponadto usunięto <?=$deletedDirs?> katalogów oraz <?=$deletedFiles?> plików.</h4>
  933. <?php
  934. endif;
  935. ?>
  936. <br/><a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  937. </div>
  938. <?php
  939. } catch (Exception $e) {
  940. SE_Layout::alert('danger', $e->getMessage());
  941. }
  942. }
  943. private function clearTable_form() {
  944. if (!isset($this->clearTable_tables[$this->SOURCE['TABLE']])) SE_Layout::alert('danger', 'Błąd parametru');
  945. $a = rand(10, 50);
  946. $b = rand(10, 50);
  947. if ($a == $b) $op = 1;
  948. else $op = rand(0, 1);
  949. if ($op) {
  950. $suma = $a + $b;
  951. $string = "{$a} + {$b}";
  952. } else {
  953. if ($a < $b) {
  954. $suma = $b - $a;
  955. $string = "{$b} - {$a}";
  956. } else {
  957. $suma = $a - $b;
  958. $string = "{$a} - {$b}";
  959. }
  960. }
  961. $string .= " = ";
  962. $_SESSION['_BiAuditGenerate_ctrl'] = base64_encode(gzcompress($suma));
  963. $im = imagecreate((strlen($string) - 1) * 10, 24);
  964. $bg = imagecolorallocate($im, 255, 255, 255);
  965. $textcolor = imagecolorallocate($im, 0, 0, 0);
  966. imagestring($im, 5, 0, 0, $string, $textcolor);
  967. ob_start();
  968. imagepng($im);
  969. $image = ob_get_contents();
  970. ob_end_clean();
  971. /*
  972. $image = new Imagick();
  973. $draw = new ImagickDraw();
  974. $pixel = new ImagickPixel('white');
  975. $image->newImage(200, 24, $pixel);
  976. // $image->setFont("schema/WPS_Functions/mapserver_gml_to_png/map/fonts/Arial_Bold.ttf");
  977. // $image->newPseudoImage(100, 100, "label:\"{$a} {$op} {$b}\"");
  978. // $image->newPseudoImage(100, 100, "caption:Hello");
  979. $image->setImageFormat('png');
  980. $draw->setFillColor('black');
  981. // $draw->setFont('Arial');
  982. $draw->setFontSize(24);
  983. $image->annotateImage($draw, 0, 24, 0, $s);
  984. $image->trimImage(0);
  985. */
  986. $imageBase64 = base64_encode($image);
  987. //echo $imageBase64;
  988. ?>
  989. <div style="text-align: center;">
  990. <h2>Czy jesteś pewien, że chcesz usunąć<br/><b>wszystkie dane</b> z tabeli <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>?</h2><br/>
  991. <h3>Podaj wynik działania:</h3>
  992. <form method="post">
  993. <img src="data:image/png;base64,<?=$imageBase64?>" height="36px"/><input type="text" name="wynik" style="font-size: 24px; width: 50px;" pattern="^[0-9]{1,3}$" oninvalid="setCustomValidity('Nieprawidłowy format')" maxlength="3" autofocus required autocomplete="off"/><br/><br/>
  994. <?php
  995. if ($this->SOURCE['TABLE'] == 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'):
  996. ?>
  997. <h4><input type="checkbox" name="deleteFiles"/>&nbsp;&nbsp;Usuń również wszystkie pliki</h4><br/>
  998. <?php
  999. endif;
  1000. ?>
  1001. <button type="submit" class="btn btn-primary" name="action" value="doClearTable" style="width: 80px;">Tak</button>
  1002. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>">
  1003. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Anuluj</a>
  1004. </form>
  1005. </div>
  1006. <?php
  1007. }
  1008. private function clearTable() {
  1009. $this->clearTable_tables = [
  1010. 'BI_audit_ENERGA_PRACOWNICY' => 'pracowników',
  1011. 'BI_audit_ENERGA_PRACOWNICY_import' => 'pracowników (import)',
  1012. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => 'kontrahentów',
  1013. 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA' => 'raportów',
  1014. 'BI_audit_ENERGA_RUM_UMOWY' => 'umów',
  1015. 'BI_audit_ENERGA_FAKTURY' => 'faktur',
  1016. ];
  1017. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS'";
  1018. if (DB::getPDO()->fetchValue($query)) {
  1019. ?>
  1020. <div style="text-align: center;">
  1021. <h2>Nie można usunąć żadnych danych<br/>(wykryto uruchomione zadania)</h2><br/>
  1022. <a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  1023. </div>
  1024. <?php
  1025. return;
  1026. }
  1027. $action = V::get('action', '', $_POST);
  1028. switch ($action) {
  1029. case "doClearTable":
  1030. $this->clearTable_do();
  1031. break;
  1032. default: $this->clearTable_form();
  1033. }
  1034. }
  1035. private function benford_form($edit = false) {
  1036. if (!($valueField = V::get('_benfordValueField', '', $_GET))) throw new Exception ("Błąd konfiguracji UrlAction - brak parametru _benfordField (DANE )");
  1037. $groupField = V::get('_benfordGroupField', '', $_GET);
  1038. if (!($namespace = V::get('_fromNamespace', '', $_GET))) throw new Exception("Błąd formularza");
  1039. Lib::loadClass('FeatureAttrSelected');
  1040. $count = FeatureAttrSelected::getTotalSelected($namespace);
  1041. $selectedTable = FeatureAttrSelected::getAttributeTableName($namespace, User::getID());
  1042. $query = "select `t`.`ID`, `{$valueField}` from `{$this->SOURCE['TABLE']}` `t` join `{$selectedTable}` `s` on `t`.`ID` = `s`.`primaryKey` where `t`.`{$valueField}` != 0 order by `s`.`primaryKey`";
  1043. $values = [];
  1044. try {
  1045. $result = DB::getPDO()->fetchAll($query);
  1046. foreach ($result as $row) $values[$row['ID']] = $row[$valueField];
  1047. } catch (Exception $e) {
  1048. throw new Exception("Błąd zapytania SQL ({$e->getMessage()})");
  1049. }
  1050. if (!$values) throw new Exception("Nie wybrano żadnych obiektów lub wszystkie wybrane obiekty mają zerową wartość");
  1051. Lib::loadClass('Benford');
  1052. try {
  1053. $benfordObj = new Benford($values);
  1054. $benford = $benfordObj->getAllResult();
  1055. } catch (Exception $e) {
  1056. die($e->getMessage());
  1057. }
  1058. ?>
  1059. <div class="container" style="margin-top:20px">
  1060. <form method="post">
  1061. <legend>
  1062. Analiza rozkładu Benford'a
  1063. <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?></span>
  1064. </legend>
  1065. <div class="form-group">
  1066. <div class="col-sm-12">
  1067. <h5>Analiza na podstawie kolumny <?=$valueField?>. Liczba znalezionych obiektów z niezerową wartością: <?=count($values)?> (wybrano obiektów: <?=$count?>)</h5>
  1068. </div>
  1069. </div>
  1070. <?php if($edit):?>
  1071. <div class="form-group">
  1072. <div class="col-sm-12">
  1073. <center>
  1074. <h3>Generowanie raportu analizy rozkładu Benford'a</h3>
  1075. <table>
  1076. <tr>
  1077. <td>
  1078. <select name="stage" class="form-control" onChange="toggleStage(this)">
  1079. <option value="first" selected>Pierwszy stopień analizy</option>
  1080. <option value="second">Drugi stopień analizy</option>
  1081. </select>
  1082. </td>
  1083. <td>&nbsp;&nbsp;</td>
  1084. <td><input type="text" class="form-control" name="L_APPOITMENT_INFO" title="Tytuł raportu" placeholder="Tytuł raportu" required/ size="50"></td>
  1085. <td>&nbsp;&nbsp;</td>
  1086. <td><button type="submit" class="btn btn-primary" name="action" value="generate" style="width: 80px;">Generuj</button></td>
  1087. </tr>
  1088. </table>
  1089. </center>
  1090. <br/><br/>
  1091. </div>
  1092. </div>
  1093. <?php endif;?>
  1094. <div class="form-group" id="benford">
  1095. <div class="col-sm-offset-2 col-sm-8">
  1096. <table class="table table-bordered table-hover table-striped table-condensed" id="benford">
  1097. <thead style="text-align:center; font-weight:bold; background-color:lightgray">
  1098. <tr>
  1099. <td style="vertical-align:middle;" rowspan="2">Pierwsze cyfry</td>
  1100. <td style="vertical-align:middle;" rowspan="2">Stopień analizy</td>
  1101. <td style="vertical-align:middle;" rowspan="2">Liczba wystąpień</td>
  1102. <td style="vertical-align:middle;" rowspan="2">Procent występowania</td>
  1103. <td colspan="3">Rozkład Benford'a</td>
  1104. <td style="vertical-align:middle;" rowspan="2">Szczegóły</td>
  1105. <?php if($edit):?>
  1106. <td style="vertical-align:middle;" rowspan="2">Załącz obiekty<br/>do&nbsp;raportu</td>
  1107. <?php endif;?>
  1108. </tr>
  1109. <tr>
  1110. <td nowrap>Norma (%)</td>
  1111. <td nowrap>Odchylenie od&nbsp;normy (%)</td>
  1112. <td>Zgodność</td>
  1113. </tr>
  1114. </thead>
  1115. <tbody>
  1116. <?php
  1117. $number_format = function($n) {
  1118. return number_format($n, 3, ',', '');
  1119. };
  1120. $genShowDetails = function($a, $groupField) {
  1121. try {
  1122. if (!$groupField) throw new Exception("Brak konfiguracji kolumny grupującej");
  1123. $tempTable = uniqid('_temp_benford_ids_');
  1124. DB::getPDO()->query("create temporary table `{$tempTable}` (`ID` int(11) NOT NULL, UNIQUE KEY `ID` (`ID`))");
  1125. foreach (array_chunk($a, 100) as $ids) {
  1126. DB::getPDO()->query("insert into `{$tempTable}` values (" . implode('),(', $ids) . ")");
  1127. }
  1128. $query = "select `table`.`{$groupField}` as `field`, count(*) as `count` from `{$this->SOURCE['TABLE']}` `table` join `{$tempTable}` `temp` on `table`.`ID` = `temp`.`ID` where coalesce(`table`.`{$groupField}`,'') != '' group by `table`.`{$groupField}` having `count` > 1 order by `count` desc limit 10";
  1129. try {
  1130. $result = DB::getPDO()->fetchAll($query);
  1131. } catch (Exception $e) {
  1132. throw new Exception("Nieznany błąd, prawdopodobnie błędna konfiguracja kolumny grupującej");
  1133. }
  1134. $showDetails = "<h4>Najczęściej występujące wartości kolumny {$groupField}</h4>";
  1135. if ($result) {
  1136. $showDetails .= "<table class=\"table table-bordered table-hover table-striped table-condensed\"><thead><tr style=\"font-weight:bold;\"><td>Wartość</td><td>Liczba wystąpień</td></tr></thead><tbody>";
  1137. $showDetails .= implode('', array_map(function($v) {
  1138. return "<tr><td>{$v['field']}</td><td>{$v['count']}</td></tr>";
  1139. }, $result));
  1140. $showDetails .= "</tbody></table>";
  1141. } else {
  1142. $showDetails .= "<h5>Żadna wartość nie występuje wiele razy</h5>";
  1143. }
  1144. } catch (Exception $e) {
  1145. $showDetails = $e->getMessage();
  1146. }
  1147. $showDetails .= '<button type="submit" class="btn btn-primary btn-sm" onClick="hideAlert()">Zamknij</button>';
  1148. return htmlentities($showDetails);
  1149. };
  1150. for ($ka = 1; $ka < 10; $ka++) {
  1151. if (!isset($benford['firstStage'][$ka])) $benford['firstStage'][$ka] = ['count' => 0, 'value' => 0, 'correct' => true];
  1152. $va = $benford['firstStage'][$ka];
  1153. $odchylenie = round(($va['value'] / Benford::benford($ka) - 1) * 100, 3);
  1154. if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
  1155. else $odchylenie = $number_format($odchylenie);
  1156. if (!$va['correct']) $showDetails = $genShowDetails($va['keys'], $groupField);
  1157. ?>
  1158. <tr style="text-align:center; font-weight:bold;<?=$va['correct'] ? '' : ' cursor:pointer;'?>"<?=$va['correct'] ? '' : ' onClick="toggleSecondStage(' . $ka . ');"'?>>
  1159. <td style="text-align:left" class="stage1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$ka?></td>
  1160. <td class="stage1-<?=$va['correct'] ? 'green' : 'red'?>">I</td>
  1161. <td style="text-align:right" class="stage1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$va['count']?></td>
  1162. <td style="text-align:right" class="stage1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round($va['value'] * 100, 3))?></td>
  1163. <td style="text-align:right" class="stage1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round(Benford::benford($ka) * 100, 3))?></td>
  1164. <td style="text-align:right" class="stage1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
  1165. <td <?=$va['correct'] ? 'class="stage1-green">Tak' : 'class="stage1-red" name="firstStageDesc" data-ka="' . $ka . '" nowrap>Nie (rozwiń)'?></td>
  1166. <td<?=$va['correct'] ? '>' : ' onClick="showAlert(\''. $showDetails .'\')"><span class="glyphicon glyphicon-search"></span>'?></td>
  1167. <?php if($edit):?>
  1168. <td<?=$va['correct'] ? '' : ' onClick="_click(\'checkFirstStage_' . $ka . '\')"'?>><input type="checkbox" <?=$va['correct'] ? 'disabled' : 'checked id="checkFirstStage_' . $ka . '" name="checkFirstStage[]" value="' . $ka . '" onClick="toggleCheckFirst(this)"'?>></td>
  1169. <?php endif;?>
  1170. </tr>
  1171. <?php
  1172. if (!$va['correct']) {
  1173. for ($kb = 0; $kb < 10; $kb++) {
  1174. if (!isset($benford['secondStage'][$ka][$kb])) $benford['secondStage'][$ka][$kb] = ['count' => 0, 'value' => 0, 'correct' => true];
  1175. $vb = $benford['secondStage'][$ka][$kb];
  1176. $odchylenie = round(($vb['value'] / Benford::benford($ka * 10 + $kb) - 1) * 100, 3);
  1177. if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
  1178. else $odchylenie = $number_format($odchylenie);
  1179. if (!$vb['correct']) $showDetails = $genShowDetails($vb['keys'], $groupField);
  1180. ?>
  1181. <tr style="text-align:center;" name="secondStage" data-ka="<?=$ka?>" hidden>
  1182. <td style="text-align:left" class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$ka . $kb?></td>
  1183. <td class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>">II</td>
  1184. <td style="text-align:right" class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['count']?></td>
  1185. <td style="text-align:right" class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round($vb['value'] * 100, 3))?></td>
  1186. <td style="text-align:right" class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round(Benford::benford($ka * 10 + $kb) * 100, 3))?></td>
  1187. <td style="text-align:right" class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
  1188. <td class="stage2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['correct'] ? 'Tak' : 'Nie'?></td>
  1189. <td<?=$vb['correct'] ? '>' : ' style="cursor:pointer;" onClick="showAlert(\''. $showDetails .'\')"><span class="glyphicon glyphicon-search"></span>'?></td>
  1190. <?php if($edit):?>
  1191. <td<?=$vb['correct'] ? '' : ' style="cursor:pointer;" onClick="_click(\'checkSecondStage_' . $ka . $kb . '\')"'?>><input type="checkbox"<?=$vb['correct'] ?: ' checked id="checkSecondStage_' . $ka . $kb . '" name="checkSecondStage[]" value="' . $ka . $kb . '" onClick="toggleCheckSecond(this)"'?> disabled></td>
  1192. <?php endif;?>
  1193. </tr>
  1194. <?php
  1195. }
  1196. }
  1197. }
  1198. ?>
  1199. </tbody>
  1200. </table>
  1201. </div>
  1202. </div>
  1203. </form>
  1204. </div>
  1205. <div id="alert">
  1206. <div id="alertMsg"></div>
  1207. </div>
  1208. <style type="text/css">
  1209. <!--
  1210. #benford .stage1-green,#benford .stage1-red {font-weight:bold;}
  1211. #benford .stage1-green,#benford .stage2-green {color:#008800;}
  1212. #benford .stage1-red,#benford .stage2-red {color:#ff0000;}
  1213. #benford table { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;}
  1214. td {font-size: 12px;}
  1215. #benford ::selection {background: transparent;}
  1216. #alert {display:none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; text-align: center; z-index: 1000; background-color: rgba(0,0,0,0.5);}
  1217. #alert div {width: 500px; height: auto; margin: 200px auto; background: #fff; padding: 10px; text-align: center; overflow: hidden;}
  1218. -->
  1219. </style>
  1220. <script src="static/sweetalert2.min.js"></script>
  1221. <script language="JavaScript">
  1222. <!--
  1223. function showAlert(s) {
  1224. event.stopPropagation();
  1225. document.getElementById('alertMsg').innerHTML = s;
  1226. document.getElementById('alert').style.display = 'block';
  1227. }
  1228. function hideAlert() {
  1229. document.getElementById('alert').style.display = 'none';
  1230. }
  1231. function _click(id) {
  1232. event.stopPropagation();
  1233. document.getElementById(id).click();
  1234. }
  1235. function toggleSecondStage(ka) {
  1236. var rows = document.getElementsByName('secondStage');
  1237. var hidden = false;
  1238. for(var i = 0, n = rows.length; i < n; i++) {
  1239. if (rows[i].dataset.ka == ka) {
  1240. rows[i].hidden = !rows[i].hidden;
  1241. hidden = rows[i].hidden;
  1242. }
  1243. }
  1244. var descs = document.getElementsByName('firstStageDesc');
  1245. for(var i = 0, n = descs.length; i < n; i++) {
  1246. if (descs[i].dataset.ka == ka) {
  1247. descs[i].innerHTML = (hidden ? 'Nie (rozwiń)' : 'Nie (zwiń)');
  1248. }
  1249. }
  1250. }
  1251. function toggleStage(option) {
  1252. if (option.value == 'first') first = true;
  1253. else if (option.value == 'second') first = false;
  1254. else {
  1255. alert('Wystąpił nieznany błąd formularza');
  1256. return;
  1257. }
  1258. var checks = document.getElementsByName('checkSecondStage[]');
  1259. var all = [];
  1260. for(var i = 0, n = checks.length; i < n; i++) {
  1261. checks[i].disabled = first;
  1262. ka = checks[i].value / 10 | 0;
  1263. if (all[ka] === 'undefined') all[ka] = checks[i].checked;
  1264. else if (checks[i].checked) all[ka] = true;
  1265. }
  1266. var checks = document.getElementsByName('checkFirstStage[]');
  1267. for(var i = 0, n = checks.length; i < n; i++) {
  1268. checks[i].disabled = !(first);
  1269. if (checks[i].checked != all[checks[i].value]) {
  1270. checks[i].checked = all[checks[i].value];
  1271. toggleCheckFirst(checks[i]);
  1272. }
  1273. }
  1274. var descs = document.getElementsByName('firstStageDesc');
  1275. for(var i = 0, n = descs.length; i < n; i++) {
  1276. descs[i].innerHTML = (first ? 'Nie (rozwiń)' : 'Nie (zwiń)');
  1277. }
  1278. var rows = document.getElementsByName('secondStage');
  1279. for(var i = 0, n = rows.length; i < n; i++) {
  1280. rows[i].hidden = first;
  1281. }
  1282. }
  1283. function toggleCheckFirst(check) {
  1284. event.stopPropagation();
  1285. var checks = document.getElementsByName('checkSecondStage[]');
  1286. for(var i = 0, n = checks.length; i < n; i++) {
  1287. if ((checks[i].value / 10 | 0) == check.value) checks[i].checked = check.checked;
  1288. }
  1289. }
  1290. function toggleCheckSecond(check) {
  1291. event.stopPropagation();
  1292. var checks = document.getElementsByName('checkSecondStage[]');
  1293. var all = true;
  1294. var ka = check.value / 10 | 0;
  1295. for(var i = 0, n = checks.length; i < n; i++) {
  1296. if ((checks[i].value / 10 | 0) == ka) {
  1297. if (!checks[i].checked) {
  1298. all = false;
  1299. break;
  1300. }
  1301. }
  1302. }
  1303. var checks = document.getElementsByName('checkFirstStage[]');
  1304. for(var i = 0, n = checks.length; i < n; i++) {
  1305. if (checks[i].value == ka) {
  1306. checks[i].checked = all;
  1307. break;
  1308. }
  1309. }
  1310. }
  1311. -->
  1312. </script>
  1313. <?php
  1314. }
  1315. private function benford_generate() {
  1316. SE_Layout::alert('warning', 'Not implemented yet');
  1317. ?>
  1318. <br><br>
  1319. <div style="text-align:center">
  1320. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Powrót</a>
  1321. </div>
  1322. <?php
  1323. }
  1324. private function benford() {
  1325. try {
  1326. $action = V::get('action', '', $_POST);
  1327. switch ($action) {
  1328. case "generate":
  1329. $this->benford_generate();
  1330. break;
  1331. default:
  1332. $this->benford_form(true);
  1333. }
  1334. } catch (Exception $e) {
  1335. SE_Layout::alert('danger', $e->getMessage());
  1336. }
  1337. }
  1338. public function defaultAction() {
  1339. SE_Layout::gora();
  1340. SE_Layout::menu();
  1341. if (isset($_SESSION['REFERER'])) {
  1342. $this->REFERER = $_SESSION['REFERER'];
  1343. unset($_SESSION['REFERER']);
  1344. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  1345. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  1346. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  1347. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  1348. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1349. elseif (($ID = V::get('ID_BI_audit_MSIG', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_MSIG';
  1350. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  1351. if ($this->SOURCE) {
  1352. $this->SOURCE['ID'] = $ID;
  1353. $this->powiazania();
  1354. }
  1355. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  1356. $this->SOURCE['TABLE'] = ACL::getAclByTypeName($TABLE)->getRootTableName();
  1357. $_subUrlAction = V::get('_subUrlAction', '', $_GET);
  1358. switch ($this->SOURCE['TABLE']) {
  1359. case "BI_audit_ENERGA_PRACOWNICY":
  1360. switch ($_subUrlAction) {
  1361. case "clearTable":
  1362. $this->clearTable();
  1363. break;
  1364. case "importFromKRS":
  1365. $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1366. $this->importToPracownicy();
  1367. break;
  1368. default: SE_Layout::alert('danger', 'Błąd parametru #21');
  1369. }
  1370. break;
  1371. case "BI_audit_ENERGA_PRACOWNICY_import":
  1372. switch ($_subUrlAction) {
  1373. case "clearTable":
  1374. $this->clearTable();
  1375. break;
  1376. default: SE_Layout::alert('danger', 'Błąd parametru #22');
  1377. }
  1378. break;
  1379. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  1380. switch ($_subUrlAction) {
  1381. case "clearTable":
  1382. $this->clearTable();
  1383. break;
  1384. default: SE_Layout::alert('danger', 'Błąd parametru #23');
  1385. }
  1386. break;
  1387. case "BI_audit_ENERGA_RUM_UMOWY":
  1388. switch ($_subUrlAction) {
  1389. case "clearTable":
  1390. $this->clearTable();
  1391. break;
  1392. case "benford":
  1393. $this->benford();
  1394. break;
  1395. default: SE_Layout::alert('danger', 'Błąd parametru #24');
  1396. }
  1397. break;
  1398. case "BI_audit_ENERGA_FAKTURY":
  1399. switch ($_subUrlAction) {
  1400. case "clearTable":
  1401. $this->clearTable();
  1402. break;
  1403. case "benford":
  1404. $this->benford();
  1405. break;
  1406. default: SE_Layout::alert('danger', 'Błąd parametru #25');
  1407. }
  1408. break;
  1409. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  1410. switch ($_subUrlAction) {
  1411. case "clearTable":
  1412. $this->clearTable();
  1413. break;
  1414. default: SE_Layout::alert('danger', 'Błąd parametru #25');
  1415. }
  1416. break;
  1417. default:
  1418. switch ($_subUrlAction) {
  1419. case "benford":
  1420. $this->benford();
  1421. break;
  1422. default: SE_Layout::alert('danger', 'Błąd parametru #1');
  1423. }
  1424. }
  1425. }
  1426. else SE_Layout::alert('danger', 'Błąd parametru #0');
  1427. echo "<br/><br/>";
  1428. SE_Layout::dol();
  1429. }
  1430. private static function truncatePowiazaniaFromDB($ID) {
  1431. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1432. if (!$refTables) return null;
  1433. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1434. $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
  1435. $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  1436. foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1437. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1438. DB::getPDO()->query($query);
  1439. }
  1440. private static function deleteResultsFromDB($ID) {
  1441. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1442. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  1443. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1444. $sqlDeleteFrom = "delete from
  1445. `{$refPowiazaniaToPowiazaniaRow}`,
  1446. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  1447. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  1448. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  1449. $sqlUsing = "
  1450. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  1451. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  1452. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  1453. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  1454. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  1455. $sqlWhere = "
  1456. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1457. foreach ($refTables as $refTable) {
  1458. $sqlDeleteFrom .= ",\n`{$refTable}`";
  1459. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1460. }
  1461. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  1462. DB::getPDO()->query($query);
  1463. }
  1464. public function doGenerate() {
  1465. $generatePhpScript = function($function) {
  1466. return '<?php
  1467. ini_set("memory_limit", "4G");
  1468. define("DS", DIRECTORY_SEPARATOR);
  1469. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  1470. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  1471. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  1472. ini_set("display_startup_errors", "0");
  1473. ini_set("display_errors", "1");
  1474. ini_set("log_errors", "1");
  1475. ini_set("error_log", "/var/log/apache2/error_log");
  1476. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  1477. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  1478. date_default_timezone_set("Europe/Warsaw");
  1479. Lib::loadClass("Router");
  1480. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  1481. ';
  1482. };
  1483. try {
  1484. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  1485. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  1486. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  1487. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  1488. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  1489. ### Ustawienie zmiennych
  1490. $powiazaniaDirLocation = self::getMainDirectory();
  1491. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1492. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  1493. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1494. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1495. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  1496. ### Utworzenie niezbędnych katalogów i plików
  1497. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
  1498. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  1499. ### Wyłączenie wcześniej używanego mechanizmu wymuszania częściowego (oraz pełnego od 2018-04-19) odświeżania cache - teraz działa to z automatu
  1500. $sqlArr = [
  1501. 'BI_analiza_reloadCache' => 'No',
  1502. ];
  1503. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part', 'Full') and FILE_STATUS = 'TO_GENERATE'";
  1504. $result = DB::getPDO()->fetchAll($query);
  1505. foreach ($result as $row) {
  1506. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1507. }
  1508. /* 2018-04-19 - zmieniono działanie silnika tak, aby sam wykrywał czy należy wykonać pełne odświeżenie cache
  1509. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  1510. $doGenerate = true;
  1511. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
  1512. $result = DB::getPDO()->fetchAll($query);
  1513. if ($result) {
  1514. $doGenerate = false;
  1515. $sqlArr = [];
  1516. if (file_exists($reloadCachePhpFile)) {
  1517. if (file_exists($reloadCacheResultFile)) {
  1518. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  1519. if ($reloadCacheResult == "ok") {
  1520. $sqlArr = [
  1521. 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
  1522. 'BI_analiza_reloadCache' => 'No',
  1523. ];
  1524. $doGenerate = true;
  1525. } else {
  1526. $sqlArr = [
  1527. 'FILE_STATUS' => 'ERROR',
  1528. 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
  1529. ];
  1530. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1531. $result = DB::getPDO()->fetchAll($query);
  1532. }
  1533. unlink($reloadCachePhpFile);
  1534. unlink($reloadCachePidFile);
  1535. unlink($reloadCacheResultFile);
  1536. } elseif (file_exists($reloadCachePidFile)) {
  1537. $pid = file_get_contents($reloadCachePidFile);
  1538. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1539. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  1540. if ($processRunning != $processShouldBeRunning) {
  1541. if (!file_exists($reloadCacheResultFile)) {
  1542. $sqlArr = [
  1543. 'FILE_STATUS' => 'ERROR',
  1544. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
  1545. ];
  1546. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1547. $result = DB::getPDO()->fetchAll($query);
  1548. unlink($reloadCachePhpFile);
  1549. unlink($reloadCachePidFile);
  1550. unlink($reloadCacheResultFile);
  1551. }
  1552. }
  1553. }
  1554. } else {
  1555. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1556. $result2 = DB::getPDO()->fetchValue($query);
  1557. if ($result2) {
  1558. $sqlArr = [
  1559. 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1560. ];
  1561. } else {
  1562. $sqlArr = [
  1563. 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
  1564. ];
  1565. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1566. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1567. file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
  1568. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1569. }
  1570. }
  1571. if ($sqlArr) {
  1572. foreach ($result as $row) {
  1573. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1574. }
  1575. }
  1576. }
  1577. */ $doGenerate = true;
  1578. ### Generowanie powiązań
  1579. if ($doGenerate) {
  1580. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1581. $result = DB::getPDO()->fetchAll($query);
  1582. foreach ($result as $row) {
  1583. $sqlArr = [
  1584. 'ID' => $row['ID'],
  1585. 'FILE_STATUS' => 'IN_PROGRESS',
  1586. 'FILE_STATUS_info' => 'Zadanie wyzwolone',
  1587. ];
  1588. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1589. self::deleteResultsFromDB($row['ID']);
  1590. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1591. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1592. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1593. $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
  1594. if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
  1595. if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
  1596. file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1597. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1598. }
  1599. }
  1600. ### Weryfikacja świeżo wygenerowanych powiązań
  1601. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1602. $result = DB::getPDO()->fetchAll($query);
  1603. foreach ($result as $row) {
  1604. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1605. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1606. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1607. $error = false;
  1608. $success = false;
  1609. $sqlArr = [];
  1610. if (file_exists($generatePowiazaniaResultFile)) {
  1611. $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
  1612. if ($generatePowiazaniaResult['result'] == "ok") {
  1613. $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1614. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
  1615. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1616. else $success = true;
  1617. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
  1618. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1619. $pid = file_get_contents($generatePowiazaniaPidFile);
  1620. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1621. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1622. if ($processRunning != $processShouldBeRunning) {
  1623. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1624. }
  1625. }
  1626. if ($error) {
  1627. $sqlArr = [
  1628. 'FILE_STATUS' => 'ERROR',
  1629. 'FILE_STATUS_info' => $error,
  1630. ];
  1631. //self::deleteResultsFromDB($row['ID']);
  1632. //if (file_exists($xmlFile)) unlink($xmlFile);
  1633. } elseif ($success) {
  1634. $sqlArr = [
  1635. 'FILE_STATUS' => 'GENERATED',
  1636. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1637. ];
  1638. if ($generatePowiazaniaResult['parts']) {
  1639. for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
  1640. $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
  1641. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
  1642. $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
  1643. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1644. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1645. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1646. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
  1647. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
  1648. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
  1649. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
  1650. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1651. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1652. if (file_exists($generatePowiazaniaHtmlDir)) {
  1653. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1654. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1655. }
  1656. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1657. }
  1658. } else {
  1659. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
  1660. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1661. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1662. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1663. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
  1664. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
  1665. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
  1666. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
  1667. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1668. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1669. if (file_exists($generatePowiazaniaHtmlDir)) {
  1670. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1671. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1672. }
  1673. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1674. }
  1675. }
  1676. if ($sqlArr) {
  1677. $sqlArr['ID'] = $row['ID'];
  1678. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1679. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  1680. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  1681. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  1682. }
  1683. }
  1684. } catch (Exception $e) {
  1685. echo $e->getMessage()."\n";
  1686. }
  1687. }
  1688. private static function importPracownicy($full = false) {
  1689. $fields = [
  1690. 'BI_audit_ENERGA_PRACOWNICY' => [
  1691. 'imiona' => 'imiona',
  1692. 'nazwisko' => 'nazwisko',
  1693. 'pesel' => 'pesel',
  1694. 'jednostka_organizacyjna' => 'jednostka_organizacyjna',
  1695. 'GUID' => 'GUID',
  1696. ],
  1697. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  1698. 'kodPocztowy' => 'kodPocztowy',
  1699. 'miejscowosc' => 'miejscowosc',
  1700. 'ulica' => 'ulica',
  1701. 'nrBudynku' => 'nr',
  1702. 'nrLokalu' => 'nrLokalu',
  1703. ],
  1704. ];
  1705. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', true);
  1706. if ($full) DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'");
  1707. DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `pesel` = null where `A_STATUS` = 'WAITING' and isPesel(`pesel`) = 0");
  1708. $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `A_STATUS` = 'WAITING'";
  1709. $pracownicy = DB::getPDO()->query($query);
  1710. while ($pracownik = $pracownicy->fetch()) {
  1711. if ($pracownik['pesel']) {
  1712. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}' or (coalesce(`pesel`, '') = '' and `GUID` = '{$pracownik['GUID']}')");
  1713. } elseif ($pracownik['GUID']) {
  1714. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `GUID` = '{$pracownik['GUID']}'");
  1715. } else {
  1716. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
  1717. continue;
  1718. }
  1719. $sqlArr = [];
  1720. $sqlArr['source'] = 'import';
  1721. $sqlArr['cached'] = '0';
  1722. foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $tableField => $importField) {
  1723. $sqlArr[$tableField] = trim($pracownik[$importField]);
  1724. if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
  1725. }
  1726. if ($ID_pracownik) {
  1727. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID_pracownik, $sqlArr);
  1728. $full = true;
  1729. }
  1730. else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
  1731. $sqlArr = [];
  1732. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
  1733. $sqlArr[$tableField] = trim($pracownik[$importField]);
  1734. if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
  1735. }
  1736. if (!$sqlArr) {
  1737. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
  1738. continue;
  1739. }
  1740. $sqlWhereArr = [];
  1741. $sqlWhereArr[] = "`{$refTable}`.`PRIMARY_KEY` = '{$ID_pracownik}'";
  1742. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
  1743. if (isset($sqlArr[$tableField])) $sqlWhereArr[] = "`BI_audit_ENERGA_PRACOWNICY_adresy`.`{$tableField}` = " . DB::getPDO()->quote($sqlArr[$tableField]);
  1744. else $sqlWhereArr[] = "`{$tableField}` is null";
  1745. }
  1746. $query = "select count(*) from `{$refTable}` join `BI_audit_ENERGA_PRACOWNICY_adresy` on `{$refTable}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_PRACOWNICY_adresy`.`ID` where " . implode(' and ', $sqlWhereArr);
  1747. if (!(DB::getPDO()->fetchValue($query))) {
  1748. $ID_adres = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_adresy', $sqlArr);
  1749. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $ID_pracownik, 'REMOTE_PRIMARY_KEY' => $ID_adres]);
  1750. }
  1751. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'NORMAL']);
  1752. }
  1753. return $full;
  1754. }
  1755. private static function reloadCache_parseFakturyUmowy($full = false) {
  1756. $fields = [
  1757. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  1758. 'Tytul_dokumentu',
  1759. 'Pelna_nazwa_kontrahenta',
  1760. 'NIP',
  1761. 'REGON',
  1762. 'KRS',
  1763. 'Kraj',
  1764. 'Kod_pocztowy',
  1765. 'Miejscowosc',
  1766. 'Ulica',
  1767. 'Numer_budynku',
  1768. 'Numer_mieszkania_lokalu',
  1769. 'TERYT_SYM',
  1770. 'TERYT_SYM_UL',
  1771. ],
  1772. 'BI_audit_KRS' => [
  1773. '"Zaimportowano z KRS na podstawie faktury/umowy"',
  1774. 'nazwa',
  1775. 'nip',
  1776. 'regon',
  1777. 'krs',
  1778. 'A_kraj',
  1779. 'A_kod',
  1780. 'A_miejscowosc',
  1781. 'A_ulica',
  1782. 'A_nrDomu',
  1783. 'A_nrLokalu',
  1784. 'TERYT_SYM',
  1785. 'TERYT_SYM_UL',
  1786. ],
  1787. 'BI_audit_CEIDG' => [
  1788. '"Zaimportowano z CEiDG na podstawie faktury/umowy"',
  1789. 'firma',
  1790. 'nip',
  1791. 'regon',
  1792. 'null',
  1793. 'kraj',
  1794. 'kodPocztowy',
  1795. 'miejscowosc',
  1796. 'ulica',
  1797. 'budynek',
  1798. 'lokal',
  1799. 'TERYT_SYM',
  1800. 'TERYT_SYM_UL',
  1801. ],
  1802. ];
  1803. $refTableFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1804. $refTableUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1805. if ($full) {
  1806. DB::getPDO()->query("truncate table `{$refTableFakturyToKontrahenci}`");
  1807. DB::getPDO()->query("truncate table `{$refTableUmowyToKontrahenci}`");
  1808. DB::getPDO()->query("update `BI_audit_ENERGA_FAKTURY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1809. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  1810. }
  1811. $query = "select `ID`, `NIP` from `BI_audit_ENERGA_FAKTURY` where `A_STATUS` = 'WAITING'";
  1812. $result = DB::getPDO()->fetchAll($query);
  1813. foreach ($result as $row) {
  1814. $ID = $row['ID'];
  1815. $nip = trim($row['NIP']);
  1816. if (!$full) {
  1817. $query = "delete from `{$refTableFakturyToKontrahenci}` where PRIMARY_KEY = '{$row['ID']}'";
  1818. DB::getPDO()->query($query);
  1819. }
  1820. if (!$nip) {
  1821. DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'OFF_SOFT']);
  1822. continue;
  1823. }
  1824. $K_IDs = [];
  1825. $query = "select `ID` from `BI_audit_ENERGA_RUM_KONTRAHENCI` where `NIP` = '{$nip}'";
  1826. if ($result2 = DB::getPDO()->fetchall($query)) {
  1827. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1828. } else {
  1829. $query = "select ID from BI_audit_KRS where nip = '{$nip}' order by `ID` desc limit 1";
  1830. if ($result2 = DB::getPDO()->fetchall($query)) {
  1831. foreach ($result2 as $item) {
  1832. $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1833. " select " . implode(', ', $fields['BI_audit_KRS']) . " from `BI_audit_KRS` where `ID` = '{$item['ID']}'";
  1834. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1835. }
  1836. } else {
  1837. $query = "select `ID` from `BI_audit_CEIDG` where `nip` = '{$nip}' order by `ID` desc limit 1";
  1838. if ($result2 = DB::getPDO()->fetchall($query)) {
  1839. foreach ($result2 as $item) {
  1840. $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1841. " select " . implode(', ', $fields['BI_audit_CEIDG']) . " from `BI_audit_CEIDG` where `ID` = '{$item['ID']}'";
  1842. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1843. }
  1844. }
  1845. }
  1846. }
  1847. foreach ($K_IDs as $K_ID) {
  1848. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableFakturyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1849. DB::getPDO()->query("insert into `{$refTableFakturyToKontrahenci}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`) values ({$ID}, {$K_ID})");
  1850. }
  1851. }
  1852. DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1853. }
  1854. $query = <<<SQL
  1855. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` = replace(
  1856. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`,
  1857. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`,
  1858. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`,
  1859. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`,
  1860. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` not in ('0', '0,1', ''), `Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, 0))))),
  1861. ',', '.') where `A_STATUS` = 'WAITING';
  1862. SQL;
  1863. DB::getPDO()->query($query);
  1864. $query = "select `ID`, `Kontrahenci` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  1865. $result = DB::getPDO()->fetchAll($query);
  1866. foreach ($result as $row) {
  1867. $ID = $row['ID'];
  1868. if (!$full) {
  1869. $query = "delete from `{$refTableUmowyToKontrahenci}` where PRIMARY_KEY = '{$ID}'";
  1870. DB::getPDO()->query($query);
  1871. }
  1872. $kontrahenci = array_map('trim', explode("|", $row['Kontrahenci']));
  1873. $K_IDs = [];
  1874. foreach ($kontrahenci as $item) {
  1875. $kontrahent = array_map('trim', explode(";", $item));
  1876. $nr = null;
  1877. if (count($kontrahent) == 3) $i = 1;//$nr = $kontrahent[1];
  1878. elseif (count($kontrahent) == 4) $i = 2;//$nr = $kontrahent[2];
  1879. elseif (count($kontrahent) >= 5 && count($kontrahent) <= 6) $i = 3;//$nr = $kontrahent[3];
  1880. else $i = null;
  1881. if ($i) $nr = $kontrahent[$i];
  1882. $notFound = false;
  1883. if (is_numeric($nr)) {
  1884. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}' and not (NIP is null and REGON is null and KRS is null)";
  1885. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  1886. $K_IDs[] = $K_ID;
  1887. } else {
  1888. $nazwa = $kontrahent[$i+1];
  1889. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "' and not (NIP is null and REGON is null and KRS is null)";
  1890. if ($result2 = DB::getPDO()->fetchAll($query)) {
  1891. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1892. } else $notFound = true;
  1893. }
  1894. } else $notFound = true;
  1895. if ($notFound) {
  1896. list($nip, $regon) = self::parseNipRegon($item);
  1897. if ($nip || $regon) {
  1898. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  1899. if ($result2 = DB::getPDO()->fetchall($query)) {
  1900. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  1901. } else {
  1902. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
  1903. if ($result2 = DB::getPDO()->fetchall($query)) {
  1904. foreach ($result2 as $item) {
  1905. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1906. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  1907. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1908. }
  1909. } else {
  1910. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
  1911. if ($result2 = DB::getPDO()->fetchall($query)) {
  1912. foreach ($result2 as $item) {
  1913. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  1914. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  1915. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  1916. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  1917. }
  1918. }
  1919. }
  1920. }
  1921. }
  1922. }
  1923. }
  1924. foreach ($K_IDs as $K_ID) {
  1925. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableUmowyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  1926. DB::getPDO()->query("insert into `{$refTableUmowyToKontrahenci}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  1927. }
  1928. }
  1929. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  1930. }
  1931. $query = "select ID, NIP, REGON, KRS from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null or KRS is null) and not (NIP is null and REGON is null and KRS is null) and `cached` = 0";
  1932. $result = DB::getPDO()->fetchAll($query);
  1933. foreach ($result as $row) {
  1934. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  1935. if ($items = DB::getPDO()->fetchAll($query)) {
  1936. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  1937. if (count($items) > 1) {
  1938. for ($i = 1; $i < count($items); $i++) {
  1939. if ($nip != $items[$i]["nip"]) $nip = null;
  1940. if ($regon != $items[$i]["regon"]) $regon = null;
  1941. if ($krs != $items[$i]["krs"]) $krs = null;
  1942. }
  1943. }
  1944. $set = [];
  1945. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1946. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1947. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  1948. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  1949. }
  1950. }
  1951. $query = "select ID, NIP, REGON from BI_audit_ENERGA_RUM_KONTRAHENCI where (NIP is null or REGON is null) and not (NIP is null and REGON is null) and `cached` = 0";
  1952. $result = DB::getPDO()->fetchAll($query);
  1953. foreach ($result as $row) {
  1954. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  1955. if ($items = DB::getPDO()->fetchAll($query)) {
  1956. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  1957. if (count($items) > 1) {
  1958. for ($i = 1; $i < count($items); $i++) {
  1959. if ($nip != $items[$i]["nip"]) $nip = null;
  1960. if ($regon != $items[$i]["regon"]) $regon = null;
  1961. }
  1962. }
  1963. $set = [];
  1964. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  1965. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  1966. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  1967. }
  1968. }
  1969. }
  1970. public static function reloadCache_reTeryt($full = false, $forceAll = false) {
  1971. Lib::loadClass('Teryt');
  1972. $tables = [
  1973. 'BI_audit_CEIDG' => [
  1974. 'fields' => [
  1975. 'wojewodztwo' => 'wojewodztwo',
  1976. 'powiat' => 'powiat',
  1977. 'gmina' => 'gmina',
  1978. 'miejscowosc' => 'miejscowosc',
  1979. 'ulica' => 'ulica',
  1980. 'kodPocztowy' => 'kodPocztowy',
  1981. ],
  1982. 'fieldsTeryt' => [
  1983. 'TERYT_SYM' => 'TERYT_SYM',
  1984. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  1985. 'nrDomu' => 'budynek',
  1986. 'nrLokalu' => 'lokal',
  1987. ],
  1988. 'base' => '1',
  1989. ],
  1990. 'BI_audit_CEIDG_pelnomocnicy' => [
  1991. 'fields' => [
  1992. 'wojewodztwo' => 'wojewodztwo',
  1993. 'powiat' => 'powiat',
  1994. 'gmina' => 'gmina',
  1995. 'miejscowosc' => 'miejscowosc',
  1996. 'ulica' => 'ulica',
  1997. 'kodPocztowy' => 'kodPocztowy',
  1998. ],
  1999. 'fieldsTeryt' => [
  2000. 'TERYT_SYM' => 'TERYT_SYM',
  2001. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2002. 'nrDomu' => 'budynek',
  2003. 'nrLokalu' => 'lokal',
  2004. ],
  2005. 'base' => '1',
  2006. ],
  2007. 'BI_audit_ENERGA_PRACOWNICY' => [
  2008. 'fields' => [
  2009. 'miejscowosc' => 'miejscowosc',
  2010. 'kodPocztowy' => 'kodPocztowy',
  2011. 'ulica' => 'ulica',
  2012. ],
  2013. 'fieldsTeryt' => [
  2014. 'TERYT_SYM' => 'TERYT_SYM',
  2015. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2016. 'nrDomu' => 'nr',
  2017. 'nrLokalu' => 'nrLokalu',
  2018. ],
  2019. 'base' => '0',
  2020. ],
  2021. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2022. 'fields' => [
  2023. 'kodPocztowy' => 'kodPocztowy',
  2024. 'miejscowosc' => 'miejscowosc',
  2025. 'ulica' => 'ulica',
  2026. ],
  2027. 'fieldsTeryt' => [
  2028. 'TERYT_SYM' => 'TERYT_SYM',
  2029. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2030. 'nrDomu' => 'nrBudynku',
  2031. 'nrLokalu' => 'nrLokalu',
  2032. ],
  2033. 'base' => '0',
  2034. ],
  2035. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2036. 'fields' => [
  2037. 'kodPocztowy' => 'Kod_pocztowy',
  2038. 'miejscowosc' => 'Miejscowosc',
  2039. 'ulica' => 'Ulica',
  2040. ],
  2041. 'fieldsTeryt' => [
  2042. 'TERYT_SYM' => 'TERYT_SYM',
  2043. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2044. 'nrDomu' => 'Numer_budynku',
  2045. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  2046. ],
  2047. 'base' => '0',
  2048. ],
  2049. 'BI_audit_KRS' => [
  2050. 'fields' => [
  2051. 'wojewodztwo' => 'S_wojewodztwo',
  2052. 'powiat' => 'S_powiat',
  2053. 'gmina' => 'S_gmina',
  2054. 'miejscowosc' => 'A_miejscowosc',
  2055. 'ulica' => 'A_ulica',
  2056. 'kodPocztowy' => 'A_kod',
  2057. ],
  2058. 'fieldsTeryt' => [
  2059. 'TERYT_SYM' => 'TERYT_SYM',
  2060. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2061. 'nrDomu' => 'A_nrDomu',
  2062. 'nrLokalu' => 'A_nrLokalu',
  2063. ],
  2064. 'base' => '1',
  2065. ],
  2066. 'BI_audit_KRS_address' => [
  2067. 'fields' => [
  2068. 'wojewodztwo' => 'S_wojewodztwo',
  2069. 'powiat' => 'S_powiat',
  2070. 'gmina' => 'S_gmina',
  2071. 'miejscowosc' => 'A_miejscowosc',
  2072. 'ulica' => 'A_ulica',
  2073. 'kodPocztowy' => 'A_kod',
  2074. ],
  2075. 'fieldsTeryt' => [
  2076. 'TERYT_SYM' => 'TERYT_SYM',
  2077. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2078. 'nrDomu' => 'A_nrDomu',
  2079. 'nrLokalu' => 'A_nrLokalu',
  2080. ],
  2081. 'base' => '1',
  2082. ],
  2083. 'BI_audit_MSIG_address' => [
  2084. 'fields' => [
  2085. 'wojewodztwo' => 'S_wojewodztwo',
  2086. 'powiat' => 'S_powiat',
  2087. 'gmina' => 'S_gmina',
  2088. 'miejscowosc' => 'A_miejscowosc',
  2089. 'ulica' => 'A_ulica',
  2090. 'kodPocztowy' => 'A_kod',
  2091. ],
  2092. 'fieldsTeryt' => [
  2093. 'TERYT_SYM' => 'TERYT_SYM',
  2094. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2095. 'nrDomu' => 'A_nrDomu',
  2096. 'nrLokalu' => 'A_nrLokalu',
  2097. ],
  2098. 'base' => '1',
  2099. ],
  2100. ];
  2101. foreach ($tables as $table => $tableConf) {
  2102. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
  2103. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
  2104. $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  2105. $query = "select * from `{$table}` {$where}";
  2106. $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
  2107. $terytJoinArr = [];
  2108. foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
  2109. $terytJoinArr[] = (
  2110. $terytField == 'nrLokalu'
  2111. ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
  2112. : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
  2113. );
  2114. }
  2115. $terytJoin = implode(" and ", $terytJoinArr);
  2116. $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
  2117. $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
  2118. //$adresy = DB::getPDO()->queryNotBuffered($query);
  2119. $adresy = DB::getPDO()->query($query);
  2120. while ($adres = $adresy->fetch()) {
  2121. DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
  2122. if (!($forceAll and $adres['TERYT_SYM'])) {
  2123. $search = [];
  2124. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  2125. try {
  2126. $teryt = Teryt::search($search);
  2127. } catch (Exception $e) {
  2128. continue;
  2129. }
  2130. if (empty($teryt['SYM'])) continue;
  2131. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  2132. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  2133. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  2134. }
  2135. if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
  2136. $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
  2137. if (!$terytID) {
  2138. if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
  2139. if (!($terytID = DB::getPDO()->lastInsertId())) {
  2140. throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
  2141. }
  2142. } else {
  2143. throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
  2144. }
  2145. }
  2146. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
  2147. }
  2148. }
  2149. }
  2150. private static function reloadCache_updateAll($full, $onlyBase) {
  2151. $tablesConf = [
  2152. 'BI_audit_CEIDG' => [
  2153. 'fields' => [
  2154. 'nip' => 'nip',
  2155. 'regon' => 'regon',
  2156. ],
  2157. 'base' => '1',
  2158. ],
  2159. 'BI_audit_CEIDG_pelnomocnicy' => [
  2160. 'fields' => [
  2161. 'nip' => 'nip',
  2162. ],
  2163. 'base' => '1',
  2164. ],
  2165. 'BI_audit_CEIDG_powiazania' => [
  2166. 'fields' => [
  2167. 'nip' => 'nip',
  2168. 'regon' => 'regon',
  2169. ],
  2170. 'base' => '1',
  2171. ],
  2172. 'BI_audit_ENERGA_PRACOWNICY' => [
  2173. 'fields' => [
  2174. 'nip' => 'nip',
  2175. 'regon' => 'regon',
  2176. 'pesel' => 'pesel',
  2177. 'krs' => 'krs',
  2178. ],
  2179. 'base' => '0',
  2180. //'where' => '',
  2181. ],
  2182. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2183. 'fields' => [],
  2184. 'base' => '0',
  2185. //'where' => '',
  2186. ],
  2187. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2188. 'fields' => [
  2189. 'krs' => 'KRS',
  2190. 'nip' => 'NIP',
  2191. 'regon' => 'REGON',
  2192. 'pesel' => 'PESEL',
  2193. ],
  2194. 'base' => '0',
  2195. 'where' => "and ownCompany != 'Y'",
  2196. ],
  2197. 'BI_audit_KRS' => [
  2198. 'fields' => [
  2199. 'krs' => 'krs',
  2200. 'nip' => 'nip',
  2201. 'regon' => 'regon',
  2202. ],
  2203. 'base' => '1',
  2204. ],
  2205. 'BI_audit_KRS_address' => [
  2206. 'fields' => [],
  2207. 'base' => '1',
  2208. ],
  2209. 'BI_audit_KRS_company' => [
  2210. 'fields' => [
  2211. 'regon' => 'regon',
  2212. 'krs' => 'krs',
  2213. ],
  2214. 'base' => '1',
  2215. ],
  2216. 'BI_audit_KRS_person' => [
  2217. 'fields' => [
  2218. 'pesel' => 'pesel',
  2219. ],
  2220. 'base' => '1',
  2221. ],
  2222. 'BI_audit_MSIG' => [
  2223. 'fields' => [
  2224. 'krs' => 'krs',
  2225. 'nip' => 'nip',
  2226. 'regon' => 'regon',
  2227. ],
  2228. 'base' => '1',
  2229. ],
  2230. 'BI_audit_MSIG_address' => [
  2231. 'fields' => [],
  2232. 'base' => '1',
  2233. ],
  2234. 'BI_audit_MSIG_company' => [
  2235. 'fields' => [
  2236. 'regon' => 'regon',
  2237. 'krs' => 'krs',
  2238. ],
  2239. 'base' => '1',
  2240. ],
  2241. 'BI_audit_MSIG_person' => [
  2242. 'fields' => [
  2243. 'pesel' => 'pesel',
  2244. ],
  2245. 'base' => '1',
  2246. ],
  2247. // 'BI_audit_KW_requested_person' => [
  2248. // 'fields' => [
  2249. // 'pesel' => 'Seller_person_pesel',
  2250. // 'krs' => 'Seller_person_KRS',
  2251. // 'nip' => 'Seller_person_NIP',
  2252. // 'regon' => 'Seller_person_REGON',
  2253. // ],
  2254. // 'base' => '0',
  2255. // //'where' => '',
  2256. // ],
  2257. 'TERYT_adresy' => [
  2258. 'fields' => [],
  2259. 'base' => '1',
  2260. ],
  2261. ];
  2262. $refTablesConf = [
  2263. 'BI_audit_CEIDG' => [
  2264. 'refTablesTo' => [
  2265. 'BI_audit_CEIDG_pelnomocnicy',
  2266. 'BI_audit_CEIDG_powiazania',
  2267. 'TERYT_adresy',
  2268. ],
  2269. 'base' => 1,
  2270. ],
  2271. 'BI_audit_CEIDG_pelnomocnicy' => [
  2272. 'refTablesTo' => [
  2273. 'TERYT_adresy',
  2274. ],
  2275. 'base' => 1,
  2276. ],
  2277. 'BI_audit_ENERGA_PRACOWNICY' => [
  2278. 'refTablesTo' => [
  2279. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  2280. //'TERYT_adresy',
  2281. ],
  2282. 'base' => 0,
  2283. ],
  2284. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2285. 'refTablesTo' => [
  2286. 'TERYT_adresy',
  2287. ],
  2288. 'base' => 0,
  2289. ],
  2290. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2291. 'refTablesTo' => [
  2292. 'TERYT_adresy',
  2293. ],
  2294. 'base' => 0,
  2295. ],
  2296. 'BI_audit_KRS' => [
  2297. 'refTablesTo' => [
  2298. 'BI_audit_KRS_address',
  2299. 'BI_audit_KRS_company',
  2300. 'BI_audit_KRS_person',
  2301. 'TERYT_adresy',
  2302. ],
  2303. 'base' => 1,
  2304. ],
  2305. 'BI_audit_KRS_address' => [
  2306. 'refTablesTo' => [
  2307. 'TERYT_adresy',
  2308. ],
  2309. 'base' => 1,
  2310. ],
  2311. 'BI_audit_MSIG' => [
  2312. 'refTablesTo' => [
  2313. 'BI_audit_MSIG_address',
  2314. 'BI_audit_MSIG_company',
  2315. 'BI_audit_MSIG_person',
  2316. ],
  2317. 'base' => 1,
  2318. ],
  2319. 'BI_audit_MSIG_address' => [
  2320. 'refTablesTo' => [
  2321. 'TERYT_adresy',
  2322. ],
  2323. 'base' => 1,
  2324. ],
  2325. ];
  2326. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  2327. if ($full) {
  2328. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  2329. $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
  2330. // $queries[] = "optimize table `BI_audit_ALL`";
  2331. $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
  2332. // $queries[] = "optimize table `BI_audit_ALL_ref`";
  2333. $allTables = [];
  2334. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  2335. $allTables[] = $refTableFrom;
  2336. // if ($refTableConf['base']) continue;
  2337. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  2338. $allTables[] = $refTableTo;
  2339. if ($refTableConf['base']) continue;
  2340. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  2341. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  2342. // $queries[] = "insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `all1`.`ID`, `all2`.`ID`, '-1', 'NORMAL' from `BI_audit_ALL` as `all1` join `BI_audit_ALL_ref` as `ref` on `all1`.`ID` = `ref`.`ID1` join `BI_audit_ALL` as `all2` on `ref`.`ID2` = `all2`.`ID` where `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all2`.`REMOTE_TABLE` = '{$refTableTo}'";
  2343. }
  2344. }
  2345. $allTables = array_unique($allTables);
  2346. foreach ($allTables as $refTableFrom) {
  2347. foreach ($allTables as $refTableTo) {
  2348. if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
  2349. $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
  2350. $queries[] = "optimize table `{$refTable}`";
  2351. $queries[] = "insert into `{$refTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `all1`.`REMOTE_ID`, `all2`.`REMOTE_ID`, '-1', 'NORMAL' from `BI_audit_ALL` as `all1` join `BI_audit_ALL_ref` as `ref` on `all1`.`ID` = `ref`.`ID1` join `BI_audit_ALL` as `all2` on `ref`.`ID2` = `all2`.`ID` left join `${refTable}` as `ref2` on `all1`.`REMOTE_ID` = `ref2`.`PRIMARY_KEY` and `all2`.`REMOTE_ID` = `ref2`.`REMOTE_PRIMARY_KEY` where `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref2`.`PRIMARY_KEY` is null";
  2352. }
  2353. }
  2354. }
  2355. }
  2356. foreach ($tablesConf as $table => $tableConf) {
  2357. if ($onlyBase && (!$tableConf['base'])) continue;
  2358. $where = "where `{$table}`.`cached` = 0";
  2359. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  2360. // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  2361. // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  2362. $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
  2363. $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
  2364. $updates = ["`BI_audit_ALL`.`reffed` = 0", "`{$table}`.`cached` = 1"];
  2365. foreach ($tableConf['fields'] as $field => $value) {
  2366. $fields[] = "`{$field}`";
  2367. $values[] = "`{$value}`";
  2368. $updates[] = "`BI_audit_ALL`.`{$field}` = `{$table}`.`{$value}`";
  2369. }
  2370. $queries[] = "update `BI_audit_ALL` join `{$table}` on `BI_audit_ALL`.`REMOTE_TABLE` = '{$table}' and `BI_audit_ALL`.`REMOTE_ID` = `{$table}`.`ID` set " . implode(", ", $updates) . " {$where}";
  2371. $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
  2372. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  2373. }
  2374. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  2375. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  2376. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  2377. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  2378. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  2379. $queries[] = "insert into `BI_audit_ALL_ref_RELATIONS` (`ID`, `RELATION`, `BASE`) select @var:=@var*2, `a`.`RELATION`, `a`.`BASE` from (select `a`.`REMOTE_TABLE` as `RELATION`, `a`.`BASE` as `BASE` from `BI_audit_ALL` `a` where `a`.`REMOTE_TABLE` not in ('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person') group by `a`.`REMOTE_TABLE` order by `a`.`BASE` desc) as `a` left join `BI_audit_ALL_ref_RELATIONS` `r` on `a`.`RELATION` = `r`.`RELATION` where `r`.`RELATION` is null";
  2380. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  2381. if ($onlyBase && (!$tableConf['base'])) continue;
  2382. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  2383. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  2384. $queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all1`.`ID`, `all2`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all1`.`REMOTE_TABLE` = `rel`.`RELATION`";
  2385. if (!in_array($refTableFrom, $sourceTables)) {
  2386. $queries[] = "insert into `BI_audit_ALL_ref` (`ID1`, `ID2`, `RELATION_ID`, `BASE`) select `all2`.`ID`, `all1`.`ID`, `rel`.`ID`, {$refTableConf['base']} from `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` join `BI_audit_ALL_ref_RELATIONS` `rel` on `all2`.`REMOTE_TABLE` = `rel`.`RELATION`";
  2387. }
  2388. if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
  2389. $queries[] = "insert into `{$backRefTable}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`, `TRANSACTION_ID`, `A_STATUS`) select `REMOTE_PRIMARY_KEY`, `PRIMARY_KEY`, '-1', 'NORMAL' from `{$refTable}` where `A_STATUS` = 'WAITING'";
  2390. }
  2391. $queries[] = "update `BI_audit_ALL` as `all1` join `{$refTable}` as `ref` on `all1`.`REMOTE_TABLE` = '{$refTableFrom}' and `all1`.`REMOTE_ID` = `ref`.`PRIMARY_KEY` and `ref`.`A_STATUS` = 'WAITING' join `BI_audit_ALL` as `all2` on `all2`.`REMOTE_TABLE` = '{$refTableTo}' and `ref`.`REMOTE_PRIMARY_KEY` = `all2`.`REMOTE_ID` set `ref`.`A_STATUS` = 'NORMAL'";
  2392. }
  2393. }
  2394. foreach ($queries as $query) {
  2395. echo "SQL: {$query}\n";
  2396. DB::getPDO()->query($query);
  2397. }
  2398. $BiAuditRelations = new BiAuditRelations();
  2399. //$result = DB::getPDO()->queryNotBuffered("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  2400. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  2401. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  2402. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  2403. }
  2404. public function doReloadCache($full = false) {
  2405. if ($full === 'base') {
  2406. $onlyBase = true;
  2407. $full = false;
  2408. } else {
  2409. $onlyBase = false;
  2410. }
  2411. $setFull = function() {
  2412. BiAuditPowiazania::saveToLog("Wykryto niespójność tabel - uruchamiam pełne odświeżenie cache");
  2413. $sqlArr = [
  2414. 'BI_analiza_reloadCache' => 'Full',
  2415. 'FILE_STATUS_info' => 'Odświeżam w pełni cache',
  2416. ];
  2417. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $this->POWIAZANIA_ID, $sqlArr);
  2418. };
  2419. if ($this->POWIAZANIA_ID && (!$full)) {
  2420. $checkTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', 'BI_audit_ENERGA_RUM_KONTRAHENCI'];
  2421. foreach ($checkTables as $table) {
  2422. $query = "select count(*) from `BI_audit_ALL` `all` left join `{$table}` `t` on `all`.`REMOTE_ID`=`t`.`ID` and `t`.`cached` = '1' where `all`.`REMOTE_TABLE`='{$table}' and `t`.`ID` is null";
  2423. if (DB::getPDO()->fetchValue($query)) {
  2424. $full = true;
  2425. $setFull();
  2426. break;
  2427. }
  2428. }
  2429. }
  2430. $powiazaniaDirLocation = self::getMainDirectory();
  2431. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2432. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  2433. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  2434. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCachePidFile, getmypid());
  2435. try {
  2436. error_log('now: self::importPracownicy');
  2437. $_full = self::importPracownicy($full);
  2438. if ((!$full) && $_full) {
  2439. $full = true;
  2440. if ($this->POWIAZANIA_ID) $setFull();
  2441. }
  2442. error_log('now: self::reloadCache_parseFakturyUmowy');
  2443. self::reloadCache_parseFakturyUmowy($full);
  2444. error_log('now: self::reloadCache_reTeryt');
  2445. self::reloadCache_reTeryt($full);
  2446. error_log('now: self::reloadCache_updateAll');
  2447. self::reloadCache_updateAll($full, $onlyBase);
  2448. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, "ok");
  2449. } catch (Exception $e) {
  2450. var_dump($e);
  2451. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, $e->getMessage());
  2452. else throw new Exception($e->getMessage());
  2453. }
  2454. }
  2455. public function doGeneratePowiazania($ID) {
  2456. $this->POWIAZANIA_ID = $ID;
  2457. $powiazaniaDirLocation = self::getMainDirectory();
  2458. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2459. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  2460. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  2461. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  2462. file_put_contents($pidFile, getmypid());
  2463. /* $tablesConf = [
  2464. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  2465. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  2466. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  2467. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  2468. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  2469. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  2470. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  2471. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  2472. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  2473. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  2474. ];*/
  2475. try {
  2476. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  2477. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS' and `BI_analiza_reloadCache` in ('Part', 'Full') and ID != ${ID}";
  2478. $sqlArr = [
  2479. 'BI_analiza_reloadCache' => 'Part',
  2480. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  2481. ];
  2482. do {
  2483. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  2484. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  2485. if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2486. DB::getPDO()->query("unlock tables");
  2487. if ($activeReloadingCache) {
  2488. BiAuditPowiazania::saveToLog("Czekam na zakończenie odświeżania cache przez inne zadanie");
  2489. sleep(30);
  2490. }
  2491. } while ($activeReloadingCache);
  2492. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  2493. $this->doReloadCache(); //DUPA testowe wylaczanie
  2494. BiAuditPowiazania::saveToLog("Odświeżono cache");
  2495. $sqlArr = [
  2496. 'BI_analiza_reloadCache' => 'No',
  2497. 'FILE_STATUS_info' => 'Szukam powiązań',
  2498. ];
  2499. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2500. $BiAuditPowiazania->run();
  2501. //if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  2502. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  2503. $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
  2504. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2505. //$BiAuditPowiazania->saveXml();
  2506. $BiAuditPowiazania->generatePdfAndHtml();
  2507. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  2508. } catch (Exception $e) {
  2509. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  2510. }
  2511. }
  2512. public function reinstallAction() {
  2513. $this->reinstall();
  2514. die('OK');
  2515. }
  2516. public function reinstall() {
  2517. $sqlList = array();
  2518. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  2519. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  2520. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  2521. SQL;
  2522. $sqlList['ChangeStructure1'] = <<<SQL
  2523. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Y','N','Full','Part','No') NOT NULL DEFAULT 'No';
  2524. SQL;
  2525. $sqlList['ChangeStructure2'] = <<<SQL
  2526. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  2527. SQL;
  2528. $sqlList['ChangeStructure3'] = <<<SQL
  2529. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  2530. SQL;
  2531. $sqlList['ChangeStructure4'] = <<<SQL
  2532. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  2533. SQL;
  2534. $sqlList['ChangeStructure5'] = <<<SQL
  2535. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  2536. SQL;
  2537. $sqlList['ChangeStructure6'] = <<<SQL
  2538. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  2539. SQL;
  2540. $db = DB::getDB();
  2541. if ($db->has_errors()) {
  2542. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  2543. }
  2544. foreach ($sqlList as $sqlName => $sql) {
  2545. $res = $db->query($sql);
  2546. if ($db->has_errors()) {
  2547. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  2548. }
  2549. }
  2550. }
  2551. }
  2552. class BiAuditRelations {
  2553. private $RELATIONS_ID = [];
  2554. private $relations = [
  2555. 'nip' => ['nip'],
  2556. 'regon' => ['regon'],
  2557. 'krs' => ['krs'],
  2558. 'pesel' => ['pesel'],
  2559. ];
  2560. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  2561. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  2562. public function __construct() {
  2563. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  2564. $result = DB::getPDO()->fetchAll($query);
  2565. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  2566. }
  2567. private function getRelationID($name) {
  2568. if (!isset($this->RELATIONS_ID[$name])) {
  2569. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  2570. $newID = DB::getPDO()->fetchValue($query);
  2571. $this->RELATIONS_ID[$name] = $newID;
  2572. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  2573. DB::getPDO()->query($query);
  2574. }
  2575. return $this->RELATIONS_ID[$name];
  2576. }
  2577. private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
  2578. if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
  2579. if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
  2580. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
  2581. }
  2582. }
  2583. }
  2584. public function findRelations($ID) {
  2585. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  2586. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  2587. $row = $result[0];
  2588. $joins = [];
  2589. $items = '';
  2590. foreach ($this->relations as $name => $columns) {
  2591. $ok = 0;
  2592. $join = [];
  2593. foreach ($columns as $column) {
  2594. $join[] = "t1.{$column} = t2.{$column}";
  2595. if ($row[$column] !== null) $ok++;
  2596. }
  2597. if ($ok / count($columns) > 0.5) {
  2598. $joins[] = "(" . implode(" and ", $join) . ")";
  2599. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  2600. }
  2601. }
  2602. if (!$joins) return false;
  2603. $query = "select t2.ID as ID, t1.REMOTE_TABLE as REMOTE_TABLE_1, t1.REMOTE_ID as REMOTE_ID_1, t2.REMOTE_TABLE as REMOTE_TABLE_2, t2.REMOTE_ID as REMOTE_ID_2 {$items}, t1.BASE * t2.BASE as BASE " .
  2604. "from BI_audit_ALL t1 join BI_audit_ALL t2 on " . implode(" or ", $joins) . " where t1.ID = {$ID} and (t2.reffed = 1 or t2.ID > {$ID})";
  2605. $result = DB::getPDO()->fetchAll($query);
  2606. foreach ($result as $row) {
  2607. $relationID = 0;
  2608. foreach ($this->relations as $name => $v) {
  2609. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  2610. }
  2611. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  2612. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  2613. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  2614. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  2615. if (!($start2 || $end1)) {
  2616. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  2617. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2618. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2619. DB::getPDO()->query($query);
  2620. }
  2621. if (!($start1 || $end2)) {
  2622. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  2623. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2624. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2625. DB::getPDO()->query($query);
  2626. }
  2627. }
  2628. }
  2629. }
  2630. class BiAuditRefTables {
  2631. public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
  2632. static $refTables = [];
  2633. static $tempRefTables = [];
  2634. if (is_array($tableTo)) {
  2635. if (!$tableTo) throw new Exception('BiAuditRefTables::getRefTable - bad parameter $tableTo');
  2636. if (count($tableTo) == 1) return self::getRefTable($tableFrom, reset($tableTo), $returnException);
  2637. $key = implode("__", $tableTo);
  2638. if (!isset($tempRefTables[$tableFrom][$key])) {
  2639. try {
  2640. $_tableFrom = $tableFrom;
  2641. foreach ($tableTo as $_tableTo) {
  2642. $_refTables[] = self::getRefTable($_tableFrom, $_tableTo, true);
  2643. $_tableFrom = $_tableTo;
  2644. }
  2645. $name = "TEMP__#REF_TABLE__" . (count($tempRefTables) + 1);
  2646. $first = reset($_refTables);
  2647. $last = end($_refTables);
  2648. $prev = array_shift($_refTables);
  2649. $query = "create temporary table `{$name}` select `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY` from `{$first}`";
  2650. while ($next = array_shift($_refTables)) {
  2651. $query .= " join `{$next}` on `{$prev}`.`REMOTE_PRIMARY_KEY` = `{$next}`.`PRIMARY_KEY`";
  2652. $prev = $next;
  2653. }
  2654. $query .= " group by `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY`";
  2655. DB::getPDO()->query($query);
  2656. $tempRefTables[$tableFrom][$key] = $name;
  2657. } catch (Exception $e) {
  2658. if ($returnException) throw new Exception($e->getMessage());
  2659. $tempRefTables[$tableFrom][$key] = false;
  2660. }
  2661. }
  2662. return $tempRefTables[$tableFrom][$key];
  2663. } else {
  2664. if (!isset($refTables[$tableFrom][$tableTo])) {
  2665. try {
  2666. $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  2667. } catch (Exception $e) {
  2668. if ($returnException) throw new Exception($e->getMessage());
  2669. $refTables[$tableFrom][$tableTo] = false;
  2670. }
  2671. }
  2672. return $refTables[$tableFrom][$tableTo];
  2673. }
  2674. }
  2675. public static function getRefTables($tableFrom) {
  2676. static $refTables = [];
  2677. if (!isset($refTables[$tableFrom])) {
  2678. $namespace = "default_db/{$tableFrom}/{$tableFrom}";
  2679. try {
  2680. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  2681. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  2682. $fields = $item['field'];
  2683. $_refTables = [];
  2684. foreach ($fields as $field) {
  2685. list($type, $child) = explode(":", $field['xsdType'], 2);
  2686. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
  2687. try {
  2688. $_refTable = ACL::getRefTable($namespace, $child);
  2689. $_refTables[] = $_refTable;
  2690. } catch (Exception $e) {
  2691. }
  2692. }
  2693. }
  2694. $refTables[$tableFrom] = $_refTables;
  2695. } catch (Exception $e) {
  2696. $refTables[$tableFrom] = [];
  2697. }
  2698. }
  2699. return $refTables[$tableFrom];
  2700. }
  2701. }
  2702. class BiAuditPowiazania {
  2703. private $minDepth;
  2704. private $maxDepth, $origMaxDepth;
  2705. private $onlyTargets;
  2706. private $ID;
  2707. private $nodes = [];
  2708. private $endNodes;
  2709. private $path = [];
  2710. private $results = [];
  2711. private $items_results = [];
  2712. private $relations = [];
  2713. private $srcTables = ['BI_audit_ENERGA_PRACOWNICY']; //, ['BI_audit_POWIAZANIA_OD', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2714. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person']; //, ['BI_audit_POWIAZANIA_DO', 'BI_audit_POWIAZANIA_OBIEKTY']];
  2715. private $step = 0;
  2716. private $tasksDirLocation;
  2717. private $progressFile;
  2718. private $progress = [
  2719. 'summary' => [
  2720. 'count' => 0,
  2721. 'message' => 'Inicjacja',
  2722. 'ts' => null,
  2723. 'step' => 'initialize',
  2724. 'reportsCount' => 0,
  2725. 'reportsCreated' => 0,
  2726. ],
  2727. 'details' => [],
  2728. ];
  2729. private $lastProgress = 0;
  2730. private $lastProgress_slowCheck = 0;
  2731. private $lastResults = 0;
  2732. private $startTimestamp = null;
  2733. private $lastTimestamp = null;
  2734. private $lowProgressCount = 0;
  2735. private $count, $i;
  2736. private $splittedResults = [];
  2737. private $maxResults = 1000000;
  2738. private $fidRow = [];
  2739. private $itemID = 0;
  2740. private $reverseSearch = false;
  2741. private $query = "";
  2742. private static function generateJson($type, $data) {
  2743. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  2744. }
  2745. public static function saveToLog($message) {
  2746. $messageJson = self::generateJson('message', ['message' => $message]);
  2747. echo $messageJson . "\n";
  2748. }
  2749. private static function exec($cmd) {
  2750. $path = 'export PATH=$PATH:/usr/sbin;';
  2751. $cmd = "{$path} {$cmd}";
  2752. echo "CMD :: {$cmd}\n";
  2753. shell_exec($cmd);
  2754. }
  2755. private function saveProgress($args = []) {
  2756. $timestamp = microtime(true);
  2757. if (isset($args['progress']) && $this->i) {
  2758. $elapsed = $timestamp - $this->startTimestamp;
  2759. if ($args['progress']) {
  2760. $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
  2761. } else $estimated = "N/A";
  2762. $this->lastProgress = $args['progress'];
  2763. $this->lastTimestamp = $timestamp;
  2764. $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
  2765. echo $progressJson . "\n";
  2766. $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
  2767. }
  2768. if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
  2769. if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
  2770. if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
  2771. $this->progress['summary']['ts'] = $timestamp;
  2772. file_put_contents($this->progressFile, json_encode($this->progress));
  2773. }
  2774. private static function throwException($message) {
  2775. self::saveToLog($message);
  2776. throw new Exception($message);
  2777. }
  2778. public function __construct($ID = 0, $tasksDirLocation = null) {
  2779. if (!$ID) self::throwException("Wrong ID parameter");
  2780. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  2781. $this->ID = $ID;
  2782. $this->tasksDirLocation = $tasksDirLocation;
  2783. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  2784. $this->saveProgress();
  2785. }
  2786. public function run() {
  2787. $query = "select BI_analiza_minDepth, BI_analiza_maxDepth, BI_analiza_onlyTargets from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache not in ('Full')";
  2788. $result = DB::getPDO()->fetchAll($query);
  2789. if (!$result) self::throwException("Błąd danych");
  2790. if ($this->loadResults()) {
  2791. $this->splitResults();
  2792. return;
  2793. }
  2794. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  2795. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  2796. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  2797. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  2798. if (!$this->minDepth) $this->minDepth = 1;
  2799. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  2800. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  2801. $subQueries = [];
  2802. $resultDest = [];
  2803. foreach ($this->destTables as $destTable) {
  2804. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destTable)) {
  2805. $subQueries[] = "select `all`.`ID` from `BI_audit_ALL` `all` join `{$refTable}` `ref` on `all`.`REMOTE_TABLE` = '{$destTable}' and `all`.`REMOTE_ID` = `ref`.`REMOTE_PRIMARY_KEY` and `ref`.`PRIMARY_KEY` = '{$this->ID}'";
  2806. }
  2807. }
  2808. if ($subQueries) {
  2809. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2810. $resultDest = DB::getPDO()->fetchAll($query);
  2811. }
  2812. if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  2813. $subQueries = [];
  2814. $resultSrc = [];
  2815. foreach ($this->srcTables as $srcTable) {
  2816. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcTable)) {
  2817. $subQueries[] = "select `all`.`ID` from `BI_audit_ALL` `all` join `{$refTable}` `ref` on `all`.`REMOTE_TABLE` = '{$srcTable}' and `all`.`REMOTE_ID` = `ref`.`REMOTE_PRIMARY_KEY` and `ref`.`PRIMARY_KEY` = '{$this->ID}'";
  2818. }
  2819. }
  2820. if ($subQueries) {
  2821. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  2822. $resultSrc = DB::getPDO()->fetchAll($query);
  2823. }
  2824. if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
  2825. if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
  2826. $result = $resultSrc;
  2827. $this->endNodes = array_map('reset', $resultDest);
  2828. $this->reverseSearch = false;
  2829. $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
  2830. } else {
  2831. $result = $resultDest;
  2832. $this->endNodes = array_map('reset', $resultSrc);
  2833. $this->reverseSearch = true;
  2834. $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
  2835. self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
  2836. }
  2837. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  2838. $this->count = count($result);
  2839. $this->progress['summary']['count'] = $this->count;
  2840. $this->origMaxDepth = $this->maxDepth;
  2841. $this->saveProgress(['step' => 'relations']);
  2842. try {
  2843. foreach ($result as $i => $row) {
  2844. $this->i = $i + 1;
  2845. $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
  2846. $this->startTimestamp = microtime(true);
  2847. $this->lastProgress = 0;
  2848. $this->lastProgress_slowCheck = 0;
  2849. $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2850. if ($this->maxDepth != $this->origMaxDepth) {
  2851. $this->maxDepth = $this->origMaxDepth;
  2852. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  2853. }
  2854. $this->findPowiazania($row['ID']);
  2855. $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  2856. $this->lastResults = count($this->results);
  2857. }
  2858. } catch (Exception $e) {
  2859. if ($this->i < $this->count) {
  2860. $this->startTimestamp = microtime(true);
  2861. $this->lastProgress = 0;
  2862. $this->lastResults = count($this->results);
  2863. while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
  2864. }
  2865. if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
  2866. }
  2867. $this->nodes = [];
  2868. self::saveToLog("Zakończono wyszukiwanie powiązań");
  2869. $this->sortResults();
  2870. $this->saveResults();
  2871. //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
  2872. $this->splitResults();
  2873. }
  2874. private static function reversePath($path) {
  2875. $arr = array_reverse($path, true);
  2876. $keys = array_keys($arr);
  2877. array_unshift($arr, array_pop($arr));
  2878. return array_combine($keys, $arr);
  2879. }
  2880. private function addResult($progress) {
  2881. if (count($this->results) == $this->maxResults) {
  2882. $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
  2883. self::saveToLog($message);
  2884. $this->saveProgress(['progress' => $progress, 'message' => $message]);
  2885. throw new Exception('');
  2886. }
  2887. if ($this->reverseSearch) $path = self::reversePath($this->path);
  2888. else $path = $this->path;
  2889. $this->results[] = $path;
  2890. $this->saveToDb($path);
  2891. }
  2892. private static function weightCalc($n) {
  2893. if ($n < 21) return 1;
  2894. if ($n < 41) return 2;
  2895. if ($n < 81) return 3;
  2896. if ($n < 161) return 4;
  2897. if ($n < 321) return 5;
  2898. if ($n < 641) return 6;
  2899. if ($n < 1281) return 7;
  2900. if ($n < 2561) return 8;
  2901. if ($n < 5121) return 9;
  2902. return 10;
  2903. }
  2904. public function findPowiazania($ID, $progress = 0, $steps = 1, $relation = "", $weight = 0) {
  2905. $this->step++;
  2906. if ($this->maxDepth > $this->minDepth) {
  2907. if (($this->step % 1000000) == 0) {
  2908. $progressDiff = $progress - $this->lastProgress_slowCheck;
  2909. if ($progressDiff < 0.00005) {
  2910. $this->lowProgressCount++;
  2911. if ($this->lowProgressCount == 10) {
  2912. $this->maxDepth--;
  2913. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
  2914. $this->lowProgressCount = 0;
  2915. }
  2916. } else $this->lowProgressCount = 0;
  2917. $this->lastProgress_slowCheck = $progress;
  2918. }
  2919. }
  2920. if ((($this->step) % 100000) == 0) {
  2921. $this->saveProgress(['progress' => $progress]);
  2922. }
  2923. if ((($this->step) % 10000) == 0) {
  2924. if (memory_get_usage(true) > 3000000000) {
  2925. $this->nodes = [];
  2926. self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
  2927. }
  2928. }
  2929. if (isset($this->path[$ID])) return false;
  2930. $this->path[$ID] = $relation;
  2931. if (!$relation) $relation = 0;
  2932. if (in_array($ID, $this->endNodes)) {
  2933. if (count($this->path) > $this->minDepth) $this->addResult($progress);
  2934. array_pop($this->path);
  2935. return;
  2936. }
  2937. if (count($this->path) > $this->maxDepth) {
  2938. if (!$this->onlyTargets) $this->addResult($progress);
  2939. array_pop($this->path);
  2940. return;
  2941. }
  2942. if (!isset($this->nodes[$ID][$relation])) {
  2943. $where = $relation ? "and ({$relation} & ref.RELATION_ID) = 0" : "";
  2944. $query = "{$this->query} = {$ID} {$where}";
  2945. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  2946. }
  2947. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  2948. if (isset($this->path[$node['ID']])) return false;
  2949. return true;
  2950. }));
  2951. $count = count($nodes);
  2952. $weight += self::weightCalc($count);
  2953. if ($weight <= $this->maxDepth) {
  2954. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID'], $weight);
  2955. }
  2956. array_pop($this->path);
  2957. }
  2958. private function sortResults() {
  2959. if (!$this->results) return;
  2960. uasort($this->results, function ($a, $b) {
  2961. $ca = count($a);
  2962. $cb = count($b);
  2963. $c = min($ca, $cb);
  2964. $ka = array_keys($a);
  2965. $kb = array_keys($b);
  2966. for ($i = 0; $i < $c; $i++) {
  2967. if ($ka[$i] < $kb[$i]) return -1;
  2968. if ($ka[$i] > $kb[$i]) return 1;
  2969. }
  2970. if ($ca < $cb) return -1;
  2971. if ($ca > $cb) return 1;
  2972. return 0;
  2973. });
  2974. }
  2975. private function saveResults() {
  2976. self::saveToLog("Zapisuję wyliczone dane do pliku");
  2977. // if (!$this->results) {
  2978. // self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  2979. // return false;
  2980. // }
  2981. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2982. $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
  2983. file_put_contents($dataFile, $data);
  2984. self::saveToLog("Zapisano wyliczone dane do pliku");
  2985. return true;
  2986. }
  2987. private function loadResults() {
  2988. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  2989. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  2990. if (!file_exists($dataFile)) {
  2991. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  2992. return false;
  2993. }
  2994. $data = file_get_contents($dataFile);
  2995. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  2996. if (!$results) {
  2997. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  2998. return false;
  2999. }
  3000. if (isset($results['results'])) {
  3001. $this->results = $results['results'];
  3002. if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
  3003. } else $this->results = $results;
  3004. self::saveToLog("Wczytano wcześniej wyliczone dane");
  3005. return true;
  3006. }
  3007. private function relationName($ID) {
  3008. if (!$ID) return '';
  3009. if (!isset($this->relations[$ID])) {
  3010. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  3011. $result = DB::getPDO()->fetchAll($query);
  3012. $rels = array_map('reset', $result);
  3013. $this->relations[$ID] = implode(", ", $rels);
  3014. }
  3015. return $this->relations[$ID];
  3016. }
  3017. private function splitResults() {
  3018. $MAX = 1000;
  3019. $countBySource = [];
  3020. $resultsKeys = [];
  3021. foreach ($this->results as $resultKey => $result) {
  3022. $_keys = array_keys($result);
  3023. $countBySource[reset($_keys)][] = $resultKey;
  3024. }
  3025. foreach ($countBySource as $resultKeys) {
  3026. if (count($resultKeys) > $MAX) {
  3027. $countByDest = [];
  3028. foreach ($resultKeys as $resultKey) {
  3029. $_keys = array_keys($this->results[$resultKey]);
  3030. $countByDest[end($_keys)][] = $resultKey;
  3031. }
  3032. foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
  3033. } else $resultsKeys[] = $resultKeys;
  3034. }
  3035. $results = [];
  3036. while ($resultsKeys) {
  3037. $resultKeys = array_shift($resultsKeys);
  3038. while ($next = current($resultsKeys)) {
  3039. if (count($resultKeys) + count($next) <= $MAX) {
  3040. $resultKeys = array_merge($resultKeys, $next);
  3041. unset($resultsKeys[key($resultsKeys)]);
  3042. } else break; //next($resultsKeys);
  3043. }
  3044. $_results = [];
  3045. foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
  3046. $results[] = $_results;
  3047. // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  3048. }
  3049. if ($results) $this->splittedResults = $results;
  3050. else $this->splittedResults[] = $this->results;
  3051. $this->progress['summary']['reportsCount'] = count($results);
  3052. }
  3053. public function getPartsCount() {
  3054. return count($this->splittedResults);
  3055. }
  3056. private function generateItemsResults($resultsPart = null) {
  3057. if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
  3058. else {
  3059. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  3060. if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
  3061. }
  3062. $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  3063. $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  3064. $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
  3065. $items_kontrahenci = [];
  3066. $items_kw_person = [];
  3067. $kontrahenci = [];
  3068. $kw_person = [];
  3069. $_items_results = [];
  3070. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  3071. $refFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  3072. $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
  3073. $this->items_results[$resultsPart] = [];
  3074. $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  3075. $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
  3076. if ($resultsPart === null) {
  3077. $results = $this->results;
  3078. } else {
  3079. $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  3080. $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
  3081. }
  3082. foreach ($results as $key => $result) {
  3083. if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
  3084. foreach ($result as $ID => $rel) {
  3085. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  3086. $row = DB::getPDO()->fetchFirst($query);
  3087. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  3088. $obj = DB::fetch(DB::query($query));
  3089. $item_result = [];
  3090. if ($this->fidRow) {
  3091. $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
  3092. }
  3093. $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
  3094. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  3095. $query = "select `note`.* from `BI_audit_operational_raport_note` `note` join `{$refTable}` `ref` on `note`.`ID` = `ref`.`PRIMARY_KEY` where `ref`.`REMOTE_PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
  3096. if ($notes = DB::getPDO()->fetchAll($query)) $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'] = $notes;
  3097. }
  3098. if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  3099. $query = "select `taxpayer`.* from `{$refTable}` `ref` join `BI_audit_taxpayer` `taxpayer` on `ref`.`REMOTE_PRIMARY_KEY` = `taxpayer`.`ID` where `ref`.`PRIMARY_KEY` = '{$row['REMOTE_ID']}'";
  3100. if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
  3101. $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
  3102. }
  3103. }
  3104. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  3105. $item_results[$xmlObject][] = $item_result;
  3106. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  3107. $kontrahenci[] = $row['REMOTE_ID'];
  3108. $query = "select faktury.* from BI_audit_ENERGA_FAKTURY faktury join `{$refFakturyToKontrahenci}` ref on faktury.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  3109. $res = DB::query($query);
  3110. $faktury = [];
  3111. if (mysql_num_rows($res)) {
  3112. while ($obj = DB::fetch($res)) {
  3113. $faktura = (array) $obj;
  3114. $faktura = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_FAKTURY.{$faktura['ID']}"]], $faktura);
  3115. $faktury[] = $faktura;
  3116. }
  3117. }
  3118. $query = "select umowy.* from BI_audit_ENERGA_RUM_UMOWY umowy join `{$refUmowyToKontrahenci}` ref on umowy.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  3119. $res = DB::query($query);
  3120. $umowy = [];
  3121. if (mysql_num_rows($res)) {
  3122. while ($obj = DB::fetch($res)) {
  3123. $umowa = (array) $obj;
  3124. $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
  3125. $umowy[] = $umowa;
  3126. }
  3127. }
  3128. if ($faktury || $umowy) {
  3129. $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  3130. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  3131. if ($faktury) $item_kontrahenci['BI_audit_ENERGA_FAKTURY'] = $faktury;
  3132. if ($umowy) $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  3133. $items_kontrahenci[] = $item_kontrahenci;
  3134. }
  3135. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  3136. $kw_person[] = $row['REMOTE_ID'];
  3137. $query = "select kw.* from BI_audit_KW_requested kw join `{$refKwRequestedToKwRequestedPerson}` ref on kw.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
  3138. $res = DB::query($query);
  3139. if (mysql_num_rows($res)) {
  3140. $kws = [];
  3141. while ($obj = DB::fetch($res)) {
  3142. $kw = (array) $obj;
  3143. $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
  3144. $kws[] = $kw;
  3145. }
  3146. $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  3147. $item_kw_person['ID'] = $row['REMOTE_ID'];
  3148. $item_kw_person['BI_audit_KW_requested'] = $kws;
  3149. $items_kw_person[] = $item_kw_person;
  3150. }
  3151. }
  3152. }
  3153. $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
  3154. }
  3155. $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  3156. $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
  3157. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  3158. }
  3159. private function saveToDb($result = null, $key = null) {
  3160. if ($result === null) {
  3161. self::saveToLog("Zapisuję wyliczone dane do bazy");
  3162. if (!$this->results) {
  3163. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  3164. return null;
  3165. }
  3166. foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
  3167. self::saveToLog("Zapisano wyliczone dane do bazy");
  3168. } else {
  3169. if ($key === null) {
  3170. end($this->results);
  3171. $key = key($this->results);
  3172. }
  3173. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  3174. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  3175. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  3176. $fidObj = [];
  3177. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  3178. foreach ($result as $ID => $rel) {
  3179. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  3180. $object = DB::getPDO()->fetchFirst($query);
  3181. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
  3182. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  3183. $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
  3184. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  3185. $fidObj[$ID] = $idPowiazaniaRowObject;
  3186. }
  3187. $this->fidRow[$key] = [
  3188. 'fid' => $IdPowiazaniaRow,
  3189. 'obj' => $fidObj,
  3190. ];
  3191. }
  3192. }
  3193. public function saveXml($resultsPart = null) {
  3194. if ($this->getPartsCount()) {
  3195. if ($resultsPart === null) {
  3196. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  3197. for ($i =0; $i < $this->getPartsCount(); $i++) {
  3198. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  3199. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  3200. file_put_contents($xmlFile, $this->asXml($i));
  3201. }
  3202. self::saveToLog("Zakończono generowanie plików XML");
  3203. } else {
  3204. if ($resultsPart >= $this->getPartsCount()) {
  3205. self::saveToLog("saveXml() error - bad result number");
  3206. return;
  3207. }
  3208. $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  3209. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  3210. file_put_contents($xmlFile, $this->asXml($resultsPart));
  3211. }
  3212. } else {
  3213. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  3214. file_put_contents($xmlFile, $this->asXml());
  3215. }
  3216. }
  3217. public function asXml($resultsPart = null) {
  3218. self::saveToLog("Generuję plik XML ({$resultsPart})");
  3219. if (!$this->results) {
  3220. self::saveToLog("Brak wyników (#1), wygenerowano pusty plik XML ({$resultsPart})");
  3221. // self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  3222. // return null;
  3223. }
  3224. if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
  3225. if (!isset($this->items_results[$resultsPart])) {
  3226. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  3227. return null;
  3228. }
  3229. $xmlRoot = "RelatedFeatureRoot";
  3230. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  3231. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  3232. return $return;
  3233. }
  3234. public function asArray($resultsPart = null, $subArray = null) {
  3235. if (!$this->results) return null;
  3236. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  3237. if (!$this->items_results[$resultsPart]) return null;
  3238. if ($subArray) {
  3239. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  3240. else return [];
  3241. } else return $this->items_results[$resultsPart];
  3242. }
  3243. public function powiazaniaFound() {
  3244. if ($this->results) return true;
  3245. else return false;
  3246. }
  3247. public function generatePdfAndHtml() {
  3248. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  3249. if (!file_exists($antDir)) mkdir($antDir, 0770, true);
  3250. if (!is_dir($antDir)) {
  3251. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  3252. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  3253. $this->saveProgress(['reportsCreated' => 1]);
  3254. return;
  3255. }
  3256. $this->saveProgress(['step' => 'reports']);
  3257. if ($this->getPartsCount()) {
  3258. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  3259. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  3260. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  3261. } else $this->_generatePdfAndHtml();
  3262. }
  3263. private function _generatePdfAndHtml($resultsPart = null) {
  3264. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  3265. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  3266. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  3267. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  3268. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  3269. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  3270. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  3271. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  3272. $antXmlFile = $antDir . "/" . $antXmlFilename;
  3273. //$baseDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}";
  3274. $baseDir = "/opt/local/pl.procesy5/p5build_SE/temp/WPS_Functions/temp/default_db/CRM_PROCES_tree/relations-{$id_part}";
  3275. $ditamapFile = "{$baseDir}/relations-{$id_part}.ditamap";
  3276. $pdfFile = "{$baseDir}/pdf/relations-{$id_part}.pdf";
  3277. $htmlDir = "{$baseDir}/html";
  3278. $htmlFile = "{$htmlDir}/relations-{$id_part}.html";
  3279. //if (!file_exists($xmlFile))
  3280. $this->saveXml($resultsPart);
  3281. if (!file_exists($xmlFile)) {
  3282. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
  3283. self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
  3284. $this->saveProgress(['reportsCreated' => 1]);
  3285. return;
  3286. }
  3287. $this->saveProgress(['reportsCreated' => 0.05]);
  3288. copy($xmlFile, $antXmlFile);
  3289. self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
  3290. self::exec("cd /Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree && /opt/local/bin/ant -f build_CRM_PROCES_tree.xml default_db:PROCES_INIT:tree:dita -Duuid=relations-{$id_part}");
  3291. if (file_exists($ditamapFile))
  3292. {
  3293. self::saveToLog("Wygenerowano plik przejściowy");
  3294. $this->saveProgress(['reportsCreated' => 0.15]);
  3295. } else {
  3296. self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
  3297. $this->saveProgress(['reportsCreated' => 1]);
  3298. return;
  3299. }
  3300. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  3301. self::exec("cd \"{$baseDir}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i relations-{$id_part}.ditamap -f pdf");
  3302. if (file_exists($pdfFile)) {
  3303. rename($pdfFile, $pdfDestFile);
  3304. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  3305. } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  3306. $this->saveProgress(['reportsCreated' => 0.45]);
  3307. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  3308. self::exec("cd \"{$baseDir}\" && /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o html -i relations-{$id_part}.ditamap -f tocjs");
  3309. if (file_exists($htmlDir) && is_dir($htmlDir) && file_exists($htmlFile)) {
  3310. self::exec("cd \"{$baseDir}\" && zip -r \"{$htmlZipDestFile}\" html");
  3311. if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
  3312. self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  3313. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  3314. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  3315. $this->saveProgress(['reportsCreated' => 0.35]);
  3316. }
  3317. }