BiAuditGenerate.php 126 KB

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