BiAuditGenerate.php 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964
  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 btn-sm" 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 showPowiazania_progress() {
  436. ?>
  437. <div class="container" style="margin-top:20px">
  438. <legend>
  439. Postęp generowania raportu nr <?=$this->powiazanie['ID']?>
  440. </legend>
  441. Panel w przygotowaniu
  442. <?php
  443. $action = V::get('action', '', $_POST);
  444. switch ($action) {
  445. case "abort":
  446. $powiazaniaDirLocation = self::getMainDirectory();
  447. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  448. $abortFile = "{$tasksDirLocation}/generatePowiazania-{$this->powiazanie['ID']}.abort";
  449. touch($abortFile);
  450. ?>
  451. <h4>Zlecono przerwanie badania - odczekaj kilka minut</h4>
  452. <?php
  453. break;
  454. default:
  455. ?>
  456. <form method="post">
  457. <button type="submit" name="action" value="abort">Przerwij badanie</button>
  458. </form>
  459. </div>
  460. <?php
  461. }
  462. }
  463. private function urlActionOnItem() {
  464. try {
  465. if (!$this->SOURCE) throw new Exception("Błąd danych");
  466. elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
  467. $_subUrlAction = V::get('_subUrlAction', '', $_GET);
  468. switch ($_subUrlAction) {
  469. case "importToPracownicy":
  470. if (in_array($this->SOURCE['TABLE'], ['BI_audit_KRS', 'BI_audit_MSIG'])) $this->importToPracownicySearch($this->SOURCE['ID']);
  471. else throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  472. break;
  473. case "showKrsForKrsPerson":
  474. if (in_array($this->SOURCE['TABLE'], ['BI_audit_KRS_person'])) $this->showKrsForKrsPerson();
  475. else throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  476. break;
  477. default:
  478. switch ($this->SOURCE['TABLE']) {
  479. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  480. $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
  481. if (!$powiazania) throw new Exception("Błąd danych");
  482. $this->powiazanie = $powiazania[0];
  483. switch ($this->powiazanie['FILE_STATUS']) {
  484. case "NONE":
  485. $this->initializePowiazania();
  486. break;
  487. case "IN_PROGRESS":
  488. $this->showPowiazania_progress();
  489. break;
  490. case "GENERATED":
  491. $this->showPowiazania();
  492. break;
  493. default: throw new Exception("Błędny status rekordu");
  494. }
  495. break;
  496. case "BI_audit_ENERGA_PRACOWNICY":
  497. $this->showPowiazaniaList();
  498. break;
  499. default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
  500. }
  501. }
  502. } catch (Exception $e) {
  503. SE_Layout::alert('danger',$e->getMessage());
  504. $_SESSION['REFERER'] = $this->REFERER;
  505. ?>
  506. <div class="container" style="text-align:center">
  507. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
  508. </div>
  509. <?php
  510. }
  511. }
  512. private function importToPracownicy() {
  513. $action = V::get('action', '', $_POST);
  514. switch ($action) {
  515. case "search":
  516. $this->importToPracownicySearch();
  517. break;
  518. default: $this->importToPracownicyForm();
  519. }
  520. }
  521. private $tableDesc = ['BI_audit_KRS' => 'KRS', 'BI_audit_MSIG' => 'MSiG'];
  522. private function importToPracownicyForm() {
  523. $TABLE = $this->SOURCE['TABLE'];
  524. $DESC = $this->tableDesc[$TABLE];
  525. ?>
  526. <div class="container" style="margin-top:20px">
  527. <legend>
  528. Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
  529. </legend>
  530. <div class="form-group">
  531. <div class="col-sm-12">
  532. <h4>Znajdź podmiot</h4>
  533. </div>
  534. </div>
  535. <form class="form-horizontal" method="post">
  536. <div class="form-group">
  537. <label class="col-sm-1 control-label">Nazwa</label>
  538. <div class="col-sm-4">
  539. <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu">
  540. </div>
  541. </div>
  542. <div class="form-group">
  543. <label class="col-sm-1 control-label">KRS</label>
  544. <div class="col-sm-2">
  545. <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
  546. </div>
  547. </div>
  548. <div class="form-group">
  549. <label class="col-sm-1 control-label">NIP</label>
  550. <div class="col-sm-2">
  551. <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
  552. </div>
  553. </div>
  554. <div class="form-group">
  555. <label class="col-sm-1 control-label">Regon</label>
  556. <div class="col-sm-2">
  557. <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
  558. </div>
  559. </div>
  560. <div class="form-group">
  561. <div class="col-sm-offset-1 col-sm-11">
  562. <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
  563. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  564. </div>
  565. </div>
  566. </form>
  567. </div>
  568. <?php
  569. }
  570. private function importToPracownicySearch($krsId = null) {
  571. $TABLE = $this->SOURCE['TABLE'];
  572. $DESC = $this->tableDesc[$TABLE];
  573. $formItems = [
  574. "nazwa" => 'like',
  575. "krs" => '=',
  576. "nip" => '=',
  577. "regon" => '=',
  578. ];
  579. try {
  580. $subaction = V::get('subaction', '', $_POST);
  581. switch ($subaction) {
  582. case "listPerson":
  583. $krsId = V::get('krsId', 0, $_POST, int);
  584. break;
  585. case "addPersonToPracownicy":
  586. $krsId = V::get('krsId', 0, $_POST, int);
  587. $personId = V::get('personId', [], $_POST);
  588. if (!$personId) throw new Exception("Błąd formularza");
  589. $query = "insert into BI_audit_ENERGA_PRACOWNICY (source, imiona, nazwisko, pesel) select 'KRS', imiona, nazwisko, pesel from {$TABLE}_person where ID in (" . implode(", ", $personId) . ")";
  590. DB::getPDO()->query($query);
  591. SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
  592. break;
  593. case "addToKontrahenci":
  594. $krsId = V::get('krsId', 0, $_POST, int);
  595. if (!$krsId) throw new Exception("Błąd formularza");
  596. $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}'";
  597. $kontrahentExists = DB::getPDO()->fetchValue($query);
  598. if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
  599. $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." ";
  600. DB::getPDO()->query($query);
  601. SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
  602. break;
  603. }
  604. if ($krsId) {
  605. $where = ["ID = '{$krsId}'"];
  606. } else {
  607. $form = [];
  608. foreach ($formItems as $item => $type) {
  609. if ($param = V::get($item, '', $_POST)) {
  610. if ($type == 'like') $param = "%{$param}%";
  611. $form[$item] = DB::getPDO()->quote($param);
  612. }
  613. }
  614. if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
  615. $where = [];
  616. foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
  617. }
  618. } catch (Exception $e) {
  619. SE_Layout::alert('danger', $e->getMessage());
  620. $this->importToPracownicyForm();
  621. return;
  622. }
  623. $query = "select * from `{$TABLE}` where " . implode(" and ", $where) . "order by ID limit 1001";
  624. $result = DB::getPDO()->fetchAll($query);
  625. if (count($result) == 1001) {
  626. SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
  627. $this->importToPracownicyForm();
  628. return;
  629. } elseif (count($result) == 1) {
  630. $krsId = $result[0]['ID'];
  631. }
  632. ?>
  633. <div class="container" style="margin-top:20px">
  634. <form method="post">
  635. <legend>
  636. Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
  637. </legend>
  638. <div class="form-group">
  639. <div class="col-sm-12">
  640. <h4>Znalezione podmioty:</h4>
  641. </div>
  642. </div>
  643. <div class="form-group">
  644. <div class="col-sm-12">
  645. <table class="table table-bordered table-hover table-striped" height=5>
  646. <thead>
  647. <tr style="text-align:center; background-color:lightgray">
  648. <td width=1>Lp.</td>
  649. <td>Nazwa</td>
  650. <td>Adres</td>
  651. <td>KRS</td>
  652. <td>NIP</td>
  653. <td>Regon</td>
  654. <?php
  655. if (count($result) > 1) {
  656. ?>
  657. <td width=1>Wybierz</td>
  658. <?php
  659. }
  660. ?>
  661. </tr>
  662. </thead>
  663. <tbody>
  664. <?php
  665. if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
  666. else {
  667. $lp = 1;
  668. foreach ($result as $row) {
  669. $adres = $row['A_miejscowosc'];
  670. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  671. if ($row['A_nrDomu']) {
  672. $adres .= " {$row['A_nrDomu']}";
  673. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  674. }
  675. ?>
  676. <tr>
  677. <td align="right"><?=$lp++?></td>
  678. <td><?=htmlspecialchars($row['nazwa'])?></td>
  679. <td><?=htmlspecialchars($adres)?></td>
  680. <td><?=$row['krs']?></td>
  681. <td><?=$row['nip']?></td>
  682. <td><?=$row['regon']?></td>
  683. <?php
  684. if (count($result) > 1) {
  685. ?>
  686. <td align="center">
  687. <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
  688. </td>
  689. <?php
  690. }
  691. ?>
  692. </tr>
  693. <?php
  694. }
  695. }
  696. ?>
  697. </tbody>
  698. </table>
  699. </div>
  700. </div>
  701. <?php
  702. if (count($result) > 1) {
  703. ?>
  704. <div class="form-group">
  705. <div class="col-sm-12">
  706. <?php
  707. foreach (array_keys($formItems) as $item) {
  708. ?>
  709. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  710. <?php
  711. }
  712. ?>
  713. <input type="hidden" name="back" value="search"/>
  714. <div class="containter" style="text-align:center">
  715. <button type="submit" class="btn btn-primary" name="subaction" value="listPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
  716. <a href="" class="btn btn-default">Powrót</a>
  717. </div>
  718. </div>
  719. </div>
  720. <?php
  721. } elseif ($krsId) {
  722. ?>
  723. <div class="form-group">
  724. <div class="col-sm-12">
  725. <h4>Znalezione osoby:</h4>
  726. </div>
  727. </div>
  728. <div class="form-group">
  729. <div class="col-sm-12">
  730. <table class="table table-bordered table-hover table-striped" height=5>
  731. <thead>
  732. <tr style="text-align:center; background-color:lightgray">
  733. <td width=1>Lp.</td>
  734. <td>Nazwisko</td>
  735. <td>Imiona</td>
  736. <td>Pesel</td>
  737. <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
  738. </tr>
  739. </thead>
  740. <tbody>
  741. <?php
  742. $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}'";
  743. $kontrahentExists = DB::getPDO()->fetchValue($query);
  744. $refToPerson = BiAuditRefTables::getRefTable($TABLE, "{$TABLE}_person", true);
  745. $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}'";
  746. $result = DB::getPDO()->fetchAll($query);
  747. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
  748. else {
  749. $lp = 1;
  750. foreach ($result as $row) {
  751. ?>
  752. <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
  753. <td align="right"><?=$lp++?></td>
  754. <td><?=$row['nazwisko']?></td>
  755. <td><?=$row['imiona']?></td>
  756. <td><?=$row['pesel']?></td>
  757. <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
  758. </tr>
  759. <?php
  760. }
  761. }
  762. ?>
  763. </tbody>
  764. </table>
  765. </div>
  766. </div>
  767. <!-- <div class="form-group">
  768. <div class="col-sm-12">
  769. <label class="col-sm-4 control-label">Opis/źródło</label>
  770. <div class="col-sm-4">
  771. <input type="text" class="form-control" name="source" placeholder="KRS"/>
  772. </div>
  773. </div>
  774. </div>-->
  775. <div class="form-group">
  776. <div class="col-sm-12" style="text-align: center;">
  777. <button type="submit" class="btn btn-primary" name="subaction" value="addToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
  778. <button type="submit" class="btn btn-primary" name="subaction" value="addPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
  779. <input type="hidden" name="krsId" value="<?=$krsId?>"/>
  780. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
  781. <?php
  782. if (V::get('back', '', $_POST) == 'search') {
  783. foreach (array_keys($formItems) as $item) {
  784. ?>
  785. <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
  786. <?php
  787. }
  788. ?>
  789. <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
  790. <?php
  791. } else {
  792. ?>
  793. <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
  794. <?php
  795. }
  796. ?>
  797. </div>
  798. </div>
  799. <?php
  800. }
  801. ?>
  802. <input type="hidden" name="action" value="search">
  803. </form>
  804. </div>
  805. <script language="JavaScript">
  806. <!--
  807. function toggleAll(source) {
  808. checkboxes = document.getElementsByName('personId[]');
  809. checked = false;
  810. for(var i=0, n=checkboxes.length;i<n;i++) {
  811. if (!checkboxes[i].disabled) {
  812. checkboxes[i].checked = source.checked;
  813. checked = true;
  814. }
  815. }
  816. if (source.checked && (!checked)) source.checked = false;
  817. }
  818. function toggle(source) {
  819. checkboxes = document.getElementsByName('personId[]');
  820. all = true;
  821. for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
  822. source.form['checkAll'].checked = all;
  823. }
  824. function validatePerson(source) {
  825. checkboxes = document.getElementsByName('personId[]');
  826. checked = false;
  827. for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
  828. if (!checked) alert('Nie wybrano żadnej osoby!');
  829. return checked;
  830. }
  831. function validateCompany(source) {
  832. radios = document.getElementsByName('krsId');
  833. checked = false;
  834. for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
  835. if (!checked) alert('Nie wybrano żadnej firmy!');
  836. return checked;
  837. }
  838. -->
  839. </script>
  840. <?php
  841. }
  842. private function showKrsForKrsPerson() {
  843. $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
  844. $result = DB::getPDO()->fetchFirst($query);
  845. ?>
  846. <div class="container" style="margin-top:20px">
  847. <legend>
  848. Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
  849. </legend>
  850. <div class="form-group">
  851. <div class="col-sm-12">
  852. <table class="table table-bordered table-hover table-striped" height=5>
  853. <thead>
  854. <tr style="text-align:center; background-color:lightgray">
  855. <td width=1>Lp.</td>
  856. <td>Nazwa</td>
  857. <td>Adres</td>
  858. <td>KRS</td>
  859. <td>NIP</td>
  860. <td>Regon</td>
  861. <td width=1></td>
  862. </tr>
  863. </thead>
  864. <tbody>
  865. <?php
  866. $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
  867. $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']}'";
  868. $result = DB::getPDO()->fetchAll($query);
  869. if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
  870. else {
  871. $lp = 1;
  872. foreach ($result as $row) {
  873. $adres = $row['A_miejscowosc'];
  874. if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
  875. if ($row['A_nrDomu']) {
  876. $adres .= " {$row['A_nrDomu']}";
  877. if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
  878. }
  879. ?>
  880. <tr>
  881. <td align="right"><?=$lp++?></td>
  882. <td><?=htmlspecialchars($row['nazwa'])?></td>
  883. <td><?=htmlspecialchars($adres)?></td>
  884. <td><?=$row['krs']?></td>
  885. <td><?=$row['nip']?></td>
  886. <td><?=$row['regon']?></td>
  887. <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>
  888. </tr>
  889. <?php
  890. }
  891. }
  892. ?>
  893. </tbody>
  894. </table>
  895. </div>
  896. </div>
  897. <div class="form-group">
  898. <div class="col-sm-12">
  899. <div class="containter" style="text-align:center">
  900. <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
  901. </div>
  902. </div>
  903. </div>
  904. </div>
  905. <?php
  906. }
  907. private function clearTable_do() {
  908. try {
  909. $wynik = V::get('wynik', 0, $_POST, 'int');
  910. $ctrl = @gzuncompress(@base64_decode(V::get('_BiAuditGenerate_ctrl', '', $_SESSION)));
  911. unset($_SESSION['_BiAuditGenerate_ctrl']);
  912. $deleteFiles = (V::get('deleteFiles', '', $_POST) === 'on');
  913. $deletedDirs = 0; $deletedFiles = 0;
  914. if (!($ctrl)) throw new Exception('Błąd parametru');
  915. if (!($wynik == $ctrl)) {
  916. SE_Layout::alert('warning', 'Podano błędny wynik działania');
  917. $this->clearTable_form();
  918. return;
  919. }
  920. $refs = []; $backRefs = []; $tables = []; $queries = [];
  921. switch ($this->SOURCE['TABLE']) {
  922. case "BI_audit_ENERGA_PRACOWNICY":
  923. $refs[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
  924. $tables[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
  925. $queries[] = "update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'";
  926. break;
  927. case "BI_audit_ENERGA_PRACOWNICY_import":
  928. break;
  929. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  930. $backRefs[] = 'BI_audit_ENERGA_RUM_UMOWY';
  931. $backRefs[] = 'BI_audit_ENERGA_FAKTURY';
  932. $queries[] = "update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING'";
  933. break;
  934. case "BI_audit_ENERGA_RUM_UMOWY":
  935. $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  936. break;
  937. case "BI_audit_ENERGA_FAKTURY":
  938. $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
  939. break;
  940. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  941. $query = "select ID from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  942. $result = DB::getPDO()->fetchAll($query);
  943. foreach ($result as $row) {
  944. if ($deleteFiles) {
  945. $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  946. if (!file_exists($dir)) continue;
  947. $deleted = V::deleteWholeDirectory($dir, true, false);
  948. $deletedDirs += count($deleted['dirs']);
  949. $deletedFiles += count($deleted['files']);
  950. }
  951. self::deleteResultsFromDB($row['ID']);
  952. self::truncatePowiazaniaFromDB($row['ID']);
  953. }
  954. break;
  955. default: throw new Exception('Błąd parametru');
  956. }
  957. $tables[] = $this->SOURCE['TABLE'];
  958. foreach ($refs as $ref) $tables[] = BiAuditRefTables::getRefTable($this->SOURCE['TABLE'], $ref, true);
  959. foreach ($backRefs as $backRef) $tables[] = BiAuditRefTables::getRefTable($backRef, $this->SOURCE['TABLE'], true);
  960. foreach ($tables as $table) $queries[] = "delete from `{$table}`";
  961. foreach ($queries as $query) DB::getPDO()->query($query);
  962. ?>
  963. <div style="text-align: center;">
  964. <h2>Pomyślnie wyczyszczono tabelę <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>.</h2>
  965. <?php
  966. if ($deleteFiles && ($deletedDirs || $deletedFiles)):
  967. ?>
  968. <h4>Ponadto usunięto <?=$deletedDirs?> katalogów oraz <?=$deletedFiles?> plików.</h4>
  969. <?php
  970. endif;
  971. ?>
  972. <br/><a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  973. </div>
  974. <?php
  975. } catch (Exception $e) {
  976. SE_Layout::alert('danger', $e->getMessage());
  977. }
  978. }
  979. private function clearTable_form() {
  980. if (!isset($this->clearTable_tables[$this->SOURCE['TABLE']])) SE_Layout::alert('danger', 'Błąd parametru');
  981. $a = rand(10, 50);
  982. $b = rand(10, 50);
  983. if ($a == $b) $op = 1;
  984. else $op = rand(0, 1);
  985. if ($op) {
  986. $suma = $a + $b;
  987. $string = "{$a} + {$b}";
  988. } else {
  989. if ($a < $b) {
  990. $suma = $b - $a;
  991. $string = "{$b} - {$a}";
  992. } else {
  993. $suma = $a - $b;
  994. $string = "{$a} - {$b}";
  995. }
  996. }
  997. $string .= " = ";
  998. $_SESSION['_BiAuditGenerate_ctrl'] = base64_encode(gzcompress($suma));
  999. $im = imagecreate((strlen($string) - 1) * 10, 24);
  1000. $bg = imagecolorallocate($im, 255, 255, 255);
  1001. $textcolor = imagecolorallocate($im, 0, 0, 0);
  1002. imagestring($im, 5, 0, 0, $string, $textcolor);
  1003. ob_start();
  1004. imagepng($im);
  1005. $image = ob_get_contents();
  1006. ob_end_clean();
  1007. /*
  1008. $image = new Imagick();
  1009. $draw = new ImagickDraw();
  1010. $pixel = new ImagickPixel('white');
  1011. $image->newImage(200, 24, $pixel);
  1012. // $image->setFont("schema/WPS_Functions/mapserver_gml_to_png/map/fonts/Arial_Bold.ttf");
  1013. // $image->newPseudoImage(100, 100, "label:\"{$a} {$op} {$b}\"");
  1014. // $image->newPseudoImage(100, 100, "caption:Hello");
  1015. $image->setImageFormat('png');
  1016. $draw->setFillColor('black');
  1017. // $draw->setFont('Arial');
  1018. $draw->setFontSize(24);
  1019. $image->annotateImage($draw, 0, 24, 0, $s);
  1020. $image->trimImage(0);
  1021. */
  1022. $imageBase64 = base64_encode($image);
  1023. //echo $imageBase64;
  1024. ?>
  1025. <div style="text-align: center;">
  1026. <h2>Czy jesteś pewien, że chcesz usunąć<br/><b>wszystkie dane</b> z tabeli <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>?</h2><br/>
  1027. <h3>Podaj wynik działania:</h3>
  1028. <form method="post">
  1029. <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/>
  1030. <?php
  1031. if ($this->SOURCE['TABLE'] == 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'):
  1032. ?>
  1033. <h4><input type="checkbox" name="deleteFiles"/>&nbsp;&nbsp;Usuń również wszystkie pliki</h4><br/>
  1034. <?php
  1035. endif;
  1036. ?>
  1037. <button type="submit" class="btn btn-primary" name="action" value="doClearTable" style="width: 80px;">Tak</button>
  1038. <input type="hidden" name="REFERER" value="<?=$this->REFERER?>">
  1039. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Anuluj</a>
  1040. </form>
  1041. </div>
  1042. <?php
  1043. }
  1044. private function clearTable() {
  1045. $this->clearTable_tables = [
  1046. 'BI_audit_ENERGA_PRACOWNICY' => 'pracowników',
  1047. 'BI_audit_ENERGA_PRACOWNICY_import' => 'pracowników (import)',
  1048. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => 'kontrahentów',
  1049. 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA' => 'raportów',
  1050. 'BI_audit_ENERGA_RUM_UMOWY' => 'umów',
  1051. 'BI_audit_ENERGA_FAKTURY' => 'faktur',
  1052. ];
  1053. $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS'";
  1054. if (DB::getPDO()->fetchValue($query)) {
  1055. ?>
  1056. <div style="text-align: center;">
  1057. <h2>Nie można usunąć żadnych danych<br/>(wykryto uruchomione zadania)</h2><br/>
  1058. <a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
  1059. </div>
  1060. <?php
  1061. return;
  1062. }
  1063. $action = V::get('action', '', $_POST);
  1064. switch ($action) {
  1065. case "doClearTable":
  1066. $this->clearTable_do();
  1067. break;
  1068. default: $this->clearTable_form();
  1069. }
  1070. }
  1071. private static function getNamespace($table, $field = null) {
  1072. if ($field === null) return "default_db__x3A__{$table}";
  1073. return "default_db__x3A__{$table}:{$field}";
  1074. }
  1075. private static function arrayWithNamespace($table, $array) {
  1076. $keys = array_map(function($key) use ($table) {
  1077. return self::getNamespace($table, $key);
  1078. }, array_keys($array));
  1079. return array_combine($keys, $array);
  1080. }
  1081. private function benford_getDetails($a = null, $b = null) {
  1082. try {
  1083. if (!($benford = V::get('benford', '', $_SESSION))) throw new Exception("Nieznany błąd wewnętrzny #1");
  1084. if (isset($benford[$this->SOURCE['TABLE']]['details'][$a][$b])) throw new Exception(@gzuncompress($benford[$this->SOURCE['TABLE']]['details'][$a][$b]));
  1085. if (!($benford = @unserialize(@gzuncompress($benford[$this->SOURCE['TABLE']]['data'])))) throw new Exception("Nieznany błąd wewnętrzny #2");
  1086. if (!isset($benford['conf']['groupField'])) throw new Exception("Nieznany błąd wewnętrzny #3");
  1087. if (!($groupField = $benford['conf']['groupField'])) throw new Exception("Nieznany błąd wewnętrzny #4");
  1088. if ($a === null) throw new Exception("Nieznany błąd wewnętrzny #5");
  1089. if ($b === null) {
  1090. if (!isset($benford['firstStep'][$a]['keys'])) throw new Exception("Nieznany błąd wewnętrzny #6");
  1091. $keys = $benford['firstStep'][$a]['keys'];
  1092. } else {
  1093. if (!isset($benford['secondStep'][$a][$b]['keys'])) throw new Exception("Nieznany błąd wewnętrzny #7");
  1094. $keys = $benford['secondStep'][$a][$b]['keys'];
  1095. }
  1096. $tempTable = uniqid('_temp_benford_ids_');
  1097. DB::getPDO()->query("create temporary table `{$tempTable}` (`ID` int(11) NOT NULL, UNIQUE KEY `ID` (`ID`))");
  1098. foreach (array_chunk($keys, 100) as $ids) {
  1099. DB::getPDO()->query("insert into `{$tempTable}` values (" . implode('),(', $ids) . ")");
  1100. }
  1101. $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";
  1102. try {
  1103. $result = DB::getPDO()->fetchAll($query);
  1104. } catch (Exception $e) {
  1105. throw new Exception("Nieznany błąd, prawdopodobnie błędna konfiguracja kolumny grupującej");
  1106. }
  1107. $showDetails = "<h4>Najczęściej występujące wartości kolumny {$groupField}</h4>";
  1108. if ($result) {
  1109. $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><td>Procent występowania</td></tr></thead><tbody>";
  1110. $showDetails .= implode('', array_map(function($v) use ($keys) {
  1111. return "<tr><td>{$v['field']}</td><td>{$v['count']}</td><td>" . number_format(round($v['count'] / count($keys) * 100, 3), 3, ',', '') . "</td></tr>";
  1112. }, $result));
  1113. $showDetails .= "</tbody></table>";
  1114. } else {
  1115. $showDetails .= "<h5>Żadna wartość nie występuje wiele razy</h5>";
  1116. }
  1117. } catch (Exception $e) {
  1118. $showDetails = "<h4>{$e->getMessage()}</h4>";
  1119. }
  1120. $_SESSION['benford'][$this->SOURCE['TABLE']]['details'][$a][$b] = gzcompress($showDetails);
  1121. $showDetails .= '<button type="submit" class="btn btn-primary btn-sm" onClick="hideDetails()">Zamknij</button>';
  1122. return $showDetails;
  1123. }
  1124. private function benford_form($edit = false) {
  1125. if (!($valueField = V::get('_benfordValueField', '', $_GET))) throw new Exception ("Błąd konfiguracji UrlAction - brak parametru _benfordField (DANE )");
  1126. if (!($groupField = V::get('_benfordGroupField', '', $_GET))) throw new Exception("Brak konfiguracji kolumny grupującej");
  1127. if (!($namespace = V::get('_fromNamespace', '', $_GET))) throw new Exception("Błąd formularza");
  1128. Lib::loadClass('FeatureAttrSelected');
  1129. $count = FeatureAttrSelected::getTotalSelected($namespace);
  1130. $selectedTable = FeatureAttrSelected::getAttributeTableName($namespace, User::getID());
  1131. $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`";
  1132. $values = [];
  1133. try {
  1134. $result = DB::getPDO()->fetchAll($query);
  1135. foreach ($result as $row) $values[$row['ID']] = $row[$valueField];
  1136. } catch (Exception $e) {
  1137. throw new Exception("Błąd zapytania SQL ({$e->getMessage()})");
  1138. }
  1139. if (!$values) throw new Exception("Nie wybrano żadnych obiektów lub wszystkie wybrane obiekty mają zerową wartość");
  1140. Lib::loadClass('Benford');
  1141. try {
  1142. $benfordObj = new Benford($values);
  1143. $benford = $benfordObj->getAllResult();
  1144. $benford['conf'] = [
  1145. 'count' => count($values),
  1146. 'valueField' => $valueField,
  1147. 'groupField' => $groupField,
  1148. ];
  1149. $_SESSION['benford'][$this->SOURCE['TABLE']] = ['data' => gzcompress(serialize($benford))];
  1150. } catch (Exception $e) {
  1151. die($e->getMessage());
  1152. }
  1153. ?>
  1154. <div class="container" style="margin-top:20px">
  1155. <form method="post">
  1156. <legend>
  1157. Analiza rozkładu Benford'a
  1158. <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?></span>
  1159. </legend>
  1160. <div class="form-group">
  1161. <div class="col-sm-12">
  1162. <h5>Analiza na podstawie kolumny <?=$valueField?>. Liczba znalezionych obiektów z niezerową wartością: <?=count($values)?> (wybrano obiektów: <?=$count?>)</h5>
  1163. </div>
  1164. </div>
  1165. <?php if($edit):?>
  1166. <div class="form-group">
  1167. <div class="col-sm-12">
  1168. <center>
  1169. <h3>Generowanie raportu analizy rozkładu Benford'a</h3>
  1170. <table>
  1171. <tr>
  1172. <td>
  1173. <select name="step" class="form-control" onChange="toggleStep(this)">
  1174. <option value="first" selected>Pierwszy stopień analizy</option>
  1175. <option value="second">Drugi stopień analizy</option>
  1176. </select>
  1177. </td>
  1178. <td>&nbsp;&nbsp;</td>
  1179. <td><input type="text" class="form-control" name="L_APPOITMENT_INFO" title="Tytuł raportu" placeholder="Tytuł raportu" required/ size="50"></td>
  1180. <td>&nbsp;&nbsp;</td>
  1181. <td><button type="submit" class="btn btn-primary" name="action" value="generate" style="width: 80px;">Generuj</button></td>
  1182. </tr>
  1183. </table>
  1184. </center>
  1185. <br/><br/>
  1186. </div>
  1187. </div>
  1188. <?php endif;?>
  1189. <div class="form-group" id="benford">
  1190. <div class="col-sm-offset-2 col-sm-8">
  1191. <table class="table table-bordered table-hover table-striped table-condensed" id="benford">
  1192. <thead style="text-align:center; font-weight:bold; background-color:lightgray">
  1193. <tr>
  1194. <td style="vertical-align:middle;" rowspan="2">Pierwsze cyfry</td>
  1195. <td style="vertical-align:middle;" rowspan="2">Stopień analizy</td>
  1196. <td style="vertical-align:middle;" rowspan="2">Liczba wystąpień</td>
  1197. <td style="vertical-align:middle;" rowspan="2">Procent występowania</td>
  1198. <td colspan="3">Rozkład Benford'a</td>
  1199. <td style="vertical-align:middle;" rowspan="2">Szczegóły</td>
  1200. <?php if($edit):?>
  1201. <td style="vertical-align:middle;" rowspan="2">Załącz obiekty<br/>do&nbsp;raportu</td>
  1202. <?php endif;?>
  1203. </tr>
  1204. <tr>
  1205. <td nowrap>Norma (%)</td>
  1206. <td nowrap>Odchylenie od&nbsp;normy (%)</td>
  1207. <td>Zgodność</td>
  1208. </tr>
  1209. </thead>
  1210. <tbody>
  1211. <?php
  1212. $number_format = function($n) {
  1213. return number_format($n, 3, ',', '');
  1214. };
  1215. for ($ka = 1; $ka < 10; $ka++) {
  1216. if (!isset($benford['firstStep'][$ka])) $benford['firstStep'][$ka] = ['count' => 0, 'value' => 0, 'correct' => true];
  1217. $va = $benford['firstStep'][$ka];
  1218. $odchylenie = round(($va['value'] / Benford::benford($ka) - 1) * 100, 3);
  1219. if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
  1220. else $odchylenie = $number_format($odchylenie);
  1221. ?>
  1222. <tr style="text-align:center; font-weight:bold;<?=$va['correct'] ? '' : ' cursor:pointer;'?>"<?=$va['correct'] ? '' : ' onClick="toggleSecondStep(' . $ka . ');"'?>>
  1223. <td style="text-align:left" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$ka?></td>
  1224. <td class="step1-<?=$va['correct'] ? 'green' : 'red'?>">I</td>
  1225. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$va['count']?></td>
  1226. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round($va['value'] * 100, 3))?></td>
  1227. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round($va['norm'] * 100, 3))?></td>
  1228. <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
  1229. <td <?=$va['correct'] ? 'class="step1-green">Tak' : 'class="step1-red" name="firstStepDesc" data-ka="' . $ka . '" nowrap>Nie (rozwiń)'?></td>
  1230. <td<?=$va['correct'] ? '>' : ' onClick="showDetails(' . $ka . ', null)"><span class="glyphicon glyphicon-search"></span>'?></td>
  1231. <?php if($edit):?>
  1232. <td<?=$va['correct'] ? '' : ' onClick="_click(\'checkFirstStep_' . $ka . '\')"'?>><input type="checkbox" <?=$va['correct'] ? 'disabled' : 'checked id="checkFirstStep_' . $ka . '" name="checkFirstStep[]" value="' . $ka . '" onClick="toggleCheckFirst(this)"'?>></td>
  1233. <?php endif;?>
  1234. </tr>
  1235. <?php
  1236. if (!$va['correct']) {
  1237. for ($kb = 0; $kb < 10; $kb++) {
  1238. if (!isset($benford['secondStep'][$ka][$kb])) $benford['secondStep'][$ka][$kb] = ['count' => 0, 'value' => 0, 'correct' => true];
  1239. $vb = $benford['secondStep'][$ka][$kb];
  1240. $odchylenie = round(($vb['value'] / Benford::benford($ka * 10 + $kb) - 1) * 100, 3);
  1241. if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
  1242. else $odchylenie = $number_format($odchylenie);
  1243. ?>
  1244. <tr style="text-align:center;" name="secondStep" data-ka="<?=$ka?>" hidden>
  1245. <td style="text-align:left" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$ka . $kb?></td>
  1246. <td class="step2-<?=$vb['correct'] ? 'green' : 'red'?>">II</td>
  1247. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['count']?></td>
  1248. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round($vb['value'] * 100, 3))?></td>
  1249. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round($vb['norm'] * 100, 3))?></td>
  1250. <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
  1251. <td class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['correct'] ? 'Tak' : 'Nie'?></td>
  1252. <td<?=$vb['correct'] ? '>' : ' style="cursor:pointer;" onClick="showDetails(' . "{$ka}, {$kb}" . ')"><span class="glyphicon glyphicon-search"></span>'?></td>
  1253. <?php if($edit):?>
  1254. <td<?=$vb['correct'] ? '' : ' style="cursor:pointer;" onClick="_click(\'checkSecondStep_' . $ka . $kb . '\')"'?>><input type="checkbox"<?=$vb['correct'] ?: ' checked id="checkSecondStep_' . $ka . $kb . '" name="checkSecondStep[]" value="' . $ka . $kb . '" onClick="toggleCheckSecond(this)"'?> disabled></td>
  1255. <?php endif;?>
  1256. </tr>
  1257. <?php
  1258. }
  1259. }
  1260. }
  1261. ?>
  1262. </tbody>
  1263. </table>
  1264. </div>
  1265. </div>
  1266. </form>
  1267. </div>
  1268. <div id="details" onClick="hideDetails();">
  1269. <div id="detailsMsg" onClick="event.stopPropagation();"></div>
  1270. </div>
  1271. <style type="text/css">
  1272. <!--
  1273. #benford .step1-green,#benford .step1-red {font-weight:bold;}
  1274. #benford .step1-green,#benford .step2-green {color:#008800;}
  1275. #benford .step1-red,#benford .step2-red {color:#ff0000;}
  1276. #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;}
  1277. td {font-size: 12px;}
  1278. #benford ::selection {background: transparent;}
  1279. #details {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);}
  1280. #details div {width: 500px; height: auto; margin: 100px auto; background: #fff; padding: 10px; text-align: center; overflow: hidden; border-radius: 5px; box-shadow: 0 0 7px 7px rgba(0,0,0,0.25);}
  1281. -->
  1282. </style>
  1283. <script language="JavaScript">
  1284. <!--
  1285. function showDetails(ka, kb) {
  1286. event.stopPropagation();
  1287. document.getElementById('detailsMsg').innerHTML = "<h4>Proszę czekać...</h4>";
  1288. document.getElementById('details').style.display = 'block';
  1289. var post = "_noMenu=1&action=getDetails&_ka=" + ka;
  1290. if (kb !== null) post += "&_kb=" + kb;
  1291. var xhttp = new XMLHttpRequest();
  1292. xhttp.open("POST", '', true);
  1293. xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  1294. xhttp.onreadystatechange = function() {
  1295. if (this.readyState == 4 && this.status == 200) {
  1296. document.getElementById('detailsMsg').innerHTML = this.responseText;
  1297. }
  1298. }
  1299. xhttp.send(post);
  1300. }
  1301. function hideDetails() {
  1302. document.getElementById('details').style.display = 'none';
  1303. }
  1304. function _click(id) {
  1305. event.stopPropagation();
  1306. document.getElementById(id).click();
  1307. }
  1308. function toggleSecondStep(ka) {
  1309. var rows = document.getElementsByName('secondStep');
  1310. var hidden = false;
  1311. for(var i = 0, n = rows.length; i < n; i++) {
  1312. if (rows[i].dataset.ka == ka) {
  1313. rows[i].hidden = !rows[i].hidden;
  1314. hidden = rows[i].hidden;
  1315. }
  1316. }
  1317. var descs = document.getElementsByName('firstStepDesc');
  1318. for(var i = 0, n = descs.length; i < n; i++) {
  1319. if (descs[i].dataset.ka == ka) {
  1320. descs[i].innerHTML = (hidden ? 'Nie (rozwiń)' : 'Nie (zwiń)');
  1321. }
  1322. }
  1323. }
  1324. function toggleStep(option) {
  1325. if (option.value == 'first') first = true;
  1326. else if (option.value == 'second') first = false;
  1327. else {
  1328. alert('Wystąpił nieznany błąd formularza');
  1329. return;
  1330. }
  1331. var checks = document.getElementsByName('checkSecondStep[]');
  1332. var all = [];
  1333. for(var i = 0, n = checks.length; i < n; i++) {
  1334. checks[i].disabled = first;
  1335. ka = checks[i].value / 10 | 0;
  1336. if (all[ka] === 'undefined') all[ka] = checks[i].checked;
  1337. else if (checks[i].checked) all[ka] = true;
  1338. }
  1339. var checks = document.getElementsByName('checkFirstStep[]');
  1340. for(var i = 0, n = checks.length; i < n; i++) {
  1341. checks[i].disabled = !(first);
  1342. if (checks[i].checked != all[checks[i].value]) {
  1343. checks[i].checked = all[checks[i].value];
  1344. toggleCheckFirst(checks[i]);
  1345. }
  1346. }
  1347. var descs = document.getElementsByName('firstStepDesc');
  1348. for(var i = 0, n = descs.length; i < n; i++) {
  1349. descs[i].innerHTML = (first ? 'Nie (rozwiń)' : 'Nie (zwiń)');
  1350. }
  1351. var rows = document.getElementsByName('secondStep');
  1352. for(var i = 0, n = rows.length; i < n; i++) {
  1353. rows[i].hidden = first;
  1354. }
  1355. }
  1356. function toggleCheckFirst(check) {
  1357. event.stopPropagation();
  1358. var checks = document.getElementsByName('checkSecondStep[]');
  1359. for(var i = 0, n = checks.length; i < n; i++) {
  1360. if ((checks[i].value / 10 | 0) == check.value) checks[i].checked = check.checked;
  1361. }
  1362. }
  1363. function toggleCheckSecond(check) {
  1364. event.stopPropagation();
  1365. var checks = document.getElementsByName('checkSecondStep[]');
  1366. var all = true;
  1367. var ka = check.value / 10 | 0;
  1368. for(var i = 0, n = checks.length; i < n; i++) {
  1369. if ((checks[i].value / 10 | 0) == ka) {
  1370. if (!checks[i].checked) {
  1371. all = false;
  1372. break;
  1373. }
  1374. }
  1375. }
  1376. var checks = document.getElementsByName('checkFirstStep[]');
  1377. for(var i = 0, n = checks.length; i < n; i++) {
  1378. if (checks[i].value == ka) {
  1379. checks[i].checked = all;
  1380. break;
  1381. }
  1382. }
  1383. }
  1384. -->
  1385. </script>
  1386. <?php
  1387. }
  1388. private function benford_generate() {
  1389. $benfordId = null;
  1390. try {
  1391. $benford = @unserialize(@gzuncompress(V::get('benford', '', $_SESSION)[$this->SOURCE['TABLE']]['data']));
  1392. unset($_SESSION['benford'][$this->SOURCE['TABLE']]);
  1393. if (!$benford) {
  1394. $this->benford_form(true);
  1395. return;
  1396. }
  1397. $mainTable = 'BI_audit_BENFORD';
  1398. if (!($refTable = BiAuditRefTables::getRefTable($mainTable, $this->SOURCE['TABLE'], false))) throw new Exception("Nie znaleziono relacji do obiektu \"{$this->SOURCE['TABLE']}\" w konfiguracji obiektu \"{$mainTable}\" - nie można wygenerować raportu.");
  1399. $sqlArr = [
  1400. 'step' => V::get('step', '', $_POST),
  1401. 'table' => $this->SOURCE['TABLE'],
  1402. 'valueField' => $benford['conf']['valueField'],
  1403. 'groupField' => $benford['conf']['groupField'],
  1404. 'count' => $benford['conf']['count'],
  1405. 'L_APPOITMENT_INFO' => V::get('L_APPOITMENT_INFO', '', $_POST),
  1406. 'A_RECORD_CREATE_AUTHOR' => User::getName(),
  1407. 'A_RECORD_CREATE_DATE' => date('Y-m-d-H:i'),
  1408. ];
  1409. if (!($benfordId = DB::getPDO()->insert($mainTable, $sqlArr))) throw new Exception("Nie wygenerowano raportu - Wystąpił nieznany błąd podczas zapisywania raportu do bazy");
  1410. $dir = self::getDirectory($mainTable, $benfordId);
  1411. if (!file_exists($dir)) mkdir($dir, 0770, true);
  1412. if (!is_dir($dir)) throw new Exception("Nie wygenerowano raportu - wystąpił błąd podczas tworzenia katalogu dla rekordu");
  1413. $root = 'RelatedFeatureRoot';
  1414. $array = [];
  1415. $array['@attributes'] = [
  1416. 'xmlns' => 'http://www.opengis.net/wfs',
  1417. 'xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd',
  1418. 'xmlns:p5' => 'https://biuro.biall-net.pl/wfs',
  1419. 'xmlns:'.self::getNamespace($mainTable) => 'https://biuro.biall-net.pl/wfs',
  1420. 'xmlns:'.self::getNamespace($this->SOURCE['TABLE']) => 'https://biuro.biall-net.pl/wfs'
  1421. ];
  1422. $array[self::getNamespace($mainTable, $mainTable)] = array_merge(['@attributes' => ['fid' => "{$mainTable}.{$benfordId}", 'p5:primaryKey' => $benfordId]], self::arrayWithNamespace($mainTable, array_merge(['ID' => $benfordId], $sqlArr)));
  1423. $checked = [
  1424. 'firstStep' => V::get('checkFirstStep', [], $_POST),
  1425. 'secondStep' => V::get('checkSecondStep', [], $_POST),
  1426. ];
  1427. $firstStep = [];
  1428. for ($ka = 1; $ka <= 9; $ka++) {
  1429. if (!isset($benford['firstStep'][$ka])) $va = ['count' => 0, 'value' => 0, 'correct' => true];
  1430. else $va = $benford['firstStep'][$ka];
  1431. $_firstStep = [
  1432. '@attributes' => ['leadingNumber' => $ka],
  1433. 'count' => $va['count'],
  1434. 'value' => (double) round($va['value'], 5),
  1435. 'norm' => (double) round($va['norm'], 5),
  1436. 'deviation' => (double) round($va['value'] / $va['norm'] - 1, 5),
  1437. 'correct' => $va['correct'] ? 'true' : 'false',
  1438. ];
  1439. if ($array[self::getNamespace($mainTable, $mainTable)][self::getNamespace($mainTable, 'step')] == 'second' && (!$va['correct'])) {
  1440. $secondStep = [];
  1441. for ($kb = 0; $kb <= 9; $kb++) {
  1442. if (!isset($benford['secondStep'][$ka][$kb])) $vb = ['count' => 0, 'value' => 0, 'correct' => true];
  1443. else $vb = $benford['secondStep'][$ka][$kb];
  1444. $_secondStep = [
  1445. '@attributes' => ['leadingNumber' => $ka.$kb],
  1446. 'count' => $vb['count'],
  1447. 'value' => (double) round($vb['value'], 5),
  1448. 'norm' => (double) round($vb['norm'], 5),
  1449. 'deviation' => (double) round($vb['value'] / $vb['norm'] - 1, 5),
  1450. 'correct' => $vb['correct'] ? 'true' : 'false',
  1451. ];
  1452. if ((!$vb['correct']) && in_array($ka.$kb, $checked['secondStep'])) {
  1453. $objects = [];
  1454. foreach ($benford['secondStep'][$ka][$kb]['keys'] as $id) {
  1455. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $benfordId, 'REMOTE_PRIMARY_KEY' => $id]);
  1456. $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
  1457. if (!$object) continue;
  1458. $objects[] = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}", 'p5:primaryKey' => $id]], self::arrayWithNamespace($this->SOURCE['TABLE'], $object));
  1459. }
  1460. $_secondStep[self::getNamespace($this->SOURCE['TABLE'], $this->SOURCE['TABLE'])][] = $objects;
  1461. }
  1462. $secondStep[] = $_secondStep;
  1463. }
  1464. $_firstStep['secondStep'] = $secondStep;
  1465. } elseif ((!$va['correct']) && in_array($ka, $checked['firstStep'])) {
  1466. $objects = [];
  1467. foreach ($benford['firstStep'][$ka]['keys'] as $id) {
  1468. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $benfordId, 'REMOTE_PRIMARY_KEY' => $id]);
  1469. $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
  1470. if (!$object) continue;
  1471. $objects[] = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}", 'p5:primaryKey' => $id]], self::arrayWithNamespace($this->SOURCE['TABLE'], $object));
  1472. }
  1473. $_firstStep[self::getNamespace($this->SOURCE['TABLE'], $this->SOURCE['TABLE'])][] = $objects;
  1474. }
  1475. $firstStep[] = $_firstStep;
  1476. }
  1477. $array[self::getNamespace($mainTable, $mainTable)]['firstStep'] = $firstStep;
  1478. $xml = V::arrayToXML($array, true, $root);
  1479. file_put_contents($dir . DIRECTORY_SEPARATOR . "{$mainTable}_{$benfordId}.xml", $xml);
  1480. DB::getPDO()->update($mainTable, 'ID', $benfordId, ['A_STATUS' => 'NORMAL', 'A_STATUS_INFO' => 'Poprawnie wygenerowano raport']);
  1481. } catch (Exception $e) {
  1482. if ($benfordId) DB::getPDO()->update($mainTable, 'ID', $benfordId, ['A_STATUS' => 'DELETED', 'A_STATUS_INFO' => $e->getMessage()]);
  1483. SE_Layout::alert('danger', $e->getMessage());
  1484. }
  1485. ?>
  1486. <br><br>
  1487. <div style="text-align:center">
  1488. <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Powrót</a>
  1489. </div>
  1490. <?php
  1491. }
  1492. private function benford() {
  1493. try {
  1494. $action = V::get('action', '', $_POST);
  1495. switch ($action) {
  1496. case "generate":
  1497. $this->benford_generate();
  1498. break;
  1499. case "getDetails":
  1500. $ka = V::get('_ka', null, $_POST, 'int');
  1501. $kb = V::get('_kb', null, $_POST, 'int');
  1502. echo $this->benford_getDetails($ka, $kb);
  1503. break;
  1504. default:
  1505. $this->benford_form(true);
  1506. }
  1507. } catch (Exception $e) {
  1508. SE_Layout::alert('danger', $e->getMessage());
  1509. }
  1510. }
  1511. private function validate_form() {
  1512. if (!($namespace = V::get('_fromNamespace', '', $_GET))) throw new Exception("Błąd formularza");
  1513. Lib::loadClass('FeatureAttrSelected');
  1514. $count = FeatureAttrSelected::getTotalSelected($namespace);
  1515. $selectedTable = FeatureAttrSelected::getAttributeTableName($namespace, User::getID());
  1516. $query = "select `t`.`ID` from `{$this->SOURCE['TABLE']}` `t` join `{$selectedTable}` `s` on `t`.`ID` = `s`.`primaryKey` order by `s`.`primaryKey`";
  1517. $values = [];
  1518. try {
  1519. $result = DB::getPDO()->fetchAll($query);
  1520. $values = array_map('reset', $result);
  1521. } catch (Exception $e) {
  1522. throw new Exception("Błąd zapytania SQL ({$e->getMessage()})");
  1523. }
  1524. if (!$values) throw new Exception("Nie wybrano żadnych obiektów lub wszystkie wybrane obiekty mają zerową wartość");
  1525. $_SESSION['validate'][$this->SOURCE['TABLE']] = gzcompress(serialize($values));
  1526. ?>
  1527. <div class="container" style="margin-top:20px">
  1528. <form method="post">
  1529. <legend>
  1530. Analiza błędów
  1531. <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?></span>
  1532. </legend>
  1533. <div class="form-group">
  1534. <div class="col-sm-12">
  1535. <h5>Liczba wybranych obiektów: <?=count($values)?></h5>
  1536. </div>
  1537. </div>
  1538. <div class="form-group">
  1539. <div class="col-sm-12">
  1540. <center>
  1541. <h3>Generowanie raportu analizy błędów</h3>
  1542. <table>
  1543. <tr>
  1544. <td><input type="text" class="form-control" name="L_APPOITMENT_INFO" title="Tytuł raportu" placeholder="Tytuł raportu" required/ size="50"></td>
  1545. <td>&nbsp;&nbsp;</td>
  1546. <td><button type="submit" class="btn btn-primary" name="action" value="generate" style="width: 80px;">Generuj</button></td>
  1547. </tr>
  1548. </table>
  1549. </center>
  1550. <br/><br/>
  1551. </div>
  1552. </div>
  1553. </form>
  1554. </div>
  1555. <?php
  1556. }
  1557. private function validate_generate() {
  1558. $validateId = null;
  1559. try {
  1560. $validate = @unserialize(@gzuncompress(V::get('validate', '', $_SESSION)[$this->SOURCE['TABLE']]));
  1561. unset($_SESSION['validate'][$this->SOURCE['TABLE']]);
  1562. if (!$validate) {
  1563. $this->validate_form();
  1564. return;
  1565. }
  1566. $mainTable = 'BI_audit_VALIDATE';
  1567. if (!($refTable = BiAuditRefTables::getRefTable($mainTable, $this->SOURCE['TABLE'], false))) throw new Exception("Nie znaleziono relacji do obiektu \"{$this->SOURCE['TABLE']}\" w konfiguracji obiektu \"{$mainTable}\" - nie można wygenerować raportu.");
  1568. $sqlArr = [
  1569. 'table' => $this->SOURCE['TABLE'],
  1570. 'L_APPOITMENT_INFO' => V::get('L_APPOITMENT_INFO', '', $_POST),
  1571. 'A_RECORD_CREATE_AUTHOR' => User::getName(),
  1572. 'A_RECORD_CREATE_DATE' => date('Y-m-d-H:i'),
  1573. ];
  1574. if (!($validateId = DB::getPDO()->insert($mainTable, $sqlArr))) throw new Exception("Nie wygenerowano raportu - Wystąpił nieznany błąd podczas zapisywania raportu do bazy");
  1575. $dir = self::getDirectory($mainTable, $validateId);
  1576. if (!file_exists($dir)) mkdir($dir, 0770, true);
  1577. if (!is_dir($dir)) throw new Exception("Nie wygenerowano raportu - wystąpił błąd podczas tworzenia katalogu dla rekordu");
  1578. $root = 'RelatedFeatureRoot';
  1579. $array = [];
  1580. $array['@attributes'] = [
  1581. 'xmlns' => 'http://www.opengis.net/wfs',
  1582. 'xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd',
  1583. 'xmlns:p5' => 'https://biuro.biall-net.pl/wfs',
  1584. 'xmlns:xlink' => 'http://www.w3.org/1999/xlink',
  1585. 'xmlns:'.self::getNamespace($mainTable) => 'https://biuro.biall-net.pl/wfs',
  1586. 'xmlns:'.self::getNamespace($this->SOURCE['TABLE']) => 'https://biuro.biall-net.pl/wfs',
  1587. 'xmlns:'.self::getNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI') => 'https://biuro.biall-net.pl/wfs',
  1588. 'xmlns:'.self::getNamespace('BI_audit_ENERGA_FAKTURY') => 'https://biuro.biall-net.pl/wfs',
  1589. ];
  1590. $array[self::getNamespace($mainTable, $mainTable)] = array_merge(['@attributes' => ['fid' => "{$mainTable}.{$validateId}", 'p5:primaryKey' => $validateId]], self::arrayWithNamespace($mainTable, array_merge(['ID' => $validateId], $sqlArr)));
  1591. $umowy = [];
  1592. $kontrahenci = [];
  1593. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1594. $refFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  1595. foreach ($validate as $id) {
  1596. $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
  1597. if (!$object) continue;
  1598. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $validateId, 'REMOTE_PRIMARY_KEY' => $id]);
  1599. $_umowa = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}", 'p5:primaryKey' => $id]], self::arrayWithNamespace($this->SOURCE['TABLE'], $object));
  1600. $kontrahenciId = array_map('reset', DB::getPDO()->fetchAll("select `REMOTE_PRIMARY_KEY` from `{$refUmowyToKontrahenci}` where `PRIMARY_KEY` = " . DB::getPDO()->quote($id)));
  1601. $_kontrahenci = [];
  1602. $_kontrahenciId = [];
  1603. foreach ($kontrahenciId as $kontrahentId) {
  1604. $_kontrahenciId[] = $kontrahentId;
  1605. if (!isset($kontrahenci[$kontrahentId])) {
  1606. if ($kontrahent = DB::getPDO()->fetchFirst("select * from `BI_audit_ENERGA_RUM_KONTRAHENCI` where `ID` = {$kontrahentId}")) {
  1607. $kontrahenci[$kontrahentId] = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_KONTRAHENCI.{$kontrahentId}", 'p5:primaryKey' => $kontrahentId]],
  1608. self::arrayWithNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI', $kontrahent));
  1609. $fakturyId = array_map('reset', DB::getPDO()->fetchAll("select `PRIMARY_KEY` from `{$refFakturyToKontrahenci}` where `REMOTE_PRIMARY_KEY` = {$kontrahentId}"));
  1610. $faktury = [];
  1611. foreach ($fakturyId as $fakturaId) {
  1612. if ($faktura = DB::getPDO()->fetchFirst("select * from `BI_audit_ENERGA_FAKTURY` where `ID` = {$fakturaId}")) {
  1613. $faktury[] = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_FAKTURY.{$fakturaId}", 'p5:primaryKey' => $fakturaId]],
  1614. self::arrayWithNamespace('BI_audit_ENERGA_FAKTURY', $faktura));
  1615. }
  1616. }
  1617. if ($faktury) $kontrahenci[$kontrahentId][self::getNamespace('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_FAKTURY')] = $faktury;
  1618. }
  1619. }
  1620. }
  1621. $_kontrahenciId = array_unique($_kontrahenciId, SORT_NUMERIC);
  1622. foreach ($_kontrahenciId as $kontrahentId) {
  1623. $_kontrahenci[] = ['@attributes' => ['xlink:href' => "https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI#BI_audit_ENERGA_RUM_KONTRAHENCI.{$kontrahentId}", 'p5:primaryKey' => $kontrahentId]];
  1624. }
  1625. $_umowa[self::getNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_ENERGA_RUM_KONTRAHENCI')] = $_kontrahenci;
  1626. $umowy[] = $_umowa;
  1627. }
  1628. if ($umowy) $array[self::getNamespace($mainTable, $mainTable)][self::getNamespace($this->SOURCE['TABLE'], $this->SOURCE['TABLE'])] = $umowy;
  1629. if ($kontrahenci) {
  1630. ksort($kontrahenci, SORT_NUMERIC);
  1631. $array[self::getNamespace($mainTable, $mainTable)][self::getNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_ENERGA_RUM_KONTRAHENCI')] = $kontrahenci;
  1632. }
  1633. $xml = V::arrayToXML($array, true, $root);
  1634. file_put_contents($dir . DIRECTORY_SEPARATOR . "{$mainTable}_{$validateId}.xml", $xml);
  1635. DB::getPDO()->update($mainTable, 'ID', $validateId, ['A_STATUS' => 'NORMAL', 'A_STATUS_INFO' => 'Poprawnie wygenerowano raport']);
  1636. SE_Layout::alert('success', "Poprawnie wygenerowano raport");
  1637. } catch (Exception $e) {
  1638. if ($validateId) DB::getPDO()->update($mainTable, 'ID', $validateId, ['A_STATUS' => 'DELETED', 'A_STATUS_INFO' => $e->getMessage()]);
  1639. SE_Layout::alert('danger', $e->getMessage());
  1640. }
  1641. }
  1642. private function validate() {
  1643. try {
  1644. $action = V::get('action', '', $_POST);
  1645. switch ($action) {
  1646. case "generate":
  1647. $this->validate_generate();
  1648. break;
  1649. default:
  1650. $this->validate_form();
  1651. }
  1652. } catch (Exception $e) {
  1653. SE_Layout::alert('danger', $e->getMessage());
  1654. }
  1655. }
  1656. public function defaultAction() {
  1657. $showMenu = !(V::get('_noMenu', false, $_POST));
  1658. if ($showMenu) {
  1659. SE_Layout::gora();
  1660. SE_Layout::menu();
  1661. }
  1662. if (isset($_SESSION['REFERER'])) {
  1663. $this->REFERER = $_SESSION['REFERER'];
  1664. unset($_SESSION['REFERER']);
  1665. } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
  1666. else $this->REFERER=$_SERVER['HTTP_REFERER'];
  1667. if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
  1668. elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
  1669. elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1670. elseif (($ID = V::get('ID_BI_audit_MSIG', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_MSIG';
  1671. elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
  1672. if ($this->SOURCE) {
  1673. $this->SOURCE['ID'] = $ID;
  1674. $this->urlActionOnItem();
  1675. }
  1676. elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
  1677. $this->SOURCE['TABLE'] = ACL::getAclByTypeName($TABLE)->getRootTableName();
  1678. $_subUrlAction = V::get('_subUrlAction', '', $_GET);
  1679. switch ($this->SOURCE['TABLE']) {
  1680. case "BI_audit_ENERGA_PRACOWNICY":
  1681. switch ($_subUrlAction) {
  1682. case "clearTable":
  1683. $this->clearTable();
  1684. break;
  1685. case "importFromKRS":
  1686. $this->SOURCE['TABLE'] = 'BI_audit_KRS';
  1687. $this->importToPracownicy();
  1688. break;
  1689. default: SE_Layout::alert('danger', 'Błąd parametru #21');
  1690. }
  1691. break;
  1692. case "BI_audit_ENERGA_PRACOWNICY_import":
  1693. switch ($_subUrlAction) {
  1694. case "clearTable":
  1695. $this->clearTable();
  1696. break;
  1697. default: SE_Layout::alert('danger', 'Błąd parametru #22');
  1698. }
  1699. break;
  1700. case "BI_audit_ENERGA_RUM_KONTRAHENCI":
  1701. switch ($_subUrlAction) {
  1702. case "clearTable":
  1703. $this->clearTable();
  1704. break;
  1705. default: SE_Layout::alert('danger', 'Błąd parametru #23');
  1706. }
  1707. break;
  1708. case "BI_audit_ENERGA_RUM_UMOWY":
  1709. switch ($_subUrlAction) {
  1710. case "clearTable":
  1711. $this->clearTable();
  1712. break;
  1713. case "benford":
  1714. $this->benford();
  1715. break;
  1716. case "validate":
  1717. $this->validate();
  1718. break;
  1719. default: SE_Layout::alert('danger', 'Błąd parametru #24');
  1720. }
  1721. break;
  1722. case "BI_audit_ENERGA_FAKTURY":
  1723. switch ($_subUrlAction) {
  1724. case "clearTable":
  1725. $this->clearTable();
  1726. break;
  1727. case "benford":
  1728. $this->benford();
  1729. break;
  1730. default: SE_Layout::alert('danger', 'Błąd parametru #25');
  1731. }
  1732. break;
  1733. case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
  1734. switch ($_subUrlAction) {
  1735. case "clearTable":
  1736. $this->clearTable();
  1737. break;
  1738. default: SE_Layout::alert('danger', 'Błąd parametru #25');
  1739. }
  1740. break;
  1741. default:
  1742. switch ($_subUrlAction) {
  1743. case "benford":
  1744. $this->benford();
  1745. break;
  1746. default: SE_Layout::alert('danger', 'Błąd parametru #1');
  1747. }
  1748. }
  1749. }
  1750. else SE_Layout::alert('danger', 'Błąd parametru #0');
  1751. if ($showMenu) {
  1752. echo "<br/><br/>";
  1753. SE_Layout::dol();
  1754. }
  1755. }
  1756. private static function truncatePowiazaniaFromDB($ID) {
  1757. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
  1758. if (!$refTables) return null;
  1759. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1760. $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
  1761. $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
  1762. foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1763. $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1764. DB::getPDO()->query($query);
  1765. }
  1766. public static function deleteResultsFromDB($ID) {
  1767. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  1768. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  1769. $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
  1770. $sqlDeleteFrom = "delete from
  1771. `{$refPowiazaniaToPowiazaniaRow}`,
  1772. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
  1773. `{$refPowiazaniaRowToPowiazaniaRowObject}`,
  1774. `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
  1775. $sqlUsing = "
  1776. using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
  1777. join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
  1778. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
  1779. join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
  1780. join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
  1781. $sqlWhere = "
  1782. where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
  1783. foreach ($refTables as $refTable) {
  1784. $sqlDeleteFrom .= ",\n`{$refTable}`";
  1785. $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
  1786. }
  1787. $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
  1788. DB::getPDO()->query($query);
  1789. }
  1790. public function doGenerate() {
  1791. $generatePhpScript = function($function) {
  1792. return '<?php
  1793. ini_set("memory_limit", "4G");
  1794. define("DS", DIRECTORY_SEPARATOR);
  1795. define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
  1796. define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
  1797. define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
  1798. ini_set("display_startup_errors", "0");
  1799. ini_set("display_errors", "1");
  1800. ini_set("log_errors", "1");
  1801. ini_set("error_log", "/var/log/apache2/error_log");
  1802. $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
  1803. require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
  1804. date_default_timezone_set("Europe/Warsaw");
  1805. Lib::loadClass("Router");
  1806. Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
  1807. ';
  1808. };
  1809. try {
  1810. ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
  1811. $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
  1812. ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
  1813. $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
  1814. if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
  1815. ### Ustawienie zmiennych
  1816. $powiazaniaDirLocation = self::getMainDirectory();
  1817. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  1818. $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
  1819. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  1820. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  1821. $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
  1822. ### Utworzenie niezbędnych katalogów i plików
  1823. if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
  1824. if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
  1825. ### 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
  1826. $sqlArr = [
  1827. 'BI_analiza_reloadCache' => 'No',
  1828. ];
  1829. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part', 'Full') and FILE_STATUS = 'TO_GENERATE'";
  1830. $result = DB::getPDO()->fetchAll($query);
  1831. foreach ($result as $row) {
  1832. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1833. }
  1834. /* 2018-04-19 - zmieniono działanie silnika tak, aby sam wykrywał czy należy wykonać pełne odświeżenie cache
  1835. ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
  1836. $doGenerate = true;
  1837. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
  1838. $result = DB::getPDO()->fetchAll($query);
  1839. if ($result) {
  1840. $doGenerate = false;
  1841. $sqlArr = [];
  1842. if (file_exists($reloadCachePhpFile)) {
  1843. if (file_exists($reloadCacheResultFile)) {
  1844. $reloadCacheResult = file_get_contents($reloadCacheResultFile);
  1845. if ($reloadCacheResult == "ok") {
  1846. $sqlArr = [
  1847. 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
  1848. 'BI_analiza_reloadCache' => 'No',
  1849. ];
  1850. $doGenerate = true;
  1851. } else {
  1852. $sqlArr = [
  1853. 'FILE_STATUS' => 'ERROR',
  1854. 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
  1855. ];
  1856. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1857. $result = DB::getPDO()->fetchAll($query);
  1858. }
  1859. unlink($reloadCachePhpFile);
  1860. unlink($reloadCachePidFile);
  1861. unlink($reloadCacheResultFile);
  1862. } elseif (file_exists($reloadCachePidFile)) {
  1863. $pid = file_get_contents($reloadCachePidFile);
  1864. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1865. $processShouldBeRunning = "php {$reloadCachePhpFile}";
  1866. if ($processRunning != $processShouldBeRunning) {
  1867. if (!file_exists($reloadCacheResultFile)) {
  1868. $sqlArr = [
  1869. 'FILE_STATUS' => 'ERROR',
  1870. 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
  1871. ];
  1872. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
  1873. $result = DB::getPDO()->fetchAll($query);
  1874. unlink($reloadCachePhpFile);
  1875. unlink($reloadCachePidFile);
  1876. unlink($reloadCacheResultFile);
  1877. }
  1878. }
  1879. }
  1880. } else {
  1881. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1882. $result2 = DB::getPDO()->fetchValue($query);
  1883. if ($result2) {
  1884. $sqlArr = [
  1885. 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
  1886. ];
  1887. } else {
  1888. $sqlArr = [
  1889. 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
  1890. ];
  1891. $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
  1892. $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
  1893. file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
  1894. shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
  1895. }
  1896. }
  1897. if ($sqlArr) {
  1898. foreach ($result as $row) {
  1899. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
  1900. }
  1901. }
  1902. }
  1903. */ $doGenerate = true;
  1904. ### Generowanie powiązań
  1905. if ($doGenerate) {
  1906. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
  1907. $result = DB::getPDO()->fetchAll($query);
  1908. foreach ($result as $row) {
  1909. $sqlArr = [
  1910. 'ID' => $row['ID'],
  1911. 'FILE_STATUS' => 'IN_PROGRESS',
  1912. 'FILE_STATUS_info' => 'Zadanie wyzwolone',
  1913. ];
  1914. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  1915. self::deleteResultsFromDB($row['ID']);
  1916. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1917. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1918. $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
  1919. $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
  1920. if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
  1921. if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
  1922. file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
  1923. shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
  1924. }
  1925. }
  1926. ### Weryfikacja świeżo wygenerowanych powiązań
  1927. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
  1928. $result = DB::getPDO()->fetchAll($query);
  1929. foreach ($result as $row) {
  1930. $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
  1931. $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
  1932. $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
  1933. $error = false;
  1934. $success = false;
  1935. $sqlArr = [];
  1936. if (file_exists($generatePowiazaniaResultFile)) {
  1937. $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
  1938. if ($generatePowiazaniaResult['result'] == "ok") {
  1939. $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
  1940. if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
  1941. if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
  1942. else $success = true;
  1943. } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
  1944. } elseif (file_exists($generatePowiazaniaPidFile)) {
  1945. $pid = file_get_contents($generatePowiazaniaPidFile);
  1946. $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
  1947. $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
  1948. if ($processRunning != $processShouldBeRunning) {
  1949. if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
  1950. }
  1951. }
  1952. if ($error) {
  1953. $sqlArr = [
  1954. 'FILE_STATUS' => 'ERROR',
  1955. 'FILE_STATUS_info' => $error,
  1956. ];
  1957. //self::deleteResultsFromDB($row['ID']);
  1958. //if (file_exists($xmlFile)) unlink($xmlFile);
  1959. } elseif ($success) {
  1960. $sqlArr = [
  1961. 'FILE_STATUS' => 'GENERATED',
  1962. 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
  1963. ];
  1964. if ($generatePowiazaniaResult['parts']) {
  1965. for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
  1966. $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
  1967. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
  1968. $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
  1969. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1970. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1971. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1972. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
  1973. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
  1974. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
  1975. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
  1976. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1977. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1978. if (file_exists($generatePowiazaniaHtmlDir)) {
  1979. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1980. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1981. }
  1982. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  1983. }
  1984. } else {
  1985. $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
  1986. $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
  1987. $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
  1988. $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
  1989. $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
  1990. $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
  1991. $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
  1992. $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
  1993. if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
  1994. if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
  1995. if (file_exists($generatePowiazaniaHtmlDir)) {
  1996. if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
  1997. rename($generatePowiazaniaHtmlDir, $destHtmlDir);
  1998. }
  1999. if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
  2000. }
  2001. }
  2002. if ($sqlArr) {
  2003. $sqlArr['ID'] = $row['ID'];
  2004. DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
  2005. if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
  2006. if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
  2007. if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
  2008. }
  2009. }
  2010. } catch (Exception $e) {
  2011. echo $e->getMessage()."\n";
  2012. }
  2013. }
  2014. private static function importPracownicy($full = false) {
  2015. $fields = [
  2016. 'BI_audit_ENERGA_PRACOWNICY' => [
  2017. 'imiona' => 'imiona',
  2018. 'nazwisko' => 'nazwisko',
  2019. 'pesel' => 'pesel',
  2020. 'jednostka_organizacyjna' => 'jednostka_organizacyjna',
  2021. 'GUID' => 'GUID',
  2022. ],
  2023. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2024. 'kodPocztowy' => 'kodPocztowy',
  2025. 'miejscowosc' => 'miejscowosc',
  2026. 'ulica' => 'ulica',
  2027. 'nrBudynku' => 'nr',
  2028. 'nrLokalu' => 'nrLokalu',
  2029. ],
  2030. ];
  2031. $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', true);
  2032. if ($full) DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'");
  2033. DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `pesel` = null where `A_STATUS` = 'WAITING' and isPesel(`pesel`) = 0");
  2034. $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `A_STATUS` = 'WAITING'";
  2035. $pracownicy = DB::getPDO()->query($query);
  2036. while ($pracownik = $pracownicy->fetch()) {
  2037. if ($pracownik['pesel']) {
  2038. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}' or (coalesce(`pesel`, '') = '' and `GUID` = '{$pracownik['GUID']}')");
  2039. } elseif ($pracownik['GUID']) {
  2040. $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `GUID` = '{$pracownik['GUID']}'");
  2041. } else {
  2042. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
  2043. continue;
  2044. }
  2045. $sqlArr = [];
  2046. $sqlArr['source'] = 'import';
  2047. $sqlArr['cached'] = '0';
  2048. foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $tableField => $importField) {
  2049. $sqlArr[$tableField] = trim($pracownik[$importField]);
  2050. if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
  2051. }
  2052. if ($ID_pracownik) {
  2053. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID_pracownik, $sqlArr);
  2054. $full = true;
  2055. }
  2056. else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
  2057. $sqlArr = [];
  2058. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
  2059. $sqlArr[$tableField] = trim($pracownik[$importField]);
  2060. if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
  2061. }
  2062. if (!$sqlArr) {
  2063. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
  2064. continue;
  2065. }
  2066. $sqlWhereArr = [];
  2067. $sqlWhereArr[] = "`{$refTable}`.`PRIMARY_KEY` = '{$ID_pracownik}'";
  2068. foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
  2069. if (isset($sqlArr[$tableField])) $sqlWhereArr[] = "`BI_audit_ENERGA_PRACOWNICY_adresy`.`{$tableField}` = " . DB::getPDO()->quote($sqlArr[$tableField]);
  2070. else $sqlWhereArr[] = "`{$tableField}` is null";
  2071. }
  2072. $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);
  2073. if (!(DB::getPDO()->fetchValue($query))) {
  2074. $ID_adres = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_adresy', $sqlArr);
  2075. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $ID_pracownik, 'REMOTE_PRIMARY_KEY' => $ID_adres]);
  2076. }
  2077. DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'NORMAL']);
  2078. }
  2079. return $full;
  2080. }
  2081. private static function reloadCache_parseFakturyUmowy($full = false) {
  2082. $fields = [
  2083. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2084. 'Tytul_dokumentu',
  2085. 'Pelna_nazwa_kontrahenta',
  2086. 'NIP',
  2087. 'REGON',
  2088. 'KRS',
  2089. 'Kraj',
  2090. 'Kod_pocztowy',
  2091. 'Miejscowosc',
  2092. 'Ulica',
  2093. 'Numer_budynku',
  2094. 'Numer_mieszkania_lokalu',
  2095. 'TERYT_SYM',
  2096. 'TERYT_SYM_UL',
  2097. ],
  2098. 'BI_audit_KRS' => [
  2099. '"Zaimportowano z KRS na podstawie faktury/umowy"',
  2100. 'nazwa',
  2101. 'nip',
  2102. 'regon',
  2103. 'krs',
  2104. 'A_kraj',
  2105. 'A_kod',
  2106. 'A_miejscowosc',
  2107. 'A_ulica',
  2108. 'A_nrDomu',
  2109. 'A_nrLokalu',
  2110. 'TERYT_SYM',
  2111. 'TERYT_SYM_UL',
  2112. ],
  2113. 'BI_audit_CEIDG' => [
  2114. '"Zaimportowano z CEiDG na podstawie faktury/umowy"',
  2115. 'firma',
  2116. 'nip',
  2117. 'regon',
  2118. 'null',
  2119. 'kraj',
  2120. 'kodPocztowy',
  2121. 'miejscowosc',
  2122. 'ulica',
  2123. 'budynek',
  2124. 'lokal',
  2125. 'TERYT_SYM',
  2126. 'TERYT_SYM_UL',
  2127. ],
  2128. ];
  2129. $refTableFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  2130. $refTableUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  2131. if ($full) {
  2132. DB::getPDO()->query("truncate table `{$refTableFakturyToKontrahenci}`");
  2133. DB::getPDO()->query("truncate table `{$refTableUmowyToKontrahenci}`");
  2134. DB::getPDO()->query("update `BI_audit_ENERGA_FAKTURY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  2135. DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
  2136. }
  2137. $query = "select `ID`, `NIP` from `BI_audit_ENERGA_FAKTURY` where `A_STATUS` = 'WAITING'";
  2138. $result = DB::getPDO()->fetchAll($query);
  2139. foreach ($result as $row) {
  2140. $ID = $row['ID'];
  2141. $nip = trim($row['NIP']);
  2142. if (!$full) {
  2143. $query = "delete from `{$refTableFakturyToKontrahenci}` where PRIMARY_KEY = '{$row['ID']}'";
  2144. DB::getPDO()->query($query);
  2145. }
  2146. if (!$nip) {
  2147. DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'OFF_SOFT']);
  2148. continue;
  2149. }
  2150. $K_IDs = [];
  2151. $query = "select `ID` from `BI_audit_ENERGA_RUM_KONTRAHENCI` where `NIP` = '{$nip}'";
  2152. if ($result2 = DB::getPDO()->fetchall($query)) {
  2153. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  2154. } else {
  2155. $query = "select ID from BI_audit_KRS where nip = '{$nip}' order by `ID` desc limit 1";
  2156. if ($result2 = DB::getPDO()->fetchall($query)) {
  2157. foreach ($result2 as $item) {
  2158. $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  2159. " select " . implode(', ', $fields['BI_audit_KRS']) . " from `BI_audit_KRS` where `ID` = '{$item['ID']}'";
  2160. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  2161. }
  2162. } else {
  2163. $query = "select `ID` from `BI_audit_CEIDG` where `nip` = '{$nip}' order by `ID` desc limit 1";
  2164. if ($result2 = DB::getPDO()->fetchall($query)) {
  2165. foreach ($result2 as $item) {
  2166. $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  2167. " select " . implode(', ', $fields['BI_audit_CEIDG']) . " from `BI_audit_CEIDG` where `ID` = '{$item['ID']}'";
  2168. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  2169. }
  2170. }
  2171. }
  2172. }
  2173. foreach ($K_IDs as $K_ID) {
  2174. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableFakturyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  2175. DB::getPDO()->query("insert into `{$refTableFakturyToKontrahenci}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`) values ({$ID}, {$K_ID})");
  2176. }
  2177. }
  2178. DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  2179. }
  2180. foreach (['Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_', 'Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_', 'Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_', 'Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_', 'Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_'] as $field) DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `{$field}` = replace(`{$field}`, ',', '.') where `A_STATUS` = 'WAITING'");
  2181. $query = <<<SQL
  2182. update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` =
  2183. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` > 1, convert(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`, double),
  2184. if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` > 1, convert(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`, double),
  2185. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` > 1, convert(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`, double),
  2186. if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` > 1, convert(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`, double),
  2187. if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` > 1, convert(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, double), 0))))) where `A_STATUS` = 'WAITING';
  2188. SQL;
  2189. DB::getPDO()->query($query);
  2190. $query = "select `ID`, `Kontrahenci` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
  2191. $result = DB::getPDO()->fetchAll($query);
  2192. foreach ($result as $row) {
  2193. $ID = $row['ID'];
  2194. if (!$full) {
  2195. $query = "delete from `{$refTableUmowyToKontrahenci}` where PRIMARY_KEY = '{$ID}'";
  2196. DB::getPDO()->query($query);
  2197. }
  2198. $kontrahenci = array_map('trim', explode("|", $row['Kontrahenci']));
  2199. $K_IDs = [];
  2200. foreach ($kontrahenci as $item) {
  2201. $kontrahent = array_map('trim', explode(";", $item));
  2202. $nr = null;
  2203. if (count($kontrahent) == 3) $i = 1;//$nr = $kontrahent[1];
  2204. elseif (count($kontrahent) == 4) $i = 2;//$nr = $kontrahent[2];
  2205. elseif (count($kontrahent) >= 5 && count($kontrahent) <= 6) $i = 3;//$nr = $kontrahent[3];
  2206. else $i = null;
  2207. if ($i) $nr = $kontrahent[$i];
  2208. $notFound = false;
  2209. if (is_numeric($nr)) {
  2210. $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)";
  2211. if ($K_ID = DB::getPDO()->fetchValue($query)) {
  2212. $K_IDs[] = $K_ID;
  2213. } else {
  2214. $nazwa = $kontrahent[$i+1];
  2215. $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)";
  2216. if ($result2 = DB::getPDO()->fetchAll($query)) {
  2217. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  2218. } else $notFound = true;
  2219. }
  2220. } else $notFound = true;
  2221. if ($notFound) {
  2222. list($nip, $regon) = self::parseNipRegon($item);
  2223. if ($nip || $regon) {
  2224. $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
  2225. if ($result2 = DB::getPDO()->fetchall($query)) {
  2226. foreach ($result2 as $item) $K_IDs[] = $item['ID'];
  2227. } else {
  2228. $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
  2229. if ($result2 = DB::getPDO()->fetchall($query)) {
  2230. foreach ($result2 as $item) {
  2231. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  2232. " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
  2233. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  2234. }
  2235. } else {
  2236. $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
  2237. if ($result2 = DB::getPDO()->fetchall($query)) {
  2238. foreach ($result2 as $item) {
  2239. $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
  2240. " select " . implode(', ', $fields['BI_audit_CEIDG']) .
  2241. " from BI_audit_CEIDG where ID = '{$item['ID']}'";
  2242. if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
  2243. }
  2244. }
  2245. }
  2246. }
  2247. }
  2248. }
  2249. }
  2250. foreach ($K_IDs as $K_ID) {
  2251. if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableUmowyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
  2252. DB::getPDO()->query("insert into `{$refTableUmowyToKontrahenci}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
  2253. }
  2254. }
  2255. DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
  2256. }
  2257. $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";
  2258. $result = DB::getPDO()->fetchAll($query);
  2259. foreach ($result as $row) {
  2260. $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
  2261. if ($items = DB::getPDO()->fetchAll($query)) {
  2262. list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
  2263. if (count($items) > 1) {
  2264. for ($i = 1; $i < count($items); $i++) {
  2265. if ($nip != $items[$i]["nip"]) $nip = null;
  2266. if ($regon != $items[$i]["regon"]) $regon = null;
  2267. if ($krs != $items[$i]["krs"]) $krs = null;
  2268. }
  2269. }
  2270. $set = [];
  2271. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  2272. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  2273. if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
  2274. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
  2275. }
  2276. }
  2277. $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";
  2278. $result = DB::getPDO()->fetchAll($query);
  2279. foreach ($result as $row) {
  2280. $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
  2281. if ($items = DB::getPDO()->fetchAll($query)) {
  2282. list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
  2283. if (count($items) > 1) {
  2284. for ($i = 1; $i < count($items); $i++) {
  2285. if ($nip != $items[$i]["nip"]) $nip = null;
  2286. if ($regon != $items[$i]["regon"]) $regon = null;
  2287. }
  2288. }
  2289. $set = [];
  2290. if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
  2291. if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
  2292. if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
  2293. }
  2294. }
  2295. }
  2296. public static function reloadCache_reTeryt($full = false, $forceAll = false) {
  2297. Lib::loadClass('Teryt');
  2298. $tables = [
  2299. 'BI_audit_CEIDG' => [
  2300. 'fields' => [
  2301. 'wojewodztwo' => 'wojewodztwo',
  2302. 'powiat' => 'powiat',
  2303. 'gmina' => 'gmina',
  2304. 'miejscowosc' => 'miejscowosc',
  2305. 'ulica' => 'ulica',
  2306. 'kodPocztowy' => 'kodPocztowy',
  2307. ],
  2308. 'fieldsTeryt' => [
  2309. 'TERYT_SYM' => 'TERYT_SYM',
  2310. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2311. 'nrDomu' => 'budynek',
  2312. 'nrLokalu' => 'lokal',
  2313. ],
  2314. 'base' => '1',
  2315. ],
  2316. 'BI_audit_CEIDG_pelnomocnicy' => [
  2317. 'fields' => [
  2318. 'wojewodztwo' => 'wojewodztwo',
  2319. 'powiat' => 'powiat',
  2320. 'gmina' => 'gmina',
  2321. 'miejscowosc' => 'miejscowosc',
  2322. 'ulica' => 'ulica',
  2323. 'kodPocztowy' => 'kodPocztowy',
  2324. ],
  2325. 'fieldsTeryt' => [
  2326. 'TERYT_SYM' => 'TERYT_SYM',
  2327. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2328. 'nrDomu' => 'budynek',
  2329. 'nrLokalu' => 'lokal',
  2330. ],
  2331. 'base' => '1',
  2332. ],
  2333. 'BI_audit_ENERGA_PRACOWNICY' => [
  2334. 'fields' => [
  2335. 'miejscowosc' => 'miejscowosc',
  2336. 'kodPocztowy' => 'kodPocztowy',
  2337. 'ulica' => 'ulica',
  2338. ],
  2339. 'fieldsTeryt' => [
  2340. 'TERYT_SYM' => 'TERYT_SYM',
  2341. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2342. 'nrDomu' => 'nr',
  2343. 'nrLokalu' => 'nrLokalu',
  2344. ],
  2345. 'base' => '0',
  2346. ],
  2347. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2348. 'fields' => [
  2349. 'kodPocztowy' => 'kodPocztowy',
  2350. 'miejscowosc' => 'miejscowosc',
  2351. 'ulica' => 'ulica',
  2352. ],
  2353. 'fieldsTeryt' => [
  2354. 'TERYT_SYM' => 'TERYT_SYM',
  2355. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2356. 'nrDomu' => 'nrBudynku',
  2357. 'nrLokalu' => 'nrLokalu',
  2358. ],
  2359. 'base' => '0',
  2360. ],
  2361. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2362. 'fields' => [
  2363. 'kodPocztowy' => 'Kod_pocztowy',
  2364. 'miejscowosc' => 'Miejscowosc',
  2365. 'ulica' => 'Ulica',
  2366. ],
  2367. 'fieldsTeryt' => [
  2368. 'TERYT_SYM' => 'TERYT_SYM',
  2369. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2370. 'nrDomu' => 'Numer_budynku',
  2371. 'nrLokalu' => 'Numer_mieszkania_lokalu',
  2372. ],
  2373. 'base' => '0',
  2374. ],
  2375. 'BI_audit_KRS' => [
  2376. 'fields' => [
  2377. 'wojewodztwo' => 'S_wojewodztwo',
  2378. 'powiat' => 'S_powiat',
  2379. 'gmina' => 'S_gmina',
  2380. 'miejscowosc' => 'A_miejscowosc',
  2381. 'ulica' => 'A_ulica',
  2382. 'kodPocztowy' => 'A_kod',
  2383. ],
  2384. 'fieldsTeryt' => [
  2385. 'TERYT_SYM' => 'TERYT_SYM',
  2386. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2387. 'nrDomu' => 'A_nrDomu',
  2388. 'nrLokalu' => 'A_nrLokalu',
  2389. ],
  2390. 'base' => '1',
  2391. ],
  2392. 'BI_audit_KRS_address' => [
  2393. 'fields' => [
  2394. 'wojewodztwo' => 'S_wojewodztwo',
  2395. 'powiat' => 'S_powiat',
  2396. 'gmina' => 'S_gmina',
  2397. 'miejscowosc' => 'A_miejscowosc',
  2398. 'ulica' => 'A_ulica',
  2399. 'kodPocztowy' => 'A_kod',
  2400. ],
  2401. 'fieldsTeryt' => [
  2402. 'TERYT_SYM' => 'TERYT_SYM',
  2403. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2404. 'nrDomu' => 'A_nrDomu',
  2405. 'nrLokalu' => 'A_nrLokalu',
  2406. ],
  2407. 'base' => '1',
  2408. ],
  2409. 'BI_audit_MSIG_address' => [
  2410. 'fields' => [
  2411. 'wojewodztwo' => 'S_wojewodztwo',
  2412. 'powiat' => 'S_powiat',
  2413. 'gmina' => 'S_gmina',
  2414. 'miejscowosc' => 'A_miejscowosc',
  2415. 'ulica' => 'A_ulica',
  2416. 'kodPocztowy' => 'A_kod',
  2417. ],
  2418. 'fieldsTeryt' => [
  2419. 'TERYT_SYM' => 'TERYT_SYM',
  2420. 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
  2421. 'nrDomu' => 'A_nrDomu',
  2422. 'nrLokalu' => 'A_nrLokalu',
  2423. ],
  2424. 'base' => '1',
  2425. ],
  2426. ];
  2427. foreach ($tables as $table => $tableConf) {
  2428. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
  2429. DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
  2430. $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
  2431. $query = "select * from `{$table}` {$where}";
  2432. $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
  2433. $terytJoinArr = [];
  2434. foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
  2435. $terytJoinArr[] = (
  2436. $terytField == 'nrLokalu'
  2437. ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
  2438. : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
  2439. );
  2440. }
  2441. $terytJoin = implode(" and ", $terytJoinArr);
  2442. $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
  2443. $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
  2444. //$adresy = DB::getPDO()->queryNotBuffered($query);
  2445. $adresy = DB::getPDO()->query($query);
  2446. while ($adres = $adresy->fetch()) {
  2447. DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
  2448. if (!($forceAll and $adres['TERYT_SYM'])) {
  2449. $search = [];
  2450. foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
  2451. try {
  2452. $teryt = Teryt::search($search);
  2453. } catch (Exception $e) {
  2454. continue;
  2455. }
  2456. if (empty($teryt['SYM'])) continue;
  2457. $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
  2458. $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
  2459. DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
  2460. }
  2461. if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
  2462. $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
  2463. if (!$terytID) {
  2464. if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
  2465. if (!($terytID = DB::getPDO()->lastInsertId())) {
  2466. throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
  2467. }
  2468. } else {
  2469. throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
  2470. }
  2471. }
  2472. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
  2473. }
  2474. }
  2475. }
  2476. private static function reloadCache_updateAll($full, $onlyBase) {
  2477. $tablesConf = [
  2478. 'BI_audit_CEIDG' => [
  2479. 'fields' => [
  2480. 'nip' => 'nip',
  2481. 'regon' => 'regon',
  2482. ],
  2483. 'base' => '1',
  2484. ],
  2485. 'BI_audit_CEIDG_pelnomocnicy' => [
  2486. 'fields' => [
  2487. 'nip' => 'nip',
  2488. ],
  2489. 'base' => '1',
  2490. ],
  2491. 'BI_audit_CEIDG_powiazania' => [
  2492. 'fields' => [
  2493. 'nip' => 'nip',
  2494. 'regon' => 'regon',
  2495. ],
  2496. 'base' => '1',
  2497. ],
  2498. 'BI_audit_ENERGA_PRACOWNICY' => [
  2499. 'fields' => [
  2500. 'nip' => 'nip',
  2501. 'regon' => 'regon',
  2502. 'pesel' => 'pesel',
  2503. 'krs' => 'krs',
  2504. ],
  2505. 'base' => '0',
  2506. //'where' => '',
  2507. ],
  2508. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2509. 'fields' => [],
  2510. 'base' => '0',
  2511. //'where' => '',
  2512. ],
  2513. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2514. 'fields' => [
  2515. 'krs' => 'KRS',
  2516. 'nip' => 'NIP',
  2517. 'regon' => 'REGON',
  2518. 'pesel' => 'PESEL',
  2519. ],
  2520. 'base' => '0',
  2521. 'where' => "and ownCompany != 'Y'",
  2522. ],
  2523. 'BI_audit_KRS' => [
  2524. 'fields' => [
  2525. 'krs' => 'krs',
  2526. 'nip' => 'nip',
  2527. 'regon' => 'regon',
  2528. ],
  2529. 'base' => '1',
  2530. ],
  2531. 'BI_audit_KRS_address' => [
  2532. 'fields' => [],
  2533. 'base' => '1',
  2534. ],
  2535. 'BI_audit_KRS_company' => [
  2536. 'fields' => [
  2537. 'regon' => 'regon',
  2538. 'krs' => 'krs',
  2539. ],
  2540. 'base' => '1',
  2541. ],
  2542. 'BI_audit_KRS_person' => [
  2543. 'fields' => [
  2544. 'pesel' => 'pesel',
  2545. ],
  2546. 'base' => '1',
  2547. ],
  2548. 'BI_audit_MSIG' => [
  2549. 'fields' => [
  2550. 'krs' => 'krs',
  2551. 'nip' => 'nip',
  2552. 'regon' => 'regon',
  2553. ],
  2554. 'base' => '1',
  2555. ],
  2556. 'BI_audit_MSIG_address' => [
  2557. 'fields' => [],
  2558. 'base' => '1',
  2559. ],
  2560. 'BI_audit_MSIG_company' => [
  2561. 'fields' => [
  2562. 'regon' => 'regon',
  2563. 'krs' => 'krs',
  2564. ],
  2565. 'base' => '1',
  2566. ],
  2567. 'BI_audit_MSIG_person' => [
  2568. 'fields' => [
  2569. 'pesel' => 'pesel',
  2570. ],
  2571. 'base' => '1',
  2572. ],
  2573. // 'BI_audit_KW_requested_person' => [
  2574. // 'fields' => [
  2575. // 'pesel' => 'Seller_person_pesel',
  2576. // 'krs' => 'Seller_person_KRS',
  2577. // 'nip' => 'Seller_person_NIP',
  2578. // 'regon' => 'Seller_person_REGON',
  2579. // ],
  2580. // 'base' => '0',
  2581. // //'where' => '',
  2582. // ],
  2583. 'TERYT_adresy' => [
  2584. 'fields' => [],
  2585. 'base' => '1',
  2586. ],
  2587. ];
  2588. $refTablesConf = [
  2589. 'BI_audit_CEIDG' => [
  2590. 'refTablesTo' => [
  2591. 'BI_audit_CEIDG_pelnomocnicy',
  2592. 'BI_audit_CEIDG_powiazania',
  2593. 'TERYT_adresy',
  2594. ],
  2595. 'base' => 1,
  2596. ],
  2597. 'BI_audit_CEIDG_pelnomocnicy' => [
  2598. 'refTablesTo' => [
  2599. 'TERYT_adresy',
  2600. ],
  2601. 'base' => 1,
  2602. ],
  2603. 'BI_audit_ENERGA_PRACOWNICY' => [
  2604. 'refTablesTo' => [
  2605. 'BI_audit_ENERGA_PRACOWNICY_adresy',
  2606. //'TERYT_adresy',
  2607. ],
  2608. 'base' => 0,
  2609. ],
  2610. 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
  2611. 'refTablesTo' => [
  2612. 'TERYT_adresy',
  2613. ],
  2614. 'base' => 0,
  2615. ],
  2616. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
  2617. 'refTablesTo' => [
  2618. 'TERYT_adresy',
  2619. ],
  2620. 'base' => 0,
  2621. ],
  2622. 'BI_audit_KRS' => [
  2623. 'refTablesTo' => [
  2624. 'BI_audit_KRS_address',
  2625. 'BI_audit_KRS_company',
  2626. 'BI_audit_KRS_person',
  2627. 'TERYT_adresy',
  2628. ],
  2629. 'base' => 1,
  2630. ],
  2631. 'BI_audit_KRS_address' => [
  2632. 'refTablesTo' => [
  2633. 'TERYT_adresy',
  2634. ],
  2635. 'base' => 1,
  2636. ],
  2637. 'BI_audit_MSIG' => [
  2638. 'refTablesTo' => [
  2639. 'BI_audit_MSIG_address',
  2640. 'BI_audit_MSIG_company',
  2641. 'BI_audit_MSIG_person',
  2642. ],
  2643. 'base' => 1,
  2644. ],
  2645. 'BI_audit_MSIG_address' => [
  2646. 'refTablesTo' => [
  2647. 'TERYT_adresy',
  2648. ],
  2649. 'base' => 1,
  2650. ],
  2651. ];
  2652. $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
  2653. if ($full) {
  2654. foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
  2655. $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
  2656. // $queries[] = "optimize table `BI_audit_ALL`";
  2657. $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
  2658. // $queries[] = "optimize table `BI_audit_ALL_ref`";
  2659. $allTables = [];
  2660. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  2661. $allTables[] = $refTableFrom;
  2662. // if ($refTableConf['base']) continue;
  2663. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  2664. $allTables[] = $refTableTo;
  2665. if ($refTableConf['base']) continue;
  2666. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  2667. $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
  2668. // $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}'";
  2669. }
  2670. }
  2671. $allTables = array_unique($allTables);
  2672. foreach ($allTables as $refTableFrom) {
  2673. foreach ($allTables as $refTableTo) {
  2674. if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
  2675. $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
  2676. $queries[] = "optimize table `{$refTable}`";
  2677. $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";
  2678. }
  2679. }
  2680. }
  2681. }
  2682. foreach ($tablesConf as $table => $tableConf) {
  2683. if ($onlyBase && (!$tableConf['base'])) continue;
  2684. $where = "where `{$table}`.`cached` = 0";
  2685. if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
  2686. // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
  2687. // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
  2688. $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
  2689. $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
  2690. $updates = ["`BI_audit_ALL`.`reffed` = 0", "`{$table}`.`cached` = 1"];
  2691. foreach ($tableConf['fields'] as $field => $value) {
  2692. $fields[] = "`{$field}`";
  2693. $values[] = "`{$value}`";
  2694. $updates[] = "`BI_audit_ALL`.`{$field}` = `{$table}`.`{$value}`";
  2695. }
  2696. $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}";
  2697. $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
  2698. $queries[] = "update `{$table}` set `cached` = 1 {$where}";
  2699. }
  2700. $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
  2701. $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
  2702. $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
  2703. $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
  2704. $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
  2705. $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";
  2706. foreach ($refTablesConf as $refTableFrom => $refTableConf) {
  2707. if ($onlyBase && (!$tableConf['base'])) continue;
  2708. foreach ($refTableConf['refTablesTo'] as $refTableTo) {
  2709. $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
  2710. $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`";
  2711. if (!in_array($refTableFrom, $sourceTables)) {
  2712. $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`";
  2713. }
  2714. if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
  2715. $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'";
  2716. }
  2717. $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'";
  2718. }
  2719. }
  2720. foreach ($queries as $query) {
  2721. echo "SQL: {$query}\n";
  2722. DB::getPDO()->query($query);
  2723. }
  2724. $BiAuditRelations = new BiAuditRelations();
  2725. //$result = DB::getPDO()->queryNotBuffered("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  2726. $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
  2727. while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
  2728. DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
  2729. }
  2730. public function doReloadCache($full = false) {
  2731. if ($full === 'base') {
  2732. $onlyBase = true;
  2733. $full = false;
  2734. } else {
  2735. $onlyBase = false;
  2736. }
  2737. $setFull = function() {
  2738. BiAuditPowiazania::saveToLog("Wykryto niespójność tabel - uruchamiam pełne odświeżenie cache");
  2739. $sqlArr = [
  2740. 'BI_analiza_reloadCache' => 'Full',
  2741. 'FILE_STATUS_info' => 'Odświeżam w pełni cache',
  2742. ];
  2743. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $this->POWIAZANIA_ID, $sqlArr);
  2744. };
  2745. if ($this->POWIAZANIA_ID && (!$full)) {
  2746. $checkTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', 'BI_audit_ENERGA_RUM_KONTRAHENCI'];
  2747. foreach ($checkTables as $table) {
  2748. $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";
  2749. if (DB::getPDO()->fetchValue($query)) {
  2750. $full = true;
  2751. $setFull();
  2752. break;
  2753. }
  2754. }
  2755. }
  2756. $powiazaniaDirLocation = self::getMainDirectory();
  2757. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2758. $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
  2759. $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
  2760. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCachePidFile, getmypid());
  2761. try {
  2762. error_log('now: self::importPracownicy');
  2763. $_full = self::importPracownicy($full);
  2764. if ((!$full) && $_full) {
  2765. $full = true;
  2766. if ($this->POWIAZANIA_ID) $setFull();
  2767. }
  2768. error_log('now: self::reloadCache_parseFakturyUmowy');
  2769. self::reloadCache_parseFakturyUmowy($full);
  2770. error_log('now: self::reloadCache_reTeryt');
  2771. self::reloadCache_reTeryt($full);
  2772. error_log('now: self::reloadCache_updateAll');
  2773. self::reloadCache_updateAll($full, $onlyBase);
  2774. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, "ok");
  2775. } catch (Exception $e) {
  2776. var_dump($e);
  2777. if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, $e->getMessage());
  2778. else throw new Exception($e->getMessage());
  2779. }
  2780. }
  2781. public function doGeneratePowiazania($ID) {
  2782. $this->POWIAZANIA_ID = $ID;
  2783. $powiazaniaDirLocation = self::getMainDirectory();
  2784. $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
  2785. $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
  2786. $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
  2787. $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
  2788. file_put_contents($pidFile, getmypid());
  2789. /* $tablesConf = [
  2790. 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
  2791. 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
  2792. 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
  2793. 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
  2794. 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
  2795. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
  2796. 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
  2797. 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
  2798. 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
  2799. 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
  2800. ];*/
  2801. try {
  2802. $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
  2803. $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}";
  2804. $sqlArr = [
  2805. 'BI_analiza_reloadCache' => 'Part',
  2806. 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
  2807. ];
  2808. do {
  2809. DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
  2810. $activeReloadingCache = DB::getPDO()->fetchValue($query);
  2811. if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2812. DB::getPDO()->query("unlock tables");
  2813. if ($activeReloadingCache) {
  2814. BiAuditPowiazania::saveToLog("Czekam na zakończenie odświeżania cache przez inne zadanie");
  2815. sleep(30);
  2816. }
  2817. } while ($activeReloadingCache);
  2818. BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
  2819. $this->doReloadCache(); //DUPA testowe wylaczanie
  2820. BiAuditPowiazania::saveToLog("Odświeżono cache");
  2821. $sqlArr = [
  2822. 'BI_analiza_reloadCache' => 'No',
  2823. 'FILE_STATUS_info' => 'Szukam powiązań',
  2824. ];
  2825. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2826. $BiAuditPowiazania->run();
  2827. //if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
  2828. //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
  2829. $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
  2830. DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
  2831. //$BiAuditPowiazania->saveXml();
  2832. $BiAuditPowiazania->generatePdfAndHtml();
  2833. file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
  2834. } catch (Exception $e) {
  2835. file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
  2836. }
  2837. }
  2838. public function reinstallAction() {
  2839. $this->reinstall();
  2840. die('OK');
  2841. }
  2842. public function reinstall() {
  2843. $sqlList = array();
  2844. //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
  2845. $sqlList['ActivateBiAuditGenerate'] = <<<SQL
  2846. REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
  2847. SQL;
  2848. $sqlList['ChangeStructure1'] = <<<SQL
  2849. 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';
  2850. SQL;
  2851. $sqlList['ChangeStructure2'] = <<<SQL
  2852. UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
  2853. SQL;
  2854. $sqlList['ChangeStructure3'] = <<<SQL
  2855. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
  2856. SQL;
  2857. $sqlList['ChangeStructure4'] = <<<SQL
  2858. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
  2859. SQL;
  2860. $sqlList['ChangeStructure5'] = <<<SQL
  2861. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
  2862. SQL;
  2863. $sqlList['ChangeStructure6'] = <<<SQL
  2864. ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
  2865. SQL;
  2866. $db = DB::getDB();
  2867. if ($db->has_errors()) {
  2868. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  2869. }
  2870. foreach ($sqlList as $sqlName => $sql) {
  2871. $res = $db->query($sql);
  2872. if ($db->has_errors()) {
  2873. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  2874. }
  2875. }
  2876. }
  2877. }
  2878. class BiAuditRelations {
  2879. private $RELATIONS_ID = [];
  2880. private $relations = [
  2881. 'nip' => ['nip'],
  2882. 'regon' => ['regon'],
  2883. 'krs' => ['krs'],
  2884. 'pesel' => ['pesel'],
  2885. ];
  2886. private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
  2887. private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
  2888. public function __construct() {
  2889. $query = "select * from BI_audit_ALL_ref_RELATIONS";
  2890. $result = DB::getPDO()->fetchAll($query);
  2891. foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
  2892. }
  2893. private function getRelationID($name) {
  2894. if (!isset($this->RELATIONS_ID[$name])) {
  2895. $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
  2896. $newID = DB::getPDO()->fetchValue($query);
  2897. $this->RELATIONS_ID[$name] = $newID;
  2898. $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
  2899. DB::getPDO()->query($query);
  2900. }
  2901. return $this->RELATIONS_ID[$name];
  2902. }
  2903. private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
  2904. if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
  2905. if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
  2906. DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
  2907. }
  2908. }
  2909. }
  2910. public function findRelations($ID) {
  2911. $query = "select * from BI_audit_ALL where ID = '{$ID}'";
  2912. if (!($result = DB::getPDO()->fetchAll($query))) return false;
  2913. $row = $result[0];
  2914. $joins = [];
  2915. $items = '';
  2916. foreach ($this->relations as $name => $columns) {
  2917. $ok = 0;
  2918. $join = [];
  2919. foreach ($columns as $column) {
  2920. $join[] = "t1.{$column} = t2.{$column}";
  2921. if ($row[$column] !== null) $ok++;
  2922. }
  2923. if ($ok / count($columns) > 0.5) {
  2924. $joins[] = "(" . implode(" and ", $join) . ")";
  2925. $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
  2926. }
  2927. }
  2928. if (!$joins) return false;
  2929. $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 " .
  2930. "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})";
  2931. $result = DB::getPDO()->fetchAll($query);
  2932. foreach ($result as $row) {
  2933. $relationID = 0;
  2934. foreach ($this->relations as $name => $v) {
  2935. if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
  2936. }
  2937. $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
  2938. $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
  2939. $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
  2940. $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
  2941. if (!($start2 || $end1)) {
  2942. $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
  2943. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2944. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2945. DB::getPDO()->query($query);
  2946. }
  2947. if (!($start1 || $end2)) {
  2948. $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
  2949. $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
  2950. $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
  2951. DB::getPDO()->query($query);
  2952. }
  2953. }
  2954. }
  2955. }
  2956. class BiAuditRefTables {
  2957. public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
  2958. static $refTables = [];
  2959. static $tempRefTables = [];
  2960. static $tempRefTablesCount = 0;
  2961. if (is_array($tableTo)) {
  2962. if (!$tableTo) throw new Exception('BiAuditRefTables::getRefTable - bad parameter $tableTo');
  2963. if (count($tableTo) == 1) return self::getRefTable($tableFrom, reset($tableTo), $returnException);
  2964. $key = implode("__", $tableTo);
  2965. if (!isset($tempRefTables[$tableFrom][$key])) {
  2966. try {
  2967. $_tableFrom = $tableFrom;
  2968. foreach ($tableTo as $_tableTo) {
  2969. $_refTables[] = self::getRefTable($_tableFrom, $_tableTo, true);
  2970. $_tableFrom = $_tableTo;
  2971. }
  2972. $name = "TEMP__#REF_TABLE__" . (++$tempRefTablesCount);
  2973. $first = reset($_refTables);
  2974. $last = end($_refTables);
  2975. $prev = array_shift($_refTables);
  2976. $query = "create temporary table `{$name}` select `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY` from `{$first}`";
  2977. while ($next = array_shift($_refTables)) {
  2978. $query .= " join `{$next}` on `{$prev}`.`REMOTE_PRIMARY_KEY` = `{$next}`.`PRIMARY_KEY`";
  2979. $prev = $next;
  2980. }
  2981. $query .= " group by `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY`";
  2982. DB::getPDO()->query($query);
  2983. $tempRefTables[$tableFrom][$key] = $name;
  2984. } catch (Exception $e) {
  2985. if ($returnException) throw new Exception($e->getMessage());
  2986. $tempRefTables[$tableFrom][$key] = false;
  2987. }
  2988. }
  2989. return $tempRefTables[$tableFrom][$key];
  2990. } else {
  2991. if (!isset($refTables[$tableFrom][$tableTo])) {
  2992. try {
  2993. $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
  2994. } catch (Exception $e) {
  2995. if ($returnException) throw new Exception($e->getMessage());
  2996. $refTables[$tableFrom][$tableTo] = false;
  2997. }
  2998. }
  2999. return $refTables[$tableFrom][$tableTo];
  3000. }
  3001. }
  3002. public static function getRefTables($tableFrom) {
  3003. static $refTables = [];
  3004. if (!isset($refTables[$tableFrom])) {
  3005. $namespace = "default_db/{$tableFrom}/{$tableFrom}";
  3006. try {
  3007. $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
  3008. if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
  3009. $fields = $item['field'];
  3010. $_refTables = [];
  3011. foreach ($fields as $field) {
  3012. list($type, $child) = explode(":", $field['xsdType'], 2);
  3013. if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
  3014. try {
  3015. $_refTable = ACL::getRefTable($namespace, $child);
  3016. $_refTables[] = $_refTable;
  3017. } catch (Exception $e) {
  3018. }
  3019. }
  3020. }
  3021. $refTables[$tableFrom] = $_refTables;
  3022. } catch (Exception $e) {
  3023. $refTables[$tableFrom] = [];
  3024. }
  3025. }
  3026. return $refTables[$tableFrom];
  3027. }
  3028. }
  3029. class BiAuditPowiazania {
  3030. private $L_APPOITMENT_INFO;
  3031. private $minDepth;
  3032. private $maxDepth, $origMaxDepth;
  3033. private $onlyTargets;
  3034. private $ID;
  3035. private $nodes = [];
  3036. private $endNodes;
  3037. private $path = [];
  3038. private $results = [];
  3039. private $items_results = [];
  3040. private $relations = [];
  3041. private $srcTables = [
  3042. 'BI_audit_ENERGA_PRACOWNICY' => [],
  3043. 'BI_audit_KRS' => ['BI_audit_POWIAZANIA_OD'],
  3044. 'BI_audit_KRS_person' => ['BI_audit_POWIAZANIA_OD'],
  3045. 'BI_audit_MSIG' => ['BI_audit_POWIAZANIA_OD'],
  3046. 'BI_audit_MSIG_person' => ['BI_audit_POWIAZANIA_OD'],
  3047. 'BI_audit_CEIDG' => ['BI_audit_POWIAZANIA_OD'],
  3048. 'BI_audit_CEIDG_pelnomocnicy' => ['BI_audit_POWIAZANIA_OD'],
  3049. ];
  3050. private $destTables = [
  3051. 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [],
  3052. 'BI_audit_KW_requested_person' => [],
  3053. 'BI_audit_KRS' => ['BI_audit_POWIAZANIA_DO'],
  3054. 'BI_audit_KRS_person' => ['BI_audit_POWIAZANIA_DO'],
  3055. 'BI_audit_MSIG' => ['BI_audit_POWIAZANIA_DO'],
  3056. 'BI_audit_MSIG_person' => ['BI_audit_POWIAZANIA_DO'],
  3057. 'BI_audit_CEIDG' => ['BI_audit_POWIAZANIA_DO'],
  3058. 'BI_audit_CEIDG_pelnomocnicy' => ['BI_audit_POWIAZANIA_DO'],
  3059. ];
  3060. private $step = 0;
  3061. private $tasksDirLocation;
  3062. private $progressFile;
  3063. private $progress = [
  3064. 'summary' => [
  3065. 'count' => 0,
  3066. 'message' => 'Inicjacja',
  3067. 'ts' => null,
  3068. 'step' => 'initialize',
  3069. 'reportsCount' => 0,
  3070. 'reportsCreated' => 0,
  3071. ],
  3072. 'details' => [],
  3073. ];
  3074. private $lastProgress = 0;
  3075. private $lastProgress_slowCheck = 0;
  3076. private $lastResults = 0;
  3077. private $startTimestamp = null;
  3078. private $lastTimestamp = null;
  3079. private $lowProgressCount = 0;
  3080. private $count, $i;
  3081. private $splittedResults = [];
  3082. private $maxResults = 1000000;
  3083. private $fidRow = [];
  3084. private $itemID = 0;
  3085. private $reverseSearch = false;
  3086. private $query = "";
  3087. private static function generateJson($type, $data) {
  3088. return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
  3089. }
  3090. public static function saveToLog($message) {
  3091. $messageJson = self::generateJson('message', ['message' => $message]);
  3092. echo $messageJson . "\n";
  3093. }
  3094. private static function exec($cmd) {
  3095. $path = 'export PATH=$PATH:/usr/sbin;';
  3096. $cmd = "{$path} {$cmd}";
  3097. echo "CMD :: {$cmd}\n";
  3098. shell_exec($cmd);
  3099. }
  3100. private function saveProgress($args = []) {
  3101. $timestamp = microtime(true);
  3102. if (isset($args['progress']) && $this->i) {
  3103. $elapsed = $timestamp - $this->startTimestamp;
  3104. if ($args['progress']) {
  3105. $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
  3106. } else $estimated = "N/A";
  3107. $this->lastProgress = $args['progress'];
  3108. $this->lastTimestamp = $timestamp;
  3109. $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
  3110. echo $progressJson . "\n";
  3111. $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
  3112. }
  3113. if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
  3114. if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
  3115. if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
  3116. $this->progress['summary']['ts'] = $timestamp;
  3117. file_put_contents($this->progressFile, json_encode($this->progress));
  3118. if (file_exists("{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.abort")) {
  3119. unlink("{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.abort");
  3120. self::throwException("Przerwano na żądanie użytkownika");
  3121. }
  3122. }
  3123. private static function throwException($message) {
  3124. self::saveToLog($message);
  3125. throw new Exception($message);
  3126. }
  3127. public function __construct($ID = 0, $tasksDirLocation = null) {
  3128. if (!$ID) self::throwException("Wrong ID parameter");
  3129. if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
  3130. $this->ID = $ID;
  3131. $this->tasksDirLocation = $tasksDirLocation;
  3132. $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
  3133. $this->saveProgress();
  3134. }
  3135. public function run() {
  3136. $query = "select L_APPOITMENT_INFO, 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')";
  3137. $result = DB::getPDO()->fetchAll($query);
  3138. if (!$result) self::throwException("Błąd danych");
  3139. $this->L_APPOITMENT_INFO = $result[0]['L_APPOITMENT_INFO'];
  3140. if ($this->loadResults()) {
  3141. $this->splitResults();
  3142. return;
  3143. }
  3144. self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
  3145. Route_UrlAction_BiAuditGenerate::deleteResultsFromDB($this->ID);
  3146. $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
  3147. $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
  3148. $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
  3149. if (!$this->minDepth) $this->minDepth = 1;
  3150. if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
  3151. if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
  3152. $subQueries = [];
  3153. $resultDest = [];
  3154. foreach ($this->destTables as $destTable => $destPath) {
  3155. $destPath[] = $destTable;
  3156. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destPath)) {
  3157. $subQueries[] = "select `all`.`ID`, `all`.`REMOTE_TABLE` 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}'";
  3158. }
  3159. }
  3160. if ($subQueries) {
  3161. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  3162. $resultDest = DB::getPDO()->fetchAll($query);
  3163. }
  3164. if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
  3165. $subQueries = [];
  3166. $resultSrc = [];
  3167. foreach ($this->srcTables as $srcTable => $srcPath) {
  3168. $srcPath[] = $srcTable;
  3169. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcPath)) {
  3170. $subQueries[] = "select `all`.`ID`, `all`.`REMOTE_TABLE` 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}'";
  3171. }
  3172. }
  3173. if ($subQueries) {
  3174. $query = implode(" union ", $subQueries) . " order by `ID` asc";
  3175. $resultSrc = DB::getPDO()->fetchAll($query);
  3176. }
  3177. if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
  3178. if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
  3179. $result = $resultSrc;
  3180. $this->endNodes = array_map('reset', $resultDest);
  3181. $this->reverseSearch = false;
  3182. $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
  3183. } else {
  3184. $result = $resultDest;
  3185. $this->endNodes = array_map('reset', $resultSrc);
  3186. $this->reverseSearch = true;
  3187. $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
  3188. self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
  3189. }
  3190. self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
  3191. $externalTables = array_keys(array_filter(array_merge($this->srcTables, $this->destTables), function($x) {return (!count($x));}));
  3192. $this->count = count($result);
  3193. $this->progress['summary']['count'] = $this->count;
  3194. $this->origMaxDepth = $this->maxDepth;
  3195. $this->saveProgress(['step' => 'relations']);
  3196. try {
  3197. foreach ($result as $i => $row) {
  3198. $this->i = $i + 1;
  3199. $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
  3200. $this->startTimestamp = microtime(true);
  3201. $this->lastProgress = 0;
  3202. $this->lastProgress_slowCheck = 0;
  3203. $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  3204. if ($this->maxDepth != $this->origMaxDepth) {
  3205. $this->maxDepth = $this->origMaxDepth;
  3206. self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
  3207. }
  3208. // $weight = in_array($row['REMOTE_TABLE'], $externalTables) ? 0 : 1; // TODO Nie ujmowanie w glebokosci przejscia z bazy wewnetrznej Energi do baz zewnetrznych
  3209. $weight = 1;
  3210. $this->findPowiazania($row['ID'], $weight);
  3211. $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
  3212. $this->lastResults = count($this->results);
  3213. }
  3214. } catch (Exception $e) {
  3215. if ($this->i < $this->count) {
  3216. $this->startTimestamp = microtime(true);
  3217. $this->lastProgress = 0;
  3218. $this->lastResults = count($this->results);
  3219. while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
  3220. }
  3221. if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
  3222. }
  3223. $this->nodes = [];
  3224. self::saveToLog("Zakończono wyszukiwanie powiązań");
  3225. $this->sortResults();
  3226. $this->saveResults();
  3227. //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
  3228. $this->splitResults();
  3229. }
  3230. private static function reversePath($path) {
  3231. $arr = array_reverse($path, true);
  3232. $keys = array_keys($arr);
  3233. array_unshift($arr, array_pop($arr));
  3234. return array_combine($keys, $arr);
  3235. }
  3236. private function addResult($progress) {
  3237. if (count($this->results) == $this->maxResults) {
  3238. $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
  3239. self::saveToLog($message);
  3240. $this->saveProgress(['progress' => $progress, 'message' => $message]);
  3241. throw new Exception('');
  3242. }
  3243. if ($this->reverseSearch) $path = self::reversePath($this->path);
  3244. else $path = $this->path;
  3245. $this->results[] = $path;
  3246. $this->saveToDb($path);
  3247. }
  3248. private static function weightCalc($n) {
  3249. if ($n < 21) return 1;
  3250. if ($n < 41) return 2;
  3251. if ($n < 81) return 3;
  3252. if ($n < 161) return 4;
  3253. if ($n < 321) return 5;
  3254. if ($n < 641) return 6;
  3255. if ($n < 1281) return 7;
  3256. if ($n < 2561) return 8;
  3257. if ($n < 5121) return 9;
  3258. return 10;
  3259. }
  3260. public function findPowiazania($ID, $weight = 0, $progress = 0, $steps = 1, $relation = "") {
  3261. $this->step++;
  3262. if ($this->maxDepth > $this->minDepth) {
  3263. if (($this->step % 1000000) == 0) {
  3264. $progressDiff = $progress - $this->lastProgress_slowCheck;
  3265. if ($progressDiff < 0.00005) {
  3266. $this->lowProgressCount++;
  3267. if ($this->lowProgressCount == 10) {
  3268. $this->maxDepth--;
  3269. self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
  3270. $this->lowProgressCount = 0;
  3271. }
  3272. } else $this->lowProgressCount = 0;
  3273. $this->lastProgress_slowCheck = $progress;
  3274. }
  3275. }
  3276. if ((($this->step) % 100000) == 0) {
  3277. $this->saveProgress(['progress' => $progress]);
  3278. }
  3279. if ((($this->step) % 10000) == 0) {
  3280. if (memory_get_usage(true) > 3000000000) {
  3281. $this->nodes = [];
  3282. self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
  3283. }
  3284. }
  3285. if (isset($this->path[$ID])) return false;
  3286. $this->path[$ID] = $relation;
  3287. if (!$relation) $relation = 0;
  3288. if (in_array($ID, $this->endNodes)) {
  3289. if (($weight) > $this->minDepth) $this->addResult($progress);
  3290. array_pop($this->path);
  3291. return;
  3292. }
  3293. if (($weight) > $this->maxDepth) {
  3294. if (!$this->onlyTargets) $this->addResult($progress);
  3295. array_pop($this->path);
  3296. return;
  3297. }
  3298. if (!isset($this->nodes[$ID][$relation])) {
  3299. $where = $relation ? "and ({$relation} & ref.RELATION_ID) = 0" : "";
  3300. $query = "{$this->query} = {$ID} {$where}";
  3301. $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
  3302. }
  3303. $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
  3304. if (isset($this->path[$node['ID']])) return false;
  3305. return true;
  3306. }));
  3307. $count = count($nodes);
  3308. $weight += self::weightCalc($count);
  3309. if ($weight <= $this->maxDepth) {
  3310. foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], $weight, ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID']);
  3311. }
  3312. array_pop($this->path);
  3313. }
  3314. private function sortResults() {
  3315. if (!$this->results) return;
  3316. uasort($this->results, function ($a, $b) {
  3317. $ca = count($a);
  3318. $cb = count($b);
  3319. $c = min($ca, $cb);
  3320. $ka = array_keys($a);
  3321. $kb = array_keys($b);
  3322. for ($i = 0; $i < $c; $i++) {
  3323. if ($ka[$i] < $kb[$i]) return -1;
  3324. if ($ka[$i] > $kb[$i]) return 1;
  3325. }
  3326. if ($ca < $cb) return -1;
  3327. if ($ca > $cb) return 1;
  3328. return 0;
  3329. });
  3330. }
  3331. private function saveResults() {
  3332. self::saveToLog("Zapisuję wyliczone dane do pliku");
  3333. // if (!$this->results) {
  3334. // self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
  3335. // return false;
  3336. // }
  3337. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  3338. $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
  3339. file_put_contents($dataFile, $data);
  3340. self::saveToLog("Zapisano wyliczone dane do pliku");
  3341. return true;
  3342. }
  3343. private function loadResults() {
  3344. self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
  3345. $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
  3346. if (!file_exists($dataFile)) {
  3347. self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
  3348. return false;
  3349. }
  3350. $data = file_get_contents($dataFile);
  3351. $results = @json_decode(gzuncompress(base64_decode($data)), true);
  3352. if (!$results) {
  3353. self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
  3354. return false;
  3355. }
  3356. if (isset($results['results'])) {
  3357. $this->results = $results['results'];
  3358. if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
  3359. } else $this->results = $results;
  3360. self::saveToLog("Wczytano wcześniej wyliczone dane");
  3361. return true;
  3362. }
  3363. private function relationName($ID) {
  3364. if (!$ID) return '';
  3365. if (!isset($this->relations[$ID])) {
  3366. $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
  3367. $result = DB::getPDO()->fetchAll($query);
  3368. $rels = array_map('reset', $result);
  3369. $this->relations[$ID] = implode(", ", $rels);
  3370. }
  3371. return $this->relations[$ID];
  3372. }
  3373. private function splitResults() {
  3374. $MAX = 1000;
  3375. $countBySource = [];
  3376. $resultsKeys = [];
  3377. foreach ($this->results as $resultKey => $result) {
  3378. $_keys = array_keys($result);
  3379. $countBySource[reset($_keys)][] = $resultKey;
  3380. }
  3381. foreach ($countBySource as $resultKeys) {
  3382. if (count($resultKeys) > $MAX) {
  3383. $countByDest = [];
  3384. foreach ($resultKeys as $resultKey) {
  3385. $_keys = array_keys($this->results[$resultKey]);
  3386. $countByDest[end($_keys)][] = $resultKey;
  3387. }
  3388. foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
  3389. } else $resultsKeys[] = $resultKeys;
  3390. }
  3391. $results = [];
  3392. while ($resultsKeys) {
  3393. $resultKeys = array_shift($resultsKeys);
  3394. while ($next = current($resultsKeys)) {
  3395. if (count($resultKeys) + count($next) <= $MAX) {
  3396. $resultKeys = array_merge($resultKeys, $next);
  3397. unset($resultsKeys[key($resultsKeys)]);
  3398. } else break; //next($resultsKeys);
  3399. }
  3400. $_results = [];
  3401. foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
  3402. $results[] = $_results;
  3403. // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
  3404. }
  3405. if ($results) $this->splittedResults = $results;
  3406. else $this->splittedResults[] = $this->results;
  3407. $this->progress['summary']['reportsCount'] = count($results);
  3408. }
  3409. public function getPartsCount() {
  3410. return count($this->splittedResults);
  3411. }
  3412. private function generateItemsResults($resultsPart = null) {
  3413. if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
  3414. else {
  3415. self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  3416. if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
  3417. }
  3418. $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
  3419. $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
  3420. $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
  3421. $items_kontrahenci = [];
  3422. $items_kw_person = [];
  3423. $kontrahenci = [];
  3424. $kw_person = [];
  3425. $_items_results = [];
  3426. $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  3427. $refFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
  3428. $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
  3429. $this->items_results[$resultsPart] = [];
  3430. $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
  3431. $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
  3432. $this->items_results[$resultsPart][$xmlTask]['L_APPOITMENT_INFO'] = $this->L_APPOITMENT_INFO;
  3433. if ($resultsPart === null) {
  3434. $results = $this->results;
  3435. } else {
  3436. $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
  3437. $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
  3438. }
  3439. foreach ($results as $key => $result) {
  3440. if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
  3441. foreach ($result as $ID => $rel) {
  3442. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  3443. $row = DB::getPDO()->fetchFirst($query);
  3444. $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
  3445. $obj = DB::fetch(DB::query($query));
  3446. $item_result = [];
  3447. if ($this->fidRow) {
  3448. $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
  3449. }
  3450. $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
  3451. if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
  3452. $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']}'";
  3453. $notes = DB::getPDO()->fetchAll($query);
  3454. foreach ($notes as $note) {
  3455. $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'][] = array_merge(['@attributes' => ['fid' => "BI_audit_operational_raport_note.{$note['ID']}"]], $note);
  3456. }
  3457. }
  3458. if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
  3459. $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']}'";
  3460. if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
  3461. $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
  3462. }
  3463. }
  3464. if ($rel) $item_result['relation_from'] = $this->relationName($rel);
  3465. $item_results[$xmlObject][] = $item_result;
  3466. if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
  3467. $kontrahenci[] = $row['REMOTE_ID'];
  3468. $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']}'";
  3469. $res = DB::query($query);
  3470. $faktury = [];
  3471. if (mysql_num_rows($res)) {
  3472. while ($obj = DB::fetch($res)) {
  3473. $faktura = (array) $obj;
  3474. $faktura = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_FAKTURY.{$faktura['ID']}"]], $faktura);
  3475. $faktury[] = $faktura;
  3476. }
  3477. }
  3478. $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']}'";
  3479. $res = DB::query($query);
  3480. $umowy = [];
  3481. if (mysql_num_rows($res)) {
  3482. while ($obj = DB::fetch($res)) {
  3483. $umowa = (array) $obj;
  3484. $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
  3485. $umowy[] = $umowa;
  3486. }
  3487. }
  3488. if ($faktury || $umowy) {
  3489. $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  3490. $item_kontrahenci['ID'] = $row['REMOTE_ID'];
  3491. if ($faktury) $item_kontrahenci['BI_audit_ENERGA_FAKTURY'] = $faktury;
  3492. if ($umowy) $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
  3493. $items_kontrahenci[] = $item_kontrahenci;
  3494. }
  3495. } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
  3496. $kw_person[] = $row['REMOTE_ID'];
  3497. $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']}'";
  3498. $res = DB::query($query);
  3499. if (mysql_num_rows($res)) {
  3500. $kws = [];
  3501. while ($obj = DB::fetch($res)) {
  3502. $kw = (array) $obj;
  3503. $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
  3504. $kws[] = $kw;
  3505. }
  3506. $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
  3507. $item_kw_person['ID'] = $row['REMOTE_ID'];
  3508. $item_kw_person['BI_audit_KW_requested'] = $kws;
  3509. $items_kw_person[] = $item_kw_person;
  3510. }
  3511. }
  3512. }
  3513. $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
  3514. }
  3515. $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
  3516. $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
  3517. self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
  3518. }
  3519. private function saveToDb($result = null, $key = null) {
  3520. if ($result === null) {
  3521. self::saveToLog("Zapisuję wyliczone dane do bazy");
  3522. if (!$this->results) {
  3523. self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
  3524. return null;
  3525. }
  3526. foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
  3527. self::saveToLog("Zapisano wyliczone dane do bazy");
  3528. } else {
  3529. if ($key === null) {
  3530. end($this->results);
  3531. $key = key($this->results);
  3532. }
  3533. $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
  3534. $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
  3535. $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
  3536. $fidObj = [];
  3537. DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
  3538. foreach ($result as $ID => $rel) {
  3539. $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
  3540. $object = DB::getPDO()->fetchFirst($query);
  3541. $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
  3542. DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
  3543. $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
  3544. DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
  3545. $fidObj[$ID] = $idPowiazaniaRowObject;
  3546. }
  3547. $this->fidRow[$key] = [
  3548. 'fid' => $IdPowiazaniaRow,
  3549. 'obj' => $fidObj,
  3550. ];
  3551. }
  3552. }
  3553. public function saveXml($resultsPart = null) {
  3554. if ($this->getPartsCount()) {
  3555. if ($resultsPart === null) {
  3556. self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
  3557. for ($i =0; $i < $this->getPartsCount(); $i++) {
  3558. $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
  3559. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  3560. file_put_contents($xmlFile, $this->asXml($i));
  3561. }
  3562. self::saveToLog("Zakończono generowanie plików XML");
  3563. } else {
  3564. if ($resultsPart >= $this->getPartsCount()) {
  3565. self::saveToLog("saveXml() error - bad result number");
  3566. return;
  3567. }
  3568. $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  3569. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
  3570. file_put_contents($xmlFile, $this->asXml($resultsPart));
  3571. }
  3572. } else {
  3573. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
  3574. file_put_contents($xmlFile, $this->asXml());
  3575. }
  3576. }
  3577. public function asXml($resultsPart = null) {
  3578. self::saveToLog("Generuję plik XML ({$resultsPart})");
  3579. if (!$this->results) {
  3580. self::saveToLog("Brak wyników (#1), wygenerowano pusty plik XML ({$resultsPart})");
  3581. // self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
  3582. // return null;
  3583. }
  3584. if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
  3585. if (!isset($this->items_results[$resultsPart])) {
  3586. self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
  3587. return null;
  3588. }
  3589. $xmlRoot = "RelatedFeatureRoot";
  3590. $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
  3591. self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
  3592. return $return;
  3593. }
  3594. public function asArray($resultsPart = null, $subArray = null) {
  3595. if (!$this->results) return null;
  3596. if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
  3597. if (!$this->items_results[$resultsPart]) return null;
  3598. if ($subArray) {
  3599. if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
  3600. else return [];
  3601. } else return $this->items_results[$resultsPart];
  3602. }
  3603. public function powiazaniaFound() {
  3604. if ($this->results) return true;
  3605. else return false;
  3606. }
  3607. public function generatePdfAndHtml() {
  3608. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  3609. if (!file_exists($antDir)) mkdir($antDir, 0770, true);
  3610. if (!is_dir($antDir)) {
  3611. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
  3612. self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
  3613. $this->saveProgress(['reportsCreated' => 1]);
  3614. return;
  3615. }
  3616. $this->saveProgress(['step' => 'reports']);
  3617. if ($this->getPartsCount()) {
  3618. self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
  3619. for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
  3620. self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
  3621. } else $this->_generatePdfAndHtml();
  3622. }
  3623. private function _generatePdfAndHtml($resultsPart = null) {
  3624. $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
  3625. self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
  3626. $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
  3627. $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
  3628. $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
  3629. $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
  3630. $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
  3631. $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
  3632. $antXmlFile = $antDir . "/" . $antXmlFilename;
  3633. //$baseDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}";
  3634. $baseDir = "/opt/local/pl.procesy5/p5build_SE/temp/WPS_Functions/temp/default_db/CRM_PROCES_tree/relations-{$id_part}";
  3635. $ditamapFile = "{$baseDir}/relations-{$id_part}.ditamap";
  3636. $pdfFile = "{$baseDir}/pdf/relations-{$id_part}.pdf";
  3637. $htmlDir = "{$baseDir}/html";
  3638. $htmlFile = "{$htmlDir}/relations-{$id_part}.html";
  3639. //if (!file_exists($xmlFile))
  3640. $this->saveXml($resultsPart);
  3641. if (!file_exists($xmlFile)) {
  3642. $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
  3643. self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
  3644. $this->saveProgress(['reportsCreated' => 1]);
  3645. return;
  3646. }
  3647. $this->saveProgress(['reportsCreated' => 0.05]);
  3648. copy($xmlFile, $antXmlFile);
  3649. self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
  3650. 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}");
  3651. if (file_exists($ditamapFile))
  3652. {
  3653. self::saveToLog("Wygenerowano plik przejściowy");
  3654. $this->saveProgress(['reportsCreated' => 0.15]);
  3655. } else {
  3656. self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
  3657. $this->saveProgress(['reportsCreated' => 1]);
  3658. return;
  3659. }
  3660. self::saveToLog("Generuję plik PDF ({$resultsPart})");
  3661. 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");
  3662. if (file_exists($pdfFile)) {
  3663. rename($pdfFile, $pdfDestFile);
  3664. self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
  3665. } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
  3666. $this->saveProgress(['reportsCreated' => 0.45]);
  3667. self::saveToLog("Generuję pliki HTML ({$resultsPart})");
  3668. 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");
  3669. if (file_exists($htmlDir) && is_dir($htmlDir) && file_exists($htmlFile)) {
  3670. self::exec("cd \"{$baseDir}\" && zip -r \"{$htmlZipDestFile}\" html");
  3671. if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
  3672. self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
  3673. self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
  3674. } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
  3675. $this->saveProgress(['reportsCreated' => 0.35]);
  3676. }
  3677. }