DealsSales.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('ProcesHelper');
  4. Lib::loadClass('Typespecial');
  5. class Route_DealsSales extends RouteBase {
  6. public function handleAuth() {
  7. if (!User::logged()) {
  8. throw new HttpException('Unauthorized', 401);
  9. }
  10. }
  11. public function defaultAction() {
  12. SE_Layout::gora();
  13. SE_Layout::menu();
  14. $this->legacy_DEALS_SALES();
  15. SE_Layout::dol();
  16. }
  17. public function typespecialAction() {
  18. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  19. header("Content-type: application/json");
  20. $fld = V::get('fld', '', $_GET);
  21. switch ($fld) {
  22. case 'id_telboxes': {
  23. Lib::loadClass('TypespecialVariable');
  24. $typeSpecialTelboxes = TypespecialVariable::getInstance(-1, '__DEALS_SALES_TELBOXES_NAME');
  25. $query = V::get('q', '', $_REQUEST);
  26. $rawRows = null;
  27. $rows = $typeSpecialTelboxes->getValuesWithExports($query);
  28. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  29. foreach ($rows as $kID => $vItem) {
  30. $itemJson = new stdClass();
  31. $itemJson->id = $vItem->id;
  32. $itemJson->name = $vItem->param_out;
  33. if (!empty($vItem->exports)) {
  34. $itemJson->exports = $vItem->exports;
  35. }
  36. $jsonData[] = $itemJson;
  37. }
  38. echo json_encode($jsonData);
  39. }
  40. break;
  41. case 'id_companies': {
  42. Lib::loadClass('TypespecialVariable');
  43. $typeSpecialCompanies = TypespecialVariable::getInstance(-1, '__COMPANIES');
  44. $query = V::get('q', '', $_REQUEST);
  45. $rawRows = null;
  46. $rows = $typeSpecialCompanies->getValuesWithExports($query);
  47. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  48. foreach ($rows as $kID => $vItem) {
  49. $itemJson = new stdClass();
  50. $itemJson->id = $vItem->id;
  51. $itemJson->name = $vItem->param_out;
  52. if (!empty($vItem->exports)) {
  53. $itemJson->exports = $vItem->exports;
  54. }
  55. $jsonData[] = $itemJson;
  56. }
  57. echo json_encode($jsonData);
  58. }
  59. break;
  60. }
  61. }
  62. public function getDataAjaxAction() {
  63. header("Content-type: application/json");
  64. $response = new stdClass();
  65. $response->msg = 'TODO: F. ' . __FUNCTION__ . ' L.' . __LINE__;
  66. echo json_encode($response);
  67. }
  68. public function inlineEditAjaxAction() {
  69. //header("Content-type: application/json");
  70. $response = new stdClass();
  71. $response->msg = 'TODO: F. ' . __FUNCTION__ . ' L.' . __LINE__;// TODO: DBG
  72. $response->_request = $_REQUEST;// TODO: DBG
  73. $year = V::get('year', 0, $_REQUEST, 'int');
  74. $month = V::get('month', 0, $_REQUEST, 'int');
  75. $telbox = V::get('telbox', '', $_REQUEST, 'word');
  76. if ($year <= 0) throw new Exception('Error: wrong year');
  77. if ($month <= 0 || $month > 12) throw new Exception('Error: wrong month');
  78. if (empty($telbox)) throw new Exception('Error: wrong telbox');
  79. $record = $this->_fetchSaleByParams($telbox, $year, $month);
  80. if (empty($record)) {
  81. return $this->_renderInlineCreateForm($telbox, $year, $month);
  82. } else {
  83. return $this->_renderInlineEditForm($record);
  84. }
  85. }
  86. public function saveInlineAjaxAction() {
  87. header("Content-type: application/json");
  88. $response = new stdClass();
  89. $response->msg = 'TODO: F. ' . __FUNCTION__ . ' L.' . __LINE__;
  90. $response->_request = $_REQUEST;// TODO: DBG
  91. $id = V::get('ID', 0, $_REQUEST, 'int');
  92. if ($id > 0) {
  93. return $this->_saveInlineEdit($id, $_REQUEST);
  94. } else {
  95. return $this->_saveInlineCreate($_REQUEST);
  96. }
  97. }
  98. private function _saveInlineEdit($id, $args) {
  99. $record = $this->_fetchSaleById($id);
  100. if (empty($record)) throw new HttpException("Record {$id} not exists", 404);
  101. DBG::_('DBG', '>2', "record", $record, __CLASS__, __FUNCTION__, __LINE__);// TODO: DBG
  102. DBG::_('DBG', '>2', "args", $args, __CLASS__, __FUNCTION__, __LINE__);// TODO: DBG
  103. $tblAcl = $this->_getTableAcl();
  104. $primaryKeyFieldName = 'ID';
  105. $primaryKey = V::get($primaryKeyFieldName, 0, $record);
  106. $itemPatch = new stdClass();
  107. $itemPatch->{$primaryKeyFieldName} = $primaryKey;
  108. $visibleCols = array('SALES_VALUE', 'marka', 'A_STATUS');
  109. foreach ($visibleCols as $fieldName) {
  110. $fieldID = $tblAcl->getFieldIdByName($fieldName);
  111. if (!$fieldID) throw new Exception("No field by name ({$fieldName})");
  112. if (!$tblAcl->isAllowed($fieldID, 'W', $record)) {
  113. throw new Exception("Brak uprawnień do zapisu ({$fieldName})");
  114. }
  115. $argsFieldName = "f{$fieldID}";
  116. if (!isset($args[$argsFieldName])) throw new Exception("Brak danych dla pola ({$fieldName})");
  117. $itemPatch->{$fieldName} = $args[$argsFieldName];
  118. }
  119. DBG::_('DBG', '>1', "TODO: save record", $itemPatch, __CLASS__, __FUNCTION__, __LINE__);// TODO: DBG
  120. $response = new stdClass();
  121. try {
  122. $affected = $tblAcl->updateItem($itemPatch);
  123. if ($affected > 0) {
  124. $response->type = 'success';
  125. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  126. } else if ($affected == 0) {
  127. $response->type = 'info';
  128. $response->msg = "Nie wprowadzono żadnych zmian";
  129. }
  130. $response->record = $tblAcl->getItem($primaryKey);
  131. }
  132. catch (Exception $e) {
  133. $response->type = 'error';
  134. $response->msg = $e->getMessage();
  135. }
  136. echo json_encode($response);
  137. }
  138. private function _saveInlineCreate($args) {
  139. $year = V::get('SALES_YEAR', 0, $args, 'int');
  140. $month = V::get('SALES_MONTH', 0, $args, 'int');
  141. $telbox = V::get('T_TELBOX_NEIGHBOUR_IN', '', $args, 'word');
  142. if ($year <= 0) throw new Exception('Error: wrong year');
  143. if ($month <= 0 || $month > 12) throw new Exception('Error: wrong month');
  144. if (empty($telbox)) throw new Exception('Error: wrong telbox');
  145. $tblAcl = $this->_getTableAcl();
  146. $primaryKeyFieldName = 'ID';
  147. $primaryKey = V::get($primaryKeyFieldName, 0, $record);
  148. $item = new stdClass();//$tblAcl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  149. $item->T_TELBOX_NEIGHBOUR_IN = $telbox;
  150. $item->SALES_YEAR = $year;
  151. $item->SALES_MONTH = $month;
  152. $visibleCols = array('SALES_VALUE', 'marka');
  153. foreach ($visibleCols as $fieldName) {
  154. $fieldID = $tblAcl->getFieldIdByName($fieldName);
  155. if (!$fieldID) throw new Exception("No field by name ({$fieldName})");
  156. if (!$tblAcl->isAllowed($fieldID, 'C', $record)) {
  157. throw new Exception("Brak uprawnień do utworzenia ({$fieldName})");
  158. }
  159. $argsFieldName = "f{$fieldID}";
  160. if (!isset($args[$argsFieldName])) throw new Exception("Brak danych dla pola ({$fieldName})");
  161. $item->{$fieldName} = $args[$argsFieldName];
  162. }
  163. try {
  164. $createdId = $tblAcl->addItem($item);
  165. if ($createdId) {
  166. $response->type = 'success';
  167. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  168. $response->id = $createdId;
  169. $response->record = $tblAcl->getItem($createdId);
  170. }
  171. else {
  172. $response->type = 'error';
  173. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  174. }
  175. }
  176. catch (Exception $e) {
  177. $response->type = 'error';
  178. $response->msg = "Wystąpiły błędy!";
  179. $response->msg = $e->getMessage();
  180. }
  181. echo json_encode($response);
  182. }
  183. private function _fetchSaleByParams($telbox, $year, $month) {
  184. $record = null;
  185. $db = DB::getDB();
  186. $sqlWhere = array();
  187. $sqlWhere[] = " o.`A_STATUS`!='DELETED' ";
  188. $sqlIdTelboxes = $db->_($telbox);
  189. $sqlWhere[] = " o.`T_TELBOX_NEIGHBOUR_IN`='{$sqlIdTelboxes}' ";
  190. $sqlWhere[] = " o.`SALES_YEAR`='{$year}' ";
  191. $sqlWhere[] = " o.`SALES_MONTH`='{$month}' ";
  192. $sqlWhere = (!empty($sqlWhere))? implode(" and ", $sqlWhere) : '';
  193. $sql = "select o.`ID`
  194. , o.`T_TELBOX_NEIGHBOUR_IN`
  195. , o.`ID_DEALS_TABLE`
  196. , o.`SALES_YEAR`
  197. , o.`SALES_MONTH`
  198. , o.`SALES_VALUE`
  199. , o.`marka`
  200. , o.`A_STATUS`
  201. from `DEALS_SALES` as o
  202. where
  203. {$sqlWhere}
  204. ";
  205. DBG::_('DBG_SQL', '>1', "sql:fetch({telbox:{$telbox},year:{$year},month:{$month}})", $sql, __CLASS__, __FUNCTION__, __LINE__);
  206. $res = $db->query($sql);
  207. while ($r = $db->fetch($res)) {
  208. $record = $r;
  209. }
  210. return $record;
  211. }
  212. private function _fetchSaleById($idSale) {
  213. $record = null;
  214. $db = DB::getDB();
  215. $sqlWhere = array();
  216. $sqlWhere[] = " o.`A_STATUS`!='DELETED' ";
  217. $sqlWhere[] = " o.`ID`='{$idSale}' ";
  218. $sqlWhere = (!empty($sqlWhere))? implode(" and ", $sqlWhere) : '';
  219. $sql = "select o.`ID`
  220. , o.`T_TELBOX_NEIGHBOUR_IN`
  221. , o.`ID_DEALS_TABLE`
  222. , o.`SALES_YEAR`
  223. , o.`SALES_MONTH`
  224. , o.`SALES_VALUE`
  225. , o.`marka`
  226. , o.`A_STATUS`
  227. from `DEALS_SALES` as o
  228. where
  229. {$sqlWhere}
  230. ";
  231. DBG::_('DBG_SQL', '>1', "sql:fetch({telbox:{$telbox},year:{$year},month:{$month}})", $sql, __CLASS__, __FUNCTION__, __LINE__);
  232. $res = $db->query($sql);
  233. while ($r = $db->fetch($res)) {
  234. $record = $r;
  235. }
  236. return $record;
  237. }
  238. private function _renderInlineCreateForm($telbox, $year, $month) {
  239. //DBG::_(true, true, "TODO: Edit Form for record", $record, __CLASS__, __FUNCTION__, __LINE__);// TODO: DBG
  240. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  241. header("Content-type: text/plain");
  242. $row = $record;// TODO: refactor
  243. $tblAcl = $this->_getTableAcl();
  244. $visibleCols = array('SALES_VALUE', 'marka');
  245. $hasTypeSpecial = false;
  246. foreach ($visibleCols as $fieldName) {
  247. $fieldID = $tblAcl->getFieldIdByName($fieldName);
  248. if (!$fieldID) throw new Exception("No field by name ({$fieldName})");
  249. $fieldVal = ($tblAcl->isAllowed($fieldID, 'R', $row))? V::get($fieldName, '', $row) : '*****';
  250. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  251. $vCol = $tblAcl->getField($fieldID);
  252. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  253. $tsValues = array();
  254. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  255. if ($typeSpecial) {
  256. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  257. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  258. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  259. if (!empty($specialValues)) {
  260. $tsValues[$row->ID] = implode('<br>', $specialValues);
  261. }
  262. }
  263. ?>
  264. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  265. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  266. <?php if (!empty($vCol['opis'])) : ?>
  267. <em><?php echo $vCol['opis']; ?></em>
  268. <?php $perms = $tblAcl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  269. <?php endif; ?>
  270. </label>
  271. <?php
  272. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  273. if (!empty($tsValues[$row->ID])) {
  274. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  275. }
  276. $vDefault = $tblAcl->getColDefault($fieldName);
  277. if (!empty($vDefault)) {
  278. $fieldParams['default'] = $vDefault;
  279. }
  280. echo $tblAcl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  281. if ($typeSpecial) $hasTypeSpecial = true;
  282. }
  283. if ($hasTypeSpecial) {
  284. echo '<p style="padding:100px 0;"></p>';
  285. }
  286. ?>
  287. <input type="hidden" name="T_TELBOX_NEIGHBOUR_IN" value="<?php echo $telbox; ?>" />
  288. <input type="hidden" name="SALES_YEAR" value="<?php echo $year; ?>" />
  289. <input type="hidden" name="SALES_MONTH" value="<?php echo $month; ?>" />
  290. <?php
  291. exit;
  292. }
  293. private function _renderInlineEditForm($record) {
  294. //DBG::_(true, true, "TODO: Edit Form for record", $record, __CLASS__, __FUNCTION__, __LINE__);// TODO: DBG
  295. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  296. header("Content-type: text/plain");
  297. $row = $record;// TODO: refactor
  298. $tblAcl = $this->_getTableAcl();
  299. // TODO: $cols = array('T_TELBOX_NEIGHBOUR_IN','SALES_YEAR','SALES_MONTH','SALES_VALUE','marka');
  300. // TODO: form for only 'SALES_VALUE' and eventually 'marka'
  301. $visibleCols = array('SALES_VALUE', 'marka', 'A_STATUS');
  302. $hasTypeSpecial = false;
  303. foreach ($visibleCols as $fieldName) {
  304. $fieldID = $tblAcl->getFieldIdByName($fieldName);
  305. if (!$fieldID) throw new Exception("No field by name ({$fieldName})");
  306. $fieldVal = ($tblAcl->isAllowed($fieldID, 'R', $row))? V::get($fieldName, '', $row) : '*****';
  307. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  308. $vCol = $tblAcl->getField($fieldID);
  309. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  310. $tsValues = array();
  311. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  312. if ($typeSpecial) {
  313. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  314. if (!empty($specialValues)) {
  315. $tsValues[$row->ID] = implode('<br>', $specialValues);
  316. }
  317. }
  318. ?>
  319. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  320. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  321. <?php if (!empty($vCol['opis'])) : ?>
  322. <em><?php echo $vCol['opis']; ?></em>
  323. <?php $perms = $tblAcl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  324. <?php endif; ?>
  325. </label>
  326. <?php
  327. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  328. if (!empty($tsValues[$row->ID])) {
  329. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  330. }
  331. $vDefault = $tblAcl->getColDefault($fieldName);
  332. if (!empty($vDefault)) {
  333. $fieldParams['default'] = $vDefault;
  334. }
  335. echo $tblAcl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  336. if ($typeSpecial) $hasTypeSpecial = true;
  337. }
  338. if ($hasTypeSpecial) {
  339. echo '<p style="padding:100px 0;"></p>';
  340. }
  341. ?>
  342. <input type="hidden" name="ID" value="<?php echo $record->ID; ?>" />
  343. <?php
  344. exit;
  345. }
  346. private function _getTableAcl() {
  347. $zasobObj = ProcesHelper::getZasobTableInfoByUri('default_db/deals_sales');
  348. if (!$zasobObj) throw new Exception("Zasob tabela deals_sales nie istnieje.");
  349. $userAcl = User::getAcl();
  350. $userAcl->fetchGroups();
  351. if (!$userAcl->hasTableAcl($zasobObj->ID)) throw new Exception("Brak uprawnień do tabeli ");
  352. $tblAcl = $userAcl->getTableAcl($zasobObj->ID);
  353. return $tblAcl;
  354. }
  355. public function legacy_DEALS_SALES() {
  356. $id_telboxes = V::get('id_telboxes', '', $_REQUEST);
  357. $id_companies = V::get('id_companies', '', $_REQUEST, 'int');
  358. $idTelboxes = $id_telboxes;
  359. if (!empty($idTelboxes)) {
  360. if (!empty($idTelboxes)) {
  361. if (false !== strpos($idTelboxes, ': ')) {
  362. $parts = explode(': ', $idTelboxes, 2);
  363. $idTelboxes = $parts[0];
  364. }
  365. }
  366. }
  367. SE_Layout::menu();
  368. Lib::loadClass('TypespecialVariable');
  369. $typeSpecialTelboxes = TypespecialVariable::getInstance(-1, '__DEALS_SALES_TELBOXES_NAME');
  370. $typeSpecialCompanies = null;// TypespecialVariable::getInstance(-1, '__COMPANIES');
  371. $obroty = array();
  372. $obrotyByYear = array();
  373. $marki = array();
  374. $obrotyToMarki = array();
  375. if (!empty($idTelboxes)) {
  376. $db = DB::getDB();
  377. $sqlWhere = array();
  378. $sqlWhere[] = " o.`A_STATUS`!='DELETED' ";
  379. $sqlIdTelboxes = $db->_($idTelboxes);
  380. $sqlWhere[] = " o.`T_TELBOX_NEIGHBOUR_IN`='{$sqlIdTelboxes}' ";
  381. $sqlWhere = (!empty($sqlWhere))? implode(" and ", $sqlWhere) : '';
  382. $sql = "select o.`ID`
  383. -- , d.`T_TELBOX_NEIGHBOUR_IN`
  384. , o.`T_TELBOX_NEIGHBOUR_IN`
  385. , o.`ID_DEALS_TABLE`
  386. -- , o.`SALES_DATE`
  387. , o.`SALES_YEAR`
  388. , o.`SALES_MONTH`
  389. , o.`SALES_VALUE`
  390. , o.`marka`
  391. from `DEALS_SALES` as o
  392. -- join `DEALS_TABLE` as d on (d.`ID`=o.`ID_DEALS_TABLE`)
  393. where
  394. {$sqlWhere}
  395. ";
  396. if(V::get('DBG','',$_GET)){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  397. $res = $db->query($sql);
  398. while ($r = $db->fetch($res)) {
  399. $year = $r->SALES_YEAR;
  400. $month = sprintf("%02d", $r->SALES_MONTH);
  401. $obroty[$r->ID_DEALS_TABLE][$year][$month] = $r->SALES_VALUE;
  402. $obrotyByYear[$year][$month] = floatval($r->SALES_VALUE);
  403. $marki[$r->marka] = true;
  404. $obrotyToMarki[$year][$month] = $r->marka;
  405. }
  406. }
  407. krsort($obrotyByYear);
  408. //DBG::_(true, true, "obrotyByYear", $obrotyByYear, __CLASS__, __FUNCTION__, __LINE__);
  409. //DBG::_('DBG', '>0', "marki", $marki, __CLASS__, __FUNCTION__, __LINE__);
  410. //DBG::_('DBG', '>0', "obrotyToMarki", $obrotyToMarki, __CLASS__, __FUNCTION__, __LINE__);
  411. $markiOut = array();
  412. {
  413. $markiLabels = array('primary', 'success', 'warning', 'danger', 'default');
  414. // <span class="label label-default">Default</span>
  415. reset($markiLabels);
  416. foreach ($marki as $marka => $vBool) {
  417. $markiOut[$marka] = current($markiLabels);
  418. if (!next($markiLabels)) reset($markiLabels);
  419. }
  420. }// Default Primary Success Info Warning Danger
  421. $monthsOut = array();
  422. for ($i = 0; $i < 12; $i++) $monthsOut[] = sprintf("%02d", $i + 1);
  423. $initData = new stdClass();
  424. $initData->obroty = $obrotyByYear;
  425. $initData->marki = $markiOut;
  426. $initData->obrotyToMarki = $obrotyToMarki;
  427. $initData->months = $monthsOut;
  428. $initData->years = array_keys($obrotyByYear);
  429. if (!empty($initData->years)) {
  430. $lastYear = date("Y", mktime(date('H'), date('i'), date('s'), date("m") + 3, date("d"), date("Y")));
  431. $firstYear = end($initData->years);
  432. if ($firstYear <= $lastYear) {
  433. $years = array();
  434. for ($i = $firstYear; $i <= $lastYear; $i++) {
  435. $years[] = $i;
  436. }
  437. $initData->years = array_reverse($years);
  438. }
  439. }
  440. //DBG::_(true, true, "initData", $initData, __CLASS__, __FUNCTION__, __LINE__);
  441. ?>
  442. <style type="text/css">
  443. .cell_marka_primary { background-color: #d9edf7; }
  444. .cell_marka_success { background-color: #dff0d8; }
  445. .cell_marka_warning { background-color: #fcf8e3; }
  446. .cell_marka_danger { background-color: #f2dede; }
  447. .cell_marka_default { background-color: #f5f5f5; }
  448. </style>
  449. <div class="container-fluid">
  450. <p></p>
  451. <form action="" method="GET" class="form-inline">
  452. <input type="hidden" name="_route" value="DealsSales">
  453. <table>
  454. <!--
  455. <summary>Wybierz lokal i/lub firmę w celu przeglądania obrotów </summary>
  456. -->
  457. <thead>
  458. <tr>
  459. <th style="text-align:left">Wyszukaj lokal lub markę</th>
  460. <th style="text-align:left">
  461. <?php if ($typeSpecialCompanies) : ?>
  462. Firma
  463. <?php endif; ?>
  464. </th>
  465. </tr>
  466. </thead>
  467. <tbody>
  468. <tr>
  469. <td>
  470. <?php if ($typeSpecialTelboxes) : ?>
  471. <?php
  472. $fName = 'id_telboxes';
  473. $fldParams = array();
  474. $fldParams['allowCreate'] = false;
  475. $fldParams['ajaxDataUrlBase'] = "index.php?_route=DealsSales&_task=typespecial&fld={$fName}";
  476. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  477. echo $typeSpecialTelboxes->showFormItem($tblID = -1, $fName, $selValue = $id_telboxes, $fldParams);
  478. ?>
  479. <?php endif; ?>
  480. </td>
  481. <td>
  482. <?php if ($typeSpecialCompanies) : ?>
  483. <?php
  484. $fName = 'id_companies';
  485. $fldParams = array();
  486. $fldParams['allowCreate'] = false;
  487. $fldParams['ajaxDataUrlBase'] = "index.php?_route=DealsSales&_task=typespecial&fld={$fName}";
  488. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  489. echo $typeSpecialCompanies->showFormItem($tblID = -1, $fName, $selValue = $id_companies, $fldParams);
  490. ?>
  491. <?php endif; ?>
  492. </td>
  493. </tr>
  494. <tr>
  495. <td clspan="2">
  496. <button class="btn">wybierz</button>
  497. </td>
  498. </tr>
  499. </tbody>
  500. </table>
  501. </form>
  502. <?php if (empty($obroty)) : ?>
  503. <?php else : ?>
  504. <hr>
  505. <div id="dealsSalesByMonth"></div>
  506. <script>
  507. (function($, undefined) {
  508. var DealsSalesTable = function () {
  509. var priv = {};// private api
  510. var publ = {};// public api
  511. priv.options = {};
  512. var defaults = {
  513. url: '',
  514. urlInlineEdit: '',
  515. urlSaveInlineEdit: '',
  516. initData: {},
  517. debug: false
  518. },
  519. _uiNodeCont = null,// container node
  520. _uiNode$Table = null,
  521. _inlineEditBox$Node = null,
  522. _state = {};// state - to replace variables below (date, ...)
  523. priv.init = function () {
  524. _uiNodeCont = priv.options.id;
  525. _state = {};// init state
  526. priv.initEvents();
  527. priv.initData();
  528. priv.initialRender();// set up _uiNode$...
  529. };
  530. priv.initEvents = function () {
  531. jQuery(_uiNodeCont).on('DealsSalesTable:render', priv.onRender);
  532. };
  533. priv.initData = function () {
  534. if (!priv.options.initData) return;
  535. if (priv.options.initData.obroty) _state.obroty = priv.options.initData.obroty;
  536. if (priv.options.initData.marki) _state.marki = priv.options.initData.marki;
  537. if (priv.options.initData.obrotyToMarki) _state.obrotyToMarki = priv.options.initData.obrotyToMarki;
  538. if (priv.options.initData.months) _state.months = priv.options.initData.months;
  539. if (priv.options.initData.years) _state.years = priv.options.initData.years;
  540. if (priv.options.initData.fltrMarka) _state.fltrMarka = priv.options.initData.fltrMarka;
  541. };
  542. priv.initialRender = function () {
  543. _uiNode$Marki = $('<table class="table table-bordered" style="width:auto"></table>');
  544. $('<tbody><tr><th>Marki:</th></tr></tbody>').appendTo(_uiNode$Marki);
  545. _uiNode$Marki.appendTo(_uiNodeCont);
  546. _uiNode$Table = $('<table class="table table-bordered table-hover"></table>');
  547. {// thead
  548. var thead$Node = $('<thead></thead>').appendTo(_uiNode$Table);
  549. var theadTr$Node = $('<tr></tr>').appendTo(thead$Node);
  550. $('<th></th>').appendTo(theadTr$Node);
  551. $.each(_state.months, function(index, value) {
  552. $('<th>' + value + '</th>').appendTo(theadTr$Node);
  553. });
  554. $('<th>suma</th>').appendTo(theadTr$Node);
  555. }
  556. $('<tbody></tbody>').appendTo(_uiNode$Table);
  557. _uiNode$Table.appendTo(_uiNodeCont);
  558. _uiNode$GraphByYear = $('<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto"></div>');
  559. $('<canvas id="wykres03" width="1760" height="300">[No canvas support]</canvas>').appendTo(_uiNode$GraphByYear);
  560. _uiNode$GraphByYear.appendTo(_uiNodeCont);
  561. _uiNode$GraphByMonth = $('<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto"></div>');
  562. $('<canvas id="wykres04" width="1760" height="300">[No canvas support]</canvas>').appendTo(_uiNode$GraphByMonth);
  563. _uiNode$GraphByMonth.appendTo(_uiNodeCont);
  564. priv.renderHeaderMarki();
  565. priv.renderTableBody();
  566. priv.renderGraphByYear();
  567. priv.renderGraphByMonth();
  568. priv.renderInitInlineEditBox();// .dealsSales__inlineEditBox
  569. };
  570. priv.renderGraphByYear = function(record) {
  571. var jsonData = [],
  572. jsonLabels = [],
  573. jsonTooltips = [],
  574. jsonColors = ['Gradient(#fe783e:#EC561B:#F59F7D)', 'Gradient(#99f:#27afe9:#058DC7:#058DC7)', 'Gradient(#94f776:#50B332:#B1E59F)', 'Gradient(#CC76F7:#8832B3:#CE9FE5)', 'Gradient(#768CF7:#3247B3:#9FABE5)', 'Gradient(#F77681:#B3323C:#E59FA5)'],
  575. jsonColorsAll = [],
  576. wykresWidth = 940,
  577. wykresMinItemWidth = 15,
  578. graphGutterLeft = 60,
  579. graphGutterRight = 25,
  580. itemsInLabelCount = 0,
  581. currentNode = _uiNode$GraphByYear.children('canvas'),
  582. node = $('<canvas id="wykres03" width="1760" height="300">[No canvas support]</canvas>')
  583. ;
  584. {// replace node
  585. currentNode.replaceWith(node);
  586. }
  587. $.each(_state.obroty, function(kYear, vSalesByMonth) {
  588. var jsonYearData = {},
  589. yearDataValues = []
  590. ;
  591. jsonLabels.push(parseInt(kYear));
  592. $.each(_state.months, function(monthIdx, vMonth) {
  593. var isFilteredOutByMarka = false;
  594. if (_state.fltrMarka) {
  595. if (_state.fltrMarka != _state.obrotyToMarki[kYear][vMonth]) {
  596. isFilteredOutByMarka = true;
  597. }
  598. }
  599. if (undefined === vSalesByMonth[vMonth] || isFilteredOutByMarka) {
  600. jsonYearData['' + kYear + '-' + vMonth] = 0;
  601. } else {
  602. jsonYearData['' + kYear + '-' + vMonth] = vSalesByMonth[vMonth];
  603. }
  604. });
  605. $.each(jsonYearData, function(kLabel, vValue) {
  606. jsonTooltips.push('Obrót ' + numeral(vValue).format('0,0[.]00') + ' w ' + kLabel);
  607. });
  608. yearDataValues = Object.keys(jsonYearData).map(function (key) {
  609. return jsonYearData[key];
  610. });
  611. jsonData.push(yearDataValues);
  612. itemsInLabelCount = Math.max(itemsInLabelCount, yearDataValues.length);
  613. });
  614. {// colors
  615. for (var i = 0, mi = 0, mc = jsonColors.length; i < 12; i++) {
  616. jsonColorsAll.push(jsonColors[mi]);
  617. if (++mi >= mc) {
  618. mi = 0;
  619. }
  620. }
  621. jsonColors = jsonColorsAll;
  622. }
  623. {// wykres width
  624. wykresTestWidth = jsonLabels.length * (20 * 2 + itemsInLabelCount * wykresMinItemWidth) + graphGutterLeft + graphGutterRight;
  625. wykresWidth = Math.max(wykresWidth, wykresTestWidth);
  626. jQuery('#wykres03').css({width: wykresWidth});
  627. }
  628. var bar = new RGraph.Bar('wykres03', jsonData)
  629. .Set('labels', jsonLabels)
  630. .Set('colors', jsonColors)
  631. .Set('strokestyle', 'white')
  632. .Set('linewidth', 1)
  633. .Set('shadow', true)
  634. .Set('shadow.color', '#ccc')
  635. .Set('shadow.offsetx', 0)
  636. .Set('shadow.offsety', 0)
  637. .Set('shadow.blur', 10)
  638. .Set('gutter.bottom', 30)
  639. .Set('gutter.left', graphGutterLeft)
  640. .Set('gutter.right', graphGutterRight)
  641. .Set('tooltips', RGraph.ISOLD ? null : jsonTooltips)
  642. .Set('tooltips.event', 'mousemove')
  643. .Set('labels.above', true)
  644. .Set('hmargin', 20)
  645. .Draw();
  646. };
  647. priv.renderGraphByMonth = function(record) {
  648. var jsonData = [],
  649. jsonLabels = ['styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec','sierpień','wrzesień','październik','listopad','grudzień'],
  650. jsonTooltips = [],
  651. jsonColors = ['Gradient(#fe783e:#EC561B:#F59F7D)', 'Gradient(#99f:#27afe9:#058DC7:#058DC7)', 'Gradient(#94f776:#50B332:#B1E59F)', 'Gradient(#CC76F7:#8832B3:#CE9FE5)', 'Gradient(#768CF7:#3247B3:#9FABE5)', 'Gradient(#F77681:#B3323C:#E59FA5)'],
  652. jsonColorsAll = [],
  653. wykresWidth = 940,
  654. wykresMinItemWidth = 15,
  655. graphGutterLeft = 60,
  656. graphGutterRight = 25,
  657. itemsInLabelCount = 0,
  658. currentNode = _uiNode$GraphByMonth.children('canvas'),
  659. node = $('<canvas id="wykres04" width="1760" height="300">[No canvas support]</canvas>')
  660. ;
  661. {// replace node
  662. currentNode.replaceWith(node);
  663. }
  664. $.each(_state.months, function(monthIdx, vMonth) {
  665. var jsonByMonthData = {},
  666. byMonthDataValues = []
  667. ;
  668. $.each(_state.obroty, function(kYear, vSalesByMonth) {
  669. var isFilteredOutByMarka = false;
  670. if (_state.fltrMarka) {
  671. if (_state.fltrMarka != _state.obrotyToMarki[kYear][vMonth]) {
  672. isFilteredOutByMarka = true;
  673. }
  674. }
  675. if (undefined === vSalesByMonth[vMonth] || isFilteredOutByMarka) {
  676. jsonByMonthData['' + kYear + '-' + vMonth] = 0;
  677. } else {
  678. jsonByMonthData['' + kYear + '-' + vMonth] = vSalesByMonth[vMonth];
  679. }
  680. });
  681. $.each(jsonByMonthData, function(kLabel, vValue) {
  682. jsonTooltips.push('Obrót ' + numeral(vValue).format('0,0[.]00') + ' w ' + kLabel);
  683. });
  684. byMonthDataValues = Object.keys(jsonByMonthData).map(function (key) {
  685. return jsonByMonthData[key];
  686. });
  687. jsonData.push(byMonthDataValues);
  688. itemsInLabelCount = Math.max(itemsInLabelCount, byMonthDataValues.length);
  689. });
  690. {// colors
  691. for (var i = 0, mi = 0, mc = jsonColors.length; i < 12; i++) {
  692. jsonColorsAll.push(jsonColors[mi]);
  693. if (++mi >= mc) {
  694. mi = 0;
  695. }
  696. }
  697. jsonColors = jsonColorsAll;
  698. }
  699. {// wykres width
  700. wykresTestWidth = jsonLabels.length * (20 * 2 + itemsInLabelCount * wykresMinItemWidth) + graphGutterLeft + graphGutterRight;
  701. wykresWidth = Math.max(wykresWidth, wykresTestWidth);
  702. jQuery('#wykres04').css({width: wykresWidth});
  703. }
  704. var bar = new RGraph.Bar('wykres04', jsonData)
  705. .Set('labels', jsonLabels)
  706. .Set('colors', jsonColors)
  707. .Set('strokestyle', 'white')
  708. .Set('linewidth', 1)
  709. .Set('shadow', true)
  710. .Set('shadow.color', '#ccc')
  711. .Set('shadow.offsetx', 0)
  712. .Set('shadow.offsety', 0)
  713. .Set('shadow.blur', 10)
  714. .Set('gutter.bottom', 30)
  715. .Set('gutter.left', graphGutterLeft)
  716. .Set('gutter.right', graphGutterRight)
  717. .Set('tooltips', RGraph.ISOLD ? null : jsonTooltips)
  718. .Set('tooltips.event', 'mousemove')
  719. .Set('labels.above', true)
  720. .Set('hmargin', 20)
  721. .Draw();
  722. };
  723. priv.renderHeaderMarki = function(record) {
  724. var currentNode = _uiNode$Marki.children('tbody').children('tr'),
  725. node = $('<tr></tr>'),
  726. marki = _state.marki,
  727. th$ = $('<th><i class="glyphicon glyphicon-filter"></i> Marki:</th>').appendTo(node);
  728. ;
  729. if (_state.fltrMarka) {
  730. rmFltrBtn = $('<i title="Pokaż wszystkie marki" class="glyphicon glyphicon-remove" style="cursor:pointer; color:red; opacity:0.4;"></i>');
  731. rmFltrBtn.on('click', priv.removeFltrMarka);
  732. rmFltrBtn.prependTo(th$);
  733. }
  734. $.each(_state.marki, function(markaLabel, markaClassName) {
  735. var isFiltered = (_state.fltrMarka == markaLabel),
  736. markaInput = '<input type="radio" title="Pokaż tylko markę ' + markaLabel + '" name="fltr_marka" value="' + markaLabel + '" ' + (isFiltered ? ' checked="checked"' : '') + '>',
  737. td$Node = $('<td>' + markaInput + ' <b>' + markaLabel + '</b></td>').appendTo(node)
  738. ;
  739. td$Node.addClass('cell_marka_' + markaClassName);
  740. td$Node.on('click', 'input', priv.filterMarka);
  741. });
  742. currentNode.replaceWith(node);
  743. };
  744. priv.removeFltrMarka = function(e) {
  745. _state.fltrMarka = null;
  746. jQuery(_uiNodeCont).trigger('DealsSalesTable:render', ['body','marki','graphs']);
  747. };
  748. priv.filterMarka = function(e) {
  749. var target$ = $(e.target),
  750. isChecked = target$.is(':checked');
  751. console.log('isChecked', isChecked, 'target$', target$, 'e', e);
  752. _state.fltrMarka = (isChecked)? target$.val() : null;
  753. jQuery(_uiNodeCont).trigger('DealsSalesTable:render', ['body','marki','graphs']);
  754. };
  755. priv.renderTableBody = function(record) {
  756. var currentNode = _uiNode$Table.children('tbody'),
  757. node = $('<tbody></tbody>'),
  758. vSalesByYear = _state.obroty
  759. ;
  760. $.each(_state.years, function(yearIdx, vYearId) {
  761. var vSalesByMonth = vSalesByYear[vYearId];
  762. var tr$Node = $('<tr></tr>').appendTo(node);
  763. $('<th>' + vYearId + '</th>').appendTo(tr$Node);
  764. var suma = 0;
  765. $.each(_state.months, function(monthsIdx, vMonth) {
  766. var td$Node = $('<td></td>').appendTo(tr$Node);
  767. td$Node.css({textAlign: 'right'});
  768. var saleValue = NaN;
  769. if (vSalesByMonth) {
  770. saleValue = parseFloat(vSalesByMonth[vMonth]);
  771. if (_state.fltrMarka) {
  772. if (_state.fltrMarka != _state.obrotyToMarki[vYearId][vMonth]) {
  773. saleValue = NaN;
  774. }
  775. }
  776. }
  777. if (isNaN(saleValue)) {
  778. td$Node.text('...');
  779. td$Node.css({color: '#ddd'});
  780. } else {
  781. suma += saleValue;
  782. $('<nobr>' + numeral(saleValue).format('0,0[.]00') + '</nobr>').appendTo(td$Node);
  783. if (undefined !== _state.obrotyToMarki[vYearId][vMonth]) {
  784. var marka = _state.obrotyToMarki[vYearId][vMonth];
  785. td$Node.addClass('cell_marka_' + _state.marki[marka]);
  786. }
  787. }
  788. td$Node.on('dblclick', {year:vYearId, month:vMonth}, priv.cellDblClicked);
  789. });
  790. var suma$Node = $('<td>' + numeral(suma).format('0,0[.]00') + '</td>').appendTo(tr$Node);
  791. suma$Node.css({textAlign: 'right'});
  792. });
  793. currentNode.replaceWith(node);
  794. };
  795. priv.renderInitInlineEditBox = function() {
  796. var nodeClass = 'dealsSales__inlineEditBox',
  797. node;
  798. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  799. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  800. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  801. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  802. var iebHead = $('<div class="modal-header">').appendTo(frmInlineEdit);
  803. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(iebHead);
  804. $('<h3 id="myModalLabel">Edytuj</h3>').appendTo(iebHead);
  805. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  806. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  807. //$('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  808. //$('<input type="hidden" name="col" value="">').appendTo(iebBody);
  809. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  810. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  811. $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  812. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  813. frmInlineEdit.on('submit', function() {
  814. var data = _inlineEditBox$Node.find('form').serialize();
  815. _inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  816. function notifyAjaxCallback(data) {
  817. var notify = {};
  818. notify.type = (data && data.type)? data.type : '';
  819. notify.msg = (data && data.msg)? data.msg : '';
  820. switch (notify.type) {
  821. case 'success':
  822. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  823. break;
  824. case 'info':
  825. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  826. break;
  827. case 'error':
  828. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  829. break;
  830. case 'warning':
  831. notify.type = 'warn';
  832. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  833. break;
  834. default:
  835. notify.msg = 'Nieznany błąd';
  836. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  837. notify.type = '';
  838. }
  839. jQuery.notify(notify.msg, notify.type);
  840. }
  841. $.ajax({
  842. data: data,
  843. dataType: 'json',
  844. type: "POST",
  845. url: priv.options.urlSaveInlineEdit
  846. })
  847. .done(function(data, textStatus, jqXHR){
  848. notifyAjaxCallback(data);
  849. if (data.record) {
  850. var year = data.record.SALES_YEAR,
  851. month = data.record.SALES_MONTH,
  852. status = data.record.A_STATUS,
  853. saleValue = parseFloat(data.record.SALES_VALUE),
  854. marka = data.record.marka,
  855. state = {}
  856. ;
  857. if (month < 10) month = '0' + month;
  858. // TODO: if marka changed - fix state
  859. if ('DELETED' === status) {
  860. state.obroty = {};
  861. state.obroty[year] = {};
  862. state.obroty[year][month] = null;
  863. state.obrotyToMarki = {};
  864. state.obrotyToMarki[year] = {};
  865. state.obrotyToMarki[year][month] = null;
  866. } else {
  867. state.obroty = {};
  868. state.obroty[year] = {};
  869. state.obroty[year][month] = saleValue;
  870. state.obrotyToMarki = {};
  871. state.obrotyToMarki[year] = {};
  872. state.obrotyToMarki[year][month] = marka;
  873. }
  874. priv.setState(state);
  875. }
  876. _inlineEditBox$Node.modal('hide');
  877. })
  878. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  879. if (jqXHR.responseJSON) {
  880. notifyAjaxCallback(jqXHR.responseJSON);
  881. }
  882. else {
  883. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  884. if (jqXHR.status == 404) {
  885. jQuery.notify(jqXHR.responseText, 'error');
  886. } else {
  887. jQuery.notify(jqXHR.responseText, 'warn');
  888. }
  889. }
  890. _inlineEditBox$Node.modal('hide');
  891. });
  892. return false;
  893. });
  894. node.appendTo(_uiNodeCont);//currentNode.replaceWith(node);
  895. _inlineEditBox$Node = node;
  896. };
  897. priv.cellDblClicked = function(e) {
  898. if ('year' in e.data && 'month' in e.data && e.data.year > 0 && e.data.month > 0) {
  899. _inlineEditBox$Node.modal();
  900. _inlineEditBox$Node.show();
  901. _inlineEditBox$Node.on('shown.bs.modal', function(e) {
  902. var dialogBox = jQuery(this).find('.modal-dialog'),
  903. modalBody = dialogBox.find('.modal-body'),
  904. boudingRect = dialogBox.get(0).getBoundingClientRect();
  905. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  906. modalBody.css({overflow: 'scroll'});
  907. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  908. dialogBox.draggable();
  909. });
  910. _inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  911. var dialogBox = jQuery(this).find('.modal-dialog'),
  912. modalBody = dialogBox.find('.modal-body');
  913. dialogBox.removeAttr('style');
  914. modalBody.removeAttr('style');
  915. modalBody.css({padding: '0'});
  916. dialogBox.resizable();
  917. dialogBox.draggable();
  918. dialogBox.resizable('destroy');
  919. dialogBox.draggable('destroy');
  920. });
  921. _inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  922. _inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  923. _inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  924. $.ajax({
  925. url: priv.options.urlInlineEdit,
  926. type: 'GET',
  927. dataType: 'text',
  928. data: e.data,
  929. async: true,
  930. success: function (data) {
  931. _inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
  932. _inlineEditBox$Node.find('.btn-save').show();
  933. initDateTimePicker(_inlineEditBox$Node);
  934. _inlineEditBox$Node.find('textarea').autosize();
  935. var fld = _inlineEditBox$Node.find('input[id^="f"]:first');
  936. if (fld && !fld.hasClass('se_type-date')) {
  937. fld.focus();
  938. fld.keydown(function(event) {
  939. if (event.which == 13) {
  940. event.preventDefault();
  941. _inlineEditBox$Node.find('form').submit();
  942. }
  943. });
  944. }
  945. },
  946. error: function (err) {
  947. if (priv.options.debug) console.log('err');
  948. }
  949. });
  950. } else {
  951. if (priv.options.debug) console.log('NO data');
  952. return false;
  953. }
  954. };
  955. priv.onRender = function(e) {// jQuery(_uiNodeCont).trigger('DealsSalesTable:render', [...]);
  956. if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  957. if (arguments.length > 1) {
  958. for (var i=1; i<arguments.length; i++) {
  959. switch (arguments[i]) {
  960. case 'body': priv.renderTableBody(); break;
  961. case 'marki': priv.renderHeaderMarki(); break;
  962. case 'graphs': priv.renderGraphByYear(); priv.renderGraphByMonth(); break;
  963. }
  964. }
  965. }
  966. };
  967. priv.setState = function(state) {
  968. var oldState = _state,// TODO: use to check what really changed (use extend!)
  969. renderParts = {};
  970. if (state.obroty) {
  971. $.each(state.obroty, function(kYear, vSalesByMonth) {
  972. $.each(vSalesByMonth, function(kMonth, vSaleValue) {
  973. if (null === vSaleValue) {
  974. _state.obroty[kYear][kMonth] = undefined;
  975. } else {
  976. _state.obroty[kYear][kMonth] = vSaleValue;
  977. }
  978. });
  979. });
  980. renderParts['body'] = true;
  981. renderParts['graphs'] = true;
  982. }
  983. /*
  984. state.obrotyToMarki[year][month] = marka;
  985. */
  986. if (state.obrotyToMarki) {
  987. $.each(state.obrotyToMarki, function(kYear, vMarkiByMonth) {
  988. $.each(vMarkiByMonth, function(kMonth, vMarka) {
  989. if (null === vMarka) {
  990. _state.obrotyToMarki[kYear][kMonth] = undefined;
  991. } else {
  992. _state.obrotyToMarki[kYear][kMonth] = vMarka;
  993. if (undefined === _state.marki[vMarka]) {
  994. _state.marki[vMarka] = 'default';
  995. }
  996. }
  997. });
  998. });
  999. renderParts['marki'] = true;
  1000. }
  1001. renderParts = Object.keys(renderParts);
  1002. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1003. if (renderParts.length > 0) {
  1004. jQuery(_uiNodeCont).trigger('DealsSalesTable:render', renderParts);
  1005. }
  1006. };
  1007. publ.init = function (options) {
  1008. if (priv.options.debug) console.log('DealsSalesTable initialization...');
  1009. //merge supplied options with defaults
  1010. $.extend(priv.options, defaults, options);
  1011. priv.init();
  1012. return publ;
  1013. };
  1014. return publ;
  1015. };
  1016. $.fn.DealsSalesTable = function (options) {
  1017. options = options || {};
  1018. return this.each(function () {
  1019. options.id = this;
  1020. $(this).data('DealsSalesTable', new DealsSalesTable().init(options));
  1021. });
  1022. };
  1023. })(jQuery);
  1024. jQuery(document).ready(function() {
  1025. jQuery('#dealsSalesByMonth').DealsSalesTable({
  1026. url: 'index.php?_route=DealsSales&_task=getDataAjax&telbox=<?php echo $idTelboxes; ?>',
  1027. urlInlineEdit: 'index.php?_route=DealsSales&_task=inlineEditAjax&telbox=<?php echo $idTelboxes; ?>',
  1028. urlSaveInlineEdit: 'index.php?_route=DealsSales&_task=saveInlineAjax&telbox=<?php echo $idTelboxes; ?>',
  1029. initData: <?php echo json_encode($initData); ?>
  1030. });
  1031. });
  1032. </script>
  1033. <script src="stuff/RGraph/libraries/RGraph.common.core.js?_v=20140626"></script>
  1034. <script src="stuff/RGraph/libraries/RGraph.common.dynamic.js?_v=20140626"></script>
  1035. <script src="stuff/RGraph/libraries/RGraph.common.key.js?_v=20140626"></script>
  1036. <script src="stuff/RGraph/libraries/RGraph.drawing.rect.js?_v=20140626"></script>
  1037. <script src="stuff/RGraph/libraries/RGraph.common.tooltips.js?_v=20140626"></script>
  1038. <script src="stuff/RGraph/libraries/RGraph.bar.js?_v=20140626"></script>
  1039. <script src="stuff/RGraph/libraries/RGraph.line.js?_v=20140626"></script>
  1040. <?php endif; ?>
  1041. </div>
  1042. <?php
  1043. }
  1044. }