Budget.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. class Route_Budget extends RouteBase {
  4. private $_costs = array();
  5. private $_plan = array();
  6. private $_projectInfo = array();
  7. private $_projectPathsOrder = array();
  8. public function handleAuth() {
  9. if (!User::logged()) {
  10. throw new HttpException('Unauthorized', 401);
  11. }
  12. }
  13. public function defaultAction() {
  14. $args = array();
  15. $args['year'] = V::get('year', '', $_REQUEST, 'int');
  16. $args['_print'] = V::get('_print', '', $_REQUEST, 'int');
  17. SE_Layout::gora();
  18. SE_Layout::menu();
  19. if (!$args['_print']) {
  20. $this->menu($args['year']);
  21. }
  22. SE_Layout::dol();
  23. }
  24. public function yearBudgetAction() {
  25. $args = array();
  26. $args['year'] = V::get('year', '', $_REQUEST, 'int');
  27. $args['_print'] = V::get('_print', '', $_REQUEST, 'int');
  28. SE_Layout::gora();
  29. SE_Layout::menu();
  30. if (!$args['_print']) {
  31. $this->menu($args['year']);
  32. }
  33. if (empty($args['year'])) {
  34. ?>
  35. <div class="alert alert-warning">
  36. Nie wybrano roku.
  37. </div>
  38. <?php
  39. SE_Layout::dol();
  40. exit;
  41. }
  42. $hasData = $this->fetchDataByYear($args['year']);
  43. if (!$hasData) {
  44. ?>
  45. <div class="alert alert-warning">
  46. Brak danych na wybrany rok.
  47. </div>
  48. <?php
  49. return;
  50. }
  51. //echo'<pre style="border:1px solid red;overflow:auto;max-height:400px">$costs: ';print_r($costs);echo'</pre>';
  52. $this->printCostsForYear($args['year']);
  53. SE_Layout::dol();
  54. }
  55. private function menu($selectedYear) {
  56. //SE_Layout::menu();
  57. $year = ($selectedYear)? $selectedYear : date("Y");
  58. ?>
  59. <div class="jumbotron">
  60. <div class="container">
  61. <form class="form-inline" method="POST">
  62. <input type="hidden" name="_task" value="yearBudget" />
  63. <label for="year">Zestawienie kosztów projektów na podstawie korespondencji:</label>
  64. <div class="input-group date" id="fldZestYear">
  65. <input type="text" name="year" class="form-control" value="" />
  66. <span class="input-group-addon"><span class="glyphicon glyphicon-time"></span></span>
  67. </div>
  68. <button type="submit" id="fldZestYearBtn" class="btn btn-primary" autocomplete="off">
  69. Pokaż
  70. </button>
  71. </form>
  72. </div>
  73. </div>
  74. <script type="text/javascript">
  75. jQuery(document).ready(function () {
  76. jQuery('#fldZestYearBtn').on('click', function () {
  77. jQuery(this).text(jQuery(this).text() + '...').attr('disabled', 'disabled');
  78. jQuery(this).parent().submit();
  79. })
  80. jQuery("#fldZestYear").datetimepicker({
  81. format: "YYYY",
  82. defaultDate: new Date(<?php echo $year; ?>, <?php echo intval(date("m")); ?>, 1),
  83. // minDate: new Date(2014, 11, 1),
  84. // maxDate: "<?php echo date("Y"); ?>"
  85. });
  86. });
  87. </script>
  88. <?php
  89. }
  90. function css() {
  91. ?>
  92. <style type="text/css">
  93. .c { text-align:center; }
  94. .r { text-align:right; }
  95. .zestawienie-kosztow-tbl { border-collapse:collapse; border:1px solid #aaa; }
  96. .zestawienie-kosztow-tbl td { border:1px solid #aaa; }
  97. .zestawienie-kosztow-tbl .p2 { padding:0 2px; }
  98. .zestawienie-kosztow-tbl .nr { color:#7A7A7A; }
  99. .zestawienie-kosztow-tbl thead th { border:1px solid #aaa; }
  100. .zestawienie-kosztow-tbl tbody tr:hover td { background:#cafbfd; }
  101. .row-selected td {background-color:#d8fded;}
  102. .showOnlySelected tr { display:none; }
  103. .showOnlySelected tr.row-selected { display:table-row; }
  104. .cell-cost { padding:0 2px; min-width:30px; text-align:right; }
  105. .cell-cost-only_self { color:#197fe6; }
  106. .cell-cost-self_and_child { color:#33b2cc; }
  107. .cell-cost-only_child { color:#59a680; }
  108. .cell-plan { padding:0 2px; min-width:30px; text-align:right; color:#777; }
  109. .cell-procent { padding:0 2px; min-width:20px; text-align:right; color:#777; }
  110. .cell-procent-below100 { color:#777; }
  111. .cell-procent-100 { color:#777; }
  112. .cell-procent-over100 { color:#ff9b00; }
  113. .cell-procent-over200 { color:#f00; }
  114. /* print table background colors */
  115. table td, table th { -webkit-print-color-adjust:exact; }
  116. table { page-break-after:auto }
  117. tr { page-break-inside:avoid; page-break-after:auto; position:relative; }
  118. td { page-break-inside:avoid; page-break-after:auto; position:relative; }
  119. thead { display:table-header-group }
  120. tfoot { display:table-footer-group }
  121. </style>
  122. <?php
  123. }
  124. function printCostsForYear($year) {
  125. $months = array();
  126. for ($i = 0; $i < 12; $i++) {
  127. $months[] = $i + 1;
  128. }
  129. $this->css();
  130. if(V::get('DBG','',$_GET)){echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;display:none">';print_r($this->_costs);echo'</pre>';}
  131. ?>
  132. <div class="container">
  133. <div style="float:right;color:#aaa;"><?php echo date("Y-m-d"); ?></div>
  134. <h1>Zestawienie kosztów projektów na rok <?php echo $year; ?></h1>
  135. </div>
  136. <table cellspacing="0" cellpadding="0" border="0" id="zestawienie-kosztow-projektow" class="zestawienie-kosztow-tbl">
  137. <thead>
  138. <tr>
  139. <td colspan="3" class="p2">
  140. <span class="pull-right"><b>miesiąc</b></span>
  141. </td>
  142. <?php foreach ($months as $month) { ?>
  143. <th class="c" colspan="3"><?php echo sprintf("%02d", $month); ?></th>
  144. <?php } ?>
  145. </tr>
  146. <tr>
  147. <td colspan="3" class="p2">
  148. <span class="pull-left">
  149. <input type="checkbox" onclick="return showHideAll(this);"/> pokaż tylko zaznaczone
  150. </span>
  151. </td>
  152. <?php foreach ($months as $month) { ?>
  153. <th class="c" title="Koszty wprowadzone do korespondencji">Koszty</th>
  154. <th class="c" title="Plan budżetu">Plan</th>
  155. <th class="c" title="Procent przekroczenia planu">%</th>
  156. <?php } ?>
  157. </tr>
  158. </thead>
  159. <tbody>
  160. <?php $t = 1; ?>
  161. <?php foreach ($this->_projectPathsOrder as $projPath => $projId) : ?>
  162. <?php $projectID = $projId; ?>
  163. <?php $projectDesc = $this->_projectInfo[$projId]->M_DIST_DESC; ?>
  164. <?php $projectPath = $this->_projectInfo[$projId]->path; ?>
  165. <tr class="row-<?php echo ($t = 1 - $t); ?>"
  166. data-proj_id="<?php echo $projectID; ?>"
  167. data-path="<?php echo $projectPath; ?>">
  168. <td class="p2 r nr">
  169. <input type="checkbox" name="selectedProject" onclick="return selectProject(this);" value="<?php echo $projectID; ?>" />
  170. </td>
  171. <td class="p2 l nr"><nobr><?php echo $projectPath; ?></nobr></td>
  172. <td class="p2" style="max-width:300px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?php echo $projectDesc; ?>"><?php echo $projectDesc; ?></td>
  173. <?php foreach ($months as $month) : ?>
  174. <?php $vMonthCost = $this->getCost($projectID, $month); ?>
  175. <?php $monthCostTotal = ($vMonthCost)? $vMonthCost->COST_TOTAL : 0; ?>
  176. <?php if (!$vMonthCost) : ?>
  177. <td style="min-width:30px">&nbsp;</td>
  178. <?php else : ?>
  179. <?php
  180. $vCostChildOut = number_format($vMonthCost->COST_CHILD, 2);
  181. $vCostSelfOut = number_format($vMonthCost->COST_SELF, 2);
  182. $vCostTotalOut = number_format($vMonthCost->COST_TOTAL, 2);
  183. $title = "Koszt projektu {$vCostSelfOut} / koszt podprojektów $vCostChildOut";
  184. $cellCostCls = '';
  185. if ($vMonthCost->COST_CHILD > 0) {
  186. if ($vMonthCost->COST_SELF > 0) {
  187. $cellCostCls = 'cell-cost-self_and_child';
  188. } else {
  189. $cellCostCls = 'cell-cost-only_child';
  190. }
  191. } else {
  192. $cellCostCls = 'cell-cost-only_self';
  193. }
  194. ?>
  195. <td class="cell-cost <?php echo $cellCostCls; ?>"
  196. data-month_num="<?php echo $month; ?>"
  197. data-cost="<?php echo $vCostTotalOut; ?>"
  198. data-proj_path="<?php echo $projectPath; ?>"
  199. data-proj_id="<?php echo $projectID; ?>">
  200. <span class="ttip" title="<?php echo $title; ?>"><?php echo $vCostTotalOut; ?></span>
  201. </td>
  202. <?php endif; ?>
  203. <td class="cell-plan">
  204. <?php $monthPlan = $this->getPlan($projectID, $month); ?>
  205. <?php $monthPlanOut = number_format($monthPlan, 2); ?>
  206. <?php if ($monthPlan > 0) : ?>
  207. <?php echo $monthPlan; ?>
  208. <?php else : ?>
  209. &nbsp;
  210. <?php endif; ?>
  211. </td>
  212. <?php
  213. $cellProcentCls = '';
  214. $procentOut = '&nbsp;';
  215. $monthPlan = $this->getPlan($projectID, $month);
  216. if ($monthPlan > 0) {
  217. $procentOut = round(($monthCostTotal * 100) / $monthPlan);
  218. if ($procentOut > 200) {
  219. $cellProcentCls = 'cell-procent-over200';
  220. } else if ($procentOut > 100) {
  221. $cellProcentCls = 'cell-procent-over100';
  222. } else if ($procentOut == 100) {
  223. $cellProcentCls = 'cell-procent-100';
  224. } else {
  225. $cellProcentCls = 'cell-procent-below100';
  226. }
  227. }
  228. ?>
  229. <td class="cell-procent <?php echo $cellProcentCls; ?>"><?php echo $procentOut; ?></td>
  230. <?php endforeach; ?>
  231. </tr>
  232. <?php endforeach; ?>
  233. </tbody>
  234. </table>
  235. <script>
  236. jQuery(document).ready(function() {
  237. jQuery('#zestawienie-kosztow-projektow')
  238. .find('.cell-cost')
  239. .on('click', function(e) {
  240. var $n = jQuery(this),
  241. $modal = jQuery('#projectMonthCostDetails'),
  242. projId = $n.data('proj_id'),
  243. monthNum = $n.data('month_num'),
  244. projPath = '' + $n.data('proj_path'),
  245. projPathLength = projPath.length,
  246. modalBody = document.createElement('table'),
  247. totalDescrCell = document.createElement('td'),
  248. totalCostCell = document.createElement('td'),
  249. totalEmptyCell = document.createElement('td'),
  250. totalRow = document.createElement('tr');
  251. modalBody.className = 'zestawienie-kosztow-tbl';
  252. modalBody.style.width = '100%';
  253. // $n.data() = {proj_id: 3943, proj_path: "0-4132-3943", month_num: 2}
  254. // table#proj-koresp-info > tbody#row-proj-2055-koresp-by-month-2
  255. jQuery('#proj-koresp-info').find('tbody').each(function(i, tbody) {
  256. var vPath = jQuery(tbody).data('proj_path'),
  257. vMonthNum = jQuery(tbody).data('month_num');
  258. if (monthNum != vMonthNum) return;
  259. if (projPathLength > vPath.length) return;
  260. if (projPath == vPath
  261. || (projPathLength < vPath.length && projPath + '-' == vPath.substr(0, projPathLength + 1))
  262. ) {
  263. modalBody.appendChild(tbody.cloneNode(true));
  264. }
  265. });
  266. {
  267. totalDescrCell.className = 'p2';
  268. totalDescrCell.style.textAlign = 'right';
  269. totalDescrCell.setAttribute('colspan', '2');
  270. totalDescrCell.appendChild(document.createTextNode('Suma:'));
  271. totalCostCell.className = 'cell-cost';
  272. totalCostCell.style.textAlign = 'right';
  273. totalCostCell.appendChild(document.createTextNode($n.data('cost')));
  274. totalRow.appendChild(totalDescrCell);
  275. totalRow.appendChild(totalCostCell);
  276. modalBody.appendChild(totalRow);
  277. }
  278. $modal.find('.modal-title').text('Koszty projektu nr ' + projId + ' w miesiącu <?php echo $year; ?>-' + ((monthNum > 9)? monthNum : '0' + monthNum));
  279. $modal.find('.modal-body').html(modalBody);
  280. $modal.modal({});
  281. })
  282. })
  283. </script>
  284. <!-- Modal -->
  285. <div class="modal fade" id="projectMonthCostDetails" tabindex="-1" role="dialog" aria-labelledby="projectCostDMonthetailsLabel">
  286. <div class="modal-dialog" role="document" style="min-width:800px;">
  287. <div class="modal-content">
  288. <div class="modal-header">
  289. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  290. <h4 class="modal-title" id="projectCostDMonthetailsLabel">Modal title</h4>
  291. </div>
  292. <div class="modal-body">
  293. TODO: projectMonthCostDetails...
  294. </div>
  295. <div class="modal-footer">
  296. <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  297. </div>
  298. </div>
  299. </div>
  300. </div>
  301. <table id="proj-koresp-info" style="display:none">
  302. <?php foreach ($this->_projectPathsOrder as $projPath => $projId) : ?>
  303. <?php
  304. $projectInfo = $this->_costs[$projId];
  305. if (!$projectInfo) {
  306. continue;
  307. }
  308. $projectID = $projId;
  309. $projectDesc = $this->_projectInfo[$projId]->M_DIST_DESC;
  310. $projectPath = $this->_projectInfo[$projId]->path;
  311. ?>
  312. <?php if (!empty($projectInfo->korespByMonth)) : ?>
  313. <?php foreach ($projectInfo->korespByMonth as $kMonth => $vKorespMonthList) : ?>
  314. <tbody id="row-proj-<?php echo $projectID; ?>-koresp-by-month-<?php echo $kMonth; ?>"
  315. data-month_num="<?php echo $kMonth; ?>"
  316. data-proj_path="<?php echo $projectPath; ?>"
  317. data-proj_id="<?php echo $projectID; ?>">
  318. <tr>
  319. <td style="padding:3px;font-size:1em;background:#eee;"><nobr><?php echo $projectPath; ?></nobr></td>
  320. <td colspan="3" style="padding:3px;font-size:1.1em;background:#eee;max-width:500px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?php echo $projectDesc; ?>">
  321. <!-- Koszty projektu nr <?php echo $projectID; ?> -->
  322. <!-- - miesiąc <?php echo $year; ?>-<?php echo sprintf("%02d", $kMonth); ?> -->
  323. <?php echo $projectDesc; ?>
  324. </td>
  325. </tr>
  326. <?php foreach ($vKorespMonthList as $kKorespIdx => $vKorespInfo) : ?>
  327. <?php /*
  328. * [ID] => 41235
  329. * [MONTH] => 2015-02
  330. * [K_ZAWARTOS] => Faktura za pomiar powykonawczy sieci telekomunikacyjnej
  331. * [COST] => 1000.00
  332. * [INCOME] => 0.00
  333. ? [TRANSFER_OPPOSITE_ID_PROJECT] => int
  334. */ ?>
  335. <tr>
  336. <td class="p2 r nr"><?php echo $vKorespInfo->ID; ?></td>
  337. <td class="p2" style="max-width:400px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?php echo $vKorespInfo->K_ZAWARTOS; ?>"><?php echo $vKorespInfo->K_ZAWARTOS; ?></td>
  338. <?php $vKorespCostOut = number_format($vKorespInfo->COST, 2); ?>
  339. <td class="cell-cost cell-cost-only_child"><?php echo $vKorespCostOut; ?></td>
  340. <td>
  341. <?php $dekretId = V::get('TRANSFER_OPPOSITE_ID_PROJECT', 0, $vKorespInfo) ?>
  342. <?php if ($dekretId > 0) : ?>
  343. Dekret z projektu nr <?php echo $dekretId; ?>
  344. <?php endif; ?>
  345. </td>
  346. </tr>
  347. <?php endforeach; ?>
  348. </tbody>
  349. <?php endforeach; ?>
  350. <?php endif; ?>
  351. <?php endforeach; ?>
  352. </table>
  353. <script>
  354. jQuery(document).ready(function(){
  355. jQuery('.ttip').tooltip();
  356. });
  357. function selectProject(n) {
  358. var $n = jQuery(n);
  359. var $p = $n.parent().parent();
  360. if (n.checked) {
  361. $p.addClass('row-selected');
  362. } else {
  363. $p.removeClass('row-selected');
  364. }
  365. markSubProjects($p, $p.data('path'), n.checked);
  366. function markSubProjects($p, path, checked) {
  367. var $nextRow = $p.next('tr'),
  368. nextPath = $nextRow.data('path'),
  369. nextCheckbox = $nextRow.find('input[type="checkbox"]').get(0);
  370. if (0 !== nextPath.indexOf(path)) {
  371. return;
  372. }
  373. if (checked) {
  374. $nextRow.addClass('row-selected');
  375. } else {
  376. $nextRow.removeClass('row-selected');
  377. }
  378. nextCheckbox.checked = checked;
  379. markSubProjects($nextRow, path, checked);
  380. }
  381. }
  382. function showHideAll(n) {
  383. if (n.checked) {
  384. jQuery('#zestawienie-kosztow-projektow').find('tbody').addClass('showOnlySelected');
  385. } else {
  386. jQuery('#zestawienie-kosztow-projektow').find('tbody').removeClass('showOnlySelected');
  387. }
  388. }
  389. </script>
  390. <?php
  391. }
  392. public function getCost($idProject, $month) {
  393. if (!array_key_exists($idProject, $this->_costs)) {
  394. return null;
  395. }
  396. if (!array_key_exists($month, $this->_costs[$idProject]->costsByMonth)) {
  397. return null;
  398. }
  399. return $this->_costs[$idProject]->costsByMonth[$month];
  400. }
  401. public function getPlan($idProject, $month) {
  402. if (!array_key_exists($idProject, $this->_plan)) {
  403. return 0;
  404. }
  405. if (!array_key_exists($month, $this->_plan[$idProject])) {
  406. return 0;
  407. }
  408. return $this->_plan[$idProject][$month];
  409. }
  410. public function fetchDataByYear($year) {
  411. $this->_fetchCostsByYear($year);
  412. $this->_fetchPlanByYear($year);
  413. $this->_fetchProjectInfo();
  414. $this->_buildProjectTree();
  415. $this->_reacountCostsFromKoresp();
  416. return count($this->_projectInfo) > 1;// $this->_projectInfo[0] - Wszystkie projekty
  417. }
  418. public function _fetchPlanByYear($year) {
  419. $db = DB::getDB();
  420. $this->_plan = array();
  421. $sql = "
  422. select plan.`ID`
  423. , plan.`ID_PROJECT` AS `ID_PROJECT`
  424. , plan.`MONTH_1_VALUE`
  425. , plan.`MONTH_2_VALUE`
  426. , plan.`MONTH_3_VALUE`
  427. , plan.`MONTH_4_VALUE`
  428. , plan.`MONTH_5_VALUE`
  429. , plan.`MONTH_6_VALUE`
  430. , plan.`MONTH_7_VALUE`
  431. , plan.`MONTH_8_VALUE`
  432. , plan.`MONTH_9_VALUE`
  433. , plan.`MONTH_10_VALUE`
  434. , plan.`MONTH_11_VALUE`
  435. , plan.`MONTH_12_VALUE`
  436. from `projects_budget_year_month` plan
  437. where plan.`year`='{$year}'
  438. -- TODO: acl
  439. ";
  440. //echo'<pre style="border:1px solid red;overflow:auto;max-height:400px">';print_r($sql);echo'</pre>';
  441. $res = $db->query($sql);
  442. while ($r = $db->fetch($res)) {
  443. $plan = array();
  444. for ($i = 1; $i < 12; $i++) {
  445. $plan[$i] = V::get("MONTH_{$i}_VALUE", 0, $r);
  446. }
  447. $this->_plan[$r->ID_PROJECT] = $plan;
  448. }
  449. return $this->_plan;
  450. }
  451. public function _fetchCostsByYear($year) {
  452. $db = DB::getDB();
  453. $this->_costs = array();
  454. $sql = "
  455. select k.`ID`
  456. , k.`ID_PROJECT` AS `ID_PROJECT`
  457. , date_format(k.`K_DATA_OTRZYMANEJ_KORESP`,'%Y-%m') AS `MONTH`
  458. , k.`COST_VALUE` AS `COST`
  459. , k.`INCOME_VALUE` AS `INCOME`
  460. , 0 as `TRANSFER_OPPOSITE_ID_PROJECT` -- TRANSFER_OPPOSITE_ID_PROJECT
  461. , k.`path`
  462. -- , IF(k.`TRANSFER_OPPOSITE_ID_PROJECT`>0
  463. -- , (select p.`path`
  464. -- from `IN7_MK_BAZA_DYSTRYBUCJI` p
  465. -- where p.`ID`=k.`TRANSFER_OPPOSITE_ID_PROJECT`
  466. -- limit 1
  467. -- )
  468. -- , '') as TRANSFER_OPPOSITE_PROJECT_PATH
  469. , '' as TRANSFER_OPPOSITE_PROJECT_PATH
  470. , k.`K_ZAWARTOS`
  471. from `IN7_DZIENNIK_KORESP` k
  472. where ((k.`COST_VALUE` > 0) or (k.`INCOME_VALUE` > 0))
  473. and k.`K_DATA_OTRZYMANEJ_KORESP` like '{$year}-%'
  474. -- TODO: acl
  475. ";
  476. //echo'<pre style="border:1px solid red;overflow:auto;max-height:400px">';print_r($sql);echo'</pre>';
  477. $res = $db->query($sql);
  478. while ($r = $db->fetch($res)) {
  479. $vProjId = ($r->ID_PROJECT > 0)? $r->ID_PROJECT : 0;
  480. $vProjPaths = array();
  481. $vProjIds = array(0 => true);
  482. if ($r->ID_PROJECT > 0) {
  483. $vProjPaths[] = $r->ID_PROJECT;
  484. if (!empty($r->path)) {
  485. $vProjPaths[] = $r->path;
  486. }
  487. }
  488. if ($r->TRANSFER_OPPOSITE_ID_PROJECT > 0) {
  489. $vProjPaths[] = $r->TRANSFER_OPPOSITE_ID_PROJECT;
  490. if (!empty($r->TRANSFER_OPPOSITE_PROJECT_PATH)) {
  491. $vProjPaths[] = $r->TRANSFER_OPPOSITE_PROJECT_PATH;
  492. }
  493. }
  494. if (!empty($vProjPaths)) {
  495. //echo'<p>DBG:$r->ID_PROJECT['.$r->ID_PROJECT.']: $vProjPaths = ' . json_encode($vProjPaths) . '</p>';
  496. $vProjPaths = implode('-', $vProjPaths);
  497. $projIds = explode('-', $vProjPaths);
  498. //echo'<p>DBG:$r->ID_PROJECT['.$r->ID_PROJECT.']: $projIds = ' . json_encode($projIds) . '</p>';
  499. foreach ($projIds as $vProjId) {
  500. if ($vProjId > 0) $vProjIds[$vProjId] = true;
  501. }
  502. }
  503. {
  504. $projectZeroInfo = new stdClass();
  505. $projectZeroInfo->ID_PROJECT = 0;
  506. $projectZeroInfo->costsByMonth = array();
  507. $projectZeroInfo->korespByMonth = array();
  508. $this->_costs[0] = $projectZeroInfo;
  509. }
  510. foreach ($vProjIds as $vProjId => $vBool) {
  511. if (!array_key_exists($vProjId, $this->_costs)) {
  512. $projectInfo = new stdClass();
  513. $projectInfo->ID_PROJECT = $vProjId;
  514. $projectInfo->costsByMonth = array();
  515. $projectInfo->korespByMonth = array();
  516. $this->_costs[$vProjId] = $projectInfo;
  517. }
  518. }
  519. $korespInfo = new stdClass();
  520. $korespInfo->ID = $r->ID;
  521. $korespInfo->MONTH = $r->MONTH;
  522. $korespInfo->K_ZAWARTOS = $r->K_ZAWARTOS;
  523. $monthNum = intval(substr($r->MONTH, 5, 2));
  524. if ($r->TRANSFER_OPPOSITE_ID_PROJECT > 0) {
  525. $korespInfo->COST = $r->COST;
  526. $korespInfo->INCOME = $r->INCOME;
  527. $korespInfo->TRANSFER_OPPOSITE_ID_PROJECT = $r->TRANSFER_OPPOSITE_ID_PROJECT;
  528. $this->_costs[$r->TRANSFER_OPPOSITE_ID_PROJECT]->korespByMonth[$monthNum][] = $korespInfo;
  529. } else if ($r->ID_PROJECT) {
  530. $korespInfo->COST = $r->COST;
  531. $korespInfo->INCOME = $r->INCOME;
  532. $this->_costs[$r->ID_PROJECT]->korespByMonth[$monthNum][] = $korespInfo;
  533. } else {
  534. $korespInfo->COST = $r->COST;
  535. $korespInfo->INCOME = $r->INCOME;
  536. $this->_costs[0]->korespByMonth[$monthNum][] = $korespInfo;
  537. }
  538. }
  539. return $this->_costs;
  540. }
  541. private function _fetchProjectInfo() {
  542. $db = DB::getDB();
  543. $projectIds = array();
  544. $projectsFromCostIds = array_keys($this->_costs);
  545. foreach ($projectsFromCostIds as $idProject) $projectIds[$idProject] = true;
  546. $projectsFromPlanIds = array_keys($this->_plan);
  547. foreach ($projectsFromPlanIds as $idProject) $projectIds[$idProject] = true;
  548. foreach ($projectIds as $idProject => $vBool) $this->_projectInfo[$idProject] = new stdClass();
  549. $projectIds = array_keys($projectIds);
  550. $sqlProjIds = "'" . implode("','", $projectIds) . "'";
  551. $sql = "select p.`ID`, p.`P_ID`, p.`path`, p.`M_DIST_DESC`
  552. from `IN7_MK_BAZA_DYSTRYBUCJI` p
  553. where p.`ID` in({$sqlProjIds})
  554. ";
  555. $res = $db->query($sql);
  556. while ($r = $db->fetch($res)) {
  557. $this->_projectInfo[$r->ID]->path = $r->path;
  558. $this->_projectInfo[$r->ID]->M_DIST_DESC = $r->M_DIST_DESC;
  559. }
  560. $this->_projectInfo[0]->path = '0';
  561. $this->_projectInfo[0]->M_DIST_DESC = "Wszystkie projekty";
  562. }
  563. private function _reacountCostsFromKoresp() {
  564. $projMonthHasCostSelfIds = array();
  565. foreach ($this->_costs as $kProjId => $vProjInfo) {
  566. $projectPath = $this->_projectInfo[$kProjId]->path;
  567. foreach ($vProjInfo->korespByMonth as $kMonthNum => $vKorespList) {
  568. $this->_createCostIfNotDefined($kProjId, $kMonthNum);
  569. foreach ($vKorespList as $vKoresp) {
  570. $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->COST_SELF += $vKoresp->COST;
  571. $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->INCOME_SELF += $vKoresp->INCOME;
  572. }
  573. $projHasCostSelfIds[$kProjId][$kMonthNum] = $projectPath;
  574. }
  575. }
  576. //echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;">$projHasCostSelfIds: ';print_r($projHasCostSelfIds);echo'</pre>';
  577. foreach ($projHasCostSelfIds as $kProjId => $vProjMonthsList) {
  578. if ($kProjId <= 0) continue;
  579. foreach ($vProjMonthsList as $kMonthNum => $vProjPath) {
  580. $vProjPathIds = explode('-', $vProjPath);
  581. $vProjPathIds = array_reverse($vProjPathIds);
  582. $vProjMonthCostSelf = $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->COST_SELF;
  583. $vProjMonthIncomeSelf = $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->INCOME_SELF;
  584. foreach ($vProjPathIds as $vProjId) {
  585. if ($vProjId == $kProjId) continue;
  586. $this->_createCostIfNotDefined($vProjId, $kMonthNum);
  587. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->COST_CHILD += $vProjMonthCostSelf;
  588. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->INCOME_CHILD += $vProjMonthIncomeSelf;
  589. }
  590. }
  591. }
  592. // recount total
  593. foreach ($this->_costs as $vProjId => $vProjInfo) {
  594. foreach ($vProjInfo->costsByMonth as $kMonthNum => $vCost) {
  595. $this->_createCostIfNotDefined($vProjId, $kMonthNum);
  596. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->COST_TOTAL = $vCost->COST_SELF + $vCost->COST_CHILD;
  597. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->INCOME_TOTAL = $vCost->INCOME_SELF + $vCost->INCOME_CHILD;
  598. }
  599. }
  600. }
  601. private function _createCostIfNotDefined($projId, $monthNum) {
  602. if (empty($this->_costs[$projId]->costsByMonth[$monthNum])) {
  603. $vEmptyCost = new stdClass();
  604. $vEmptyCost->COST_SELF = 0;
  605. $vEmptyCost->INCOME_SELF = 0;
  606. $vEmptyCost->COST_CHILD = 0;
  607. $vEmptyCost->INCOME_CHILD = 0;
  608. $vEmptyCost->COST_TOTAL = 0;
  609. $vEmptyCost->INCOME_TOTAL = 0;
  610. $this->_costs[$projId]->costsByMonth[$monthNum] = $vEmptyCost;
  611. }
  612. }
  613. public function _buildProjectTree() {
  614. $this->_projectPathsOrder = array();
  615. foreach ($this->_projectInfo as $idProject => $projectInfo) {
  616. $this->_projectPathsOrder[$projectInfo->path] = $idProject;
  617. }
  618. //echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;">projPaths: ';print_r($this->_projectPathsOrder);echo'</pre>';
  619. uksort($this->_projectPathsOrder, array($this, 'sortPathsCallback'));
  620. //echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;">projPaths sorted: ';print_r($this->_projectPathsOrder);echo'</pre>';
  621. return $this->_projectPathsOrder;
  622. }
  623. public function sortPathsCallback($a, $b) {
  624. $ea = explode('-', $a);
  625. $eb = explode('-', $b);
  626. $la = count($ea);
  627. $lb = count($eb);
  628. $lmin = min($la, $lb);
  629. for ($i = 0; $i < $lmin; $i++) {
  630. if ($ea[$i] < $eb[$i]) {
  631. return -1;
  632. } else if ($ea[$i] > $eb[$i]) {
  633. return 1;
  634. }
  635. }
  636. return $la - $lb;
  637. }
  638. public function updatePaths() {
  639. $sqlList = array();
  640. $sqlList['updateAllPaths'] = <<<SQL
  641. update `projects_budget_year_month` b
  642. set path = (select coalesce(
  643. (select p.`path` from `IN7_MK_BAZA_DYSTRYBUCJI` p where p.`ID`=b.`ID_PROJECT` limit 1)
  644. , '?'));
  645. SQL;
  646. $db = DB::getDB();
  647. if ($db->has_errors()) {
  648. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  649. }
  650. foreach ($sqlList as $sqlName => $sql) {
  651. $res = $db->query($sql);
  652. if ($db->has_errors()) {
  653. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  654. }
  655. }
  656. }
  657. public function reinstall() {
  658. $sqlList = array();
  659. $sqlList['RemoveTrigger_BudgetPlan_BeforeInsert'] = "DROP TRIGGER IF EXISTS `projects_budget_year_month_BEFORE_INSERT`";
  660. $sqlList['CreateTrigger_BudgetPlan_BeforeInsert'] = "
  661. CREATE DEFINER=`root`@`localhost` TRIGGER `projects_budget_year_month_BEFORE_INSERT` BEFORE INSERT ON `projects_budget_year_month`
  662. FOR EACH ROW BEGIN
  663. IF NEW.ID_PROJECT IS NOT NULL and NEW.ID_PROJECT>0 THEN
  664. SET NEW.path = (select coalesce(
  665. (select p.`path` from `IN7_MK_BAZA_DYSTRYBUCJI` p where p.`ID`=NEW.`ID_PROJECT` limit 1)
  666. , '?'
  667. ));
  668. END IF;
  669. END
  670. ";
  671. $sqlList['RemoveTrigger_BudgetPlan_BeforeUpdate'] = "DROP TRIGGER IF EXISTS `projects_budget_year_month_BEFORE_UPDATE `";
  672. // throws errors:
  673. // #1146 - Table '{DATABASE_NAME}.P5-MSG:Route_FixZasobPath:ERROR: Loop detected ID=PARENT_ID' doesn't exist
  674. // #1146 - Table '{DATABASE_NAME}.P5-MSG:Route_FixZasobPath:ERROR: Parent item not exists' doesn't exist
  675. // #1146 - Table '{DATABASE_NAME}.P5-MSG:Route_FixZasobPath:ERROR: Loop detected in path' doesn't exist
  676. $sqlList['CreateTrigger_BudgetPlan_BeforeUpdate'] = "
  677. CREATE DEFINER=`root`@`localhost` TRIGGER `projects_budget_year_month_BEFORE_UPDATE` BEFORE UPDATE ON `projects_budget_year_month`
  678. FOR EACH ROW BEGIN
  679. IF NEW.ID_PROJECT IS NULL THEN
  680. SET NEW.path = '';
  681. ELSEIF OLD.ID_PROJECT IS NULL or NEW.ID_PROJECT<>OLD.ID_PROJECT THEN
  682. IF NEW.ID_PROJECT>0 THEN
  683. SET NEW.path = (select coalesce(
  684. (select p.`path` from `IN7_MK_BAZA_DYSTRYBUCJI` p where p.`ID`=NEW.`ID_PROJECT` limit 1)
  685. , '?'));
  686. ELSE
  687. SET NEW.path = '';
  688. END IF;
  689. END IF;
  690. END
  691. ";
  692. $db = DB::getDB();
  693. if ($db->has_errors()) {
  694. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  695. }
  696. foreach ($sqlList as $sqlName => $sql) {
  697. $res = $db->query($sql);
  698. if ($db->has_errors()) {
  699. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  700. }
  701. }
  702. }
  703. }