| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228 |
- <?php
- //TODO optimal - akcja aby doruzcic do pracownikow do analizy jakas spolke z kontekstu przegladania KRS - zapytanie przyklad:
- // insert ignore into BI_audit_ENERGA_PRACOWNICY (imiona, nazwisko, pesel, source )
- // select p.imiona, p.nazwisko, p.pesel, 'ENSO_STORA/zadanie' from `BI_audit_KRS_person` as p
- // right join `CRM__#REF_TABLE__12` as r on r.`REMOTE_PRIMARY_KEY`=p.ID
- // right join BI_audit_KRS as k on k.ID=r.`PRIMARY_KEY`
- // where k.`nazwa` like '%Stora%enso%';
- //serwisowy skrypt jest tutaj pod nazwa xyz.
- //TODO mozliwosc przerwania przetwarzania
- Lib::loadClass('RouteBase');
- Lib::loadClass('FoldersConfig');
- Lib::loadClass('FileUploader');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('SchemaFactory');
- Lib::loadClass('Core_AclHelper');
- Lib::loadClass('Core_AclSimpleSchemaBase');
- class Route_UrlAction_BiAuditGenerate extends RouteBase {
- private $powiazanie = null;
- private $SOURCE = null;
- private $REFERER;
- private $POWIAZANIA_ID = null;
- public function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- }
- private static function getDirectory($table, $id) {
- $folderConf = FoldersConfig::getAll($table.'_COLUMN');
- $record = new stdClass;
- $record->ID = $id;
- $uploader = new FileUploader($table.'_COLUMN', $record);
- $errMsg = "";
- if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br/>\n{$errMsg}", 404);
- $uploader->findFolder();
- return $uploader->getDestLocalPath(true);
- }
- private static function getUrl($table, $id) {
- $folderConf = FoldersConfig::getAll($table.'_COLUMN');
- $record = new stdClass;
- $record->ID = $id;
- $uploader = new FileUploader($table.'_COLUMN', $record);
- $errMsg = "";
- if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych<br/>\n{$errMsg}", 404);
- return $uploader->getFolderWeb() . "/" . $uploader->getDestFolder(true);
- }
- private static function getMainDirectory() {
- $folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
- if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br/>\n{$errMsg}", 404);
- return $folderConf['mount_point'];
- }
- private static function parseNipRegon($string) {
- $nip = null; $regon = null;
- preg_match('/^(.*[^[:digit:]])?([[:digit:]]{10})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
- if (!empty($matches[2])) $nip = trim($matches[2]);
- if ($nip && !V::isNip($nip)) $nip = null;
- preg_match('/^(.*[^[:digit:]])?([[:digit:]]{9})([^[:digit:]].*)?$/', str_replace('-', '', $string), $matches);
- if (!empty($matches[2])) $regon = trim($matches[2]);
- if ($regon && !V::isRegon($regon)) $regon = null;
- return [$nip, $regon];
- }
- private function initializePowiazaniaForm() {
- ?>
- <div class="container" style="margin-top:20px">
- <form class="form-horizontal" method="post">
- <legend>
- Generowanie powiązań :: <?=$this->powiazanie['L_APPOITMENT_INFO']?>
- <span class="pull-right"># <?=$this->powiazanie['ID']?></span>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Wybierz pracowników, dla których mają zostać wyszukane powiązania</h4>
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
- <td width=1>ID</td>
- <td>Imiona</td>
- <td>Nazwisko</td>
- <td>Pesel</td>
- <td>NIP</td>
- <td>Regon</td>
- <td>source</td>
- </tr>
- </thead>
- <tbody>
- <?php
- $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
- $queryFeatures = $acl->buildQuery(['limit' => 0]);
- $pracownicy = $queryFeatures->getItems();
- foreach ($pracownicy as $pracownik) {
- ?>
- <tr>
- <td><input type="checkbox" name="prID[]" value="<?=$pracownik['ID']?>" onClick="toggle(this)"/></td>
- <td align="right"><?=$pracownik['ID']?></td>
- <td><?=$pracownik['imiona']?></td>
- <td><?=$pracownik['nazwisko']?></td>
- <td><?=$pracownik['pesel']?></td>
- <td><?=$pracownik['nip']?></td>
- <td><?=$pracownik['regon']?></td>
- <td><?=$pracownik['source']?></td>
- </tr>
- <?php
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <!-- <div class="form-group">
- <label class="col-sm-2 control-label">
- Odśwież cache
- </label>
- <div class="col-sm-2">
- <select name="reloadCache" class="form-control">
- <option value="No" selected>Nie</option>
- <!-#- <option value="Part">Częściowe</option>-#->
- <option value="Full">Pełne</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-2 col-sm-10">
- <!-#- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-#->
- Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
- Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
- </div>
- </div>-->
- <div class="form-group">
- <div class="col-sm-12">
- <div class="containter" style="text-align:center">
- <button type="submit" class="btn btn-primary btn-sm" name="action" value="initialize">Generuj</button>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Anuluj</a>
- </div>
- </div>
- </div>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- </form>
- </div>
- <script language="JavaScript">
- <!--
- function toggleAll(source) {
- checkboxes = document.getElementsByName('prID[]');
- for(var i=0, n=checkboxes.length;i<n;i++) checkboxes[i].checked = source.checked;
- }
- function toggle(source) {
- checkboxes = document.getElementsByName('prID[]');
- all = true;
- for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked == false) all = false;
- source.form['checkAll'].checked = all;
- }
- -->
- </script>
- <?php
- }
- private function initializePowiazaniaSave() {
- $prID = V::get('prID', array(), $_POST);
- if (!$prID) throw new Exception("Nie wybrano żadnego pracownika!");
- $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
- $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
- $kontrahenci = $queryFeatures->getItems();
- $acl = Core_AclHelper::getAclByNamespace('default_db/BI_audit_KW_requested_person/BI_audit_KW_requested_person');
- $queryFeatures = $acl->buildQuery(['limit' => 0, 'cols' => ['ID']]);
- $requestedPersons = $queryFeatures->getItems();
- if (!($kontrahenci || $requestedPersons)) throw new Exception("Nie znaleziono żadnego obiektu końcowego");
- $sqlUpdate = ['FILE_STATUS' => 'TO_GENERATE'];
- $reloadCache = V::get('reloadCache', 'No', $_POST);
- $reloadCacheAvailable = ['Full', 'Part', 'No'];
- if (!in_array($reloadCache, $reloadCacheAvailable)) throw new Exception("Błąd formularza!");
- $sqlUpdate['BI_analiza_reloadCache'] = $reloadCache;
- $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full', 'Part')";
- $result = DB::getPDO()->fetchValue($query);
- if ($result) $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache (wymagane dla innego rekordu)';
- elseif ($reloadCache != 'No') $sqlUpdate['FILE_STATUS_info'] = 'Oczekuje na odświeżenie cache';
- else $sqlUpdate['FILE_STATUS_info'] = "Oczekuje na wygenerowanie powiązań";
- if ($this->powiazanie) { // wyzwolone z poziomu tabeli BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA - aktualizujemy istniejący rekord
- $powiazanieID = $this->powiazanie['ID'];
- } else { // wyzwolone z poziomu tabeli BI_audit_ENERGA_PRACOWNICY - dodajemy nowy rekord
- if (count($prID) != 1) throw new Exception("Błąd formularza!");
- if (!($lAppoitmentInfo = V::get('info', false, $_POST))) throw new Exception("Błąd formularza!");
- if (!($BiAnalizaMinDepth = V::get('minDepth', false, $_POST))) throw new Exception("Błąd formularza!");
- if (!($BiAnalizaMaxDepth = V::get('maxDepth', false, $_POST))) throw new Exception("Błąd formularza!");
- if (!($BiAnalizaOnlyTargets = V::get('onlyTargets', false, $_POST))) throw new Exception("Błąd formularza!");
- $query = "select * from BI_audit_ENERGA_PRACOWNICY where ID='{$prID[0]}'";
- $result = DB::getPDO()->fetchFirst($query);
- if (!$result) throw new Exception("Błąd formularza!");
- $sqlInsert = [
- 'L_APPOITMENT_INFO' => $lAppoitmentInfo,
- 'A_STATUS' => 'NORMAL',
- 'A_STATUS_INFO' => 'Dodane przez BiAuditGenerate z poziomu tabeli BI_audit_ENERGA_PRACOWNICY',
- 'A_ADM_COMPANY' => $result['A_ADM_COMPANY'],
- 'A_CLASSIFIED' => $result['A_CLASSIFIED'],
- 'FILE_STATUS' => 'NONE',
- 'FILE_STATUS_info' => 'Oczekuję na zdefiniowanie danych wejściowych',
- 'BI_analiza_reloadCache' => $sqlUpdate['BI_analiza_reloadCache'],
- 'BI_analiza_minDepth' => $BiAnalizaMinDepth,
- 'BI_analiza_maxDepth' => $BiAnalizaMaxDepth,
- 'BI_analiza_onlyTargets' => $BiAnalizaOnlyTargets,
- ];
- $powiazanieID = DB::getDB()->ADD_NEW_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', (object)$sqlInsert);
- if ($powiazanieID) SE_Layout::alert('success','Dodano rekord do wygenerowania powiązań');
- else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
- }
- $sqlUpdate['ID'] = $powiazanieID;
- self::truncatePowiazaniaFromDB($powiazanieID);
- $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
- foreach ($prID as $v) DB::getPDO()->insert($refPowiazaniaToPracownicy, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $v]);
- $refPowiazaniaToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- foreach ($kontrahenci as $kontrahent) DB::getPDO()->insert($refPowiazaniaToKontrahenci, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $kontrahent['ID']]);
- $refPowiazaniaToKwRequestedPreson = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_KW_requested_person', true);
- foreach ($requestedPersons as $requestedPerson) DB::getPDO()->insert($refPowiazaniaToKwRequestedPreson, ['PRIMARY_KEY' => $powiazanieID, 'REMOTE_PRIMARY_KEY' => $requestedPerson['ID']]);
- $affected = DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlUpdate);
- if ($affected) {
- if ($this->powiazanie) {
- SE_Layout::alert('success','Oznaczono rekord do wygenerowania powiązań');
- ?>
- <div class="container" style="text-align:center">
- <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
- </div>
- <?php
- }
- } else throw new Exception("Wystąpił nieznany błąd @initializePowiazaniaSave");
- }
- private function initializePowiazania() {
- switch (V::get('action', '', $_POST)) {
- case "initialize":
- $this->initializePowiazaniaSave();
- break;
- default:
- $this->initializePowiazaniaForm();
- }
- }
- private function showPowiazania() {
- // echo "Statystyki znalezionych powiązań [TODO]";
- $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
- $url = self::getUrl('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $this->powiazanie['ID']);
- $reports = [
- 'pdf' => [
- 'files' => glob("{$dir}/relations*.pdf"),
- 'label' => 'Raporty PDF:<br/> ',
- 'button' => 'Pokaż raport PDF',
- 'regex' => "/^relations(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.pdf$/",
- 'parentDir' => false,
- ],
- 'html' => [
- 'files' => glob("{$dir}/html*/relations-{$this->powiazanie['ID']}*.html"),
- 'label' => 'Raporty HTML<br/>do przeglądania:',
- 'button' => 'Pokaż raport HTML',
- 'regex' => "/^relations-({$this->powiazanie['ID']})_([[:digit:]]+)\.html$/",
- 'parentDir' => true,
- ],
- 'htmlZip' => [
- 'files' => glob("{$dir}/html*.zip"),
- 'label' => 'Raporty HTML<br/>do pobrania:',
- 'button' => 'Pobież raport HTML',
- 'regex' => "/^html(-{$this->powiazanie['ID']})?_([[:digit:]]+)\.zip$/",
- 'parentDir' => false,
- ],
- ];
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Wygenerowany raport nr <?=$this->powiazanie['ID']?>
- </legend>
- <div class="form-group" style="text-align: center;">
- <?php
- array_walk($reports, function ($report) use ($url) {
- echo "<div class=\"col-sm-2\"><h4>{$report['label']}</h4>";
- $hrefs = array_filter(array_map(function ($path) use ($url, $report) {
- if (!is_file($path)) return false;
- $file = basename($path);
- if (preg_match($report['regex'], $file, $matches)) $i = " (" . ltrim($matches[2], '0') . ")";
- else $i = '';
- if ($report['parentDir']) $file = basename(dirname($path)) . "/" . $file;
- return "<a href=\"{$url}/{$file}\" target=\"_blank\" class=\"btn btn-primary\">{$report['button']}{$i}</a>";
- }, $report['files']));
- if ($hrefs) echo implode('<br/><br/>', $hrefs);
- else echo "<h5>Nie znaleziono</h5>";
- echo "</div>\n";
- });
- ?>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <?php
- }
- private function showPowiazaniaList() {
- switch (V::get('action', '', $_POST)) {
- case "initialize":
- $this->initializePowiazaniaSave();
- break;
- }
- $this->showPowiazaniaListForm();
- }
- private function showPowiazaniaListForm() {
- if (!$this->SOURCE['ID']) throw new Exception("Błąd danych");
- elseif ($this->SOURCE['TABLE'] != 'BI_audit_ENERGA_PRACOWNICY') throw new Exception("Błąd danych");
- $query = "select * from `{$this->SOURCE['TABLE']}` where ID = '{$this->SOURCE['ID']}'";
- $pracownik = DB::getPDO()->fetchFirst($query);
- if (!$pracownik) throw new Exception("Błąd danych");
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Lista wygenerowanych powiązań :: <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>
- <span class="pull-right"># <?=$pracownik['ID']?></span>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Lista wygenerowanych powiązań, w których znajduje się pracownik</h4>
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>ID</td>
- <td>Adnotacje</td>
- <td>Minimalna głębokość analizy</td>
- <td>Maksymalna głębokość analizy</td>
- <td>Powiązania tylko do celów</td>
- <td>Status raportu</td>
- <td>Status raportu - informacje</td>
- <td>Indywidualny raport</td>
- <td width=1></td>
- </tr>
- </thead>
- <tbody>
- <?php
- $refPowiazaniaToPracownicy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_PRACOWNICY', true);
- $query = "select `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.*
- from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
- join `{$refPowiazaniaToPracownicy}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPracownicy}`.`PRIMARY_KEY`
- where `REMOTE_PRIMARY_KEY` = '{$this->SOURCE['ID']}'";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) echo '<tr><td align="center" colspan="9">Brak znalezionych powiązań</td></tr>';
- else {
- foreach ($result as $row) {
- $query = "select count(*) from `{$refPowiazaniaToPracownicy}` where `PRIMARY_KEY` = '{$row['ID']}'";
- $count = DB::getPDO()->fetchValue($query);
- ?>
- <tr>
- <td align="right"><?=$row['ID']?></td>
- <td><?=$row['L_APPOITMENT_INFO']?></td>
- <td><?=$row['BI_analiza_minDepth']?></td>
- <td><?=$row['BI_analiza_maxDepth']?></td>
- <td><?=($row['BI_analiza_onlyTargets'] == 'N' ? "Nie" : "Tak")?></td>
- <td><?=$row['FILE_STATUS']?></td>
- <td><?=$row['FILE_STATUS_info']?></td>
- <td><?=($count > 1 ? 'Nie' : 'Tak')?></td>
- <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>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Dodaj nowe zadanie generowania powiazań dla tego pracownika</h4>
- </div>
- </div>
- <form class="form-horizontal" method="post">
- <div class="form-group">
- <label class="col-sm-4 control-label">Minimalna głębokość poszukiwań (liczba rekurencji)</label>
- <div class="col-sm-1">
- <input type="number" class="form-control" name="minDepth" id="minDepth" data-bind="value:replyNumber" min="1" max="9" value="1" required/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">Maksymalna głębokość poszukiwań (liczba rekurencji)</label>
- <div class="col-sm-1">
- <input type="number" class="form-control" name="maxDepth" id="maxDepth" data-bind="value:replyNumber" min="1" max="9" value="6" required/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">Czy zwracać tylko wyniki ze znalezionymi obiektami docelowymi (z tabeli kontrahentów)?</label>
- <div class="col-sm-1">
- <select name="onlyTargets" class="form-control">
- <option value="Y" selected>Tak</option>
- <option value="N">Nie</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-4 control-label">Adnotacje</label>
- <div class="col-sm-4">
- <input type="text" class="form-control" name="info" value="Indywidualnie dla <?=htmlspecialchars($pracownik['imiona'] . " " . $pracownik['nazwisko'])?>" required/>
- </div>
- </div>
- <!-- <div class="form-group">
- <label class="col-sm-4 control-label">
- Odśwież cache
- </label>
- <div class="col-sm-2">
- <select name="reloadCache" class="form-control">
- <option value="No" selected>Nie</option>
- <!-#- <option value="Part">Częściowe</option>-#->
- <option value="Full">Pełne</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-4 col-sm-8">
- <!-#- Częściowe odświeżenie wymagane w przypadku, gdy jedynie dodano nowe rekordy w tabelach pracowników/kontrahentów.<br/>-#->
- Pełne odświeżenie wymagane w przypadku edycji/usunięcia istniejących rekordów w tabelach pracowników/kontrahentów.<br/>
- Uwaga! Jeżeli aktywne są inne zadania, te zadanie zostanie wstrzymane do momentu ich ukończenia.
- </div>
- </div>-->
- <div class="form-group">
- <div class="col-sm-12">
- <div class="containter" style="text-align:center">
- <button type="submit" class="btn btn-primary" name="action" value="initialize" onClick="return validate()">Generuj</button>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- <input type="hidden" name="prID[]" value="<?=$pracownik['ID']?>"/>
- </form>
- </div>
- <script language="JavaScript">
- <!--
- function validate() {
- result = (document.getElementById('minDepth').value <= document.getElementById('maxDepth').value);
- if (!result) alert('Wartość minimalnej głębokości analizy nie może być większa od wartości maksymalnej głębokości analizy!');
- return result;
- }
- -->
- </script>
- <?php
- }
- private function showPowiazania_progress() {
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Postęp generowania raportu nr <?=$this->powiazanie['ID']?>
- </legend>
- Panel w przygotowaniu
- <?php
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "abort":
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $abortFile = "{$tasksDirLocation}/generatePowiazania-{$this->powiazanie['ID']}.abort";
- touch($abortFile);
- ?>
- <h4>Zlecono przerwanie badania - odczekaj kilka minut</h4>
- <?php
- break;
- default:
- ?>
- <form method="post">
- <button type="submit" name="action" value="abort">Przerwij badanie</button>
- </form>
- </div>
- <?php
- }
- }
- private function operationalRaportNote() {
- $refTable = BiAuditRefTables::getRefTable("BI_audit_operational_raport_note", $this->SOURCE['TABLE']);
- if (!$refTable) throw new Exception("Brak konfiguracji notatki operacyjnej dla tabeli '{$this->SOURCE['TABLE']}'");
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "add":
- $sqlArr = array_filter([
- 'OznaczenieSprawy' => trim(V::get('OznaczenieSprawy', '', $_POST)),
- 'Oznaczenie_Sprawy_dla_eskalacji' => trim(V::get('Oznaczenie_Sprawy_dla_eskalacji', '', $_POST)),
- 'Zglaszajacy' => trim(V::get('Zglaszajacy', '', $_POST)),
- 'DataZgloszenia' => trim(V::get('DataZgloszenia', '', $_POST)),
- 'note' => trim(V::get('note', '', $_POST)),
- 'long_note' => trim(V::get('long_note', '', $_POST)),
- 'Wnioski_z_analizy' => trim(V::get('Wnioski_z_analizy', '', $_POST)),
- 'Wnioski_z_analizy_opis' => trim(V::get('Wnioski_z_analizy_opis', '', $_POST)),
- 'action' => trim(V::get('form_action', '', $_POST)),
- ], function($v) {
- if ($v) return true;
- return false;
- });
- $sqlArr['A_RECORD_CREATE_AUTHOR'] = User::getName();
- $sqlArr['A_RECORD_CREATE_DATE'] = date('Y-m-d-H:i');
- $noteId = DB::getPDO()->insert('BI_audit_operational_raport_note', $sqlArr);
- if (!$noteId) throw new Exception("Wystąpił błąd podczas zapisywania notatki do bazy");
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $noteId, 'REMOTE_PRIMARY_KEY' => $this->SOURCE['ID']]);
- ?>
- <center>
- <h4>Pomyślnie dodano notatkę operacyjną.</h4>
- <a href="<?=$this->REFERER?>" class="btn btn-primary">Powrót</a>
- </center>
- <?php
- break;
- default:
- ?>
- <div class="container" style="margin-top:20px">
- <form method="post" class="form-horizontal">
- <legend>
- Dodawanie notatki operacyjnej
- <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?>, rekord ID: <?=$this->SOURCE['ID']?></span>
- </legend>
- <div class="form-group">
- <label class="col-sm-3 control-label">Oznaczenie sprawy</label>
- <div class="col-sm-9">
- <input type="text" class="form-control" name="OznaczenieSprawy" maxlength="100" autocomplete="off"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Oznaczenie sprawy dla eskalacji</label>
- <div class="col-sm-9">
- <input type="text" class="form-control" name="Oznaczenie_Sprawy_dla_eskalacji" maxlength="100" autocomplete="off"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Zgłaszający</label>
- <div class="col-sm-9">
- <input type="text" class="form-control" name="Zglaszajacy" maxlength="100" autocomplete="off"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Data zgłoszenia</label>
- <div class="col-sm-2">
- <div class="input-group">
- <input type="text" class="form-control se_type-date" id="DataZgloszenia" name="DataZgloszenia" maxlength="10">
- <span class="input-group-addon">
- <span class="glyphicon glyphicon-calendar"/>
- </span>
- </input>
- </div>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Tytuł notatki</label>
- <div class="col-sm-9">
- <input type="text" class="form-control" name="note" maxlength="255" autocomplete="off"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Pełny opis</label>
- <div class="col-sm-9">
- <textarea class="form-control" name="long_note" autocomplete="off"></textarea>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Wnioski z analizy</label>
- <div class="col-sm-9">
- <input type="text" class="form-control" name="Wnioski_z_analizy" maxlength="255" autocomplete="off"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Wnioski z analizy - opis</label>
- <div class="col-sm-9">
- <textarea class="form-control" name="Wnioski_z_analizy_opis" autocomplete="off"></textarea>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-3 control-label">Akcja zgłoszenia</label>
- <div class="col-sm-2">
- <select name="form_action" class="form-control">
- <option value="REPORT" selected>Eskaluj i alarmuj</option>
- <option value="IGNORE">Ignoruj i nie pokazuj</option>
- </select>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <center>
- <input type="hidden" name="REFERER" value="<?=$_SERVER['HTTP_REFERER']?>"/>
- <button type="submit" class="btn btn-primary" name="action" value="add" style="width: 80px;">Dodaj</button>
- <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
- </center>
- </div>
- </div>
- </form>
- </div>
- <script>
- jQuery(document.getElementById('DataZgloszenia')).parent().datetimepicker({
- format: 'YYYY-MM-DD'
- , locale: 'pl'
- , showTodayButton: false
- , date: '<?=date("Y-m-d")?>'
- , maxDate: '<?=date("Y-m-d")?>'
- });
- </script>
- <?php
- }
- }
- private function urlActionOnItem() {
- try {
- if (!$this->SOURCE) throw new Exception("Błąd danych");
- elseif (!(isset($this->SOURCE['TABLE']) && isset($this->SOURCE['ID']))) throw new Exception("Błąd danych");
- $_subUrlAction = V::get('_subUrlAction', '', $_GET);
- switch ($_subUrlAction) {
- case "importToPracownicy":
- if (in_array($this->SOURCE['TABLE'], ['BI_audit_KRS', 'BI_audit_MSIG'])) $this->importToPracownicySearch($this->SOURCE['ID']);
- else throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate #1");
- break;
- case "showKrsForKrsPerson":
- if (in_array($this->SOURCE['TABLE'], ['BI_audit_KRS_person'])) $this->showKrsForKrsPerson();
- else throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate #2");
- break;
- case "operationalRaportNote":
- $this->operationalRaportNote();
- break;
- default:
- switch ($this->SOURCE['TABLE']) {
- case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
- $powiazania = DB::getPDO()->fetchall("select * from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->SOURCE['ID']}'");
- if (!$powiazania) throw new Exception("Błąd danych");
- $this->powiazanie = $powiazania[0];
- switch ($this->powiazanie['FILE_STATUS']) {
- case "NONE":
- $this->initializePowiazania();
- break;
- case "IN_PROGRESS":
- $this->showPowiazania_progress();
- break;
- case "GENERATED":
- $this->showPowiazania();
- break;
- default: throw new Exception("Błędny status rekordu");
- }
- break;
- case "BI_audit_ENERGA_PRACOWNICY":
- $this->showPowiazaniaList();
- break;
- case "BI_audit_BENFORD":
- $this->benford_showReport();
- break;
- default: throw new Exception("Błąd wyzwolenia funkcji BiAuditGenerate");
- }
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger',$e->getMessage());
- $_SESSION['REFERER'] = $this->REFERER;
- ?>
- <div class="container" style="text-align:center">
- <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-primary">Powrót</a>
- </div>
- <?php
- }
- }
- private function importToPracownicy() {
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "search":
- $this->importToPracownicySearch();
- break;
- default: $this->importToPracownicyForm();
- }
- }
- private $tableDesc = ['BI_audit_KRS' => 'KRS', 'BI_audit_MSIG' => 'MSiG'];
- private function importToPracownicyForm() {
- $TABLE = $this->SOURCE['TABLE'];
- $DESC = $this->tableDesc[$TABLE];
-
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Znajdź podmiot</h4>
- </div>
- </div>
- <form class="form-horizontal" method="post">
- <div class="form-group">
- <label class="col-sm-1 control-label">Nazwa</label>
- <div class="col-sm-4">
- <input type="text" class="form-control" name="nazwa" title="Podaj nazwę podmiotu"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-1 control-label">KRS</label>
- <div class="col-sm-2">
- <input type="text" class="form-control" name="krs" pattern="^[0-9]{0,10}$" title="Podaj KRS"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-1 control-label">NIP</label>
- <div class="col-sm-2">
- <input type="text" class="form-control" name="nip" pattern="^[0-9]{0,10}$" title="Podaj NIP (bez kresek i bez oznaczenia kraju)"/>
- </div>
- </div>
- <div class="form-group">
- <label class="col-sm-1 control-label">Regon</label>
- <div class="col-sm-2">
- <input type="text" class="form-control" name="regon" pattern="^[0-9]{0,9}$" title="Podaj regon"/>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-1 col-sm-11">
- <button type="submit" class="btn btn-primary" name="action" value="search">Szukaj</button>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </form>
- </div>
- <?php
- }
- private function importToPracownicySearch($krsId = null) {
- $TABLE = $this->SOURCE['TABLE'];
- $DESC = $this->tableDesc[$TABLE];
- $formItems = [
- "nazwa" => 'like',
- "krs" => '=',
- "nip" => '=',
- "regon" => '=',
- ];
- try {
- $subaction = V::get('subaction', '', $_POST);
- switch ($subaction) {
- case "listPerson":
- $krsId = V::get('krsId', 0, $_POST, int);
- break;
- case "addPersonToPracownicy":
- $krsId = V::get('krsId', 0, $_POST, int);
- $personId = V::get('personId', [], $_POST);
- if (!$personId) throw new Exception("Błąd formularza");
- $query = "insert into BI_audit_ENERGA_PRACOWNICY (source, imiona, nazwisko, pesel) select 'KRS', imiona, nazwisko, pesel from {$TABLE}_person where ID in (" . implode(", ", $personId) . ")";
- DB::getPDO()->query($query);
- SE_Layout::alert('success', "Pomyślnie zaimportowano " . count($personId) . " pracownik" . ((count($personId) == 1) ? "a" : "ów"));
- break;
- case "addToKontrahenci":
- $krsId = V::get('krsId', 0, $_POST, int);
- if (!$krsId) throw new Exception("Błąd formularza");
- $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}'";
- $kontrahentExists = DB::getPDO()->fetchValue($query);
- if ($kontrahentExists) throw new Exception("Podmiot znajduje się już w tabeli kontrahentów");
- $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." ";
- DB::getPDO()->query($query);
- SE_Layout::alert('success', "Pomyślnie zaimportowano kontrahenta");
- break;
- }
- if ($krsId) {
- $where = ["ID = '{$krsId}'"];
- } else {
- $form = [];
- foreach ($formItems as $item => $type) {
- if ($param = V::get($item, '', $_POST)) {
- if ($type == 'like') $param = "%{$param}%";
- $form[$item] = DB::getPDO()->quote($param);
- }
- }
- if (!$form) throw new Exception("Nie wypełniono żadnego pola wyszukiwania!");
- $where = [];
- foreach ($form as $name => $value) $where[] = "`{$name}` {$formItems[$name]} {$value}";
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage());
- $this->importToPracownicyForm();
- return;
- }
- $query = "select * from `{$TABLE}` where " . implode(" and ", $where) . "order by ID limit 1001";
- $result = DB::getPDO()->fetchAll($query);
- if (count($result) == 1001) {
- SE_Layout::alert('danger', 'Znaleziono zbyt wiele wyników. Doprecyzuj parametry wyszukiwania.');
- $this->importToPracownicyForm();
- return;
- } elseif (count($result) == 1) {
- $krsId = $result[0]['ID'];
- }
- ?>
- <div class="container" style="margin-top:20px">
- <form method="post">
- <legend>
- Importowanie podmiotów z <?=$DESC?> do tabel kontrahentów i pracowników
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Znalezione podmioty:</h4>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>Lp.</td>
- <td>Nazwa</td>
- <td>Adres</td>
- <td>KRS</td>
- <td>NIP</td>
- <td>Regon</td>
- <?php
- if (count($result) > 1) {
- ?>
- <td width=1>Wybierz</td>
- <?php
- }
- ?>
- </tr>
- </thead>
- <tbody>
- <?php
- if (!$result) echo '<tr><td align="center" colspan="6">Nie znaleziono podmiotu</td></tr>';
- else {
- $lp = 1;
- foreach ($result as $row) {
- $adres = $row['A_miejscowosc'];
- if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
- if ($row['A_nrDomu']) {
- $adres .= " {$row['A_nrDomu']}";
- if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
- }
- ?>
- <tr>
- <td align="right"><?=$lp++?></td>
- <td><?=htmlspecialchars($row['nazwa'])?></td>
- <td><?=htmlspecialchars($adres)?></td>
- <td><?=$row['krs']?></td>
- <td><?=$row['nip']?></td>
- <td><?=$row['regon']?></td>
- <?php
- if (count($result) > 1) {
- ?>
- <td align="center">
- <input type="radio" name="krsId" value="<?=$row['ID']?>"/>
- </td>
- <?php
- }
- ?>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <?php
- if (count($result) > 1) {
- ?>
- <div class="form-group">
- <div class="col-sm-12">
- <?php
- foreach (array_keys($formItems) as $item) {
- ?>
- <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
- <?php
- }
- ?>
- <input type="hidden" name="back" value="search"/>
- <div class="containter" style="text-align:center">
- <button type="submit" class="btn btn-primary" name="subaction" value="listPerson" onClick="return validateCompany(this)">Wybierz zaznaczony podmiot</button>
- <a href="" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <?php
- } elseif ($krsId) {
- ?>
- <div class="form-group">
- <div class="col-sm-12">
- <h4>Znalezione osoby:</h4>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>Lp.</td>
- <td>Nazwisko</td>
- <td>Imiona</td>
- <td>Pesel</td>
- <td width=1><input type="checkbox" name="checkAll" onClick="toggleAll(this)"/></td>
- </tr>
- </thead>
- <tbody>
- <?php
- $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}'";
- $kontrahentExists = DB::getPDO()->fetchValue($query);
- $refToPerson = BiAuditRefTables::getRefTable($TABLE, "{$TABLE}_person", true);
- $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}'";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono osób powiązanych z podmiotem</td></tr>';
- else {
- $lp = 1;
- foreach ($result as $row) {
- ?>
- <tr<?=($row['pracownicyId'] ? ' style="color:darkgrey"' : '')?>>
- <td align="right"><?=$lp++?></td>
- <td><?=$row['nazwisko']?></td>
- <td><?=$row['imiona']?></td>
- <td><?=$row['pesel']?></td>
- <td><input type="checkbox" name="personId[]" value="<?=$row['ID']?>" onClick="toggle(this)" <?=($row['pracownicyId'] ? "disabled" : "")?>/></td>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <!-- <div class="form-group">
- <div class="col-sm-12">
- <label class="col-sm-4 control-label">Opis/źródło</label>
- <div class="col-sm-4">
- <input type="text" class="form-control" name="source" placeholder="KRS"/>
- </div>
- </div>
- </div>-->
- <div class="form-group">
- <div class="col-sm-12" style="text-align: center;">
- <button type="submit" class="btn btn-primary" name="subaction" value="addToKontrahenci"<?=($kontrahentExists ? " disabled" : "")?>>Dodaj firmę do tabeli kontrahentów</button>
- <button type="submit" class="btn btn-primary" name="subaction" value="addPersonToPracownicy" onClick="return validatePerson(this)">Dodaj zaznaczone osoby do tabeli pracowników</button>
- <input type="hidden" name="krsId" value="<?=$krsId?>"/>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- <?php
- if (V::get('back', '', $_POST) == 'search') {
- foreach (array_keys($formItems) as $item) {
- ?>
- <input type="hidden" name="<?=$item?>" value="<?=V::get($item, '', $_POST)?>"/>
- <?php
- }
- ?>
- <button type="submit" class="btn btn-default" name="action" value="search">Powrót</button>
- <?php
- } else {
- ?>
- <a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- <?php
- }
- ?>
- </div>
- </div>
- <?php
- }
- ?>
- <input type="hidden" name="action" value="search"/>
- </form>
- </div>
- <script language="JavaScript">
- <!--
- function toggleAll(source) {
- checkboxes = document.getElementsByName('personId[]');
- checked = false;
- for(var i=0, n=checkboxes.length;i<n;i++) {
- if (!checkboxes[i].disabled) {
- checkboxes[i].checked = source.checked;
- checked = true;
- }
- }
- if (source.checked && (!checked)) source.checked = false;
- }
- function toggle(source) {
- checkboxes = document.getElementsByName('personId[]');
- all = true;
- for(var i=0, n=checkboxes.length;i<n;i++) if(!checkboxes[i].disabled && checkboxes[i].checked == false) all = false;
- source.form['checkAll'].checked = all;
- }
- function validatePerson(source) {
- checkboxes = document.getElementsByName('personId[]');
- checked = false;
- for(var i=0, n=checkboxes.length;i<n;i++) if(checkboxes[i].checked) checked = true;
- if (!checked) alert('Nie wybrano żadnej osoby!');
- return checked;
- }
- function validateCompany(source) {
- radios = document.getElementsByName('krsId');
- checked = false;
- for(var i=0, n=radios.length;i<n;i++) if(radios[i].checked) checked = true;
- if (!checked) alert('Nie wybrano żadnej firmy!');
- return checked;
- }
- -->
- </script>
- <?php
- }
- private function showKrsForKrsPerson() {
- $query = "select * from BI_audit_KRS_person where ID = '{$this->SOURCE['ID']}'";
- $result = DB::getPDO()->fetchFirst($query);
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Lista podmiotów, w których występuje <?="{$result['nazwisko']} {$result['imiona']}" . ($result['pesel'] ? " (PESEL: {$result['pesel']})" : "")?>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <table class="table table-bordered table-hover table-striped" height=5>
- <thead>
- <tr style="text-align:center; background-color:lightgray">
- <td width=1>Lp.</td>
- <td>Nazwa</td>
- <td>Adres</td>
- <td>KRS</td>
- <td>NIP</td>
- <td>Regon</td>
- <td width=1></td>
- </tr>
- </thead>
- <tbody>
- <?php
- $refKrsToKrsPerson = BiAuditRefTables::getRefTable('BI_audit_KRS', 'BI_audit_KRS_person', true);
- $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']}'";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) echo '<tr><td align="center" colspan="5">Nie znaleziono powiązanych podmiotów</td></tr>';
- else {
- $lp = 1;
- foreach ($result as $row) {
- $adres = $row['A_miejscowosc'];
- if ($row['A_ulica']) $adres .= ", {$row['A_ulica']}";
- if ($row['A_nrDomu']) {
- $adres .= " {$row['A_nrDomu']}";
- if ($row['A_nrLokalu']) $adres .= "/{$row['A_nrLokalu']}";
- }
- ?>
- <tr>
- <td align="right"><?=$lp++?></td>
- <td><?=htmlspecialchars($row['nazwa'])?></td>
- <td><?=htmlspecialchars($adres)?></td>
- <td><?=$row['krs']?></td>
- <td><?=$row['nip']?></td>
- <td><?=$row['regon']?></td>
- <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>
- </tr>
- <?php
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <div class="containter" style="text-align:center">
- <a href="<?=$_SERVER['HTTP_REFERER']?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- </div>
- <?php
- }
- private function clearTable_do() {
- try {
- $wynik = V::get('wynik', 0, $_POST, 'int');
- $ctrl = @gzuncompress(@base64_decode(V::get('_BiAuditGenerate_ctrl', '', $_SESSION)));
- unset($_SESSION['_BiAuditGenerate_ctrl']);
- $deleteFiles = (V::get('deleteFiles', '', $_POST) === 'on');
- $deletedDirs = 0; $deletedFiles = 0;
- if (!($ctrl)) throw new Exception('Błąd parametru');
- if (!($wynik == $ctrl)) {
- SE_Layout::alert('warning', 'Podano błędny wynik działania');
- $this->clearTable_form();
- return;
- }
- $refs = []; $backRefs = []; $tables = []; $queries = [];
- switch ($this->SOURCE['TABLE']) {
- case "BI_audit_ENERGA_PRACOWNICY":
- $refs[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
- $tables[] = 'BI_audit_ENERGA_PRACOWNICY_adresy';
- $queries[] = "update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'";
- break;
- case "BI_audit_ENERGA_PRACOWNICY_import":
- break;
- case "BI_audit_ENERGA_RUM_KONTRAHENCI":
- $backRefs[] = 'BI_audit_ENERGA_RUM_UMOWY';
- $backRefs[] = 'BI_audit_ENERGA_FAKTURY';
- $queries[] = "update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING'";
- break;
- case "BI_audit_ENERGA_RUM_UMOWY":
- $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
- break;
- case "BI_audit_ENERGA_FAKTURY":
- $refs[] = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
- break;
- case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
- $query = "select ID from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- if ($deleteFiles) {
- $dir = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
- if (!file_exists($dir)) continue;
- $deleted = V::deleteWholeDirectory($dir, true, false);
- $deletedDirs += count($deleted['dirs']);
- $deletedFiles += count($deleted['files']);
- }
- self::deleteResultsFromDB($row['ID']);
- self::truncatePowiazaniaFromDB($row['ID']);
- }
- break;
- default: throw new Exception('Błąd parametru');
- }
- $tables[] = $this->SOURCE['TABLE'];
- foreach ($refs as $ref) $tables[] = BiAuditRefTables::getRefTable($this->SOURCE['TABLE'], $ref, true);
- foreach ($backRefs as $backRef) $tables[] = BiAuditRefTables::getRefTable($backRef, $this->SOURCE['TABLE'], true);
- foreach ($tables as $table) $queries[] = "delete from `{$table}`";
- foreach ($queries as $query) DB::getPDO()->query($query);
- ?>
- <div style="text-align: center;">
- <h2>Pomyślnie wyczyszczono tabelę <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>.</h2>
- <?php
- if ($deleteFiles && ($deletedDirs || $deletedFiles)):
- ?>
- <h4>Ponadto usunięto <?=$deletedDirs?> katalogów oraz <?=$deletedFiles?> plików.</h4>
- <?php
- endif;
- ?>
- <br/><a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
- </div>
- <?php
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage());
- }
- }
- private function clearTable_form() {
- if (!isset($this->clearTable_tables[$this->SOURCE['TABLE']])) SE_Layout::alert('danger', 'Błąd parametru');
- $a = rand(10, 50);
- $b = rand(10, 50);
- if ($a == $b) $op = 1;
- else $op = rand(0, 1);
- if ($op) {
- $suma = $a + $b;
- $string = "{$a} + {$b}";
- } else {
- if ($a < $b) {
- $suma = $b - $a;
- $string = "{$b} - {$a}";
- } else {
- $suma = $a - $b;
- $string = "{$a} - {$b}";
- }
- }
- $string .= " = ";
- $_SESSION['_BiAuditGenerate_ctrl'] = base64_encode(gzcompress($suma));
- $im = imagecreate((strlen($string) - 1) * 10, 24);
- $bg = imagecolorallocate($im, 255, 255, 255);
- $textcolor = imagecolorallocate($im, 0, 0, 0);
- imagestring($im, 5, 0, 0, $string, $textcolor);
- ob_start();
- imagepng($im);
- $image = ob_get_contents();
- ob_end_clean();
- /*
- $image = new Imagick();
- $draw = new ImagickDraw();
- $pixel = new ImagickPixel('white');
- $image->newImage(200, 24, $pixel);
- // $image->setFont("schema/WPS_Functions/mapserver_gml_to_png/map/fonts/Arial_Bold.ttf");
- // $image->newPseudoImage(100, 100, "label:\"{$a} {$op} {$b}\"");
- // $image->newPseudoImage(100, 100, "caption:Hello");
- $image->setImageFormat('png');
- $draw->setFillColor('black');
- // $draw->setFont('Arial');
- $draw->setFontSize(24);
- $image->annotateImage($draw, 0, 24, 0, $s);
- $image->trimImage(0);
- */
- $imageBase64 = base64_encode($image);
- //echo $imageBase64;
-
- ?>
- <div style="text-align: center;">
- <h2>Czy jesteś pewien, że chcesz usunąć<br/><b>wszystkie dane</b> z tabeli <?=$this->clearTable_tables[$this->SOURCE['TABLE']]?>?</h2><br/>
- <h3>Podaj wynik działania:</h3>
- <form method="post">
- <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/>
- <?php
- if ($this->SOURCE['TABLE'] == 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA'):
- ?>
- <h4><input type="checkbox" name="deleteFiles"/> Usuń również wszystkie pliki</h4><br/>
- <?php
- endif;
- ?>
- <button type="submit" class="btn btn-primary" name="action" value="doClearTable" style="width: 80px;">Tak</button>
- <input type="hidden" name="REFERER" value="<?=$this->REFERER?>"/>
- <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Anuluj</a>
- </form>
- </div>
- <?php
- }
- private function clearTable() {
- $this->clearTable_tables = [
- 'BI_audit_ENERGA_PRACOWNICY' => 'pracowników',
- 'BI_audit_ENERGA_PRACOWNICY_import' => 'pracowników (import)',
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => 'kontrahentów',
- 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA' => 'raportów',
- 'BI_audit_ENERGA_RUM_UMOWY' => 'umów',
- 'BI_audit_ENERGA_FAKTURY' => 'faktur',
- ];
- $query = "select count(*) from `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` where `FILE_STATUS` = 'IN_PROGRESS'";
- if (DB::getPDO()->fetchValue($query)) {
- ?>
- <div style="text-align: center;">
- <h2>Nie można usunąć żadnych danych<br/>(wykryto uruchomione zadania)</h2><br/>
- <a href="<?=$this->REFERER?>" class="btn btn-primary" style="width: 80px;">Powrót</a>
- </div>
- <?php
- return;
- }
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "doClearTable":
- $this->clearTable_do();
- break;
- default: $this->clearTable_form();
- }
- }
- private static function getNamespace($table, $field = null) {
- if ($field === null) return "default_db__x3A__{$table}";
- return "default_db__x3A__{$table}:{$field}";
- }
- private static function arrayWithNamespace($table, $array) {
- $keys = array_map(function($key) use ($table) {
- return self::getNamespace($table, $key);
- }, array_keys($array));
- return array_combine($keys, $array);
- }
- private function benford_getDetails($groupField = null, $a = null, $b = null) {
- try {
- if ($groupField === null) throw new Exception("Nieznany błąd wewnętrzny #1");
- if (!($benford = V::get('benford', '', $_SESSION))) throw new Exception("Nieznany błąd wewnętrzny #2");
- if (isset($benford[$this->SOURCE['TABLE']]['details'][$groupField][$a][$b])) throw new Exception(@gzuncompress($benford[$this->SOURCE['TABLE']]['details'][$groupField][$a][$b]));
- if (!($benford = @unserialize(@gzuncompress($benford[$this->SOURCE['TABLE']]['data'])))) throw new Exception("Nieznany błąd wewnętrzny #3");
- if (!isset($benford['conf']['groupFields'])) throw new Exception("Nieznany błąd wewnętrzny #4");
- if (!($groupFields = $benford['conf']['groupFields'])) throw new Exception("Nieznany błąd wewnętrzny #5");
- if (!($valueField = $benford['conf']['valueField'])) throw new Exception("Nieznany błąd wewnętrzny #6");
- if ($a === null) throw new Exception("Nieznany błąd wewnętrzny #7");
- if ($b === null) {
- if (!isset($benford['firstStep'][$a]['keys'])) throw new Exception("Nieznany błąd wewnętrzny #8");
- $keys = $benford['firstStep'][$a]['keys'];
- } else {
- if (!isset($benford['secondStep'][$a][$b]['keys'])) throw new Exception("Nieznany błąd wewnętrzny #9");
- $keys = $benford['secondStep'][$a][$b]['keys'];
- }
- $tempTable = uniqid('_temp_benford_ids_');
- DB::getPDO()->query("create temporary table `{$tempTable}` (`ID` int(11) NOT NULL, UNIQUE KEY `ID` (`ID`))");
- foreach (array_chunk($keys, 100) as $ids) {
- DB::getPDO()->query("insert into `{$tempTable}` values (" . implode('),(', $ids) . ")");
- }
- $query = "select `table`.`{$groupField}` as `field`, count(*) as `count`, sum(`table`.`{$valueField}`) as `sum` from `{$this->SOURCE['TABLE']}` `table` join `{$tempTable}` `temp` on `table`.`ID` = `temp`.`ID` where coalesce(`table`.`{$groupField}`,'') != '' group by `table`.`{$groupField}` having `count` > 1 order by `count` desc limit 10";
- try {
- $result = DB::getPDO()->fetchAll($query);
- } catch (Exception $e) {
- throw new Exception("Nieznany błąd, prawdopodobnie błędna konfiguracja kolumny grupującej");
- }
- $showDetails = '<h4>Najczęściej występujące wartości kolumny:</h4><form method="post"><select name="_groupField" class="form-control" onChange="showDetails2(this, ' . "{$a}, {$b}" . ')">';
- foreach ($groupFields as $field) {
- $selected = $field == $groupField ? ' selected' : '';
- $showDetails .= "<option value={$field}{$selected}>{$field}</option>";
- }
- $showDetails .= "</select></form></br>";
- if ($result) {
- $showDetails .= "<table name=\"NWK3\" class=\"table table-bordered table-hover table-striped table-condensed\"><thead><tr style=\"font-weight:bold;\"><td>Wartość</td><td>Liczba wystąpień</td><td>Procent występowania</td><td>Suma kwot</td></tr></thead><tbody>";
- $showDetails .= implode('', array_map(function($v) use ($keys) {
- return "<tr><td>{$v['field']}</td><td>{$v['count']}</td><td>" . number_format(round($v['count'] / count($keys) * 100, 3), 3, ',', '') . '</td><td style="text-align: right;">' . number_format(round($v['sum'], 2), 2, ',', '.') . '</td></tr>';
- }, $result));
- $showDetails .= "</tbody></table>";
- } else {
- $showDetails .= "<h5>Żadna wartość nie występuje wiele razy</h5>";
- }
- } catch (Exception $e) {
- $showDetails = "<h4>{$e->getMessage()}</h4>";
- }
- $_SESSION['benford'][$this->SOURCE['TABLE']]['details'][$groupField][$a][$b] = gzcompress($showDetails);
- $showDetails .= '<button type="submit" class="btn btn-primary btn-sm" onClick="hideDetails()">Zamknij</button>';
- return $showDetails;
- }
- private function benford_form($edit = false) {
- if (!($valueField = V::get('_benfordValueField', '', $_GET))) throw new Exception ("Błąd konfiguracji UrlAction - brak parametru _benfordField (DANE )");
- if (!($groupFields = V::get('_benfordGroupField', '', $_GET))) throw new Exception("Brak konfiguracji kolumny grupującej");
- if (!($namespace = V::get('_fromNamespace', '', $_GET))) throw new Exception("Błąd formularza");
- $groupFields = explode(',', $groupFields);
- $groupField = $groupFields[0];
- Lib::loadClass('FeatureAttrSelected');
- $count = FeatureAttrSelected::getTotalSelected($namespace);
- $selectedTable = FeatureAttrSelected::getAttributeTableName($namespace, User::getID());
- $query = "select `t`.`ID`, `{$valueField}` from `{$this->SOURCE['TABLE']}` `t` join `{$selectedTable}` `s` on `t`.`ID` = `s`.`primaryKey` where `t`.`{$valueField}` != 0 order by `s`.`primaryKey`";
- $values = [];
- try {
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) $values[$row['ID']] = $row[$valueField];
- } catch (Exception $e) {
- throw new Exception("Błąd zapytania SQL ({$e->getMessage()})");
- }
- if (!$values) throw new Exception("Nie wybrano żadnych obiektów lub wszystkie wybrane obiekty mają zerową wartość");
- Lib::loadClass('Benford');
- try {
- $benfordObj = new Benford($values);
- $benford = $benfordObj->getAllResult();
- $benford['conf'] = [
- 'count' => count($values),
- 'valueField' => $valueField,
- 'groupFields' => $groupFields,
- ];
- $_SESSION['benford'][$this->SOURCE['TABLE']] = ['data' => gzcompress(serialize($benford))];
- } catch (Exception $e) {
- die($e->getMessage());
- }
- ?>
- <div class="container" style="margin-top:20px">
- <form method="post" onSubmit="showMsg('<center>Proszę czekać, generuję raport...<br/><br/><p class=benfordLoader></p></center>');">
- <legend>
- Analiza rozkładu Benford'a
- <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?></span>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h5>Analiza na podstawie kolumny <?=$valueField?>. Liczba znalezionych obiektów z niezerową wartością: <?=count($values)?> (wybrano obiektów: <?=$count?>)</h5>
- </div>
- </div>
- <?php if($edit):?>
- <div class="form-group">
- <div class="col-sm-12">
- <center>
- <h3>Generowanie raportu analizy rozkładu Benford'a</h3>
- <table>
- <tr>
- <td>
- <select name="step" class="form-control" onChange="toggleStep(this)">
- <option value="first" selected>Pierwszy stopień analizy</option>
- <option value="second">Drugi stopień analizy</option>
- </select>
- </td>
- <td> </td>
- <td><input type="text" class="form-control" name="L_APPOITMENT_INFO" title="Tytuł raportu" placeholder="Tytuł raportu" required/ size="50"/></td>
- <td> </td>
- <td><button type="submit" class="btn btn-primary" name="action" value="generate" style="width: 80px;">Generuj</button></td>
- </tr>
- </table>
- </center>
- <br/><br/>
- </div>
- </div>
- <?php endif;?>
- <div class="form-group" id="benford">
- <div class="col-sm-offset-2 col-sm-8">
- <table class="table table-bordered table-hover table-striped table-condensed" id="benford">
- <thead style="text-align:center; font-weight:bold; background-color:lightgray">
- <tr>
- <td style="vertical-align:middle;" rowspan="2">Pierwsze cyfry</td>
- <td style="vertical-align:middle;" rowspan="2">Stopień analizy</td>
- <td style="vertical-align:middle;" rowspan="2">Liczba wystąpień</td>
- <td style="vertical-align:middle;" rowspan="2">Procent występowania</td>
- <td colspan="3">Rozkład Benford'a</td>
- <td style="vertical-align:middle;" rowspan="2">Szczegóły</td>
- <?php if($edit):?>
- <td style="vertical-align:middle;" rowspan="2">Załącz obiekty<br/>do raportu</td>
- <?php endif;?>
- </tr>
- <tr>
- <td nowrap>Norma (%)</td>
- <td nowrap>Odchylenie od normy (%)</td>
- <td>Zgodność</td>
- </tr>
- </thead>
- <tbody>
- <?php
- $number_format = function($n) {
- return number_format($n, 3, ',', '');
- };
- for ($ka = 1; $ka < 10; $ka++) {
- if (!isset($benford['firstStep'][$ka])) $benford['firstStep'][$ka] = ['count' => 0, 'value' => 0, 'correct' => true];
- $va = $benford['firstStep'][$ka];
- $odchylenie = round(($va['value'] / Benford::benford($ka) - 1) * 100, 3);
- if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
- else $odchylenie = $number_format($odchylenie);
- ?>
- <tr style="text-align:center; font-weight:bold;<?=$va['correct'] ? '' : ' cursor:pointer;'?>"<?=$va['correct'] ? '' : ' onClick="toggleSecondStep(' . $ka . ');"'?>>
- <td style="text-align:left" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$ka?></td>
- <td class="step1-<?=$va['correct'] ? 'green' : 'red'?>">I</td>
- <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$va['count']?></td>
- <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round($va['value'] * 100, 3))?></td>
- <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$number_format(round($va['norm'] * 100, 3))?></td>
- <td style="text-align:right" class="step1-<?=$va['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
- <td <?=$va['correct'] ? 'class="step1-green">Tak' : 'class="step1-red" name="firstStepDesc" data-ka="' . $ka . '" nowrap>Nie (rozwiń)'?></td>
- <td<?=$va['correct'] ? '>' : ' onClick="showDetails(' . "'{$groupField}', {$ka}" . ', null)"><span class="glyphicon glyphicon-search"></span>'?></td>
- <?php if($edit):?>
- <td<?=$va['correct'] ? '' : ' onClick="_click(\'checkFirstStep_' . $ka . '\')"'?>><input type="checkbox" <?=$va['correct'] ? 'disabled' : 'checked id="checkFirstStep_' . $ka . '" name="checkFirstStep[]" value="' . $ka . '" onClick="toggleCheckFirst(this)"'?>/></td>
- <?php endif;?>
- </tr>
- <?php
- if (!$va['correct']) {
- for ($kb = 0; $kb < 10; $kb++) {
- if (!isset($benford['secondStep'][$ka][$kb])) $benford['secondStep'][$ka][$kb] = ['count' => 0, 'value' => 0, 'correct' => true];
- $vb = $benford['secondStep'][$ka][$kb];
- $odchylenie = round(($vb['value'] / Benford::benford($ka * 10 + $kb) - 1) * 100, 3);
- if ($odchylenie > 0) $odchylenie = "+" . $number_format($odchylenie);
- else $odchylenie = $number_format($odchylenie);
- ?>
- <tr style="text-align:center;" name="secondStep" data-ka="<?=$ka?>" hidden>
- <td style="text-align:left" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$ka . $kb?></td>
- <td class="step2-<?=$vb['correct'] ? 'green' : 'red'?>">II</td>
- <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['count']?></td>
- <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round($vb['value'] * 100, 3))?></td>
- <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$number_format(round($vb['norm'] * 100, 3))?></td>
- <td style="text-align:right" class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$odchylenie?></td>
- <td class="step2-<?=$vb['correct'] ? 'green' : 'red'?>"><?=$vb['correct'] ? 'Tak' : 'Nie'?></td>
- <td<?=$vb['correct'] ? '>' : ' style="cursor:pointer;" onClick="showDetails(' . "'{$groupField}', {$ka}, {$kb}" . ')"><span class="glyphicon glyphicon-search"></span>'?></td>
- <?php if($edit):?>
- <td<?=$vb['correct'] ? '' : ' style="cursor:pointer;" onClick="_click(\'checkSecondStep_' . $ka . $kb . '\')"'?>><input type="checkbox"<?=$vb['correct'] ?: ' checked id="checkSecondStep_' . $ka . $kb . '" name="checkSecondStep[]" value="' . $ka . $kb . '" onClick="toggleCheckSecond(this)"'?> disabled/></td>
- <?php endif;?>
- </tr>
- <?php
- }
- }
- }
- ?>
- </tbody>
- </table>
- </div>
- </div>
- </form>
- </div>
- <div id="details" onClick="hideDetails();">
- <div id="detailsMsg" onClick="event.stopPropagation();"></div>
- </div>
- <div id="message">
- <div id="messageBody" onClick="event.stopPropagation();"></div>
- </div>
- <style type="text/css">
- <!--
- #benford .step1-green,#benford .step1-red {font-weight:bold;}
- #benford .step1-green,#benford .step2-green {color:#008800;}
- #benford .step1-red,#benford .step2-red {color:#ff0000;}
- #benford table { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;}
- td {font-size: 12px;}
- #benford ::selection {background: transparent;}
- #details, #message {display:none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; text-align: center; z-index: 1000; background-color: rgba(0,0,0,0.5);}
- #details div, #message div {width: 500px; height: auto; margin: 100px auto; background: #fff; padding: 10px; text-align: center; overflow: hidden; border-radius: 5px; box-shadow: 0 0 7px 7px rgba(0,0,0,0.25);}
- .benfordLoader {border: 4px solid #f3f3f3; border-radius: 50%; border-top: 4px solid #000000; width: 32px; height: 32px; -webkit-animation: spin 1s linear infinite; animation: spin 1s linear infinite;}
- @-webkit-keyframes spin {0% {-webkit-transform: rotate(0deg);} 100% {-webkit-transform: rotate(360deg);}}
- @keyframes spin {0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);}}
- -->
- </style>
- <script language="JavaScript">
- <!--
- function showDetails(groupField, ka, kb) {
- event.stopPropagation();
- document.getElementById('detailsMsg').innerHTML = "<h4>Proszę czekać...</h4>";
- document.getElementById('details').style.display = 'block';
- var post = "_noMenu=1&action=getDetails&_groupField=" + groupField + "&_ka=" + ka;
- if (kb !== null) post += "&_kb=" + kb;
- var xhttp = new XMLHttpRequest();
- xhttp.open("POST", '', true);
- xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
- xhttp.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200) {
- document.getElementById('detailsMsg').innerHTML = this.responseText;
- }
- }
- xhttp.send(post);
- }
- function showDetails2(node, ka, kb) {
- var form = node.form;
- var groupField = form['_groupField'].value;
- showDetails(groupField, ka, kb);
- }
- function showMsg(msg) {
- event.stopPropagation();
- document.getElementById('messageBody').innerHTML = "<h4>" + msg + "</h4>";
- document.getElementById('message').style.display = 'block';
- }
- function hideDetails() {
- document.getElementById('details').style.display = 'none';
- }
- function _click(id) {
- event.stopPropagation();
- document.getElementById(id).click();
- }
- function toggleSecondStep(ka) {
- var rows = document.getElementsByName('secondStep');
- var hidden = false;
- for(var i = 0, n = rows.length; i < n; i++) {
- if (rows[i].dataset.ka == ka) {
- rows[i].hidden = !rows[i].hidden;
- hidden = rows[i].hidden;
- }
- }
- var descs = document.getElementsByName('firstStepDesc');
- for(var i = 0, n = descs.length; i < n; i++) {
- if (descs[i].dataset.ka == ka) {
- descs[i].innerHTML = (hidden ? 'Nie (rozwiń)' : 'Nie (zwiń)');
- }
- }
- }
- function toggleStep(option) {
- if (option.value == 'first') first = true;
- else if (option.value == 'second') first = false;
- else {
- alert('Wystąpił nieznany błąd formularza');
- return;
- }
- var checks = document.getElementsByName('checkSecondStep[]');
- var all = [];
- for(var i = 0, n = checks.length; i < n; i++) {
- checks[i].disabled = first;
- ka = checks[i].value / 10 | 0;
- if (all[ka] === 'undefined') all[ka] = checks[i].checked;
- else if (checks[i].checked) all[ka] = true;
- }
- var checks = document.getElementsByName('checkFirstStep[]');
- for(var i = 0, n = checks.length; i < n; i++) {
- checks[i].disabled = !(first);
- if (checks[i].checked != all[checks[i].value]) {
- checks[i].checked = all[checks[i].value];
- toggleCheckFirst(checks[i]);
- }
- }
- var descs = document.getElementsByName('firstStepDesc');
- for(var i = 0, n = descs.length; i < n; i++) {
- descs[i].innerHTML = (first ? 'Nie (rozwiń)' : 'Nie (zwiń)');
- }
- var rows = document.getElementsByName('secondStep');
- for(var i = 0, n = rows.length; i < n; i++) {
- rows[i].hidden = first;
- }
- }
- function toggleCheckFirst(check) {
- event.stopPropagation();
- var checks = document.getElementsByName('checkSecondStep[]');
- for(var i = 0, n = checks.length; i < n; i++) {
- if ((checks[i].value / 10 | 0) == check.value) checks[i].checked = check.checked;
- }
- }
- function toggleCheckSecond(check) {
- event.stopPropagation();
- var checks = document.getElementsByName('checkSecondStep[]');
- var all = true;
- var ka = check.value / 10 | 0;
- for(var i = 0, n = checks.length; i < n; i++) {
- if ((checks[i].value / 10 | 0) == ka) {
- if (!checks[i].checked) {
- all = false;
- break;
- }
- }
- }
- var checks = document.getElementsByName('checkFirstStep[]');
- for(var i = 0, n = checks.length; i < n; i++) {
- if (checks[i].value == ka) {
- checks[i].checked = all;
- break;
- }
- }
- }
- -->
- </script>
- <?php
- }
- private function benford_generate() {
- $benfordId = null;
- try {
- $benford = @unserialize(@gzuncompress(V::get('benford', '', $_SESSION)[$this->SOURCE['TABLE']]['data']));
- unset($_SESSION['benford'][$this->SOURCE['TABLE']]);
- if (!$benford) {
- $this->benford_form(true);
- return;
- }
- $mainTable = 'BI_audit_BENFORD';
- if (!($refTable = BiAuditRefTables::getRefTable($mainTable, $this->SOURCE['TABLE'], false))) throw new Exception("Nie znaleziono relacji do obiektu \"{$this->SOURCE['TABLE']}\" w konfiguracji obiektu \"{$mainTable}\" - nie można wygenerować raportu.");
- $sqlArr = [
- 'step' => V::get('step', '', $_POST),
- 'table' => $this->SOURCE['TABLE'],
- 'valueField' => $benford['conf']['valueField'],
- 'groupField' => implode(',', $benford['conf']['groupFields']),
- 'count' => $benford['conf']['count'],
- 'L_APPOITMENT_INFO' => V::get('L_APPOITMENT_INFO', '', $_POST),
- 'A_RECORD_CREATE_AUTHOR' => User::getName(),
- 'A_RECORD_CREATE_DATE' => date('Y-m-d-H:i'),
- ];
- if (!($benfordId = DB::getPDO()->insert($mainTable, $sqlArr))) throw new Exception("Nie wygenerowano raportu - Wystąpił nieznany błąd podczas zapisywania raportu do bazy");
- $dir = self::getDirectory($mainTable, $benfordId);
- if (!file_exists($dir)) mkdir($dir, 0770, true);
- if (!is_dir($dir)) throw new Exception("Nie wygenerowano raportu - wystąpił błąd podczas tworzenia katalogu dla rekordu");
- $root = 'RelatedFeatureRoot';
- $array = [];
- $array['@attributes'] = [
- 'xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd',
- 'xmlns:p5' => 'https://biuro.biall-net.pl/wfs',
- 'xmlns:'.self::getNamespace($mainTable) => "https://biuro.biall-net.pl/wfs/default_db/{$mainTable}",
- 'xmlns:'.self::getNamespace($this->SOURCE['TABLE']) => "https://biuro.biall-net.pl/wfs/default_db/{$this->SOURCE['TABLE']}",
- ];
- $array[self::getNamespace($mainTable, $mainTable)] = array_merge(['@attributes' => ['fid' => "{$mainTable}.{$benfordId}", 'p5:primaryKey' => $benfordId]], self::arrayWithNamespace($mainTable, array_merge(['ID' => $benfordId], $sqlArr)));
- $checked = [
- 'firstStep' => V::get('checkFirstStep', [], $_POST),
- 'secondStep' => V::get('checkSecondStep', [], $_POST),
- ];
- $firstStep = [];
- for ($ka = 1; $ka <= 9; $ka++) {
- if (!isset($benford['firstStep'][$ka])) $va = ['count' => 0, 'value' => 0, 'correct' => true];
- else $va = $benford['firstStep'][$ka];
- $_firstStep = [
- '@attributes' => ['leadingNumber' => $ka],
- 'count' => $va['count'],
- 'value' => (double) round($va['value'], 5),
- 'norm' => (double) round($va['norm'], 5),
- 'deviation' => (double) round($va['value'] / $va['norm'] - 1, 5),
- 'correct' => $va['correct'] ? 'true' : 'false',
- ];
- if ($array[self::getNamespace($mainTable, $mainTable)][self::getNamespace($mainTable, 'step')] == 'second' && (!$va['correct'])) {
- $secondStep = [];
- for ($kb = 0; $kb <= 9; $kb++) {
- if (!isset($benford['secondStep'][$ka][$kb])) $vb = ['count' => 0, 'value' => 0, 'correct' => true];
- else $vb = $benford['secondStep'][$ka][$kb];
- $_secondStep = [
- '@attributes' => ['leadingNumber' => $ka.$kb],
- 'count' => $vb['count'],
- 'value' => (double) round($vb['value'], 5),
- 'norm' => (double) round($vb['norm'], 5),
- 'deviation' => (double) round($vb['value'] / $vb['norm'] - 1, 5),
- 'correct' => $vb['correct'] ? 'true' : 'false',
- ];
- if ((!$vb['correct']) && in_array($ka.$kb, $checked['secondStep'])) {
- $objects = [];
- foreach ($benford['secondStep'][$ka][$kb]['keys'] as $id) {
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $benfordId, 'REMOTE_PRIMARY_KEY' => $id]);
- $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
- if (!$object) continue;
- $objects[] = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}", 'p5:primaryKey' => $id]], self::arrayWithNamespace($this->SOURCE['TABLE'], $object));
- }
- $_secondStep[self::getNamespace($this->SOURCE['TABLE'], $this->SOURCE['TABLE'])][] = $objects;
- }
- $secondStep[] = $_secondStep;
- }
- $_firstStep['secondStep'] = $secondStep;
- } elseif ((!$va['correct']) && in_array($ka, $checked['firstStep'])) {
- $objects = [];
- foreach ($benford['firstStep'][$ka]['keys'] as $id) {
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $benfordId, 'REMOTE_PRIMARY_KEY' => $id]);
- $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
- if (!$object) continue;
- $objects[] = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}", 'p5:primaryKey' => $id]], self::arrayWithNamespace($this->SOURCE['TABLE'], $object));
- }
- $_firstStep[self::getNamespace($this->SOURCE['TABLE'], $this->SOURCE['TABLE'])][] = $objects;
- }
- $firstStep[] = $_firstStep;
- }
- $array[self::getNamespace($mainTable, $mainTable)]['firstStep'] = $firstStep;
- $xml = V::arrayToXML($array, true, $root);
- $basename = $dir . DIRECTORY_SEPARATOR . "{$mainTable}_{$benfordId}";
- $xmlFile = $basename . ".xml";
- $pdfFile = $basename . ".pdf";
- file_put_contents($xmlFile, $xml);
- $pdf = self::antXmlToPdf($xmlFile);
- copy($pdf, $pdfFile);
- DB::getPDO()->update($mainTable, 'ID', $benfordId, ['A_STATUS' => 'NORMAL', 'A_STATUS_INFO' => 'Poprawnie wygenerowano raport']);
- SE_Layout::alert('success', 'Poprawnie wygenerowano raport' .
- '<br/><br/><a href="index.php?_route=UrlAction_BiAuditGenerate&ID_BI_audit_BENFORD=' . $benfordId . '" class="btn btn-primary" style="width: 120px;">Pokaż raport</a>');
- } catch (Exception $e) {
- if ($benfordId) DB::getPDO()->update($mainTable, 'ID', $benfordId, ['A_STATUS' => 'DELETED', 'A_STATUS_INFO' => $e->getMessage()]);
- SE_Layout::alert('danger', $e->getMessage());
- }
- ?>
- <br/><br/>
- <div style="text-align:center">
- <a href="<?=$this->REFERER?>" class="btn btn-default" style="width: 80px;">Powrót</a>
- </div>
- <?php
- }
- private function benford_showReport() {
- $dir = self::getDirectory('BI_audit_BENFORD', $this->SOURCE['ID']);
- $url = self::getUrl('BI_audit_BENFORD', $this->SOURCE['ID']);
- $reports = [
- 'pdf' => [
- 'files' => glob("{$dir}/BI_audit_BENFORD_{$this->SOURCE['ID']}.pdf"),
- 'label' => 'Raport PDF:<br/> ',
- 'button' => 'Pokaż raport PDF',
- 'parentDir' => false,
- ],
- ];
- ?>
- <div class="container" style="margin-top:20px">
- <legend>
- Wygenerowany raport Benford'a nr <?=$this->SOURCE['ID']?>
- </legend>
- <div class="form-group" style="text-align: center;">
- <?php
- array_walk($reports, function ($report) use ($url) {
- echo "<div class=\"col-sm-2\"><h4>{$report['label']}</h4>";
- $hrefs = array_filter(array_map(function ($path) use ($url, $report) {
- if (!is_file($path)) return false;
- $file = basename($path);
- if ($report['parentDir']) $file = basename(dirname($path)) . "/" . $file;
- return "<a href=\"{$url}/{$file}\" target=\"_blank\" class=\"btn btn-primary\">{$report['button']}</a>";
- }, $report['files']));
- if ($hrefs) echo implode('<br/><br/>', $hrefs);
- else echo "<h5>Nie znaleziono</h5>";
- echo "</div>\n";
- });
- ?>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <br/><br/><a href="<?=$this->REFERER?>" class="btn btn-default">Powrót</a>
- </div>
- </div>
- </div>
- <?php
- }
- private function benford() {
- try {
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "generate":
- $this->benford_generate();
- break;
- case "getDetails":
- $groupField = V::get('_groupField', null, $_POST);
- $ka = V::get('_ka', null, $_POST, 'int');
- $kb = V::get('_kb', null, $_POST, 'int');
- echo $this->benford_getDetails($groupField, $ka, $kb);
- break;
- default:
- $this->benford_form(true);
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage());
- }
- }
- private function validate_form() {
- if (!($namespace = V::get('_fromNamespace', '', $_GET))) throw new Exception("Błąd formularza");
- Lib::loadClass('FeatureAttrSelected');
- $count = FeatureAttrSelected::getTotalSelected($namespace);
- $selectedTable = FeatureAttrSelected::getAttributeTableName($namespace, User::getID());
- $query = "select `t`.`ID` from `{$this->SOURCE['TABLE']}` `t` join `{$selectedTable}` `s` on `t`.`ID` = `s`.`primaryKey` order by `s`.`primaryKey`";
- $values = [];
- try {
- $result = DB::getPDO()->fetchAll($query);
- $values = array_map('reset', $result);
- } catch (Exception $e) {
- throw new Exception("Błąd zapytania SQL ({$e->getMessage()})");
- }
- if (!$values) throw new Exception("Nie wybrano żadnych obiektów lub wszystkie wybrane obiekty mają zerową wartość");
- $_SESSION['validate'][$this->SOURCE['TABLE']] = gzcompress(serialize($values));
- ?>
- <div class="container" style="margin-top:20px">
- <form method="post">
- <legend>
- Analiza błędów
- <span class="pull-right">Tabela: <?=$this->SOURCE['TABLE']?></span>
- </legend>
- <div class="form-group">
- <div class="col-sm-12">
- <h5>Liczba wybranych obiektów: <?=count($values)?></h5>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-12">
- <center>
- <h3>Generowanie raportu analizy błędów</h3>
- <table>
- <tr>
- <td><input type="text" class="form-control" name="L_APPOITMENT_INFO" title="Tytuł raportu" placeholder="Tytuł raportu" required/ size="50"/></td>
- <td> </td>
- <td><button type="submit" class="btn btn-primary" name="action" value="generate" style="width: 80px;">Generuj</button></td>
- </tr>
- </table>
- </center>
- <br/><br/>
- </div>
- </div>
- </form>
- </div>
- <?php
- }
-
- private function validate_generate() {
- $validateId = null;
- try {
- $validate = @unserialize(@gzuncompress(V::get('validate', '', $_SESSION)[$this->SOURCE['TABLE']]));
- unset($_SESSION['validate'][$this->SOURCE['TABLE']]);
- if (!$validate) {
- $this->validate_form();
- return;
- }
- $mainTable = 'BI_audit_VALIDATE';
- if (!($refTable = BiAuditRefTables::getRefTable($mainTable, $this->SOURCE['TABLE'], false))) throw new Exception("Nie znaleziono relacji do obiektu \"{$this->SOURCE['TABLE']}\" w konfiguracji obiektu \"{$mainTable}\" - nie można wygenerować raportu.");
- $sqlArr = [
- 'table' => $this->SOURCE['TABLE'],
- 'L_APPOITMENT_INFO' => V::get('L_APPOITMENT_INFO', '', $_POST),
- 'A_RECORD_CREATE_AUTHOR' => User::getName(),
- 'A_RECORD_CREATE_DATE' => date('Y-m-d-H:i'),
- ];
- if (!($validateId = DB::getPDO()->insert($mainTable, $sqlArr))) throw new Exception("Nie wygenerowano raportu - Wystąpił nieznany błąd podczas zapisywania raportu do bazy");
- $dir = self::getDirectory($mainTable, $validateId);
- if (!file_exists($dir)) mkdir($dir, 0770, true);
- if (!is_dir($dir)) throw new Exception("Nie wygenerowano raportu - wystąpił błąd podczas tworzenia katalogu dla rekordu");
- $root = 'RelatedFeatureRoot';
- $array = [];
- $array['@attributes'] = [
- 'xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd',
- 'xmlns:p5' => 'https://biuro.biall-net.pl/wfs',
- 'xmlns:xlink' => 'http://www.w3.org/1999/xlink',
- 'xmlns:'.self::getNamespace($mainTable) => "https://biuro.biall-net.pl/wfs/default_db/{$mainTable}",
- 'xmlns:'.self::getNamespace($this->SOURCE['TABLE']) => "https://biuro.biall-net.pl/wfs/default_db/{$this->SOURCE['TABLE']}",
- 'xmlns:'.self::getNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI') => 'https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI',
- 'xmlns:'.self::getNamespace('BI_audit_ENERGA_FAKTURY') => 'https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_FAKTURY',
- ];
- $array[self::getNamespace($mainTable, $mainTable)] = array_merge(['@attributes' => ['fid' => "{$mainTable}.{$validateId}", 'p5:primaryKey' => $validateId]], self::arrayWithNamespace($mainTable, array_merge(['ID' => $validateId], $sqlArr)));
- $umowy = [];
- $kontrahenci = [];
- $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- $refFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- foreach ($validate as $id) {
- $object = DB::getPDO()->fetchFirst("select * from `{$this->SOURCE['TABLE']}` where `ID` = " . DB::getPDO()->quote($id));
- if (!$object) continue;
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $validateId, 'REMOTE_PRIMARY_KEY' => $id]);
- $_umowa = array_merge(['@attributes' => ['fid' => "{$this->SOURCE['TABLE']}.{$id}", 'p5:primaryKey' => $id]], self::arrayWithNamespace($this->SOURCE['TABLE'], $object));
- $kontrahenciId = array_map('reset', DB::getPDO()->fetchAll("select `REMOTE_PRIMARY_KEY` from `{$refUmowyToKontrahenci}` where `PRIMARY_KEY` = " . DB::getPDO()->quote($id)));
- $_kontrahenci = [];
- $_kontrahenciId = [];
- foreach ($kontrahenciId as $kontrahentId) {
- $_kontrahenciId[] = $kontrahentId;
- if (!isset($kontrahenci[$kontrahentId])) {
- if ($kontrahent = DB::getPDO()->fetchFirst("select * from `BI_audit_ENERGA_RUM_KONTRAHENCI` where `ID` = {$kontrahentId}")) {
- $kontrahenci[$kontrahentId] = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_KONTRAHENCI.{$kontrahentId}", 'p5:primaryKey' => $kontrahentId]],
- self::arrayWithNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI', $kontrahent));
- $fakturyId = array_map('reset', DB::getPDO()->fetchAll("select `PRIMARY_KEY` from `{$refFakturyToKontrahenci}` where `REMOTE_PRIMARY_KEY` = {$kontrahentId}"));
- $faktury = [];
- foreach ($fakturyId as $fakturaId) {
- if ($faktura = DB::getPDO()->fetchFirst("select * from `BI_audit_ENERGA_FAKTURY` where `ID` = {$fakturaId}")) {
- $faktury[] = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_FAKTURY.{$fakturaId}", 'p5:primaryKey' => $fakturaId]],
- self::arrayWithNamespace('BI_audit_ENERGA_FAKTURY', $faktura));
- }
- }
- if ($faktury) $kontrahenci[$kontrahentId][self::getNamespace('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_FAKTURY')] = $faktury;
- }
- }
- }
- $_kontrahenciId = array_unique($_kontrahenciId, SORT_NUMERIC);
- foreach ($_kontrahenciId as $kontrahentId) {
- $_kontrahenci[] = ['@attributes' => ['xlink:href' => "https://biuro.biall-net.pl/wfs/default_db/BI_audit_ENERGA_RUM_KONTRAHENCI#BI_audit_ENERGA_RUM_KONTRAHENCI.{$kontrahentId}", 'p5:primaryKey' => $kontrahentId]];
- }
- $_umowa[self::getNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_ENERGA_RUM_KONTRAHENCI')] = $_kontrahenci;
- $umowy[] = $_umowa;
- }
- if ($umowy) $array[self::getNamespace($mainTable, $mainTable)][self::getNamespace($this->SOURCE['TABLE'], $this->SOURCE['TABLE'])] = $umowy;
- if ($kontrahenci) {
- ksort($kontrahenci, SORT_NUMERIC);
- $array[self::getNamespace($mainTable, $mainTable)][self::getNamespace('BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_ENERGA_RUM_KONTRAHENCI')] = $kontrahenci;
- }
- $xml = V::arrayToXML($array, true, $root);
- file_put_contents($dir . DIRECTORY_SEPARATOR . "{$mainTable}_{$validateId}.xml", $xml);
- $basename = $dir . DIRECTORY_SEPARATOR . "{$mainTable}_{$validateId}";
- $xmlFile = $basename . ".xml";
- $pdfFile = $basename . ".pdf";
- file_put_contents($xmlFile, $xml);
- $pdf = self::antXmlToPdf($xmlFile);
- copy($pdf, $pdfFile);
- DB::getPDO()->update($mainTable, 'ID', $validateId, ['A_STATUS' => 'NORMAL', 'A_STATUS_INFO' => 'Poprawnie wygenerowano raport']);
- SE_Layout::alert('success', "Poprawnie wygenerowano raport");
- } catch (Exception $e) {
- if ($validateId) DB::getPDO()->update($mainTable, 'ID', $validateId, ['A_STATUS' => 'DELETED', 'A_STATUS_INFO' => $e->getMessage()]);
- SE_Layout::alert('danger', $e->getMessage());
- }
- }
- private function validate() {
- try {
- $action = V::get('action', '', $_POST);
- switch ($action) {
- case "generate":
- $this->validate_generate();
- break;
- default:
- $this->validate_form();
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage());
- }
- }
- private static function antXmlToPdf($xmlFile) {
- if (!file_exists($xmlFile)) throw new Exception("Nie znaleziono pliku XML");
- $basename = basename($xmlFile, '.xml');
- $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
- $antXmlFilename = "{$basename}.out_task.dita.final_with_RelatedFeatureLoop.xml";
- $antXmlFile = $antDir . "/" . $antXmlFilename;
- $baseDir = "/opt/local/pl.procesy5/p5build_SE/temp/WPS_Functions/default_db/CRM_PROCES_tree/{$basename}";
- $ditamapFile = "{$baseDir}/{$basename}.ditamap";
- $pdfFile = "{$baseDir}/pdf/{$basename}.pdf";
- copy($xmlFile, $antXmlFile);
- shell_exec("cd /Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree && sudo /opt/local/bin/ant -f build_CRM_PROCES_tree.xml default_db:PROCES_INIT:tree:dita -Duuid={$basename}");
- if (!file_exists($ditamapFile)) throw new Exception("Nie udało się wygenerować pliku ditamap");
- shell_exec("cd \"{$baseDir}\" && sudo /Library/Server/Web/Data/Sites/Default/SE/stuff/dita-ot-2.3.3/bin/dita -o pdf -i {$basename}.ditamap -f pdf");
- if (!file_exists($pdfFile)) throw new Exception("Nie udało się wygenerować pliku PDF");
- return $pdfFile;
- }
- public function defaultAction() {
- $showMenu = !(V::get('_noMenu', false, $_POST));
- if ($showMenu) {
- SE_Layout::gora();
- SE_Layout::menu();
- }
- if (isset($_SESSION['REFERER'])) {
- $this->REFERER = $_SESSION['REFERER'];
- unset($_SESSION['REFERER']);
- } elseif (V::get('REFERER', '', $_POST) != '') $this->REFERER = V::get('REFERER', '', $_POST);
- else $this->REFERER=$_SERVER['HTTP_REFERER'];
- if (($ID = V::get('ID_BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA';
- elseif (($ID = V::get('ID_BI_audit_ENERGA_PRACOWNICY', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_ENERGA_PRACOWNICY';
- elseif (($ID = V::get('ID_BI_audit_KRS', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS';
- elseif (($ID = V::get('ID_BI_audit_KRS_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_KRS_person';
- elseif (($ID = V::get('ID_BI_audit_MSIG', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_MSIG';
- elseif (($ID = V::get('ID_BI_audit_MSIG_person', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_MSIG_person';
- elseif (($ID = V::get('ID_BI_audit_CEIDG', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_CEIDG';
- elseif (($ID = V::get('ID_BI_audit_CEIDG_pelnomocnicy', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_CEIDG_pelnomocnicy';
- elseif (($ID = V::get('ID_BI_audit_BENFORD', 0, $_GET, 'int')) > 0) $this->SOURCE['TABLE'] = 'BI_audit_BENFORD';
- if ($this->SOURCE) {
- $this->SOURCE['ID'] = $ID;
- $this->urlActionOnItem();
- }
- elseif ($TABLE = V::get('_fromNamespace', '', $_GET)) {
- $this->SOURCE['TABLE'] = ACL::getAclByTypeName($TABLE)->getRootTableName();
- $_subUrlAction = V::get('_subUrlAction', '', $_GET);
- switch ($this->SOURCE['TABLE']) {
- case "BI_audit_ENERGA_PRACOWNICY":
- switch ($_subUrlAction) {
- case "clearTable":
- $this->clearTable();
- break;
- case "importFromKRS":
- $this->SOURCE['TABLE'] = 'BI_audit_KRS';
- $this->importToPracownicy();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #21');
- }
- break;
- case "BI_audit_ENERGA_PRACOWNICY_import":
- switch ($_subUrlAction) {
- case "clearTable":
- $this->clearTable();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #22');
- }
- break;
- case "BI_audit_ENERGA_RUM_KONTRAHENCI":
- switch ($_subUrlAction) {
- case "clearTable":
- $this->clearTable();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #23');
- }
- break;
- case "BI_audit_ENERGA_RUM_UMOWY":
- switch ($_subUrlAction) {
- case "clearTable":
- $this->clearTable();
- break;
- case "benford":
- $this->benford();
- break;
- case "validate":
- $this->validate();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #24');
- }
- break;
- case "BI_audit_ENERGA_FAKTURY":
- switch ($_subUrlAction) {
- case "clearTable":
- $this->clearTable();
- break;
- case "benford":
- $this->benford();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #25');
- }
- break;
- case "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA":
- switch ($_subUrlAction) {
- case "clearTable":
- $this->clearTable();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #25');
- }
- break;
- default:
- switch ($_subUrlAction) {
- case "benford":
- $this->benford();
- break;
- default: SE_Layout::alert('danger', 'Błąd parametru #1');
- }
- }
- }
- else SE_Layout::alert('danger', 'Błąd parametru #0');
- if ($showMenu) {
- echo "<br/><br/>";
- SE_Layout::dol();
- }
- }
- private static function truncatePowiazaniaFromDB($ID) {
- $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA');
- if (!$refTables) return null;
- $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
- $refTables = array_diff($refTables, [$refPowiazaniaToPowiazaniaRow]);
- $query = "delete from `" . implode("`, `", $refTables) . "` using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`";
- foreach ($refTables as $refTable) $query .= " left join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
- $query .= " where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
- DB::getPDO()->query($query);
- }
- public static function deleteResultsFromDB($ID) {
- $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
- $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
- $refTables = BiAuditRefTables::getRefTables('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object');
- $sqlDeleteFrom = "delete from
- `{$refPowiazaniaToPowiazaniaRow}`,
- `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`,
- `{$refPowiazaniaRowToPowiazaniaRowObject}`,
- `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`";
- $sqlUsing = "
- using `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`
- join `{$refPowiazaniaToPowiazaniaRow}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = `{$refPowiazaniaToPowiazaniaRow}`.`PRIMARY_KEY`
- join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row` on `{$refPowiazaniaToPowiazaniaRow}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.`ID`
- join `{$refPowiazaniaRowToPowiazaniaRowObject}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row`.ID = `{$refPowiazaniaRowToPowiazaniaRowObject}`.`PRIMARY_KEY`
- join `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object` on `{$refPowiazaniaRowToPowiazaniaRowObject}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.ID";
- $sqlWhere = "
- where `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA`.`ID` = '{$ID}'";
- foreach ($refTables as $refTable) {
- $sqlDeleteFrom .= ",\n`{$refTable}`";
- $sqlUsing .= "\nleft join `{$refTable}` on `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object`.`ID` = `{$refTable}`.`PRIMARY_KEY`";
- }
- $query = $sqlDeleteFrom . $sqlUsing . $sqlWhere;
- DB::getPDO()->query($query);
- }
- public function doGenerate() {
- $generatePhpScript = function($function) {
- return '<?php
- ini_set("memory_limit", "4G");
- define("DS", DIRECTORY_SEPARATOR);
- define("APP_PATH_ROOT", "' . APP_PATH_ROOT . '");
- define("APP_PATH_WWW", "' . APP_PATH_WWW . '");
- define("APP_PATH_CONFIG", APP_PATH_ROOT . DS . "config");
- ini_set("display_startup_errors", "0");
- ini_set("display_errors", "1");
- ini_set("log_errors", "1");
- ini_set("error_log", "/var/log/apache2/error_log");
- $_SERVER["SERVER_NAME"] = "' . $_SERVER['SERVER_NAME'] . '";
- require_once(APP_PATH_ROOT . DS . "se-lib" . DS . "bootstrap.php");
- date_default_timezone_set("Europe/Warsaw");
- Lib::loadClass("Router");
- Router::getRoute("UrlAction_BiAuditGenerate")->' . $function . ';
- ';
- };
- try {
- ### Ustawiamy zmienną sesji nazwy użytkownika, aby w rekordach historycznych było widać, że autorem systemu jest moduł BiAuditGenerate
- $_SESSION['ADM_ACCOUNT']="BiAuditGenerate";
- ### Sprawdzenie czy modul BiAudit jest aktywny na danej instalacji Procesy5
- $moduleActive=DB::getPDO()->fetchValue("select count(*) from CRM_CONFIG where CONF_KEY='module_BiAudit' and CONF_VAL='on'");
- if (!$moduleActive) throw new Exception("Module BiAudit disabled/not installed.");
- ### Ustawienie zmiennych
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $reloadCachePhpFile = $tasksDirLocation . "/reloadCache.php";
- $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
- $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
- $reloadCacheLogFile = $tasksDirLocation . "/reloadCache.log";
- ### Utworzenie niezbędnych katalogów i plików
- if (!file_exists($tasksDirLocation)) mkdir($tasksDirLocation, 0770, true);
- if (!file_exists($tasksDirLocation)) throw new Exception('Error during creating temporary directory.');
- ### 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
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'No',
- ];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Part', 'Full') and FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
- }
- /* 2018-04-19 - zmieniono działanie silnika tak, aby sam wykrywał czy należy wykonać pełne odświeżenie cache
- ### Sprawdzenie czy któryś rekord wymaga odświeżenia cache
- $doGenerate = true;
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache in ('Full') and FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- if ($result) {
- $doGenerate = false;
- $sqlArr = [];
- if (file_exists($reloadCachePhpFile)) {
- if (file_exists($reloadCacheResultFile)) {
- $reloadCacheResult = file_get_contents($reloadCacheResultFile);
- if ($reloadCacheResult == "ok") {
- $sqlArr = [
- 'FILE_STATUS_info' => 'Ukończono pełne Odświeżenie cache, oczekiwanie na wygenerowanie powiązań',
- 'BI_analiza_reloadCache' => 'No',
- ];
- $doGenerate = true;
- } else {
- $sqlArr = [
- 'FILE_STATUS' => 'ERROR',
- 'FILE_STATUS_info' => "Wystąpił błąd podczas pełnego odświeżania cache ({$reloadCacheResult})",
- ];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- }
- unlink($reloadCachePhpFile);
- unlink($reloadCachePidFile);
- unlink($reloadCacheResultFile);
- } elseif (file_exists($reloadCachePidFile)) {
- $pid = file_get_contents($reloadCachePidFile);
- $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
- $processShouldBeRunning = "php {$reloadCachePhpFile}";
- if ($processRunning != $processShouldBeRunning) {
- if (!file_exists($reloadCacheResultFile)) {
- $sqlArr = [
- 'FILE_STATUS' => 'ERROR',
- 'FILE_STATUS_info' => "Wystąpił nieznany błąd podczas pełnego odświeżania cache - nie znaleziono procesu potomnego",
- ];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'";
- $result = DB::getPDO()->fetchAll($query);
- unlink($reloadCachePhpFile);
- unlink($reloadCachePidFile);
- unlink($reloadCacheResultFile);
- }
- }
- }
- } else {
- $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
- $result2 = DB::getPDO()->fetchValue($query);
- if ($result2) {
- $sqlArr = [
- 'FILE_STATUS_info' => 'Wstrzymano pełne odświeżanie cache - oczekiwanie na dokończenie szukania powiązań dla innych rekordów',
- ];
- } else {
- $sqlArr = [
- 'FILE_STATUS_info' => 'W trakcie pełnego odświeżania cache',
- ];
- $query = "select count(*) from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where BI_analiza_reloadCache = 'Full' and FILE_STATUS = 'TO_GENERATE'";
- $fullReloadCache = (DB::getPDO()->fetchValue($query) > 0);
- file_put_contents($reloadCachePhpFile, $generatePhpScript("doReloadCache({$fullReloadCache})"));
- shell_exec('su - root -c "php ' . $reloadCachePhpFile . ' > ' . $reloadCacheLogFile. ' 2>&1 &"');
- }
- }
- if ($sqlArr) {
- foreach ($result as $row) {
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', array_merge(['ID' => $row['ID']], $sqlArr));
- }
- }
- }
- */ $doGenerate = true;
- ### Generowanie powiązań
- if ($doGenerate) {
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'TO_GENERATE'"; //TODO TEST: and ID = 1
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $sqlArr = [
- 'ID' => $row['ID'],
- 'FILE_STATUS' => 'IN_PROGRESS',
- 'FILE_STATUS_info' => 'Zadanie wyzwolone',
- ];
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
- self::deleteResultsFromDB($row['ID']);
- $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
- $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
- $generatePowiazaniaLogFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.log";
- $generatePowiazaniaProgressFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.progress";
- if (file_exists($generatePowiazaniaResultFile)) unlink ($generatePowiazaniaResultFile);
- if (file_exists($generatePowiazaniaProgressFile)) unlink ($generatePowiazaniaProgressFile);
- file_put_contents($generatePowiazaniaPhpFile, $generatePhpScript("doGeneratePowiazania({$row['ID']})"));
- shell_exec('su - root -c "php ' . $generatePowiazaniaPhpFile . ' > ' . $generatePowiazaniaLogFile. ' 2>&1 &"');
- }
- }
- ### Weryfikacja świeżo wygenerowanych powiązań
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where FILE_STATUS = 'IN_PROGRESS'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $generatePowiazaniaResultFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.result";
- $generatePowiazaniaPidFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.pid";
- $generatePowiazaniaPhpFile = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}.php";
- $error = false;
- $success = false;
- $sqlArr = [];
- if (file_exists($generatePowiazaniaResultFile)) {
- $generatePowiazaniaResult = json_decode(file_get_contents($generatePowiazaniaResultFile), true);
- if ($generatePowiazaniaResult['result'] == "ok") {
- $powiazanieDirLocation = self::getDirectory('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $row['ID']);
- if (!file_exists($powiazanieDirLocation)) mkdir($powiazanieDirLocation, 0770, false);
- if (!file_exists($powiazanieDirLocation)) $error = "Nie udało się wgrać pliku xml - nie można utworzyć katalogu dla rekordu";
- else $success = true;
- } else $error = "Wystąpił błąd podczas generowania powiązań ({$generatePowiazaniaResult['message']})";
- } elseif (file_exists($generatePowiazaniaPidFile)) {
- $pid = file_get_contents($generatePowiazaniaPidFile);
- $processRunning = trim(shell_exec("ps -p {$pid} -o command | grep -v '^COMMAND$'"));
- $processShouldBeRunning = "php {$generatePowiazaniaPhpFile}";
- if ($processRunning != $processShouldBeRunning) {
- if (!file_exists($generatePowiazaniaResultFile)) $error = "Wystąpił nieznany błąd w przetwarzaniu - nie znaleziono procesu potomnego";
- }
- }
- if ($error) {
- $sqlArr = [
- 'FILE_STATUS' => 'ERROR',
- 'FILE_STATUS_info' => $error,
- ];
- //self::deleteResultsFromDB($row['ID']);
- //if (file_exists($xmlFile)) unlink($xmlFile);
- } elseif ($success) {
- $sqlArr = [
- 'FILE_STATUS' => 'GENERATED',
- 'FILE_STATUS_info' => 'Poprawnie wygenerowano powiązania',
- ];
- if ($generatePowiazaniaResult['parts']) {
- for ($i = 1; $i <= $generatePowiazaniaResult['parts']; $i++) {
- $partNo = str_pad($i, 6, '0', STR_PAD_LEFT);
- $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}_{$partNo}";
- $generatePowiazaniaXmlFile = "{$generateFilesName}.xml";
- $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
- $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
- $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
- $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.xml";
- $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}_{$partNo}.pdf";
- $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}";
- $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}_{$partNo}.zip";
- if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
- if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
- if (file_exists($generatePowiazaniaHtmlDir)) {
- if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
- rename($generatePowiazaniaHtmlDir, $destHtmlDir);
- }
- if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
- }
- } else {
- $generateFilesName = "{$tasksDirLocation}/generatePowiazania-{$row['ID']}";
- $generatePowiazaniaPdfFile = "{$generateFilesName}.pdf";
- $generatePowiazaniaHtmlDir = "{$generateFilesName}.html";
- $generatePowiazaniaHtmlZipFile = "{$generateFilesName}.zip";
- $destXmlFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.xml";
- $destPdfFile = "{$powiazanieDirLocation}/relations-{$row['ID']}.pdf";
- $destHtmlDir = "{$powiazanieDirLocation}/html-{$row['ID']}";
- $destHtmlZipFile = "{$powiazanieDirLocation}/html-{$row['ID']}.zip";
- if (file_exists($generatePowiazaniaXmlFile)) rename($generatePowiazaniaXmlFile, $destXmlFile);
- if (file_exists($generatePowiazaniaPdfFile)) rename($generatePowiazaniaPdfFile, $destPdfFile);
- if (file_exists($generatePowiazaniaHtmlDir)) {
- if (file_exists($destHtmlDir)) shell_exec("rm -rf \"{$destHtmlDir}\"");
- rename($generatePowiazaniaHtmlDir, $destHtmlDir);
- }
- if (file_exists($generatePowiazaniaHtmlZipFile)) rename($generatePowiazaniaHtmlZipFile, $destHtmlZipFile);
- }
- }
- if ($sqlArr) {
- $sqlArr['ID'] = $row['ID'];
- DB::getDB()->UPDATE_OBJ('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $sqlArr);
- // if (file_exists($generatePowiazaniaPhpFile)) unlink($generatePowiazaniaPhpFile);
- if (file_exists($generatePowiazaniaPidFile)) unlink($generatePowiazaniaPidFile);
- if (file_exists($generatePowiazaniaResultFile)) unlink($generatePowiazaniaResultFile);
- }
- }
- } catch (Exception $e) {
- echo $e->getMessage()."\n";
- }
- }
- private static function importPracownicy($full = false) {
- $fields = [
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'imiona' => 'imiona',
- 'nazwisko' => 'nazwisko',
- 'pesel' => 'pesel',
- 'jednostka_organizacyjna' => 'jednostka_organizacyjna',
- 'GUID' => 'GUID',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'kodPocztowy' => 'kodPocztowy',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- 'nrBudynku' => 'nr',
- 'nrLokalu' => 'nrLokalu',
- ],
- ];
- $refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', true);
- if ($full) DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `A_STATUS` = 'WAITING'");
- DB::getPDO()->query("update `BI_audit_ENERGA_PRACOWNICY_import` set `pesel` = null where `A_STATUS` = 'WAITING' and isPesel(`pesel`) = 0");
- $query = "select * from `BI_audit_ENERGA_PRACOWNICY_import` where `A_STATUS` = 'WAITING'";
- $pracownicy = DB::getPDO()->query($query);
- while ($pracownik = $pracownicy->fetch()) {
- if ($pracownik['pesel']) {
- $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `pesel` = '{$pracownik['pesel']}' or (coalesce(`pesel`, '') = '' and `GUID` = '{$pracownik['GUID']}')");
- } elseif ($pracownik['GUID']) {
- $ID_pracownik = DB::getPDO()->fetchValue("select `ID` from `BI_audit_ENERGA_PRACOWNICY` where `GUID` = '{$pracownik['GUID']}'");
- } else {
- DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
- continue;
- }
- $sqlArr = [];
- $sqlArr['source'] = 'import';
- $sqlArr['cached'] = '0';
- foreach ($fields['BI_audit_ENERGA_PRACOWNICY'] as $tableField => $importField) {
- $sqlArr[$tableField] = trim($pracownik[$importField]);
- if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
- }
- if ($ID_pracownik) {
- DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $ID_pracownik, $sqlArr);
- $full = true;
- }
- else $ID_pracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', $sqlArr);
- $sqlArr = [];
- foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
- $sqlArr[$tableField] = trim($pracownik[$importField]);
- if (!$sqlArr[$tableField]) unset($sqlArr[$tableField]);
- }
- if (!$sqlArr) {
- DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'OFF_SOFT']);
- continue;
- }
- $sqlWhereArr = [];
- $sqlWhereArr[] = "`{$refTable}`.`PRIMARY_KEY` = '{$ID_pracownik}'";
- foreach ($fields['BI_audit_ENERGA_PRACOWNICY_adresy'] as $tableField => $importField) {
- if (isset($sqlArr[$tableField])) $sqlWhereArr[] = "`BI_audit_ENERGA_PRACOWNICY_adresy`.`{$tableField}` = " . DB::getPDO()->quote($sqlArr[$tableField]);
- else $sqlWhereArr[] = "`{$tableField}` is null";
- }
- $query = "select count(*) from `{$refTable}` join `BI_audit_ENERGA_PRACOWNICY_adresy` on `{$refTable}`.`REMOTE_PRIMARY_KEY` = `BI_audit_ENERGA_PRACOWNICY_adresy`.`ID` where " . implode(' and ', $sqlWhereArr);
- if (!(DB::getPDO()->fetchValue($query))) {
- $ID_adres = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_adresy', $sqlArr);
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $ID_pracownik, 'REMOTE_PRIMARY_KEY' => $ID_adres]);
- }
- DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY_import', 'ID', $pracownik['ID'], ['A_STATUS' => 'NORMAL']);
- }
- return $full;
- }
- private static function reloadCache_parseFakturyUmowy($full = false) {
- $fields = [
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'Tytul_dokumentu',
- 'Pelna_nazwa_kontrahenta',
- 'NIP',
- 'REGON',
- 'KRS',
- 'Kraj',
- 'Kod_pocztowy',
- 'Miejscowosc',
- 'Ulica',
- 'Numer_budynku',
- 'Numer_mieszkania_lokalu',
- 'TERYT_SYM',
- 'TERYT_SYM_UL',
- ],
- 'BI_audit_KRS' => [
- '"Zaimportowano z KRS na podstawie faktury/umowy"',
- 'nazwa',
- 'nip',
- 'regon',
- 'krs',
- 'A_kraj',
- 'A_kod',
- 'A_miejscowosc',
- 'A_ulica',
- 'A_nrDomu',
- 'A_nrLokalu',
- 'TERYT_SYM',
- 'TERYT_SYM_UL',
- ],
- 'BI_audit_CEIDG' => [
- '"Zaimportowano z CEiDG na podstawie faktury/umowy"',
- 'firma',
- 'nip',
- 'regon',
- 'null',
- 'kraj',
- 'kodPocztowy',
- 'miejscowosc',
- 'ulica',
- 'budynek',
- 'lokal',
- 'TERYT_SYM',
- 'TERYT_SYM_UL',
- ],
- ];
- $refTableFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- $refTableUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- if ($full) {
- DB::getPDO()->query("truncate table `{$refTableFakturyToKontrahenci}`");
- DB::getPDO()->query("truncate table `{$refTableUmowyToKontrahenci}`");
- DB::getPDO()->query("update `BI_audit_ENERGA_FAKTURY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
- DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `A_STATUS` = 'WAITING' where `A_STATUS` = 'NORMAL'");
- }
- $query = "select `ID`, `NIP` from `BI_audit_ENERGA_FAKTURY` where `A_STATUS` = 'WAITING'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $ID = $row['ID'];
- $nip = trim($row['NIP']);
- if (!$full) {
- $query = "delete from `{$refTableFakturyToKontrahenci}` where PRIMARY_KEY = '{$row['ID']}'";
- DB::getPDO()->query($query);
- }
- if (!$nip) {
- DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'OFF_SOFT']);
- continue;
- }
- $K_IDs = [];
- $query = "select `ID` from `BI_audit_ENERGA_RUM_KONTRAHENCI` where `NIP` = '{$nip}'";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) $K_IDs[] = $item['ID'];
- } else {
- $query = "select ID from BI_audit_KRS where nip = '{$nip}' order by `ID` desc limit 1";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) {
- $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
- " select " . implode(', ', $fields['BI_audit_KRS']) . " from `BI_audit_KRS` where `ID` = '{$item['ID']}'";
- if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
- }
- } else {
- $query = "select `ID` from `BI_audit_CEIDG` where `nip` = '{$nip}' order by `ID` desc limit 1";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) {
- $query = "insert into `BI_audit_ENERGA_RUM_KONTRAHENCI` (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
- " select " . implode(', ', $fields['BI_audit_CEIDG']) . " from `BI_audit_CEIDG` where `ID` = '{$item['ID']}'";
- if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
- }
- }
- }
- }
- foreach ($K_IDs as $K_ID) {
- if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableFakturyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
- DB::getPDO()->query("insert into `{$refTableFakturyToKontrahenci}` (`PRIMARY_KEY`, `REMOTE_PRIMARY_KEY`) values ({$ID}, {$K_ID})");
- }
- }
- DB::getPDO()->update('BI_audit_ENERGA_FAKTURY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
- }
- foreach (['Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_', 'Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_', 'Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_', 'Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_', 'Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_'] as $field) DB::getPDO()->query("update `BI_audit_ENERGA_RUM_UMOWY` set `{$field}` = replace(`{$field}`, ',', '.') where `A_STATUS` = 'WAITING'");
- $query = <<<SQL
- update `BI_audit_ENERGA_RUM_UMOWY` set `Wartosc` =
- if(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_` > 1, convert(`Wartosc_przedmiotu_umowy_netto_w_PLN__aktualna_`, double),
- if(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_` > 1, convert(`Wartosc_przedmiotu_umowy_netto_w_PLN__pierwotna_`, double),
- if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_` > 1, convert(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__aktualna_`, double),
- if(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_` > 1, convert(`Wartosc_kosztowa_przedmiotu_umowy_netto_w_walucie__pierwotna_`, double),
- if(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_` > 1, convert(`Wartosc_przedmiotu_umowy_netto_w_walucie__pierwotna_`, double), 0))))) where `A_STATUS` = 'WAITING';
- SQL;
- DB::getPDO()->query($query);
- $query = "select `ID`, `Kontrahenci` from `BI_audit_ENERGA_RUM_UMOWY` where `A_STATUS` = 'WAITING'";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $ID = $row['ID'];
- if (!$full) {
- $query = "delete from `{$refTableUmowyToKontrahenci}` where PRIMARY_KEY = '{$ID}'";
- DB::getPDO()->query($query);
- }
- $kontrahenci = array_map('trim', explode("|", $row['Kontrahenci']));
- $K_IDs = [];
- foreach ($kontrahenci as $item) {
- $kontrahent = array_map('trim', explode(";", $item));
- $nr = null;
- if (count($kontrahent) == 3) $i = 1;//$nr = $kontrahent[1];
- elseif (count($kontrahent) == 4) $i = 2;//$nr = $kontrahent[2];
- elseif (count($kontrahent) >= 5 && count($kontrahent) <= 6) $i = 3;//$nr = $kontrahent[3];
- else $i = null;
- if ($i) $nr = $kontrahent[$i];
- $notFound = false;
- if (is_numeric($nr)) {
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Numer_kontrahenta = '{$nr}' and not (NIP is null and REGON is null and KRS is null)";
- if ($K_ID = DB::getPDO()->fetchValue($query)) {
- $K_IDs[] = $K_ID;
- } else {
- $nazwa = $kontrahent[$i+1];
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where Pelna_nazwa_kontrahenta = '" . addslashes($nazwa) . "' and not (NIP is null and REGON is null and KRS is null)";
- if ($result2 = DB::getPDO()->fetchAll($query)) {
- foreach ($result2 as $item) $K_IDs[] = $item['ID'];
- } else $notFound = true;
- }
- } else $notFound = true;
- if ($notFound) {
- list($nip, $regon) = self::parseNipRegon($item);
- if ($nip || $regon) {
- $query = "select ID from BI_audit_ENERGA_RUM_KONTRAHENCI where NIP = '{$nip}' or REGON = '{$regon}'";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) $K_IDs[] = $item['ID'];
- } else {
- $query = "select ID from BI_audit_KRS where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) {
- $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
- " select " . implode(', ', $fields['BI_audit_KRS']) . " from BI_audit_KRS where ID = '{$item['ID']}'";
- if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
- }
- } else {
- $query = "select ID from BI_audit_CEIDG where nip = '{$nip}' or regon = '{$regon}' order by `ID` desc limit 1";
- if ($result2 = DB::getPDO()->fetchall($query)) {
- foreach ($result2 as $item) {
- $query = "insert into BI_audit_ENERGA_RUM_KONTRAHENCI (" . implode(', ', $fields['BI_audit_ENERGA_RUM_KONTRAHENCI']) . ")" .
- " select " . implode(', ', $fields['BI_audit_CEIDG']) .
- " from BI_audit_CEIDG where ID = '{$item['ID']}'";
- if (DB::getPDO()->query($query)) $K_IDs[] = DB::getPDO()->lastInsertId();
- }
- }
- }
- }
- }
- }
- }
- foreach ($K_IDs as $K_ID) {
- if (!(DB::getPDO()->fetchValue("select count(*) from `{$refTableUmowyToKontrahenci}` where `PRIMARY_KEY` = {$ID} and `REMOTE_PRIMARY_KEY` = {$K_ID}"))) {
- DB::getPDO()->query("insert into `{$refTableUmowyToKontrahenci}` (PRIMARY_KEY, REMOTE_PRIMARY_KEY) values ({$ID}, {$K_ID})");
- }
- }
- DB::getPDO()->update('BI_audit_ENERGA_RUM_UMOWY', "ID", $ID, ['A_STATUS' => 'NORMAL']);
- }
- $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";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $query = "select nip, regon, krs from BI_audit_KRS where nip = '{$row['NIP']}' or regon = '{$row['REGON']}' or krs = '{$row['KRS']}'";
- if ($items = DB::getPDO()->fetchAll($query)) {
- list($nip, $regon, $krs) = [$items[0]["nip"], $items[0]["regon"], $items[0]["krs"]];
- if (count($items) > 1) {
- for ($i = 1; $i < count($items); $i++) {
- if ($nip != $items[$i]["nip"]) $nip = null;
- if ($regon != $items[$i]["regon"]) $regon = null;
- if ($krs != $items[$i]["krs"]) $krs = null;
- }
- }
- $set = [];
- if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
- if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
- if ($krs && $krs != $row['KRS']) $set[] = "KRS = '{$krs}'";
- if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row['ID']}'");
- }
- }
- $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";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $query = "select nip, regon from BI_audit_CEIDG where nip = '{$row['NIP']}' or regon = '{$row['REGON']}'";
- if ($items = DB::getPDO()->fetchAll($query)) {
- list($nip, $regon) = [$items[0]["nip"], $items[0]["regon"]];
- if (count($items) > 1) {
- for ($i = 1; $i < count($items); $i++) {
- if ($nip != $items[$i]["nip"]) $nip = null;
- if ($regon != $items[$i]["regon"]) $regon = null;
- }
- }
- $set = [];
- if ($nip && $nip != $row['NIP']) $set[] = "NIP = '{$nip}'";
- if ($regon && $regon != $row['REGON']) $set[] = "REGON = '{$regon}'";
- if ($set) DB::getPDO()->query("update BI_audit_ENERGA_RUM_KONTRAHENCI set " . implode(', ', $set) . " where ID = '{$row->ID}'");
- }
- }
- }
- public static function reloadCache_reTeryt($full = false, $forceAll = false) {
- Lib::loadClass('Teryt');
- $tables = [
- 'BI_audit_CEIDG' => [
- 'fields' => [
- 'wojewodztwo' => 'wojewodztwo',
- 'powiat' => 'powiat',
- 'gmina' => 'gmina',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- 'kodPocztowy' => 'kodPocztowy',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'budynek',
- 'nrLokalu' => 'lokal',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'fields' => [
- 'wojewodztwo' => 'wojewodztwo',
- 'powiat' => 'powiat',
- 'gmina' => 'gmina',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- 'kodPocztowy' => 'kodPocztowy',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'budynek',
- 'nrLokalu' => 'lokal',
- ],
- 'base' => '1',
- ],
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'fields' => [
- 'miejscowosc' => 'miejscowosc',
- 'kodPocztowy' => 'kodPocztowy',
- 'ulica' => 'ulica',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'nr',
- 'nrLokalu' => 'nrLokalu',
- ],
- 'base' => '0',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'fields' => [
- 'kodPocztowy' => 'kodPocztowy',
- 'miejscowosc' => 'miejscowosc',
- 'ulica' => 'ulica',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'nrBudynku',
- 'nrLokalu' => 'nrLokalu',
- ],
- 'base' => '0',
- ],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'fields' => [
- 'kodPocztowy' => 'Kod_pocztowy',
- 'miejscowosc' => 'Miejscowosc',
- 'ulica' => 'Ulica',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'Numer_budynku',
- 'nrLokalu' => 'Numer_mieszkania_lokalu',
- ],
- 'base' => '0',
- ],
- // 'BI_audit_KRS' => [
- // 'fields' => [
- // 'wojewodztwo' => 'S_wojewodztwo',
- // 'powiat' => 'S_powiat',
- // 'gmina' => 'S_gmina',
- // 'miejscowosc' => 'A_miejscowosc',
- // 'ulica' => 'A_ulica',
- // 'kodPocztowy' => 'A_kod',
- // ],
- // 'fieldsTeryt' => [
- // 'TERYT_SYM' => 'TERYT_SYM',
- // 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- // 'nrDomu' => 'A_nrDomu',
- // 'nrLokalu' => 'A_nrLokalu',
- // ],
- // 'base' => '1',
- // ],
- 'BI_audit_KRS_address' => [
- 'fields' => [
- 'wojewodztwo' => 'S_wojewodztwo',
- 'powiat' => 'S_powiat',
- 'gmina' => 'S_gmina',
- 'miejscowosc' => 'A_miejscowosc',
- 'ulica' => 'A_ulica',
- 'kodPocztowy' => 'A_kod',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'A_nrDomu',
- 'nrLokalu' => 'A_nrLokalu',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_address' => [
- 'fields' => [
- 'wojewodztwo' => 'S_wojewodztwo',
- 'powiat' => 'S_powiat',
- 'gmina' => 'S_gmina',
- 'miejscowosc' => 'A_miejscowosc',
- 'ulica' => 'A_ulica',
- 'kodPocztowy' => 'A_kod',
- ],
- 'fieldsTeryt' => [
- 'TERYT_SYM' => 'TERYT_SYM',
- 'TERYT_SYM_UL' => 'TERYT_SYM_UL',
- 'nrDomu' => 'A_nrDomu',
- 'nrLokalu' => 'A_nrLokalu',
- ],
- 'base' => '1',
- ],
- ];
- foreach ($tables as $table => $tableConf) {
- DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrDomu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrDomu']}`) = ''");
- DB::getPDO()->query("update `{$table}` set `{$tableConf['fieldsTeryt']['nrLokalu']}` = null where trim(`{$tableConf['fieldsTeryt']['nrLokalu']}`) = ''");
- $where = ($full && ($forceAll || (!$tableConf['base']))) ? "" : "where `TERYT_SYM` is null and `cached` = 0";
- $query = "select * from `{$table}` {$where}";
- $refTable = BiAuditRefTables::getRefTable($table, 'TERYT_adresy', true);
- $terytJoinArr = [];
- foreach ($tableConf['fieldsTeryt'] as $terytField => $tableField) {
- $terytJoinArr[] = (
- $terytField == 'nrLokalu'
- ? "coalesce(`teryt`.`{$terytField}`, '') = coalesce(`table`.`{$tableField}`, '')"
- : "`teryt`.`{$terytField}` = `table`.`{$tableField}`"
- );
- }
- $terytJoin = implode(" and ", $terytJoinArr);
- $insertFields = "`" . implode("`, `", array_keys($tableConf['fieldsTeryt'])) . "`";
- $selectFields = "`" . implode("`, `", $tableConf['fieldsTeryt']) . "`";
- //$adresy = DB::getPDO()->queryNotBuffered($query);
- $adresy = DB::getPDO()->query($query);
- while ($adres = $adresy->fetch()) {
- DB::getPDO()->query("delete from `{$refTable}` where `PRIMARY_KEY` = '{$adres['ID']}'");
- if (!($forceAll and $adres['TERYT_SYM'])) {
- $search = [];
- foreach ($tableConf['fields'] as $field => $param) if (!empty($adres[$param])) $search[$field] = $adres[$param];
- try {
- $teryt = Teryt::search($search);
- } catch (Exception $e) {
- continue;
- }
- if (empty($teryt['SYM'])) continue;
- $sqlArr = ['TERYT_SYM' => $teryt['SYM']];
- $sqlArr['TERYT_SYM_UL'] = (isset($teryt['SYM_UL']) ? $teryt['SYM_UL'] : 0);
- DB::getPDO()->update($table, "ID", $adres['ID'], $sqlArr);
- }
- if (!trim($adres[$tableConf['fieldsTeryt']['nrDomu']])) continue;
- $terytID = DB::getPDO()->fetchValue("select `teryt`.`ID` from `TERYT_adresy` as `teryt` join `{$table}` as `table` on {$terytJoin} where `table`.`ID` = '{$adres['ID']}'");
- if (!$terytID) {
- if (DB::getPDO()->query("insert into `TERYT_adresy` ({$insertFields}) select {$selectFields} from `{$table}` where `ID` = '{$adres['ID']}'")) {
- if (!($terytID = DB::getPDO()->lastInsertId())) {
- throw new Exception("Błąd dodania rekordu do TERYT_adresy #1");
- }
- } else {
- throw new Exception("Błąd dodania rekordu do TERYT_adresy #2");
- }
- }
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $adres['ID'], 'REMOTE_PRIMARY_KEY' => $terytID]);
- }
- }
- }
- private static function reloadCache_updateAll($full, $onlyBase) {
- $tablesConf = [
- 'BI_audit_CEIDG' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'fields' => [
- 'nip' => 'nip',
- ],
- 'base' => '1',
- ],
- 'BI_audit_CEIDG_powiazania' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'fields' => [
- 'nip' => 'nip',
- 'regon' => 'regon',
- 'pesel' => 'pesel',
- 'krs' => 'krs',
- ],
- 'base' => '0',
- //'where' => '',
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'fields' => [],
- 'base' => '0',
- //'where' => '',
- ],
-
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'fields' => [
- 'krs' => 'KRS',
- 'nip' => 'NIP',
- 'regon' => 'REGON',
- 'pesel' => 'PESEL',
- ],
- 'base' => '0',
- 'where' => "and ownCompany != 'Y'",
- ],
- 'BI_audit_KRS' => [
- 'fields' => [
- 'krs' => 'krs',
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_address' => [
- 'fields' => [],
- 'base' => '1',
- ],
- 'BI_audit_KRS_company' => [
- 'fields' => [
- 'regon' => 'regon',
- 'krs' => 'krs',
- ],
- 'base' => '1',
- ],
- 'BI_audit_KRS_person' => [
- 'fields' => [
- 'pesel' => 'pesel',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG' => [
- 'fields' => [
- 'krs' => 'krs',
- 'nip' => 'nip',
- 'regon' => 'regon',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_address' => [
- 'fields' => [],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_company' => [
- 'fields' => [
- 'regon' => 'regon',
- 'krs' => 'krs',
- ],
- 'base' => '1',
- ],
- 'BI_audit_MSIG_person' => [
- 'fields' => [
- 'pesel' => 'pesel',
- ],
- 'base' => '1',
- ],
- // 'BI_audit_KW_requested_person' => [
- // 'fields' => [
- // 'pesel' => 'Seller_person_pesel',
- // 'krs' => 'Seller_person_KRS',
- // 'nip' => 'Seller_person_NIP',
- // 'regon' => 'Seller_person_REGON',
- // ],
- // 'base' => '0',
- // //'where' => '',
- // ],
- 'TERYT_adresy' => [
- 'fields' => [],
- 'base' => '1',
- ],
- ];
- $refTablesConf = [
- 'BI_audit_CEIDG' => [
- 'refTablesTo' => [
- 'BI_audit_CEIDG_pelnomocnicy',
- 'BI_audit_CEIDG_powiazania',
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_CEIDG_pelnomocnicy' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_ENERGA_PRACOWNICY' => [
- 'refTablesTo' => [
- 'BI_audit_ENERGA_PRACOWNICY_adresy',
- //'TERYT_adresy',
- ],
- 'base' => 0,
- ],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 0,
- ],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 0,
- ],
- 'BI_audit_KRS' => [
- 'refTablesTo' => [
- 'BI_audit_KRS_address',
- 'BI_audit_KRS_company',
- 'BI_audit_KRS_person',
- // 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_KRS_address' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- 'BI_audit_MSIG' => [
- 'refTablesTo' => [
- 'BI_audit_MSIG_address',
- 'BI_audit_MSIG_company',
- 'BI_audit_MSIG_person',
- ],
- 'base' => 1,
- ],
- 'BI_audit_MSIG_address' => [
- 'refTablesTo' => [
- 'TERYT_adresy',
- ],
- 'base' => 1,
- ],
- ];
-
- $sourceTables = ['BI_audit_ENERGA_PRACOWNICY'];
- if ($full) {
- foreach ($tablesConf as $table => $tableConf) if (!$tableConf['base']) $queries[] = "update `{$table}` set `cached` = 0";
- $queries[] = "delete from `BI_audit_ALL` where `BASE` = 0";
- // $queries[] = "optimize table `BI_audit_ALL`";
- $queries[] = "delete from `BI_audit_ALL_ref` where `BASE` = 0";
- // $queries[] = "optimize table `BI_audit_ALL_ref`";
- $allTables = [];
- foreach ($refTablesConf as $refTableFrom => $refTableConf) {
- $allTables[] = $refTableFrom;
- // if ($refTableConf['base']) continue;
- foreach ($refTableConf['refTablesTo'] as $refTableTo) {
- $allTables[] = $refTableTo;
- if ($refTableConf['base']) continue;
- $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
- $queries[] = "update `{$refTable}` set `A_STATUS` = 'WAITNG' where `A_STATUS` = 'NORMAL'";
- // $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}'";
- }
- }
- $allTables = array_unique($allTables);
- foreach ($allTables as $refTableFrom) {
- foreach ($allTables as $refTableTo) {
- if ($refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, false)) {
- $queries[] = "delete from `{$refTable}` where `TRANSACTION_ID` = '-1'";
- $queries[] = "optimize table `{$refTable}`";
- $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";
- }
- }
- }
- }
- foreach ($tablesConf as $table => $tableConf) {
- if ($onlyBase && (!$tableConf['base'])) continue;
- $where = "where `{$table}`.`cached` = 0";
- if (!empty($tableConf['where'])) $where .= " {$tableConf['where']}";
- // $queries[] = "insert into `BI_audit_ALL` (`REMOTE_TABLE`, `REMOTE_ID`, `BASE`, " . implode(", ", array_keys($tableConf['fields'])) .
- // ") select '{$table}', ID, '{$tableConf['base']}', " . implode(", ", $tableConf['fields']) . " from `{$table}` {$where}";
- $fields = ["`REMOTE_TABLE`", "`REMOTE_ID`", "`BASE`"];
- $values = ["'{$table}'", "`ID`", "'{$tableConf['base']}'"];
- $updates = ["`BI_audit_ALL`.`reffed` = 0", "`{$table}`.`cached` = 1"];
- foreach ($tableConf['fields'] as $field => $value) {
- $fields[] = "`{$field}`";
- $values[] = "`{$value}`";
- $updates[] = "`BI_audit_ALL`.`{$field}` = `{$table}`.`{$value}`";
- }
- $queries[] = "update `BI_audit_ALL` join `{$table}` on `BI_audit_ALL`.`REMOTE_TABLE` = '{$table}' and `BI_audit_ALL`.`REMOTE_ID` = `{$table}`.`ID` set " . implode(", ", $updates) . " {$where}";
- $queries[] = "insert into `BI_audit_ALL` (" . implode(", ", $fields) . ") select " . implode(", ", $values) . " from `{$table}` {$where}";
- $queries[] = "update `{$table}` set `cached` = 1 {$where}";
- }
- $queries[] = "update `BI_audit_ALL` set `nip` = null where `nip` = 0";
- $queries[] = "update `BI_audit_ALL` set `regon` = null where `regon` = 0";
- $queries[] = "update `BI_audit_ALL` set `krs` = null where `krs` = 0";
- $queries[] = "update `BI_audit_ALL` set `pesel` = null where `pesel` = 0";
- $queries[] = "set @var = (select round(coalesce(max(`ID`), '0.5'), 1) from `BI_audit_ALL_ref_RELATIONS`)";
- $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";
- foreach ($refTablesConf as $refTableFrom => $refTableConf) {
- if ($onlyBase && (!$tableConf['base'])) continue;
- foreach ($refTableConf['refTablesTo'] as $refTableTo) {
- $refTable = BiAuditRefTables::getRefTable($refTableFrom, $refTableTo, true);
- $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`";
- if (!in_array($refTableFrom, $sourceTables)) {
- $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`";
- }
- if ($backRefTable = BiAuditRefTables::getRefTable($refTableTo, $refTableFrom, false)) {
- $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'";
- }
- $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'";
- }
- }
- foreach ($queries as $query) {
- echo "SQL: {$query}\n";
- DB::getPDO()->query($query);
- }
- $BiAuditRelations = new BiAuditRelations();
- //$result = DB::getPDO()->queryNotBuffered("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
- $result = DB::getPDO()->query("select `ID` from `BI_audit_ALL` where `reffed` = 0 order by `ID`");
- while ($row = $result->fetch()) $BiAuditRelations->findRelations($row['ID']);
- DB::getPDO()->query("update `BI_audit_ALL` set `reffed` = 1");
- }
- public function doReloadCache($full = false) {
- if ($full === 'base') {
- $onlyBase = true;
- $full = false;
- } else {
- $onlyBase = false;
- }
- $setFull = function() {
- BiAuditPowiazania::saveToLog("Wykryto niespójność tabel - uruchamiam pełne odświeżenie cache");
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'Full',
- 'FILE_STATUS_info' => 'Odświeżam w pełni cache',
- ];
- DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $this->POWIAZANIA_ID, $sqlArr);
- };
- if ($this->POWIAZANIA_ID && (!$full)) {
- $checkTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', 'BI_audit_ENERGA_RUM_KONTRAHENCI'];
- foreach ($checkTables as $table) {
- $query = "select count(*) from `BI_audit_ALL` `all` left join `{$table}` `t` on `all`.`REMOTE_ID`=`t`.`ID` and `t`.`cached` = '1' where `all`.`REMOTE_TABLE`='{$table}' and `t`.`ID` is null";
- if (DB::getPDO()->fetchValue($query)) {
- $full = true;
- $setFull();
- break;
- }
- }
- }
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $reloadCachePidFile = $tasksDirLocation . "/reloadCache.pid";
- $reloadCacheResultFile = $tasksDirLocation . "/reloadCache.result";
- if (!$this->POWIAZANIA_ID) file_put_contents($reloadCachePidFile, getmypid());
- try {
- error_log('now: self::importPracownicy');
- $_full = self::importPracownicy($full);
- if ((!$full) && $_full) {
- $full = true;
- if ($this->POWIAZANIA_ID) $setFull();
- }
- error_log('now: self::reloadCache_parseFakturyUmowy');
- self::reloadCache_parseFakturyUmowy($full);
- error_log('now: self::reloadCache_reTeryt');
- self::reloadCache_reTeryt($full);
- error_log('now: self::reloadCache_updateAll');
- self::reloadCache_updateAll($full, $onlyBase);
- if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, "ok");
- } catch (Exception $e) {
- var_dump($e);
- if (!$this->POWIAZANIA_ID) file_put_contents($reloadCacheResultFile, $e->getMessage());
- else throw new Exception($e->getMessage());
- }
- }
- public function doGeneratePowiazania($ID, $debug = false) {
- $this->POWIAZANIA_ID = $ID;
- $powiazaniaDirLocation = self::getMainDirectory();
- $tasksDirLocation = $powiazaniaDirLocation . "/.tasks";
- $resultFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.result";
- $xmlFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.xml";
- $pidFile = "{$tasksDirLocation}/generatePowiazania-{$ID}.pid";
- if (!$debug) file_put_contents($pidFile, getmypid());
- /* $tablesConf = [
- 'BI_audit_CEIDG' => ['ID', 'imie', 'nazwisko', 'nip', 'regon', 'firma', 'miejscowosc'],
- 'BI_audit_CEIDG_pelnomocnicy' => ['ID', 'nazwa', 'nip', 'miejscowosc'],
- 'BI_audit_CEIDG_powiazania' => ['ID', 'nip', 'regon'],
- 'BI_audit_ENERGA_PRACOWNICY' => ['ID', 'imiona', 'nazwisko', 'pesel', 'nip', 'regon'],
- 'BI_audit_ENERGA_PRACOWNICY_adresy' => ['ID', 'miejscowosc'],
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => ['ID', 'Pelna_nazwa_kontrahenta', 'NIP', 'REGON', 'PESEL', 'KRS', 'Miejscowosc'],
- 'BI_audit_KRS' => ['ID', 'krs', 'nip', 'regon', 'nazwa', 'A_miejscowosc'],
- 'BI_audit_KRS_company' => ['ID', 'nazwa', 'regon', 'krs'],
- 'BI_audit_KRS_person' => ['ID', 'nazwisko', 'imiona', 'pesel'],
- 'BI_audit_KW_requested_person' => ['ID', 'Seller_person', 'Seller_person_pesel', 'Seller_person_KRS', 'Seller_person_NIP', 'Seller_person_REGON'],
- ];*/
- try {
- $BiAuditPowiazania = new BiAuditPowiazania($ID, $tasksDirLocation);
- if (!$debug) {
- $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}";
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'Part',
- 'FILE_STATUS_info' => 'Odświeżam częściowo cache',
- ];
- do {
- DB::getPDO()->query("lock tables `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` write");
- $activeReloadingCache = DB::getPDO()->fetchValue($query);
- if (!$activeReloadingCache) DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
- DB::getPDO()->query("unlock tables");
- if ($activeReloadingCache) {
- BiAuditPowiazania::saveToLog("Czekam na zakończenie odświeżania cache przez inne zadanie");
- sleep(30);
- }
- } while ($activeReloadingCache);
- BiAuditPowiazania::saveToLog("Uruchamiam częściowe odświeżenie cache");
- $this->doReloadCache(); //DUPA testowe wylaczanie
- BiAuditPowiazania::saveToLog("Odświeżono cache");
- $sqlArr = [
- 'BI_analiza_reloadCache' => 'No',
- 'FILE_STATUS_info' => 'Szukam powiązań',
- ];
- DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
- }
- $BiAuditPowiazania->run($debug);
- //if (!$BiAuditPowiazania->powiazaniaFound()) throw new Exception("Nie znaleziono żadnych powiązań");
- //file_put_contents($xmlFile, $BiAuditPowiazania->asXml());
- if (!$debug) {
- $sqlArr = ['FILE_STATUS_info' => 'Generuję raporty PDF i HTML'];
- DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', "ID", $ID, $sqlArr);
- }
-
- //$BiAuditPowiazania->saveXml();
- $BiAuditPowiazania->generatePdfAndHtml();
- if (!$debug) file_put_contents($resultFile, json_encode(['result' => 'ok', 'parts' => $BiAuditPowiazania->getPartsCount()]));
- } catch (Exception $e) {
- if (!$debug) file_put_contents($resultFile, json_encode(['result' => 'error', 'message' => $e->getMessage()]));
- }
- }
- public function reinstallAction() {
- $this->reinstall();
- die('OK');
- }
- public function reinstall() {
- $sqlList = array();
- //$sqlList['RemoveTable'] = "DROP TABLE IF EXISTS `CRM_CONFIG`";
- $sqlList['ActivateBiAuditGenerate'] = <<<SQL
- REPLACE INTO `CRM_CONFIG` (`CONF_KEY`,`CONF_VAL`) VALUES ('module_BiAudit','on');
- SQL;
- $sqlList['ChangeStructure1'] = <<<SQL
- 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';
- SQL;
- $sqlList['ChangeStructure2'] = <<<SQL
- UPDATE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` SET `BI_analiza_reloadCache` = IF (`BI_analiza_reloadCache` = 'Y', 'Part', 'No');
- SQL;
- $sqlList['ChangeStructure3'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_reloadCache` `BI_analiza_reloadCache` ENUM('Full','Part','No') NOT NULL DEFAULT 'No';
- SQL;
- $sqlList['ChangeStructure4'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` CHANGE `BI_analiza_depth` `BI_analiza_maxDepth` INT(2) NULL DEFAULT '9';
- SQL;
- $sqlList['ChangeStructure5'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_minDepth` INT(2) NOT NULL DEFAULT '0' AFTER `FILE_STATUS_info`;
- SQL;
- $sqlList['ChangeStructure6'] = <<<SQL
- ALTER TABLE `BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA` ADD `BI_analiza_onlyTargets` ENUM('Y','N') NOT NULL DEFAULT 'Y' AFTER `BI_analiza_maxDepth`;
- SQL;
- $db = DB::getDB();
- if ($db->has_errors()) {
- throw new Exception("DB Errors: " . implode("\n<br/>", $db->get_errors()));
- }
- foreach ($sqlList as $sqlName => $sql) {
- $res = $db->query($sql);
- if ($db->has_errors()) {
- throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br/>", $db->get_errors()));
- }
- }
- }
- }
- class BiAuditRelations {
- private $RELATIONS_ID = [];
- private $relations = [
- 'nip' => ['nip'],
- 'regon' => ['regon'],
- 'krs' => ['krs'],
- 'pesel' => ['pesel'],
- ];
- private $destTables = ['BI_audit_ENERGA_RUM_KONTRAHENCI', 'BI_audit_KW_requested_person'];
- private $sourceTables = ['BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy'];
- public function __construct() {
- $query = "select * from BI_audit_ALL_ref_RELATIONS";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) $this->RELATIONS_ID[$row['RELATION']] = $row['ID'];
- }
- private function getRelationID($name) {
- if (!isset($this->RELATIONS_ID[$name])) {
- $query = "select round(coalesce(max(ID), 0.5) * 2) as newID from BI_audit_ALL_ref_RELATIONS";
- $newID = DB::getPDO()->fetchValue($query);
- $this->RELATIONS_ID[$name] = $newID;
- $query = "insert into BI_audit_ALL_ref_RELATIONS (ID, RELATION) values ('{$newID}', '{$name}')";
- DB::getPDO()->query($query);
- }
- return $this->RELATIONS_ID[$name];
- }
- private function addToRefTable($fromTable, $toTable, $fromID, $toID) {
- if ($refTable = BiAuditRefTables::getRefTable($fromTable, $toTable, false)) {
- if (!DB::getPDO()->fetchValue("select count(*) from `{$refTable}` where `PRIMARY_KEY` = '{$fromID}' and `REMOTE_PRIMARY_KEY` = '{$toID}' and `A_STATUS` != 'DELETED'")) {
- DB::getPDO()->insert($refTable, ['PRIMARY_KEY' => $fromID, 'REMOTE_PRIMARY_KEY' => $toID, 'A_STATUS' => 'NORMAL', 'TRANSACTION_ID' => '-1']);
- }
- }
- }
- public function findRelations($ID) {
- $query = "select * from BI_audit_ALL where ID = '{$ID}'";
- if (!($result = DB::getPDO()->fetchAll($query))) return false;
- $row = $result[0];
- $joins = [];
- $items = '';
- foreach ($this->relations as $name => $columns) {
- $ok = 0;
- $join = [];
- foreach ($columns as $column) {
- $join[] = "t1.{$column} = t2.{$column}";
- if ($row[$column] !== null) $ok++;
- }
- if ($ok / count($columns) > 0.5) {
- $joins[] = "(" . implode(" and ", $join) . ")";
- $items .= ", if(" . implode(" and ", $join) . ", 1, 0) as {$name}";
- }
- }
- if (!$joins) return false;
- $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 " .
- "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})";
- $result = DB::getPDO()->fetchAll($query);
- foreach ($result as $row) {
- $relationID = 0;
- foreach ($this->relations as $name => $v) {
- if (isset($row[$name]) && $row[$name]) $relationID += $this->getRelationID($name);
- }
- $start1 = (in_array($row['REMOTE_TABLE_1'], $this->sourceTables) ? 1 : 0);
- $start2 = (in_array($row['REMOTE_TABLE_2'], $this->sourceTables) ? 1 : 0);
- $end1 = (in_array($row['REMOTE_TABLE_1'], $this->destTables) ? 1 : 0);
- $end2 = (in_array($row['REMOTE_TABLE_2'], $this->destTables) ? 1 : 0);
- if (!($start2 || $end1)) {
- $query = "insert into BI_audit_ALL_ref (ID1, ID2, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end2}, {$row['BASE']})";
- $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
- $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
- DB::getPDO()->query($query);
- }
- if (!($start1 || $end2)) {
- $query = "insert into BI_audit_ALL_ref (ID2, ID1, RELATION_ID, END, BASE) values ({$ID}, {$row['ID']}, '{$relationID}', {$end1}, {$row['BASE']})";
- $this->addToRefTable($row['REMOTE_TABLE_1'], $row['REMOTE_TABLE_2'], $row['REMOTE_ID_1'], $row['REMOTE_ID_2']);
- $this->addToRefTable($row['REMOTE_TABLE_2'], $row['REMOTE_TABLE_1'], $row['REMOTE_ID_2'], $row['REMOTE_ID_1']);
- DB::getPDO()->query($query);
- }
- }
- }
- }
- class BiAuditRefTables {
- public static function getRefTable($tableFrom, $tableTo, $returnException = false) {
- static $refTables = [];
- static $tempRefTables = [];
- static $tempRefTablesCount = 0;
- if (is_array($tableTo)) {
- if (!$tableTo) throw new Exception('BiAuditRefTables::getRefTable - bad parameter $tableTo');
- if (count($tableTo) == 1) return self::getRefTable($tableFrom, reset($tableTo), $returnException);
- $key = implode("__", $tableTo);
- if (!isset($tempRefTables[$tableFrom][$key])) {
- try {
- $_tableFrom = $tableFrom;
- foreach ($tableTo as $_tableTo) {
- $_refTables[] = self::getRefTable($_tableFrom, $_tableTo, true);
- $_tableFrom = $_tableTo;
- }
- $name = "TEMP__#REF_TABLE__" . (++$tempRefTablesCount);
- $first = reset($_refTables);
- $last = end($_refTables);
- $prev = array_shift($_refTables);
- $query = "create temporary table `{$name}` select `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY` from `{$first}`";
- while ($next = array_shift($_refTables)) {
- $query .= " join `{$next}` on `{$prev}`.`REMOTE_PRIMARY_KEY` = `{$next}`.`PRIMARY_KEY`";
- $prev = $next;
- }
- $query .= " group by `{$first}`.`PRIMARY_KEY`, `{$last}`.`REMOTE_PRIMARY_KEY`";
- DB::getPDO()->query($query);
- $tempRefTables[$tableFrom][$key] = $name;
- } catch (Exception $e) {
- if ($returnException) throw new Exception($e->getMessage());
- $tempRefTables[$tableFrom][$key] = false;
- }
- }
- return $tempRefTables[$tableFrom][$key];
- } else {
- if (!isset($refTables[$tableFrom][$tableTo])) {
- try {
- $refTables[$tableFrom][$tableTo] = ACL::getRefTable("default_db/{$tableFrom}/{$tableFrom}", "default_db__x3A__{$tableTo}:{$tableTo}");
- } catch (Exception $e) {
- if ($returnException) throw new Exception($e->getMessage());
- $refTables[$tableFrom][$tableTo] = false;
- }
- }
- return $refTables[$tableFrom][$tableTo];
- }
- }
- public static function getRefTables($tableFrom) {
- static $refTables = [];
- if (!isset($refTables[$tableFrom])) {
- $namespace = "default_db/{$tableFrom}/{$tableFrom}";
- try {
- $item = SchemaFactory::loadDefaultObject('SystemObject')->getItem($namespace, [ 'propertyName' => '*,field' ]);
- if (!($item['hasStruct'] && $item['isStructInstalled'] && $item['isObjectActive'])) throw new Exception("Object error");
- $fields = $item['field'];
- $_refTables = [];
- foreach ($fields as $field) {
- list($type, $child) = explode(":", $field['xsdType'], 2);
- if ($type == "ref" && $field['idZasob'] && $field['isActive'] && (!$field['isLocal'])) {
- try {
- $_refTable = ACL::getRefTable($namespace, $child);
- $_refTables[] = $_refTable;
- } catch (Exception $e) {
- }
- }
- }
- $refTables[$tableFrom] = $_refTables;
- } catch (Exception $e) {
- $refTables[$tableFrom] = [];
- }
- }
- return $refTables[$tableFrom];
- }
- }
- class BiAuditPowiazania {
- private $L_APPOITMENT_INFO;
- private $minDepth;
- private $maxDepth, $origMaxDepth;
- private $onlyTargets;
- private $ID;
- private $nodes = [];
- private $endNodes;
- private $path = [];
- private $results = [];
- private $items_results = [];
- private $relations = [];
- private $srcTables = [
- 'BI_audit_ENERGA_PRACOWNICY' => [],
- 'BI_audit_KRS' => ['BI_audit_POWIAZANIA_OD'],
- 'BI_audit_KRS_person' => ['BI_audit_POWIAZANIA_OD'],
- 'BI_audit_MSIG' => ['BI_audit_POWIAZANIA_OD'],
- 'BI_audit_MSIG_person' => ['BI_audit_POWIAZANIA_OD'],
- 'BI_audit_CEIDG' => ['BI_audit_POWIAZANIA_OD'],
- 'BI_audit_CEIDG_pelnomocnicy' => ['BI_audit_POWIAZANIA_OD'],
- ];
- private $destTables = [
- 'BI_audit_ENERGA_RUM_KONTRAHENCI' => [],
- 'BI_audit_KW_requested_person' => [],
- 'BI_audit_KRS' => ['BI_audit_POWIAZANIA_DO'],
- 'BI_audit_KRS_person' => ['BI_audit_POWIAZANIA_DO'],
- 'BI_audit_MSIG' => ['BI_audit_POWIAZANIA_DO'],
- 'BI_audit_MSIG_person' => ['BI_audit_POWIAZANIA_DO'],
- 'BI_audit_CEIDG' => ['BI_audit_POWIAZANIA_DO'],
- 'BI_audit_CEIDG_pelnomocnicy' => ['BI_audit_POWIAZANIA_DO'],
- ];
- private $step = 0;
- private $tasksDirLocation;
- private $progressFile;
- private $progress = [
- 'summary' => [
- 'count' => 0,
- 'message' => 'Inicjacja',
- 'ts' => null,
- 'step' => 'initialize',
- 'reportsCount' => 0,
- 'reportsCreated' => 0,
- ],
- 'details' => [],
- ];
- private $lastProgress = 0;
- private $lastProgress_slowCheck = 0;
- private $lastResults = 0;
- private $startTimestamp = null;
- private $lastTimestamp = null;
- private $lowProgressCount = 0;
- private $count, $i;
- private $splittedResults = [];
- private $maxResults = 1000000;
- private $fidRow = [];
- private $itemID = 0;
- private $reverseSearch = false;
- private $query = "";
- private static function generateJson($type, $data) {
- return json_encode(['ts' => microtime(true), 'type' => $type, 'data' => $data]);
- }
- public static function saveToLog($message) {
- $messageJson = self::generateJson('message', ['message' => $message]);
- echo $messageJson . "\n";
- }
- private static function exec($cmd) {
- $path = 'export PATH=$PATH:/usr/sbin;';
- $cmd = "{$path} {$cmd}";
- echo "CMD :: {$cmd}\n";
- shell_exec($cmd);
- }
- private function saveProgress($args = []) {
- $timestamp = microtime(true);
- if (isset($args['progress']) && $this->i) {
- $elapsed = $timestamp - $this->startTimestamp;
- if ($args['progress']) {
- $estimated = ($elapsed * (1 - $args['progress'])) / $args['progress'];
- } else $estimated = "N/A";
- $this->lastProgress = $args['progress'];
- $this->lastTimestamp = $timestamp;
- $progressJson = self::generateJson('progress', ['progress' => $args['progress'], 'item' => $this->i . "/" . $this->count, 'results' => count($this->results), 'step' => $this->step, 'elapsed' => $elapsed, 'estimated' => $estimated]);
- echo $progressJson . "\n";
- $this->progress['details'][$this->itemID] = ['progress' => $args['progress'], 'results' => (count($this->results) - $this->lastResults), 'elapsed' => $elapsed, 'estimated' => $estimated];
- }
- if (isset($args['message'])) $this->progress['summary']['message'] = $args['message'];
- if (isset($args['step'])) $this->progress['summary']['step'] = $args['step'];
- if (isset($args['reportsCreated'])) $this->progress['summary']['reportsCreated'] = round($this->progress['summary']['reportsCreated'] + $args['reportsCreated'], 2);
- $this->progress['summary']['ts'] = $timestamp;
- file_put_contents($this->progressFile, json_encode($this->progress));
- if (file_exists("{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.abort")) {
- unlink("{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.abort");
- self::throwException("Przerwano na żądanie użytkownika");
- }
- }
- private static function throwException($message) {
- self::saveToLog($message);
- throw new Exception($message);
- }
- public function __construct($ID = 0, $tasksDirLocation = null) {
- if (!$ID) self::throwException("Wrong ID parameter");
- if (!$tasksDirLocation) self::throwException("Wrong directory of tasks location");
- $this->ID = $ID;
- $this->tasksDirLocation = $tasksDirLocation;
- $this->progressFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.progress";
- $this->saveProgress();
- }
- public function run($debug = false) {
- if ($debug) $query = "select L_APPOITMENT_INFO, BI_analiza_minDepth, BI_analiza_maxDepth, BI_analiza_onlyTargets from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->ID}' and FILE_STATUS = 'GENERATED' and BI_analiza_reloadCache not in ('Full')";
- else $query = "select L_APPOITMENT_INFO, BI_analiza_minDepth, BI_analiza_maxDepth, BI_analiza_onlyTargets from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = '{$this->ID}' and FILE_STATUS = 'IN_PROGRESS' and BI_analiza_reloadCache not in ('Full')";
- $result = DB::getPDO()->fetchAll($query);
- if (!$result) self::throwException("Błąd danych");
- $this->L_APPOITMENT_INFO = $result[0]['L_APPOITMENT_INFO'];
- if ($this->loadResults()) {
- $this->splitResults();
- return;
- }
- self::saveToLog("Wczytuję parametry wyszukiwania powiązań");
- Route_UrlAction_BiAuditGenerate::deleteResultsFromDB($this->ID);
- $this->minDepth = (int) $result[0]['BI_analiza_minDepth'];
- $this->maxDepth = (int) $result[0]['BI_analiza_maxDepth'];
- $this->onlyTargets = ($result[0]['BI_analiza_onlyTargets'] != 'N');
- if (!$this->minDepth) $this->minDepth = 1;
- if (!$this->maxDepth) self::throwException("Błąd danych - nieokreślono maksymalnej głębokości analizy");
- if ($this->minDepth > $this->maxDepth) self::throwException("Wartość minimalnej głębokości analizy jest większa od wartości maksymalnej głębokości analizy");
- $subQueries = [];
- $resultDest = [];
- foreach ($this->destTables as $destTable => $destPath) {
- $destPath[] = $destTable;
- if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $destPath)) {
- $subQueries[] = "select `all`.`ID`, `all`.`REMOTE_TABLE` from `BI_audit_ALL` `all` join `{$refTable}` `ref` on `all`.`REMOTE_TABLE` = '{$destTable}' and `all`.`REMOTE_ID` = `ref`.`REMOTE_PRIMARY_KEY` and `ref`.`PRIMARY_KEY` = '{$this->ID}'";
- }
- }
- if ($subQueries) {
- $query = implode(" union ", $subQueries) . " order by `ID` asc";
- $resultDest = DB::getPDO()->fetchAll($query);
- }
- if ((!$resultDest) && $this->onlyTargets) self::throwException("Błąd danych - nie zdefinowano żadnego końcowego obiektu");
- $subQueries = [];
- $resultSrc = [];
- foreach ($this->srcTables as $srcTable => $srcPath) {
- $srcPath[] = $srcTable;
- if ($refTable = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', $srcPath)) {
- $subQueries[] = "select `all`.`ID`, `all`.`REMOTE_TABLE` from `BI_audit_ALL` `all` join `{$refTable}` `ref` on `all`.`REMOTE_TABLE` = '{$srcTable}' and `all`.`REMOTE_ID` = `ref`.`REMOTE_PRIMARY_KEY` and `ref`.`PRIMARY_KEY` = '{$this->ID}'";
- }
- }
- if ($subQueries) {
- $query = implode(" union ", $subQueries) . " order by `ID` asc";
- $resultSrc = DB::getPDO()->fetchAll($query);
- }
- if (!$resultSrc) self::throwException("Błąd danych - nie zdefinowano żadnego początkowego obiektu");
- if (count($resultSrc) <= count($resultDest) || (!$this->onlyTargets)) {
- $result = $resultSrc;
- $this->endNodes = array_map('reset', $resultDest);
- $this->reverseSearch = false;
- $this->query = "select ref.ID2 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID1";
- } else {
- $result = $resultDest;
- $this->endNodes = array_map('reset', $resultSrc);
- $this->reverseSearch = true;
- $this->query = "select ref.ID1 as ID, RELATION_ID from BI_audit_ALL_ref ref where ref.ID2";
- self::saveToLog("Docelowych obiektów jest mniej, niż początkowych - włączono mechanizm odwrotnego przeszukiwania");
- }
- self::saveToLog("Rozpoczynam wyszukiwanie powiązań");
- $externalTables = array_keys(array_filter(array_merge($this->srcTables, $this->destTables), function($x) {return (!count($x));}));
- $this->count = count($result);
- $this->progress['summary']['count'] = $this->count;
- $this->origMaxDepth = $this->maxDepth;
- $this->saveProgress(['step' => 'relations']);
- try {
- foreach ($result as $i => $row) {
- $this->i = $i + 1;
- $this->itemID = DB::getPDO()->fetchValue("select `REMOTE_ID` from `BI_audit_ALL` where `ID` = :ID", [":ID" => $row['ID']]);
- $this->startTimestamp = microtime(true);
- $this->lastProgress = 0;
- $this->lastProgress_slowCheck = 0;
- $this->saveProgress(['progress' => 0, 'message' => "Wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
- if ($this->maxDepth != $this->origMaxDepth) {
- $this->maxDepth = $this->origMaxDepth;
- self::saveToLog("Przywrócono oryginalną maksymalną głębokość przeszukiwania ({$this->origMaxDepth})");
- }
- // $weight = in_array($row['REMOTE_TABLE'], $externalTables) ? 0 : 1; // TODO Nie ujmowanie w glebokosci przejscia z bazy wewnetrznej Energi do baz zewnetrznych
- $weight = 0;
- $this->findPowiazania($row['ID'], $weight);
- $this->saveProgress(['progress' => 1, 'message' => "Zakończono wyszukiwanie powiązań dla obiektu {$this->i}/{$this->count}"]);
- $this->lastResults = count($this->results);
- }
- } catch (Exception $e) {
- if ($this->i < $this->count) {
- $this->startTimestamp = microtime(true);
- $this->lastProgress = 0;
- $this->lastResults = count($this->results);
- while (++$this->i <= $this->count) $this->saveProgress(['progress' => 0]);
- }
- if ($message = $e->getMessage()) self::saveToLog("Wystąpił błąd podczas wyszukiwania powiązań - {$message}");
- }
- $this->nodes = [];
- self::saveToLog("Zakończono wyszukiwanie powiązań");
- $this->sortResults();
- $this->saveResults();
- //$this->saveToDb(); 2017-12-14 - przerobiono na zapisywanie danych do bazy w locie
- $this->splitResults();
- }
- private static function reversePath($path) {
- $arr = array_reverse($path, true);
- $keys = array_keys($arr);
- array_unshift($arr, array_pop($arr));
- return array_combine($keys, $arr);
- }
- private function addResult($progress) {
- if (count($this->results) == $this->maxResults) {
- $message = "Przerwano wyszukiwanie powiązań - osiągnięto maksymalną liczbę wyników {$this->maxResults}";
- self::saveToLog($message);
- $this->saveProgress(['progress' => $progress, 'message' => $message]);
- throw new Exception('');
- }
- if ($this->reverseSearch) $path = self::reversePath($this->path);
- else $path = $this->path;
- $this->results[] = $path;
- $this->saveToDb($path);
- }
- private static function weightCalc($n) {
- if ($n < 21) return 1;
- if ($n < 41) return 2;
- if ($n < 81) return 3;
- if ($n < 161) return 4;
- if ($n < 321) return 5;
- if ($n < 641) return 6;
- if ($n < 1281) return 7;
- if ($n < 2561) return 8;
- if ($n < 5121) return 9;
- return 10;
- }
- public function findPowiazania($ID, $weight = 0, $progress = 0, $steps = 1, $relation = "") {
- $this->step++;
- if ($this->maxDepth > $this->minDepth) {
- if (($this->step % 1000000) == 0) {
- $progressDiff = $progress - $this->lastProgress_slowCheck;
- if ($progressDiff < 0.00005) {
- $this->lowProgressCount++;
- if ($this->lowProgressCount == 10) {
- $this->maxDepth--;
- self::saveToLog("Zbyt dużo rekurencji, zmniejszono maksymalną głębokość poszukiwań do {$this->maxDepth} dla bieżącego obiektu");
- $this->lowProgressCount = 0;
- }
- } else $this->lowProgressCount = 0;
- $this->lastProgress_slowCheck = $progress;
- }
- }
- if ((($this->step) % 100000) == 0) {
- $this->saveProgress(['progress' => $progress]);
- }
- if ((($this->step) % 10000) == 0) {
- if (memory_get_usage(true) > 3000000000) {
- $this->nodes = [];
- self::saveToLog("Oczyszczam podręczny cache - zajmuje zbyt dużo pamięci");
- }
- }
- if (isset($this->path[$ID])) return false;
- $this->path[$ID] = $relation;
- if (!$relation) $relation = 0;
- if (in_array($ID, $this->endNodes)) {
- if (($weight) > $this->minDepth) $this->addResult($progress);
- array_pop($this->path);
- return;
- }
- if (($weight) >= $this->maxDepth) {
- if (!$this->onlyTargets) $this->addResult($progress);
- array_pop($this->path);
- return;
- }
- if (!isset($this->nodes[$ID][$relation])) {
- $where = $relation ? "and ({$relation} & ref.RELATION_ID) = 0" : "";
- $query = "{$this->query} = {$ID} {$where}";
- $this->nodes[$ID][$relation] = DB::getPDO()->fetchAll($query);
- }
- $nodes = array_values(array_filter($this->nodes[$ID][$relation], function ($node) {
- if (isset($this->path[$node['ID']])) return false;
- return true;
- }));
- $count = count($nodes);
- $weight += self::weightCalc($count);
- if ($weight <= $this->maxDepth) {
- foreach ($nodes as $i => $node) $this->findPowiazania($node['ID'], $weight, ($progress + ($i / ($count * $steps))), ($count * $steps), $node['RELATION_ID']);
- }
- array_pop($this->path);
- }
- private function sortResults() {
- if (!$this->results) return;
- uasort($this->results, function ($a, $b) {
- $ca = count($a);
- $cb = count($b);
- $c = min($ca, $cb);
- $ka = array_keys($a);
- $kb = array_keys($b);
- for ($i = 0; $i < $c; $i++) {
- if ($ka[$i] < $kb[$i]) return -1;
- if ($ka[$i] > $kb[$i]) return 1;
- }
- if ($ca < $cb) return -1;
- if ($ca > $cb) return 1;
- return 0;
- });
- }
- private function saveResults() {
- self::saveToLog("Zapisuję wyliczone dane do pliku");
- // if (!$this->results) {
- // self::saveToLog("Brak wyliczonych danych - niczego nie zapisaono");
- // return false;
- // }
- $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
- $data = base64_encode(gzcompress(json_encode(['results' => $this->results, 'fidRow' => $this->fidRow])));
- file_put_contents($dataFile, $data);
- self::saveToLog("Zapisano wyliczone dane do pliku");
- return true;
- }
- private function loadResults() {
- self::saveToLog("Próbuję wczytać wcześniej wyliczone dane");
- $dataFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.data";
- if (!file_exists($dataFile)) {
- self::saveToLog("Nie znaleziono pliku z wyliczonymi danymi");
- return false;
- }
- $data = file_get_contents($dataFile);
- $results = @json_decode(gzuncompress(base64_decode($data)), true);
- if (!$results) {
- self::saveToLog("Wystąpił błąd wczytywania wcześniej wyliczonych danych");
- return false;
- }
- if (isset($results['results'])) {
- $this->results = $results['results'];
- if (isset($results['fidRow'])) $this->fidRow = $results['fidRow'];
- } else $this->results = $results;
- self::saveToLog("Wczytano wcześniej wyliczone dane");
- return true;
- }
- private function relationName($ID) {
- if (!$ID) return '';
- if (!isset($this->relations[$ID])) {
- $query = "select RELATION from BI_audit_ALL_ref_RELATIONS where ID & '{$ID}' order by ID";
- $result = DB::getPDO()->fetchAll($query);
- $rels = array_map('reset', $result);
- $this->relations[$ID] = implode(", ", $rels);
- }
- return $this->relations[$ID];
- }
- private function splitResults() {
- $MAX = 1000;
- $countBySource = [];
- $resultsKeys = [];
- foreach ($this->results as $resultKey => $result) {
- $_keys = array_keys($result);
- $countBySource[reset($_keys)][] = $resultKey;
- }
- foreach ($countBySource as $resultKeys) {
- if (count($resultKeys) > $MAX) {
- $countByDest = [];
- foreach ($resultKeys as $resultKey) {
- $_keys = array_keys($this->results[$resultKey]);
- $countByDest[end($_keys)][] = $resultKey;
- }
- foreach ($countByDest as $resultKeys2) $resultsKeys = array_merge($resultsKeys, array_chunk($resultKeys2, $MAX));
- } else $resultsKeys[] = $resultKeys;
- }
- $results = [];
- while ($resultsKeys) {
- $resultKeys = array_shift($resultsKeys);
- while ($next = current($resultsKeys)) {
- if (count($resultKeys) + count($next) <= $MAX) {
- $resultKeys = array_merge($resultKeys, $next);
- unset($resultsKeys[key($resultsKeys)]);
- } else break; //next($resultsKeys);
- }
- $_results = [];
- foreach ($resultKeys as $key) $_results[$key] = $this->results[$key];
- $results[] = $_results;
- // $results[] = array_map(function ($resultKey) {return $this->results[$resultKey];}, $resultKeys);
- }
- if ($results) $this->splittedResults = $results;
- else $this->splittedResults[] = $this->results;
- $this->progress['summary']['reportsCount'] = count($results);
- }
- public function getPartsCount() {
- return count($this->splittedResults);
- }
- private function generateItemsResults($resultsPart = null) {
- Lib::loadClass('Teryt');
- if ($resultsPart === null) self::saveToLog("Generuję dane na potrzeby utworzenia pojedynczego pliku XML");
- else {
- self::saveToLog("Generuję dane na potrzeby utworzenia pliku XML ({$resultsPart})");
- if ($resultsPart >= $this->getPartsCount()) throw new Exception("generateItemsResults() error - bad part number");
- }
- $xmlTask = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA";
- $xmlRow = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row";
- $xmlObject = "BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object";
- $items_kontrahenci = [];
- $items_kw_person = [];
- $kontrahenci = [];
- $kw_person = [];
- $_items_results = [];
- $refUmowyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_UMOWY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- $refFakturyToKontrahenci = BiAuditRefTables::getRefTable('BI_audit_ENERGA_FAKTURY', 'BI_audit_ENERGA_RUM_KONTRAHENCI', true);
- $refKwRequestedToKwRequestedPerson = BiAuditRefTables::getRefTable('BI_audit_KW_requested', 'BI_audit_KW_requested_person', true);
- $refPracownicyToPracownicyAdresy = BiAuditRefTables::getRefTable('BI_audit_ENERGA_PRACOWNICY', 'BI_audit_ENERGA_PRACOWNICY_adresy', true);
- $this->items_results[$resultsPart] = [];
- $this->items_results[$resultsPart]['@attributes'] = ['xmlns:system_cache__dita' => 'http://biuro.biall-net.pl/xmlschema_procesy5/default_db_xml_cache/dita.xsd'];
- $this->items_results[$resultsPart][$xmlTask]['@attributes'] = ['fid' => "{$xmlTask}.{$this->ID}"];
- if ($resultsPart === null) {
- $results = $this->results;
- $parts = 0;
- } else {
- $results = (!empty($this->splittedResults[$resultsPart])) ? $this->splittedResults[$resultsPart] : [];
- $parts = count($this->splittedResults);
- $this->items_results[$resultsPart][$xmlTask]['@attributes']['system_cache__dita:part'] = ($resultsPart + 1);
- }
- for ($i = 1; $i <= $parts; $i++) {
- $this->items_results[$resultsPart][$xmlTask]['system_cache__dita:parts'][] = ['@attributes' => ['system_cache__dita:part' => $i]];
- }
- $this->items_results[$resultsPart][$xmlTask]['L_APPOITMENT_INFO'] = $this->L_APPOITMENT_INFO;
- foreach ($results as $key => $result) {
- if ($this->fidRow) $item_results = ['@attributes' => ['fid' => "{$xmlRow}.{$this->fidRow[$key]['fid']}"]];
- foreach ($result as $ID => $rel) {
- $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
- $row = DB::getPDO()->fetchFirst($query);
- $query = "select * from `{$row['REMOTE_TABLE']}` where ID = '{$row['REMOTE_ID']}'";
- $obj = DB::fetch(DB::query($query));
- $item_result = [];
- if ($this->fidRow) {
- $item_result['@attributes'] = ['fid' => "{$xmlObject}.{$this->fidRow[$key]['obj'][$ID]}"];
- }
- $item_result[$row['REMOTE_TABLE']] = array_merge(['@attributes' => ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"]], (array) $obj);
- if ($refTable = BiAuditRefTables::getRefTable('BI_audit_operational_raport_note', $row['REMOTE_TABLE'], false)) {
- $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']}'";
- $notes = DB::getPDO()->fetchAll($query);
- foreach ($notes as $note) {
- $item_result[$row['REMOTE_TABLE']]['BI_audit_operational_raport_note'][] = array_merge(['@attributes' => ['fid' => "BI_audit_operational_raport_note.{$note['ID']}"]], $note);
- }
- }
- if ($refTable = BiAuditRefTables::getRefTable($row['REMOTE_TABLE'], 'BI_audit_taxpayer', false)) {
- $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']}'";
- if ($taxpayer = DB::getPDO()->fetchFirst($query)) {
- $item_result[$row['REMOTE_TABLE']]['BI_audit_taxpayer'] = array_merge(['@attributes' => ['fid' => "BI_audit_taxpayer.{$taxpayer['ID']}"]], $taxpayer);
- }
- }
- if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_PRACOWNICY") {
- $query = "select pa.* from BI_audit_ENERGA_PRACOWNICY_adresy pa join `{$refPracownicyToPracownicyAdresy}` ref on pa.ID = ref.REMOTE_PRIMARY_KEY where ref.PRIMARY_KEY = '{$row['REMOTE_ID']}'";
- $adresy = DB::getPDO()->fetchAll($query);
- foreach ($adresy as $adres) {
- $item_result[$row['REMOTE_TABLE']]['BI_audit_ENERGA_PRACOWNICY_adresy'][] = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_PRACOWNICY_adresy.{$adres['ID']}"]], $adres);
- }
- } elseif ($row['REMOTE_TABLE'] == 'TERYT_adresy') {
- try {
- $teryt = Teryt::getNames(['SYM' => $obj->TERYT_SYM, 'SYM_UL' => $obj->TERYT_SYM_UL]);
- $item_result[$row['REMOTE_TABLE']]['TERYT_names'] = $teryt;
- } catch (Exception $e) {
- }
- }
- if ($rel) $item_result['relation_from'] = $this->relationName($rel);
- $item_results[$xmlObject][] = $item_result;
- if ($row['REMOTE_TABLE'] == "BI_audit_ENERGA_RUM_KONTRAHENCI" && (!in_array($row['REMOTE_ID'], $kontrahenci))) {
- $kontrahenci[] = $row['REMOTE_ID'];
- $query = "select faktury.* from BI_audit_ENERGA_FAKTURY faktury join `{$refFakturyToKontrahenci}` ref on faktury.ID = ref.PRIMARY_KEY where ref.REMOTE_PRIMARY_KEY = '{$row['REMOTE_ID']}'";
- $res = DB::query($query);
- $faktury = [];
- if (mysql_num_rows($res)) {
- while ($obj = DB::fetch($res)) {
- $faktura = (array) $obj;
- $faktura = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_FAKTURY.{$faktura['ID']}"]], $faktura);
- $faktury[] = $faktura;
- }
- }
- $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']}'";
- $res = DB::query($query);
- $umowy = [];
- if (mysql_num_rows($res)) {
- while ($obj = DB::fetch($res)) {
- $umowa = (array) $obj;
- $umowa = array_merge(['@attributes' => ['fid' => "BI_audit_ENERGA_RUM_UMOWY.{$umowa['ID']}"]], $umowa);
- $umowy[] = $umowa;
- }
- }
- if ($faktury || $umowy) {
- $item_kontrahenci = [];
- $item_kontrahenci['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
- $item_kontrahenci['ID'] = $row['REMOTE_ID'];
- if ($faktury) $item_kontrahenci['BI_audit_ENERGA_FAKTURY'] = $faktury;
- if ($umowy) $item_kontrahenci['BI_audit_ENERGA_RUM_UMOWY'] = $umowy;
- $items_kontrahenci[] = $item_kontrahenci;
- }
- } elseif ($row['REMOTE_TABLE'] == "BI_audit_KW_requested_person" && (!in_array($row['REMOTE_ID'], $kw_person))) {
- $kw_person[] = $row['REMOTE_ID'];
- $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']}'";
- $res = DB::query($query);
- if (mysql_num_rows($res)) {
- $kws = [];
- while ($obj = DB::fetch($res)) {
- $kw = (array) $obj;
- $kw = array_merge(['@attributes' => ['fid' => "BI_audit_KW_requested.{$kw['ID']}"]], $kw);
- $kws[] = $kw;
- }
- $item_kw_person['@attributes'] = ['fid' => "{$row['REMOTE_TABLE']}.{$row['REMOTE_ID']}"];
- $item_kw_person['ID'] = $row['REMOTE_ID'];
- $item_kw_person['BI_audit_KW_requested'] = $kws;
- $items_kw_person[] = $item_kw_person;
- }
- }
- }
- $this->items_results[$resultsPart][$xmlTask][$xmlRow][] = $item_results;
- }
- $this->items_results[$resultsPart][$xmlTask]['BI_audit_ENERGA_RUM_KONTRAHENCI'] = $items_kontrahenci;
- $this->items_results[$resultsPart][$xmlTask]['BI_audit_KW_requested_person'] = $items_kw_person;
- self::saveToLog("Wygenerowano dane na potrzeby utworzenia pliku XML ({$resultsPart})");
- }
- private function saveToDb($result = null, $key = null) {
- if ($result === null) {
- self::saveToLog("Zapisuję wyliczone dane do bazy");
- if (!$this->results) {
- self::saveToLog("Brak wyliczonych danych - nie zapisaono niczego do bazy");
- return null;
- }
- foreach ($this->results as $key => $result) $this->saveToDb($result, $key);
- self::saveToLog("Zapisano wyliczone dane do bazy");
- } else {
- if ($key === null) {
- end($this->results);
- $key = key($this->results);
- }
- $refPowiazaniaToPowiazaniaRow = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', true);
- $refPowiazaniaRowToPowiazaniaRowObject = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', 'BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', true);
- $IdPowiazaniaRow = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row', []);
- $fidObj = [];
- DB::getPDO()->insert($refPowiazaniaToPowiazaniaRow, ['PRIMARY_KEY' => $this->ID, 'REMOTE_PRIMARY_KEY' => $IdPowiazaniaRow]);
- foreach ($result as $ID => $rel) {
- $query = "select REMOTE_TABLE, REMOTE_ID from BI_audit_ALL where ID = '{$ID}'";
- $object = DB::getPDO()->fetchFirst($query);
- $idPowiazaniaRowObject = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', ['relation_from' => $this->relationName($rel)]);
- DB::getPDO()->insert($refPowiazaniaRowToPowiazaniaRowObject, ['PRIMARY_KEY' => $IdPowiazaniaRow, 'REMOTE_PRIMARY_KEY' => $idPowiazaniaRowObject]);
- $ref = BiAuditRefTables::getRefTable('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row_object', $object['REMOTE_TABLE'], true);
- DB::getPDO()->insert($ref, ['PRIMARY_KEY' => $idPowiazaniaRowObject, 'REMOTE_PRIMARY_KEY' => $object['REMOTE_ID']]);
- $fidObj[$ID] = $idPowiazaniaRowObject;
- }
- $this->fidRow[$key] = [
- 'fid' => $IdPowiazaniaRow,
- 'obj' => $fidObj,
- ];
- }
- }
- public function saveXml($resultsPart = null) {
- if ($this->getPartsCount()) {
- if ($resultsPart === null) {
- self::saveToLog("Generuję pliki XML (liczba plików do wygenerowania: {$this->getPartsCount()})");
- for ($i =0; $i < $this->getPartsCount(); $i++) {
- $partNo = str_pad($i + 1, 6, '0', STR_PAD_LEFT);
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
- file_put_contents($xmlFile, $this->asXml($i));
- }
- self::saveToLog("Zakończono generowanie plików XML");
- } else {
- if ($resultsPart >= $this->getPartsCount()) {
- self::saveToLog("saveXml() error - bad result number");
- return;
- }
- $partNo = str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}_{$partNo}.xml";
- file_put_contents($xmlFile, $this->asXml($resultsPart));
- }
- } else {
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$this->ID}.xml";
- file_put_contents($xmlFile, $this->asXml());
- }
- }
- public function asXml($resultsPart = null) {
- self::saveToLog("Generuję plik XML ({$resultsPart})");
- if (!$this->results) {
- self::saveToLog("Brak wyników (#1), wygenerowano pusty plik XML ({$resultsPart})");
- // self::saveToLog("Brak wyników (#1), nie wygenerowano pliku XML ({$resultsPart})");
- // return null;
- }
- if (!isset($this->items_results[$resultsPart])) $this->generateItemsResults($resultsPart);
- if (!isset($this->items_results[$resultsPart])) {
- self::saveToLog("Brak wyników (#2), nie wygenerowano pliku XML ({$resultsPart})");
- return null;
- }
- $xmlRoot = "RelatedFeatureRoot";
- $return = V::arrayToXML($this->items_results[$resultsPart], true, $xmlRoot);
- self::saveToLog("Wygenerowano plik XML ({$resultsPart})");
- return $return;
- }
- public function asArray($resultsPart = null, $subArray = null) {
- if (!$this->results) return null;
- if (!$this->items_results[$resultsPart]) $this->generateItemsResults($resultsPart);
- if (!$this->items_results[$resultsPart]) return null;
- if ($subArray) {
- if (isset($this->items_results[$resultsPart][$subArray])) return $this->items_results[$subArray];
- else return [];
- } else return $this->items_results[$resultsPart];
- }
- public function powiazaniaFound() {
- if ($this->results) return true;
- else return false;
- }
- public function generatePdfAndHtml() {
- $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
- if (!file_exists($antDir)) mkdir($antDir, 0770, true);
- if (!is_dir($antDir)) {
- $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików PDF i HTML";
- self::saveToLog("Nie wygenerowano plików PDF oraz HTML - problem z utworzeniem katalogu dla ant ({$resultsPart})");
- $this->saveProgress(['reportsCreated' => 1]);
- return;
- }
- $this->saveProgress(['step' => 'reports']);
- if ($this->getPartsCount()) {
- self::saveToLog("Generuję raporty w plikach PDF oraz HTML (liczba raportów do wygenerowania: {$this->getPartsCount()})");
- for ($i =0; $i < $this->getPartsCount(); $i++) $this->_generatePdfAndHtml($i);
- self::saveToLog("Zakończono generowanie raportów w plikach PDF oraz HTML");
- } else $this->_generatePdfAndHtml();
- }
- private function _generatePdfAndHtml($resultsPart = null) {
- $id_part = $resultsPart === null ? $this->ID : $this->ID . "_" . str_pad($resultsPart + 1, 6, '0', STR_PAD_LEFT);
- self::saveToLog("Generuję raport w pliku PDF oraz HTML ({$resultsPart})");
- $xmlFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.xml";
- $pdfDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.pdf";
- $htmlDestDir = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.html";
- $htmlZipDestFile = "{$this->tasksDirLocation}/generatePowiazania-{$id_part}.zip";
- $antDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/recurse_ant/out";
- $antXmlFilename = "relations-{$id_part}.out_task.dita.final_with_RelatedFeatureLoop.xml";
- $antXmlFile = $antDir . "/" . $antXmlFilename;
- //$baseDir = "/Library/Server/Web/Data/Sites/Default/SE/schema/WPS_Functions/default_db/CRM_PROCES_tree/temp/relations-{$id_part}";
- $baseDir = "/opt/local/pl.procesy5/p5build_SE/temp/WPS_Functions/default_db/CRM_PROCES_tree/relations-{$id_part}";
- $ditamapFile = "{$baseDir}/relations-{$id_part}.ditamap";
- $pdfFile = "{$baseDir}/pdf/relations-{$id_part}.pdf";
- $htmlDir = "{$baseDir}/html";
- $htmlFile = "{$htmlDir}/relations-{$id_part}.html";
- //if (!file_exists($xmlFile))
- $this->saveXml($resultsPart);
- if (!file_exists($xmlFile)) {
- $sqlArr['FILE_STATUS_info'] .= ", ale nie udało się utworzyć plików XML, PDF i HTML";
- self::saveToLog("Nie wygenerowano plików XML, PDF oraz HTML - problem z wygenerowaniem pliku XML ({$resultsPart})");
- $this->saveProgress(['reportsCreated' => 1]);
- return;
- }
- $this->saveProgress(['reportsCreated' => 0.05]);
- copy($xmlFile, $antXmlFile);
- self::saveToLog("Generuję plik przejściowy do wygenerowania plików PDF i HTML ({$resultsPart})");
- 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}");
- if (file_exists($ditamapFile))
- {
- self::saveToLog("Wygenerowano plik przejściowy");
- $this->saveProgress(['reportsCreated' => 0.15]);
- } else {
- self::saveToLog("Nie udało się wygenerować pliku przejściowego, przerywm");
- $this->saveProgress(['reportsCreated' => 1]);
- return;
- }
- self::saveToLog("Generuję plik PDF ({$resultsPart})");
- 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");
- if (file_exists($pdfFile)) {
- rename($pdfFile, $pdfDestFile);
- self::saveToLog("Wygenerowano plik PDF ({$resultsPart})");
- } else self::saveToLog("Nie udało się wygenerować pliku PDF ({$resultsPart})");
- $this->saveProgress(['reportsCreated' => 0.45]);
- self::saveToLog("Generuję pliki HTML ({$resultsPart})");
- 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");
- if (file_exists($htmlDir) && is_dir($htmlDir) && file_exists($htmlFile)) {
- self::exec("cd \"{$baseDir}\" && zip -r \"{$htmlZipDestFile}\" html");
- if (file_exists($htmlDestDir)) self::exec("rm -rf \"{$htmlDestDir}\"");
- self::exec("mv \"{$htmlDir}\" \"{$htmlDestDir}\"");
- self::saveToLog("Wygenerowano pliki HTML ({$resultsPart})");
- } else self::saveToLog("Nie udało się wygenerować plików HTML {$resultsPart})");
- $this->saveProgress(['reportsCreated' => 0.35]);
- }
- }
|