Budget.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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
  163. $projectID = $projId;
  164. $projectDesc = $this->_projectInfo[$projId]->M_DIST_DESC;
  165. $projectPath = $this->_projectInfo[$projId]->path;
  166. $projectAccess = $this->hasAccessToProject($projectID);
  167. ?>
  168. <tr class="row-<?php echo ($t = 1 - $t); ?>"
  169. data-proj_id="<?php echo $projectID; ?>"
  170. data-path="<?php echo $projectPath; ?>">
  171. <td class="p2 r nr">
  172. <input type="checkbox" name="selectedProject" onclick="return selectProject(this);" value="<?php echo $projectID; ?>" />
  173. </td>
  174. <td class="p2 l nr"><nobr><?php echo $projectPath; ?></nobr></td>
  175. <?php if (!$projectAccess) : ?>
  176. <td class="p2">***</td>
  177. <?php else : ?>
  178. <td class="p2" style="max-width:300px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?php echo $projectDesc; ?>"><?php echo $projectDesc; ?></td>
  179. <?php endif; ?>
  180. <?php foreach ($months as $month) : ?>
  181. <?php $vMonthCost = $this->getCost($projectID, $month); ?>
  182. <?php $monthCostTotal = ($vMonthCost)? $vMonthCost->COST_TOTAL : 0; ?>
  183. <?php if (!$projectAccess) : ?>
  184. <td style="min-width:30px;text-align:right;">***</td>
  185. <?php elseif (!$vMonthCost) : ?>
  186. <td style="min-width:30px">&nbsp;</td>
  187. <?php else : ?>
  188. <?php
  189. $vCostChildOut = number_format($vMonthCost->COST_CHILD, 2);
  190. $vCostSelfOut = number_format($vMonthCost->COST_SELF, 2);
  191. $vCostTotalOut = number_format($vMonthCost->COST_TOTAL, 2);
  192. $title = "Koszt projektu {$vCostSelfOut} / koszt podprojektów $vCostChildOut";
  193. $cellCostCls = '';
  194. if ($vMonthCost->COST_CHILD > 0) {
  195. if ($vMonthCost->COST_SELF > 0) {
  196. $cellCostCls = 'cell-cost-self_and_child';
  197. } else {
  198. $cellCostCls = 'cell-cost-only_child';
  199. }
  200. } else {
  201. $cellCostCls = 'cell-cost-only_self';
  202. }
  203. ?>
  204. <td class="cell-cost <?php echo $cellCostCls; ?>"
  205. data-month_num="<?php echo $month; ?>"
  206. data-cost="<?php echo $vCostTotalOut; ?>"
  207. data-proj_path="<?php echo $projectPath; ?>"
  208. data-proj_id="<?php echo $projectID; ?>">
  209. <span class="ttip" title="<?php echo $title; ?>"><?php echo $vCostTotalOut; ?></span>
  210. </td>
  211. <?php endif; ?>
  212. <td class="cell-plan">
  213. <?php $monthPlan = $this->getPlan($projectID, $month); ?>
  214. <?php $monthPlanOut = number_format($monthPlan, 2); ?>
  215. <?php if (!$projectAccess) : ?>
  216. ***
  217. <?php elseif ($monthPlan > 0) : ?>
  218. <?php echo $monthPlan; ?>
  219. <?php else : ?>
  220. &nbsp;
  221. <?php endif; ?>
  222. </td>
  223. <?php
  224. $cellProcentCls = '';
  225. $procentOut = '&nbsp;';
  226. $monthPlan = $this->getPlan($projectID, $month);
  227. if ($monthPlan > 0) {
  228. $procentOut = round(($monthCostTotal * 100) / $monthPlan);
  229. if ($procentOut > 200) {
  230. $cellProcentCls = 'cell-procent-over200';
  231. } else if ($procentOut > 100) {
  232. $cellProcentCls = 'cell-procent-over100';
  233. } else if ($procentOut == 100) {
  234. $cellProcentCls = 'cell-procent-100';
  235. } else {
  236. $cellProcentCls = 'cell-procent-below100';
  237. }
  238. }
  239. ?>
  240. <?php if (!$projectAccess) : ?>
  241. <td style="min-width:30px;text-align:right;">***</td>
  242. <?php else : ?>
  243. <td class="cell-procent <?php echo $cellProcentCls; ?>"><?php echo $procentOut; ?></td>
  244. <?php endif; ?>
  245. <?php endforeach; ?>
  246. </tr>
  247. <?php endforeach; ?>
  248. </tbody>
  249. </table>
  250. <script>
  251. jQuery(document).ready(function() {
  252. jQuery('#zestawienie-kosztow-projektow')
  253. .find('.cell-cost')
  254. .on('click', function(e) {
  255. var $n = jQuery(this),
  256. $modal = jQuery('#projectMonthCostDetails'),
  257. projId = $n.data('proj_id'),
  258. monthNum = $n.data('month_num'),
  259. projPath = '' + $n.data('proj_path'),
  260. projPathLength = projPath.length,
  261. modalBody = document.createElement('table'),
  262. totalDescrCell = document.createElement('td'),
  263. totalCostCell = document.createElement('td'),
  264. totalEmptyCell = document.createElement('td'),
  265. totalRow = document.createElement('tr');
  266. modalBody.className = 'zestawienie-kosztow-tbl';
  267. modalBody.style.width = '100%';
  268. // $n.data() = {proj_id: 3943, proj_path: "0-4132-3943", month_num: 2}
  269. // table#proj-koresp-info > tbody#row-proj-2055-koresp-by-month-2
  270. jQuery('#proj-koresp-info').find('tbody').each(function(i, tbody) {
  271. var vPath = jQuery(tbody).data('proj_path'),
  272. vMonthNum = jQuery(tbody).data('month_num');
  273. if (monthNum != vMonthNum) return;
  274. if (projPathLength > vPath.length) return;
  275. if (projPath == vPath
  276. || (projPathLength < vPath.length && projPath + '-' == vPath.substr(0, projPathLength + 1))
  277. ) {
  278. modalBody.appendChild(tbody.cloneNode(true));
  279. }
  280. });
  281. {
  282. totalDescrCell.className = 'p2';
  283. totalDescrCell.style.textAlign = 'right';
  284. totalDescrCell.setAttribute('colspan', '2');
  285. totalDescrCell.appendChild(document.createTextNode('Suma:'));
  286. totalCostCell.className = 'cell-cost';
  287. totalCostCell.style.textAlign = 'right';
  288. totalCostCell.appendChild(document.createTextNode($n.data('cost')));
  289. totalRow.appendChild(totalDescrCell);
  290. totalRow.appendChild(totalCostCell);
  291. modalBody.appendChild(totalRow);
  292. }
  293. $modal.find('.modal-title').text('Koszty projektu nr ' + projId + ' w miesiącu <?php echo $year; ?>-' + ((monthNum > 9)? monthNum : '0' + monthNum));
  294. $modal.find('.modal-body').html(modalBody);
  295. $modal.modal({});
  296. })
  297. })
  298. </script>
  299. <!-- Modal -->
  300. <div class="modal fade" id="projectMonthCostDetails" tabindex="-1" role="dialog" aria-labelledby="projectCostDMonthetailsLabel">
  301. <div class="modal-dialog" role="document" style="min-width:800px;">
  302. <div class="modal-content">
  303. <div class="modal-header">
  304. <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  305. <h4 class="modal-title" id="projectCostDMonthetailsLabel">Modal title</h4>
  306. </div>
  307. <div class="modal-body">
  308. TODO: projectMonthCostDetails...
  309. </div>
  310. <div class="modal-footer">
  311. <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
  312. </div>
  313. </div>
  314. </div>
  315. </div>
  316. <table id="proj-koresp-info" style="display:none">
  317. <?php foreach ($this->_projectPathsOrder as $projPath => $projId) : ?>
  318. <?php
  319. $projectInfo = $this->_costs[$projId];
  320. if (!$projectInfo) {
  321. continue;
  322. }
  323. $projectID = $projId;
  324. $projectDesc = $this->_projectInfo[$projId]->M_DIST_DESC;
  325. $projectPath = $this->_projectInfo[$projId]->path;
  326. ?>
  327. <?php if (!empty($projectInfo->korespByMonth)) : ?>
  328. <?php foreach ($projectInfo->korespByMonth as $kMonth => $vKorespMonthList) : ?>
  329. <tbody id="row-proj-<?php echo $projectID; ?>-koresp-by-month-<?php echo $kMonth; ?>"
  330. data-month_num="<?php echo $kMonth; ?>"
  331. data-proj_path="<?php echo $projectPath; ?>"
  332. data-proj_id="<?php echo $projectID; ?>">
  333. <tr>
  334. <td style="padding:3px;font-size:1em;background:#eee;"><nobr><?php echo $projectPath; ?></nobr></td>
  335. <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; ?>">
  336. <!-- Koszty projektu nr <?php echo $projectID; ?> -->
  337. <!-- - miesiąc <?php echo $year; ?>-<?php echo sprintf("%02d", $kMonth); ?> -->
  338. <?php echo $projectDesc; ?>
  339. </td>
  340. </tr>
  341. <?php foreach ($vKorespMonthList as $kKorespIdx => $vKorespInfo) : ?>
  342. <?php /*
  343. * [ID] => 41235
  344. * [MONTH] => 2015-02
  345. * [K_ZAWARTOS] => Faktura za pomiar powykonawczy sieci telekomunikacyjnej
  346. * [COST] => 1000.00
  347. * [INCOME] => 0.00
  348. ? [TRANSFER_OPPOSITE_ID_PROJECT] => int
  349. */ ?>
  350. <tr>
  351. <td class="p2 r nr"><?php echo $vKorespInfo->ID; ?></td>
  352. <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>
  353. <?php $vKorespCostOut = number_format($vKorespInfo->COST, 2); ?>
  354. <td class="cell-cost cell-cost-only_child"><?php echo $vKorespCostOut; ?></td>
  355. <td>
  356. <?php $dekretId = V::get('TRANSFER_OPPOSITE_ID_PROJECT', 0, $vKorespInfo) ?>
  357. <?php if ($dekretId > 0) : ?>
  358. Dekret z projektu nr <?php echo $dekretId; ?>
  359. <?php endif; ?>
  360. </td>
  361. </tr>
  362. <?php endforeach; ?>
  363. </tbody>
  364. <?php endforeach; ?>
  365. <?php endif; ?>
  366. <?php endforeach; ?>
  367. </table>
  368. <script>
  369. jQuery(document).ready(function(){
  370. jQuery('.ttip').tooltip();
  371. });
  372. function selectProject(n) {
  373. var $n = jQuery(n);
  374. var $p = $n.parent().parent();
  375. if (n.checked) {
  376. $p.addClass('row-selected');
  377. } else {
  378. $p.removeClass('row-selected');
  379. }
  380. markSubProjects($p, $p.data('path'), n.checked);
  381. function markSubProjects($p, path, checked) {
  382. var $nextRow = $p.next('tr'),
  383. nextPath = $nextRow.data('path'),
  384. nextCheckbox = $nextRow.find('input[type="checkbox"]').get(0);
  385. if (0 !== nextPath.indexOf(path)) {
  386. return;
  387. }
  388. if (checked) {
  389. $nextRow.addClass('row-selected');
  390. } else {
  391. $nextRow.removeClass('row-selected');
  392. }
  393. nextCheckbox.checked = checked;
  394. markSubProjects($nextRow, path, checked);
  395. }
  396. }
  397. function showHideAll(n) {
  398. if (n.checked) {
  399. jQuery('#zestawienie-kosztow-projektow').find('tbody').addClass('showOnlySelected');
  400. } else {
  401. jQuery('#zestawienie-kosztow-projektow').find('tbody').removeClass('showOnlySelected');
  402. }
  403. }
  404. </script>
  405. <?php
  406. }
  407. public function getCost($idProject, $month) {
  408. if (!array_key_exists($idProject, $this->_costs)) {
  409. return null;
  410. }
  411. if (!array_key_exists($month, $this->_costs[$idProject]->costsByMonth)) {
  412. return null;
  413. }
  414. return $this->_costs[$idProject]->costsByMonth[$month];
  415. }
  416. public function getPlan($idProject, $month) {
  417. if (!array_key_exists($idProject, $this->_plan)) {
  418. return 0;
  419. }
  420. if (!array_key_exists($month, $this->_plan[$idProject])) {
  421. return 0;
  422. }
  423. return $this->_plan[$idProject][$month];
  424. }
  425. public function fetchDataByYear($year) {
  426. $this->_fetchCostsByYear($year);
  427. $this->_fetchPlanByYear($year);
  428. $this->_fetchProjectInfo();
  429. $this->_buildProjectTree();
  430. $this->_reacountCostsFromKoresp();
  431. return count($this->_projectInfo) > 1;// $this->_projectInfo[0] - Wszystkie projekty
  432. }
  433. public function _fetchPlanByYear($year) {
  434. $db = DB::getDB();
  435. $this->_plan = array();
  436. $sql = "
  437. select plan.`ID`
  438. , plan.`ID_PROJECT` AS `ID_PROJECT`
  439. , plan.`MONTH_1_VALUE`
  440. , plan.`MONTH_2_VALUE`
  441. , plan.`MONTH_3_VALUE`
  442. , plan.`MONTH_4_VALUE`
  443. , plan.`MONTH_5_VALUE`
  444. , plan.`MONTH_6_VALUE`
  445. , plan.`MONTH_7_VALUE`
  446. , plan.`MONTH_8_VALUE`
  447. , plan.`MONTH_9_VALUE`
  448. , plan.`MONTH_10_VALUE`
  449. , plan.`MONTH_11_VALUE`
  450. , plan.`MONTH_12_VALUE`
  451. from `projects_budget_year_month` plan
  452. where plan.`year`='{$year}'
  453. -- TODO: acl
  454. ";
  455. //echo'<pre style="border:1px solid red;overflow:auto;max-height:400px">';print_r($sql);echo'</pre>';
  456. $res = $db->query($sql);
  457. while ($r = $db->fetch($res)) {
  458. $plan = array();
  459. for ($i = 1; $i <= 12; $i++) {
  460. $plan[$i] = V::get("MONTH_{$i}_VALUE", 0, $r);
  461. }
  462. $this->_plan[$r->ID_PROJECT] = $plan;
  463. }
  464. return $this->_plan;
  465. }
  466. public function _fetchCostsByYear($year) {
  467. $db = DB::getDB();
  468. $this->_costs = array();
  469. $sql = "
  470. select k.`ID`
  471. , k.`ID_PROJECT` AS `ID_PROJECT`
  472. , date_format(k.`K_DATA_OTRZYMANEJ_KORESP`,'%Y-%m') AS `MONTH`
  473. , k.`COST_VALUE` AS `COST`
  474. , k.`INCOME_VALUE` AS `INCOME`
  475. , 0 as `TRANSFER_OPPOSITE_ID_PROJECT` -- TRANSFER_OPPOSITE_ID_PROJECT
  476. , k.`path`
  477. -- , IF(k.`TRANSFER_OPPOSITE_ID_PROJECT`>0
  478. -- , (select p.`path`
  479. -- from `IN7_MK_BAZA_DYSTRYBUCJI` p
  480. -- where p.`ID`=k.`TRANSFER_OPPOSITE_ID_PROJECT`
  481. -- limit 1
  482. -- )
  483. -- , '') as TRANSFER_OPPOSITE_PROJECT_PATH
  484. , '' as TRANSFER_OPPOSITE_PROJECT_PATH
  485. , k.`K_ZAWARTOS`
  486. from `IN7_DZIENNIK_KORESP` k
  487. where ((k.`COST_VALUE` > 0) or (k.`INCOME_VALUE` > 0))
  488. and k.`K_DATA_OTRZYMANEJ_KORESP` like '{$year}-%'
  489. -- TODO: acl
  490. ";
  491. //echo'<pre style="border:1px solid red;overflow:auto;max-height:400px">';print_r($sql);echo'</pre>';
  492. $res = $db->query($sql);
  493. while ($r = $db->fetch($res)) {
  494. $vProjId = ($r->ID_PROJECT > 0)? $r->ID_PROJECT : 0;
  495. $vProjPaths = array();
  496. $vProjIds = array(0 => true);
  497. if ($r->ID_PROJECT > 0) {
  498. $vProjPaths[] = $r->ID_PROJECT;
  499. if (!empty($r->path)) {
  500. $vProjPaths[] = $r->path;
  501. }
  502. }
  503. if ($r->TRANSFER_OPPOSITE_ID_PROJECT > 0) {
  504. $vProjPaths[] = $r->TRANSFER_OPPOSITE_ID_PROJECT;
  505. if (!empty($r->TRANSFER_OPPOSITE_PROJECT_PATH)) {
  506. $vProjPaths[] = $r->TRANSFER_OPPOSITE_PROJECT_PATH;
  507. }
  508. }
  509. if (!empty($vProjPaths)) {
  510. //echo'<p>DBG:$r->ID_PROJECT['.$r->ID_PROJECT.']: $vProjPaths = ' . json_encode($vProjPaths) . '</p>';
  511. $vProjPaths = implode('-', $vProjPaths);
  512. $projIds = explode('-', $vProjPaths);
  513. //echo'<p>DBG:$r->ID_PROJECT['.$r->ID_PROJECT.']: $projIds = ' . json_encode($projIds) . '</p>';
  514. foreach ($projIds as $vProjId) {
  515. if ($vProjId > 0) $vProjIds[$vProjId] = true;
  516. }
  517. }
  518. {
  519. $projectZeroInfo = new stdClass();
  520. $projectZeroInfo->ID_PROJECT = 0;
  521. $projectZeroInfo->costsByMonth = array();
  522. $projectZeroInfo->korespByMonth = array();
  523. $this->_costs[0] = $projectZeroInfo;
  524. }
  525. foreach ($vProjIds as $vProjId => $vBool) {
  526. if (!array_key_exists($vProjId, $this->_costs)) {
  527. $projectInfo = new stdClass();
  528. $projectInfo->ID_PROJECT = $vProjId;
  529. $projectInfo->costsByMonth = array();
  530. $projectInfo->korespByMonth = array();
  531. $this->_costs[$vProjId] = $projectInfo;
  532. }
  533. }
  534. $korespInfo = new stdClass();
  535. $korespInfo->ID = $r->ID;
  536. $korespInfo->MONTH = $r->MONTH;
  537. $korespInfo->K_ZAWARTOS = $r->K_ZAWARTOS;
  538. $monthNum = intval(substr($r->MONTH, 5, 2));
  539. if ($r->TRANSFER_OPPOSITE_ID_PROJECT > 0) {
  540. $korespInfo->COST = $r->COST;
  541. $korespInfo->INCOME = $r->INCOME;
  542. $korespInfo->TRANSFER_OPPOSITE_ID_PROJECT = $r->TRANSFER_OPPOSITE_ID_PROJECT;
  543. $this->_costs[$r->TRANSFER_OPPOSITE_ID_PROJECT]->korespByMonth[$monthNum][] = $korespInfo;
  544. } else if ($r->ID_PROJECT) {
  545. $korespInfo->COST = $r->COST;
  546. $korespInfo->INCOME = $r->INCOME;
  547. $this->_costs[$r->ID_PROJECT]->korespByMonth[$monthNum][] = $korespInfo;
  548. } else {
  549. $korespInfo->COST = $r->COST;
  550. $korespInfo->INCOME = $r->INCOME;
  551. $this->_costs[0]->korespByMonth[$monthNum][] = $korespInfo;
  552. }
  553. }
  554. return $this->_costs;
  555. }
  556. private function _fetchProjectInfo() {
  557. $db = DB::getDB();
  558. $hasAccessForAllProjects = true;
  559. $projectIds = array();
  560. $projectsFromCostIds = array_keys($this->_costs);
  561. foreach ($projectsFromCostIds as $idProject) $projectIds[$idProject] = true;
  562. $projectsFromPlanIds = array_keys($this->_plan);
  563. foreach ($projectsFromPlanIds as $idProject) $projectIds[$idProject] = true;
  564. foreach ($projectIds as $idProject => $vBool) $this->_projectInfo[$idProject] = new stdClass();
  565. $projectIds = array_keys($projectIds);
  566. $sqlProjIds = "'" . implode("','", $projectIds) . "'";
  567. $sql = "
  568. select p.`ID`
  569. , p.`P_ID`
  570. , p.`path`
  571. , p.`M_DIST_DESC`
  572. , p.`A_ADM_COMPANY` as aclGroupWrite
  573. , p.`A_CLASSIFIED` as aclGroupRead
  574. , p.`L_APPOITMENT_USER` as aclOwner
  575. from `IN7_MK_BAZA_DYSTRYBUCJI` p
  576. where p.`ID` in({$sqlProjIds})
  577. ";
  578. $res = $db->query($sql);
  579. while ($r = $db->fetch($res)) {
  580. $this->_projectInfo[$r->ID]->path = $r->path;
  581. $this->_projectInfo[$r->ID]->M_DIST_DESC = $r->M_DIST_DESC;
  582. $this->_projectInfo[$r->ID]->hasAccess = $this->_userHasAccessToProject($r);
  583. if (!$this->_projectInfo[$r->ID]->hasAccess) $hasAccessForAllProjects = false;
  584. }
  585. $this->_projectInfo[0]->path = '0';
  586. $this->_projectInfo[0]->M_DIST_DESC = "Wszystkie projekty";
  587. $this->_projectInfo[0]->hasAccess = $hasAccessForAllProjects;
  588. }
  589. public function hasAccessToProject($idProject) {
  590. if ($idProject >= 0) {
  591. if (array_key_exists($idProject, $this->_projectInfo)) {
  592. return V::get('hasAccess', false, $this->_projectInfo[$idProject]);
  593. }
  594. }
  595. return false;
  596. }
  597. private function _userHasAccessToProject($project) {
  598. $groups = User::getLdapGroupsNames();
  599. $userLogin = User::getLogin();
  600. if ($project->aclOwner == $userLogin) {
  601. return true;
  602. }
  603. else if (in_array($project->aclGroupRead, $groups)) {
  604. return true;
  605. }
  606. return false;
  607. }
  608. private function _reacountCostsFromKoresp() {
  609. $projMonthHasCostSelfIds = array();
  610. foreach ($this->_costs as $kProjId => $vProjInfo) {
  611. $projectPath = $this->_projectInfo[$kProjId]->path;
  612. foreach ($vProjInfo->korespByMonth as $kMonthNum => $vKorespList) {
  613. $this->_createCostIfNotDefined($kProjId, $kMonthNum);
  614. foreach ($vKorespList as $vKoresp) {
  615. $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->COST_SELF += $vKoresp->COST;
  616. $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->INCOME_SELF += $vKoresp->INCOME;
  617. }
  618. $projHasCostSelfIds[$kProjId][$kMonthNum] = $projectPath;
  619. }
  620. }
  621. //echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;">$projHasCostSelfIds: ';print_r($projHasCostSelfIds);echo'</pre>';
  622. foreach ($projHasCostSelfIds as $kProjId => $vProjMonthsList) {
  623. if ($kProjId <= 0) continue;
  624. foreach ($vProjMonthsList as $kMonthNum => $vProjPath) {
  625. $vProjPathIds = explode('-', $vProjPath);
  626. $vProjPathIds = array_reverse($vProjPathIds);
  627. $vProjMonthCostSelf = $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->COST_SELF;
  628. $vProjMonthIncomeSelf = $this->_costs[$kProjId]->costsByMonth[$kMonthNum]->INCOME_SELF;
  629. foreach ($vProjPathIds as $vProjId) {
  630. if ($vProjId == $kProjId) continue;
  631. $this->_createCostIfNotDefined($vProjId, $kMonthNum);
  632. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->COST_CHILD += $vProjMonthCostSelf;
  633. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->INCOME_CHILD += $vProjMonthIncomeSelf;
  634. }
  635. }
  636. }
  637. // recount total
  638. foreach ($this->_costs as $vProjId => $vProjInfo) {
  639. foreach ($vProjInfo->costsByMonth as $kMonthNum => $vCost) {
  640. $this->_createCostIfNotDefined($vProjId, $kMonthNum);
  641. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->COST_TOTAL = $vCost->COST_SELF + $vCost->COST_CHILD;
  642. $this->_costs[$vProjId]->costsByMonth[$kMonthNum]->INCOME_TOTAL = $vCost->INCOME_SELF + $vCost->INCOME_CHILD;
  643. }
  644. }
  645. }
  646. private function _createCostIfNotDefined($projId, $monthNum) {
  647. if (empty($this->_costs[$projId]->costsByMonth[$monthNum])) {
  648. $vEmptyCost = new stdClass();
  649. $vEmptyCost->COST_SELF = 0;
  650. $vEmptyCost->INCOME_SELF = 0;
  651. $vEmptyCost->COST_CHILD = 0;
  652. $vEmptyCost->INCOME_CHILD = 0;
  653. $vEmptyCost->COST_TOTAL = 0;
  654. $vEmptyCost->INCOME_TOTAL = 0;
  655. $this->_costs[$projId]->costsByMonth[$monthNum] = $vEmptyCost;
  656. }
  657. }
  658. public function _buildProjectTree() {
  659. $this->_projectPathsOrder = array();
  660. foreach ($this->_projectInfo as $idProject => $projectInfo) {
  661. $this->_projectPathsOrder[$projectInfo->path] = $idProject;
  662. }
  663. //echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;">projPaths: ';print_r($this->_projectPathsOrder);echo'</pre>';
  664. uksort($this->_projectPathsOrder, array($this, 'sortPathsCallback'));
  665. //echo'<pre style="width:600px;border:1px solid red;max-height:300px;overflow:auto;">projPaths sorted: ';print_r($this->_projectPathsOrder);echo'</pre>';
  666. return $this->_projectPathsOrder;
  667. }
  668. public function sortPathsCallback($a, $b) {
  669. $ea = explode('-', $a);
  670. $eb = explode('-', $b);
  671. $la = count($ea);
  672. $lb = count($eb);
  673. $lmin = min($la, $lb);
  674. for ($i = 0; $i < $lmin; $i++) {
  675. if ($ea[$i] < $eb[$i]) {
  676. return -1;
  677. } else if ($ea[$i] > $eb[$i]) {
  678. return 1;
  679. }
  680. }
  681. return $la - $lb;
  682. }
  683. public function updatePaths() {
  684. $sqlList = array();
  685. $sqlList['updateAllPaths'] = <<<SQL
  686. update `projects_budget_year_month` b
  687. set path = (select coalesce(
  688. (select p.`path` from `IN7_MK_BAZA_DYSTRYBUCJI` p where p.`ID`=b.`ID_PROJECT` limit 1)
  689. , '?'));
  690. SQL;
  691. $db = DB::getDB();
  692. if ($db->has_errors()) {
  693. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  694. }
  695. foreach ($sqlList as $sqlName => $sql) {
  696. $res = $db->query($sql);
  697. if ($db->has_errors()) {
  698. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  699. }
  700. }
  701. }
  702. public function reinstall() {
  703. $sqlList = array();
  704. $sqlList['RemoveTrigger_BudgetPlan_BeforeInsert'] = "DROP TRIGGER IF EXISTS `projects_budget_year_month_BEFORE_INSERT`";
  705. $sqlList['CreateTrigger_BudgetPlan_BeforeInsert'] = "
  706. CREATE DEFINER=`root`@`localhost` TRIGGER `projects_budget_year_month_BEFORE_INSERT` BEFORE INSERT ON `projects_budget_year_month`
  707. FOR EACH ROW BEGIN
  708. IF NEW.ID_PROJECT IS NOT NULL and NEW.ID_PROJECT>0 THEN
  709. SET NEW.path = (select coalesce(
  710. (select p.`path` from `IN7_MK_BAZA_DYSTRYBUCJI` p where p.`ID`=NEW.`ID_PROJECT` limit 1)
  711. , '?'
  712. ));
  713. END IF;
  714. END
  715. ";
  716. $sqlList['RemoveTrigger_BudgetPlan_BeforeUpdate'] = "DROP TRIGGER IF EXISTS `projects_budget_year_month_BEFORE_UPDATE `";
  717. // throws errors:
  718. // #1146 - Table '{DATABASE_NAME}.P5-MSG:Route_FixZasobPath:ERROR: Loop detected ID=PARENT_ID' doesn't exist
  719. // #1146 - Table '{DATABASE_NAME}.P5-MSG:Route_FixZasobPath:ERROR: Parent item not exists' doesn't exist
  720. // #1146 - Table '{DATABASE_NAME}.P5-MSG:Route_FixZasobPath:ERROR: Loop detected in path' doesn't exist
  721. $sqlList['CreateTrigger_BudgetPlan_BeforeUpdate'] = "
  722. CREATE DEFINER=`root`@`localhost` TRIGGER `projects_budget_year_month_BEFORE_UPDATE` BEFORE UPDATE ON `projects_budget_year_month`
  723. FOR EACH ROW BEGIN
  724. IF NEW.ID_PROJECT IS NULL THEN
  725. SET NEW.path = '';
  726. ELSEIF OLD.ID_PROJECT IS NULL or NEW.ID_PROJECT<>OLD.ID_PROJECT THEN
  727. IF NEW.ID_PROJECT>0 THEN
  728. SET NEW.path = (select coalesce(
  729. (select p.`path` from `IN7_MK_BAZA_DYSTRYBUCJI` p where p.`ID`=NEW.`ID_PROJECT` limit 1)
  730. , '?'));
  731. ELSE
  732. SET NEW.path = '';
  733. END IF;
  734. END IF;
  735. END
  736. ";
  737. $db = DB::getDB();
  738. if ($db->has_errors()) {
  739. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  740. }
  741. foreach ($sqlList as $sqlName => $sql) {
  742. $res = $db->query($sql);
  743. if ($db->has_errors()) {
  744. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  745. }
  746. }
  747. }
  748. }