DealsSales.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. //DBG::_(true, true, "initData", $initData, __CLASS__, __FUNCTION__, __LINE__);
  430. ?>
  431. <style type="text/css">
  432. .cell_marka_primary { background-color: #d9edf7; }
  433. .cell_marka_success { background-color: #dff0d8; }
  434. .cell_marka_warning { background-color: #fcf8e3; }
  435. .cell_marka_danger { background-color: #f2dede; }
  436. .cell_marka_default { background-color: #f5f5f5; }
  437. </style>
  438. <div class="container-fluid">
  439. <p></p>
  440. <form action="" method="GET" class="form-inline">
  441. <input type="hidden" name="_route" value="DealsSales">
  442. <table>
  443. <!--
  444. <summary>Wybierz lokal i/lub firmę w celu przeglądania obrotów </summary>
  445. -->
  446. <thead>
  447. <tr>
  448. <th style="text-align:left">Wyszukaj lokal lub markę</th>
  449. <th style="text-align:left">
  450. <?php if ($typeSpecialCompanies) : ?>
  451. Firma
  452. <?php endif; ?>
  453. </th>
  454. </tr>
  455. </thead>
  456. <tbody>
  457. <tr>
  458. <td>
  459. <?php if ($typeSpecialTelboxes) : ?>
  460. <?php
  461. $fName = 'id_telboxes';
  462. $fldParams = array();
  463. $fldParams['allowCreate'] = false;
  464. $fldParams['ajaxDataUrlBase'] = "index.php?_route=DealsSales&_task=typespecial&fld={$fName}";
  465. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  466. echo $typeSpecialTelboxes->showFormItem($tblID = -1, $fName, $selValue = $id_telboxes, $fldParams);
  467. ?>
  468. <?php endif; ?>
  469. </td>
  470. <td>
  471. <?php if ($typeSpecialCompanies) : ?>
  472. <?php
  473. $fName = 'id_companies';
  474. $fldParams = array();
  475. $fldParams['allowCreate'] = false;
  476. $fldParams['ajaxDataUrlBase'] = "index.php?_route=DealsSales&_task=typespecial&fld={$fName}";
  477. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  478. echo $typeSpecialCompanies->showFormItem($tblID = -1, $fName, $selValue = $id_companies, $fldParams);
  479. ?>
  480. <?php endif; ?>
  481. </td>
  482. </tr>
  483. <tr>
  484. <td clspan="2">
  485. <button class="btn">wybierz</button>
  486. </td>
  487. </tr>
  488. </tbody>
  489. </table>
  490. </form>
  491. <?php if (empty($obroty)) : ?>
  492. <?php else : ?>
  493. <hr>
  494. <div id="dealsSalesByMonth"></div>
  495. <script>
  496. (function($, undefined) {
  497. var DealsSalesTable = function () {
  498. var priv = {};// private api
  499. var publ = {};// public api
  500. priv.options = {};
  501. var defaults = {
  502. url: '',
  503. urlInlineEdit: '',
  504. urlSaveInlineEdit: '',
  505. initData: {},
  506. debug: false
  507. },
  508. _uiNodeCont = null,// container node
  509. _uiNode$Table = null,
  510. _inlineEditBox$Node = null,
  511. _state = {};// state - to replace variables below (date, ...)
  512. priv.init = function () {
  513. _uiNodeCont = priv.options.id;
  514. _state = {};// init state
  515. priv.initEvents();
  516. priv.initData();
  517. priv.initialRender();// set up _uiNode$...
  518. };
  519. priv.initEvents = function () {
  520. jQuery(_uiNodeCont).on('DealsSalesTable:render', priv.onRender);
  521. };
  522. priv.initData = function () {
  523. if (!priv.options.initData) return;
  524. if (priv.options.initData.obroty) _state.obroty = priv.options.initData.obroty;
  525. if (priv.options.initData.marki) _state.marki = priv.options.initData.marki;
  526. if (priv.options.initData.obrotyToMarki) _state.obrotyToMarki = priv.options.initData.obrotyToMarki;
  527. if (priv.options.initData.months) _state.months = priv.options.initData.months;
  528. if (priv.options.initData.years) _state.years = priv.options.initData.years;
  529. if (priv.options.initData.fltrMarka) _state.fltrMarka = priv.options.initData.fltrMarka;
  530. };
  531. priv.initialRender = function () {
  532. _uiNode$Marki = $('<table class="table table-bordered" style="width:auto"></table>');
  533. $('<tbody><tr><th>Marki:</th></tr></tbody>').appendTo(_uiNode$Marki);
  534. _uiNode$Marki.appendTo(_uiNodeCont);
  535. _uiNode$Table = $('<table class="table table-bordered table-hover"></table>');
  536. {// thead
  537. var thead$Node = $('<thead></thead>').appendTo(_uiNode$Table);
  538. var theadTr$Node = $('<tr></tr>').appendTo(thead$Node);
  539. $('<th></th>').appendTo(theadTr$Node);
  540. $.each(_state.months, function(index, value) {
  541. $('<th>' + value + '</th>').appendTo(theadTr$Node);
  542. });
  543. $('<th>suma</th>').appendTo(theadTr$Node);
  544. }
  545. $('<tbody></tbody>').appendTo(_uiNode$Table);
  546. _uiNode$Table.appendTo(_uiNodeCont);
  547. _uiNode$GraphByYear = $('<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto"></div>');
  548. $('<canvas id="wykres03" width="1760" height="300">[No canvas support]</canvas>').appendTo(_uiNode$GraphByYear);
  549. _uiNode$GraphByYear.appendTo(_uiNodeCont);
  550. _uiNode$GraphByMonth = $('<div style="width:100%; margin:10px 0; border:1px solid gray; overflow:auto"></div>');
  551. $('<canvas id="wykres04" width="1760" height="300">[No canvas support]</canvas>').appendTo(_uiNode$GraphByMonth);
  552. _uiNode$GraphByMonth.appendTo(_uiNodeCont);
  553. priv.renderHeaderMarki();
  554. priv.renderTableBody();
  555. priv.renderGraphByYear();
  556. priv.renderGraphByMonth();
  557. priv.renderInitInlineEditBox();// .dealsSales__inlineEditBox
  558. };
  559. priv.renderGraphByYear = function(record) {
  560. var jsonData = [],
  561. jsonLabels = [],
  562. jsonTooltips = [],
  563. 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)'],
  564. jsonColorsAll = [],
  565. wykresWidth = 940,
  566. wykresMinItemWidth = 15,
  567. graphGutterLeft = 60,
  568. graphGutterRight = 25,
  569. itemsInLabelCount = 0,
  570. currentNode = _uiNode$GraphByYear.children('canvas'),
  571. node = $('<canvas id="wykres03" width="1760" height="300">[No canvas support]</canvas>')
  572. ;
  573. {// replace node
  574. currentNode.replaceWith(node);
  575. }
  576. $.each(_state.obroty, function(kYear, vSalesByMonth) {
  577. var jsonYearData = {},
  578. yearDataValues = []
  579. ;
  580. jsonLabels.push(parseInt(kYear));
  581. $.each(_state.months, function(monthIdx, vMonth) {
  582. var isFilteredOutByMarka = false;
  583. if (_state.fltrMarka) {
  584. if (_state.fltrMarka != _state.obrotyToMarki[kYear][vMonth]) {
  585. isFilteredOutByMarka = true;
  586. }
  587. }
  588. if (undefined === vSalesByMonth[vMonth] || isFilteredOutByMarka) {
  589. jsonYearData['' + kYear + '-' + vMonth] = 0;
  590. } else {
  591. jsonYearData['' + kYear + '-' + vMonth] = vSalesByMonth[vMonth];
  592. }
  593. });
  594. $.each(jsonYearData, function(kLabel, vValue) {
  595. jsonTooltips.push('Obrót ' + numeral(vValue).format('0,0[.]00') + ' w ' + kLabel);
  596. });
  597. yearDataValues = Object.keys(jsonYearData).map(function (key) {
  598. return jsonYearData[key];
  599. });
  600. jsonData.push(yearDataValues);
  601. itemsInLabelCount = Math.max(itemsInLabelCount, yearDataValues.length);
  602. });
  603. {// colors
  604. for (var i = 0, mi = 0, mc = jsonColors.length; i < 12; i++) {
  605. jsonColorsAll.push(jsonColors[mi]);
  606. if (++mi >= mc) {
  607. mi = 0;
  608. }
  609. }
  610. jsonColors = jsonColorsAll;
  611. }
  612. {// wykres width
  613. wykresTestWidth = jsonLabels.length * (20 * 2 + itemsInLabelCount * wykresMinItemWidth) + graphGutterLeft + graphGutterRight;
  614. wykresWidth = Math.max(wykresWidth, wykresTestWidth);
  615. jQuery('#wykres03').css({width: wykresWidth});
  616. }
  617. var bar = new RGraph.Bar('wykres03', jsonData)
  618. .Set('labels', jsonLabels)
  619. .Set('colors', jsonColors)
  620. .Set('strokestyle', 'white')
  621. .Set('linewidth', 1)
  622. .Set('shadow', true)
  623. .Set('shadow.color', '#ccc')
  624. .Set('shadow.offsetx', 0)
  625. .Set('shadow.offsety', 0)
  626. .Set('shadow.blur', 10)
  627. .Set('gutter.bottom', 30)
  628. .Set('gutter.left', graphGutterLeft)
  629. .Set('gutter.right', graphGutterRight)
  630. .Set('tooltips', RGraph.ISOLD ? null : jsonTooltips)
  631. .Set('tooltips.event', 'mousemove')
  632. .Set('labels.above', true)
  633. .Set('hmargin', 20)
  634. .Draw();
  635. };
  636. priv.renderGraphByMonth = function(record) {
  637. var jsonData = [],
  638. jsonLabels = ['styczeń','luty','marzec','kwiecień','maj','czerwiec','lipiec','sierpień','wrzesień','październik','listopad','grudzień'],
  639. jsonTooltips = [],
  640. 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)'],
  641. jsonColorsAll = [],
  642. wykresWidth = 940,
  643. wykresMinItemWidth = 15,
  644. graphGutterLeft = 60,
  645. graphGutterRight = 25,
  646. itemsInLabelCount = 0,
  647. currentNode = _uiNode$GraphByMonth.children('canvas'),
  648. node = $('<canvas id="wykres04" width="1760" height="300">[No canvas support]</canvas>')
  649. ;
  650. {// replace node
  651. currentNode.replaceWith(node);
  652. }
  653. $.each(_state.months, function(monthIdx, vMonth) {
  654. var jsonByMonthData = {},
  655. byMonthDataValues = []
  656. ;
  657. $.each(_state.obroty, function(kYear, vSalesByMonth) {
  658. var isFilteredOutByMarka = false;
  659. if (_state.fltrMarka) {
  660. if (_state.fltrMarka != _state.obrotyToMarki[kYear][vMonth]) {
  661. isFilteredOutByMarka = true;
  662. }
  663. }
  664. if (undefined === vSalesByMonth[vMonth] || isFilteredOutByMarka) {
  665. jsonByMonthData['' + kYear + '-' + vMonth] = 0;
  666. } else {
  667. jsonByMonthData['' + kYear + '-' + vMonth] = vSalesByMonth[vMonth];
  668. }
  669. });
  670. $.each(jsonByMonthData, function(kLabel, vValue) {
  671. jsonTooltips.push('Obrót ' + numeral(vValue).format('0,0[.]00') + ' w ' + kLabel);
  672. });
  673. byMonthDataValues = Object.keys(jsonByMonthData).map(function (key) {
  674. return jsonByMonthData[key];
  675. });
  676. jsonData.push(byMonthDataValues);
  677. itemsInLabelCount = Math.max(itemsInLabelCount, byMonthDataValues.length);
  678. });
  679. {// colors
  680. for (var i = 0, mi = 0, mc = jsonColors.length; i < 12; i++) {
  681. jsonColorsAll.push(jsonColors[mi]);
  682. if (++mi >= mc) {
  683. mi = 0;
  684. }
  685. }
  686. jsonColors = jsonColorsAll;
  687. }
  688. {// wykres width
  689. wykresTestWidth = jsonLabels.length * (20 * 2 + itemsInLabelCount * wykresMinItemWidth) + graphGutterLeft + graphGutterRight;
  690. wykresWidth = Math.max(wykresWidth, wykresTestWidth);
  691. jQuery('#wykres04').css({width: wykresWidth});
  692. }
  693. var bar = new RGraph.Bar('wykres04', jsonData)
  694. .Set('labels', jsonLabels)
  695. .Set('colors', jsonColors)
  696. .Set('strokestyle', 'white')
  697. .Set('linewidth', 1)
  698. .Set('shadow', true)
  699. .Set('shadow.color', '#ccc')
  700. .Set('shadow.offsetx', 0)
  701. .Set('shadow.offsety', 0)
  702. .Set('shadow.blur', 10)
  703. .Set('gutter.bottom', 30)
  704. .Set('gutter.left', graphGutterLeft)
  705. .Set('gutter.right', graphGutterRight)
  706. .Set('tooltips', RGraph.ISOLD ? null : jsonTooltips)
  707. .Set('tooltips.event', 'mousemove')
  708. .Set('labels.above', true)
  709. .Set('hmargin', 20)
  710. .Draw();
  711. };
  712. priv.renderHeaderMarki = function(record) {
  713. var currentNode = _uiNode$Marki.children('tbody').children('tr'),
  714. node = $('<tr></tr>'),
  715. marki = _state.marki,
  716. th$ = $('<th><i class="glyphicon glyphicon-filter"></i> Marki:</th>').appendTo(node);
  717. ;
  718. if (_state.fltrMarka) {
  719. rmFltrBtn = $('<i title="Pokaż wszystkie marki" class="glyphicon glyphicon-remove" style="cursor:pointer; color:red; opacity:0.4;"></i>');
  720. rmFltrBtn.on('click', priv.removeFltrMarka);
  721. rmFltrBtn.prependTo(th$);
  722. }
  723. $.each(_state.marki, function(markaLabel, markaClassName) {
  724. var isFiltered = (_state.fltrMarka == markaLabel),
  725. markaInput = '<input type="radio" title="Pokaż tylko markę ' + markaLabel + '" name="fltr_marka" value="' + markaLabel + '" ' + (isFiltered ? ' checked="checked"' : '') + '>',
  726. td$Node = $('<td>' + markaInput + ' <b>' + markaLabel + '</b></td>').appendTo(node)
  727. ;
  728. td$Node.addClass('cell_marka_' + markaClassName);
  729. td$Node.on('click', 'input', priv.filterMarka);
  730. });
  731. currentNode.replaceWith(node);
  732. };
  733. priv.removeFltrMarka = function(e) {
  734. _state.fltrMarka = null;
  735. jQuery(_uiNodeCont).trigger('DealsSalesTable:render', ['body','marki','graphs']);
  736. };
  737. priv.filterMarka = function(e) {
  738. var target$ = $(e.target),
  739. isChecked = target$.is(':checked');
  740. console.log('isChecked', isChecked, 'target$', target$, 'e', e);
  741. _state.fltrMarka = (isChecked)? target$.val() : null;
  742. jQuery(_uiNodeCont).trigger('DealsSalesTable:render', ['body','marki','graphs']);
  743. };
  744. priv.renderTableBody = function(record) {
  745. var currentNode = _uiNode$Table.children('tbody'),
  746. node = $('<tbody></tbody>'),
  747. vSalesByYear = _state.obroty
  748. ;
  749. $.each(_state.years, function(yearIdx, vYearId) {
  750. var vSalesByMonth = vSalesByYear[vYearId];
  751. var tr$Node = $('<tr></tr>').appendTo(node);
  752. $('<th>' + vYearId + '</th>').appendTo(tr$Node);
  753. var suma = 0;
  754. $.each(_state.months, function(monthsIdx, vMonth) {
  755. var td$Node = $('<td></td>').appendTo(tr$Node);
  756. if (_state.fltrMarka) {
  757. if (_state.fltrMarka != _state.obrotyToMarki[vYearId][vMonth]) {
  758. return;
  759. }
  760. }
  761. td$Node.css({textAlign: 'right'});
  762. var saleValue = parseFloat(vSalesByMonth[vMonth]);
  763. //if (!vSalesByMonth.hasOwnProperty(vMonth)) {
  764. if (isNaN(saleValue)) {
  765. td$Node.text('...');
  766. td$Node.css({color: '#ddd'});
  767. } else {
  768. suma += saleValue;
  769. $('<nobr>' + numeral(saleValue).format('0,0[.]00') + '</nobr>').appendTo(td$Node);
  770. if (undefined !== _state.obrotyToMarki[vYearId][vMonth]) {
  771. var marka = _state.obrotyToMarki[vYearId][vMonth];
  772. td$Node.addClass('cell_marka_' + _state.marki[marka]);
  773. }
  774. }
  775. td$Node.on('dblclick', {year:vYearId, month:vMonth}, priv.cellDblClicked);
  776. });
  777. var suma$Node = $('<td>' + numeral(suma).format('0,0[.]00') + '</td>').appendTo(tr$Node);
  778. suma$Node.css({textAlign: 'right'});
  779. });
  780. currentNode.replaceWith(node);
  781. };
  782. priv.renderInitInlineEditBox = function() {
  783. var nodeClass = 'dealsSales__inlineEditBox',
  784. node;
  785. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  786. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  787. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  788. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  789. var iebHead = $('<div class="modal-header">').appendTo(frmInlineEdit);
  790. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(iebHead);
  791. $('<h3 id="myModalLabel">Edytuj</h3>').appendTo(iebHead);
  792. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  793. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  794. //$('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  795. //$('<input type="hidden" name="col" value="">').appendTo(iebBody);
  796. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  797. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  798. $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  799. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  800. frmInlineEdit.on('submit', function() {
  801. var data = _inlineEditBox$Node.find('form').serialize();
  802. _inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  803. function notifyAjaxCallback(data) {
  804. var notify = {};
  805. notify.type = (data && data.type)? data.type : '';
  806. notify.msg = (data && data.msg)? data.msg : '';
  807. switch (notify.type) {
  808. case 'success':
  809. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  810. break;
  811. case 'info':
  812. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  813. break;
  814. case 'error':
  815. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  816. break;
  817. case 'warning':
  818. notify.type = 'warn';
  819. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  820. break;
  821. default:
  822. notify.msg = 'Nieznany błąd';
  823. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  824. notify.type = '';
  825. }
  826. jQuery.notify(notify.msg, notify.type);
  827. }
  828. $.ajax({
  829. data: data,
  830. dataType: 'json',
  831. type: "POST",
  832. url: priv.options.urlSaveInlineEdit
  833. })
  834. .done(function(data, textStatus, jqXHR){
  835. notifyAjaxCallback(data);
  836. if (data.record) {
  837. var year = data.record.SALES_YEAR,
  838. month = data.record.SALES_MONTH,
  839. status = data.record.A_STATUS,
  840. saleValue = parseFloat(data.record.SALES_VALUE),
  841. marka = data.record.marka,
  842. state = {}
  843. ;
  844. if (month < 10) month = '0' + month;
  845. // TODO: if marka changed - fix state
  846. if ('DELETED' === status) {
  847. state.obroty = {};
  848. state.obroty[year] = {};
  849. state.obroty[year][month] = null;
  850. state.obrotyToMarki = {};
  851. state.obrotyToMarki[year] = {};
  852. state.obrotyToMarki[year][month] = null;
  853. } else {
  854. state.obroty = {};
  855. state.obroty[year] = {};
  856. state.obroty[year][month] = saleValue;
  857. state.obrotyToMarki = {};
  858. state.obrotyToMarki[year] = {};
  859. state.obrotyToMarki[year][month] = marka;
  860. }
  861. priv.setState(state);
  862. }
  863. _inlineEditBox$Node.modal('hide');
  864. })
  865. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  866. if (jqXHR.responseJSON) {
  867. notifyAjaxCallback(jqXHR.responseJSON);
  868. }
  869. else {
  870. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  871. if (jqXHR.status == 404) {
  872. jQuery.notify(jqXHR.responseText, 'error');
  873. } else {
  874. jQuery.notify(jqXHR.responseText, 'warn');
  875. }
  876. }
  877. _inlineEditBox$Node.modal('hide');
  878. });
  879. return false;
  880. });
  881. node.appendTo(_uiNodeCont);//currentNode.replaceWith(node);
  882. _inlineEditBox$Node = node;
  883. };
  884. priv.cellDblClicked = function(e) {
  885. if ('year' in e.data && 'month' in e.data && e.data.year > 0 && e.data.month > 0) {
  886. _inlineEditBox$Node.modal();
  887. _inlineEditBox$Node.show();
  888. _inlineEditBox$Node.on('shown.bs.modal', function(e) {
  889. var dialogBox = jQuery(this).find('.modal-dialog'),
  890. modalBody = dialogBox.find('.modal-body'),
  891. boudingRect = dialogBox.get(0).getBoundingClientRect();
  892. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  893. modalBody.css({overflow: 'scroll'});
  894. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  895. dialogBox.draggable();
  896. });
  897. _inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  898. var dialogBox = jQuery(this).find('.modal-dialog'),
  899. modalBody = dialogBox.find('.modal-body');
  900. dialogBox.removeAttr('style');
  901. modalBody.removeAttr('style');
  902. modalBody.css({padding: '0'});
  903. dialogBox.resizable();
  904. dialogBox.draggable();
  905. dialogBox.resizable('destroy');
  906. dialogBox.draggable('destroy');
  907. });
  908. _inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  909. _inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  910. _inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  911. $.ajax({
  912. url: priv.options.urlInlineEdit,
  913. type: 'GET',
  914. dataType: 'text',
  915. data: e.data,
  916. async: true,
  917. success: function (data) {
  918. _inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
  919. _inlineEditBox$Node.find('.btn-save').show();
  920. initDateTimePicker(_inlineEditBox$Node);
  921. _inlineEditBox$Node.find('textarea').autosize();
  922. var fld = _inlineEditBox$Node.find('input[id^="f"]:first');
  923. if (fld && !fld.hasClass('se_type-date')) {
  924. fld.focus();
  925. fld.keydown(function(event) {
  926. if (event.which == 13) {
  927. event.preventDefault();
  928. _inlineEditBox$Node.find('form').submit();
  929. }
  930. });
  931. }
  932. },
  933. error: function (err) {
  934. if (priv.options.debug) console.log('err');
  935. }
  936. });
  937. } else {
  938. if (priv.options.debug) console.log('NO data');
  939. return false;
  940. }
  941. };
  942. priv.onRender = function(e) {// jQuery(_uiNodeCont).trigger('DealsSalesTable:render', [...]);
  943. if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  944. if (arguments.length > 1) {
  945. for (var i=1; i<arguments.length; i++) {
  946. switch (arguments[i]) {
  947. case 'body': priv.renderTableBody(); break;
  948. case 'marki': priv.renderHeaderMarki(); break;
  949. case 'graphs': priv.renderGraphByYear(); priv.renderGraphByMonth(); break;
  950. }
  951. }
  952. }
  953. };
  954. priv.setState = function(state) {
  955. var oldState = _state,// TODO: use to check what really changed (use extend!)
  956. renderParts = {};
  957. if (state.obroty) {
  958. $.each(state.obroty, function(kYear, vSalesByMonth) {
  959. $.each(vSalesByMonth, function(kMonth, vSaleValue) {
  960. if (null === vSaleValue) {
  961. _state.obroty[kYear][kMonth] = undefined;
  962. } else {
  963. _state.obroty[kYear][kMonth] = vSaleValue;
  964. }
  965. });
  966. });
  967. renderParts['body'] = true;
  968. renderParts['graphs'] = true;
  969. }
  970. /*
  971. state.obrotyToMarki[year][month] = marka;
  972. */
  973. if (state.obrotyToMarki) {
  974. $.each(state.obrotyToMarki, function(kYear, vMarkiByMonth) {
  975. $.each(vMarkiByMonth, function(kMonth, vMarka) {
  976. if (null === vMarka) {
  977. _state.obrotyToMarki[kYear][kMonth] = undefined;
  978. } else {
  979. _state.obrotyToMarki[kYear][kMonth] = vMarka;
  980. if (undefined === _state.marki[vMarka]) {
  981. _state.marki[vMarka] = 'default';
  982. }
  983. }
  984. });
  985. });
  986. renderParts['marki'] = true;
  987. }
  988. renderParts = Object.keys(renderParts);
  989. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  990. if (renderParts.length > 0) {
  991. jQuery(_uiNodeCont).trigger('DealsSalesTable:render', renderParts);
  992. }
  993. };
  994. publ.init = function (options) {
  995. if (priv.options.debug) console.log('DealsSalesTable initialization...');
  996. //merge supplied options with defaults
  997. $.extend(priv.options, defaults, options);
  998. priv.init();
  999. return publ;
  1000. };
  1001. return publ;
  1002. };
  1003. $.fn.DealsSalesTable = function (options) {
  1004. options = options || {};
  1005. return this.each(function () {
  1006. options.id = this;
  1007. $(this).data('DealsSalesTable', new DealsSalesTable().init(options));
  1008. });
  1009. };
  1010. })(jQuery);
  1011. jQuery(document).ready(function() {
  1012. jQuery('#dealsSalesByMonth').DealsSalesTable({
  1013. url: 'index.php?_route=DealsSales&_task=getDataAjax&telbox=<?php echo $idTelboxes; ?>',
  1014. urlInlineEdit: 'index.php?_route=DealsSales&_task=inlineEditAjax&telbox=<?php echo $idTelboxes; ?>',
  1015. urlSaveInlineEdit: 'index.php?_route=DealsSales&_task=saveInlineAjax&telbox=<?php echo $idTelboxes; ?>',
  1016. initData: <?php echo json_encode($initData); ?>
  1017. });
  1018. });
  1019. </script>
  1020. <script src="stuff/RGraph/libraries/RGraph.common.core.js?_v=20140626"></script>
  1021. <script src="stuff/RGraph/libraries/RGraph.common.dynamic.js?_v=20140626"></script>
  1022. <script src="stuff/RGraph/libraries/RGraph.common.key.js?_v=20140626"></script>
  1023. <script src="stuff/RGraph/libraries/RGraph.drawing.rect.js?_v=20140626"></script>
  1024. <script src="stuff/RGraph/libraries/RGraph.common.tooltips.js?_v=20140626"></script>
  1025. <script src="stuff/RGraph/libraries/RGraph.bar.js?_v=20140626"></script>
  1026. <script src="stuff/RGraph/libraries/RGraph.line.js?_v=20140626"></script>
  1027. <?php endif; ?>
  1028. </div>
  1029. <?php
  1030. }
  1031. }