Source: directives/rastreamento/rastreamento.js

  1. /**
  2. * @ngdoc directives
  3. * @name Rastreamento
  4. * @module s4c.directives,rastreamento.Rastreamento
  5. *
  6. * @description `s4c-rastreamento` exibe informações sobre um ponto de
  7. * interesse
  8. *
  9. * @example <s4c-rastreamento> </s4c-rastreamento>
  10. *
  11. */
  12. (function () {
  13. 'use strict';
  14. rastreamentoController.$inject = [
  15. '$scope',
  16. '$window',
  17. '$filter',
  18. '$anchorScroll',
  19. 'ngTableParams',
  20. 'MsiService',
  21. 'MsiFilter',
  22. 'CommService',
  23. 'MainState',
  24. 'DetalhamentoManager',
  25. 'IncidentesManager',
  26. 'MapaManager',
  27. 'CamadasService',
  28. 'localize',
  29. 'Base',
  30. '$http',
  31. 'API_ENDPOINT',
  32. '$mdDialog',
  33. 'PontoMovelManager'
  34. ];
  35. function rastreamentoController(
  36. $scope,
  37. $window,
  38. $filter,
  39. $anchorScroll,
  40. ngTableParams,
  41. MsiService,
  42. MsiFilter,
  43. CommService,
  44. MainState,
  45. DetalhamentoManager,
  46. IncidentesManager,
  47. MapaManager,
  48. CamadasService,
  49. localize,
  50. Base,
  51. $http,
  52. API_ENDPOINT,
  53. $mdDialog,
  54. PontoMovelManager) {
  55. $scope.res = $scope.$root.res;
  56. /**
  57. * @method _filterAfterQuery
  58. * @param {*} incidentes
  59. */
  60. function _filterAfterQuery(incidentes) {
  61. var newIncidentes = _.chain(incidentes).map(parseIncidente).value();
  62. newIncidentes = _filterAberto24h(incidentes);
  63. newIncidentes.forEach(function (obj, index) {
  64. if (obj.extras != null && obj.extras.informacoes != null) {
  65. var prioridade = obj.extras.informacoes.filter(function (item, i) {
  66. if (item.label === 'Prioridade') {
  67. delete obj.extras.informacoes[i];
  68. }
  69. });
  70. }
  71. });
  72. return newIncidentes;
  73. }
  74. // 1. Aberto 2. Fechado 3. Aberto 24h
  75. /**
  76. * @method _filterAberto24h
  77. * @param {*} incidentes
  78. */
  79. function _filterAberto24h(incidentes) {
  80. var filterData = _getFilterData();
  81. var statuses = _filtrarAtivos(filterData.statuses, 'id');
  82. var timeWindow = _setTimeWindow(filterData.timeWindow, statuses);
  83. var newIncidentes = incidentes.filter(function (incidente) {
  84. if (!statuses.length) return incidente;
  85. if (incidente.status === 'ABERTO' && statuses.indexOf(1) === -1) {
  86. if (incidente.inicio.isBefore(moment(timeWindow.start))) {
  87. return incidente;
  88. }
  89. } else {
  90. return incidente;
  91. }
  92. });
  93. return newIncidentes;
  94. }
  95. var filterInstance = MsiFilter.getInstance('filtro-msi');
  96. $scope.pontosMoveisGrid = [];
  97. $scope.pontosMoveis = [];
  98. $scope.moduleFilter = {
  99. nome: '',
  100. agencia: ''
  101. };
  102. $scope.fields = [
  103. /*{
  104. active: true,
  105. pinnedLeft: true,
  106. enableFiltering: false,
  107. name: '',
  108. field: 'statusIcon',
  109. width: 40,
  110. headerCellClass: 'tableHeader',
  111. enableColumnMenu: false,
  112. cellClass: 'tableRow',
  113. headerCellTemplate: '<md-icon md-svg-icon="settings:engine" class="settings" ng-click="grid.appScope.toggleFieldSelection()"></md-icon>',
  114. cellTemplate: '<img ng-src="{{grid.appScope.setIconUrl(row)}}" ng-click="grid.appScope.openDetalhamentoFromRow(row)" width="14" height="14" style="margin-left: 7px; margin-top: 7px;"/>'
  115. },*/{
  116. active: true,
  117. name: 'Nome',
  118. field: 'nome',
  119. enableColumnMenu: false,
  120. width: 200,
  121. headerCellClass: 'tableHeader',
  122. cellClass: 'tableRow'
  123. }, {
  124. active: true,
  125. name: 'Descrição',
  126. field: 'descricao',
  127. width: 250,
  128. enableColumnMenu: false,
  129. headerCellClass: 'tableHeader',
  130. cellClass: 'tableRow'
  131. }, {
  132. active: true,
  133. name: 'Tipo',
  134. field: 'nomeTipo',
  135. width: 150,
  136. enableColumnMenu: false,
  137. headerCellClass: 'tableHeader',
  138. cellClass: 'tableRow'
  139. }
  140. ];
  141. // Main Load of PontosMoveis
  142. $scope.loadPontosMoveis = true;
  143. /**
  144. * @method loadPontosMoveis
  145. */
  146. function loadPontosMoveis() {
  147. var filterData = _getFilterData();
  148. //var query = _setQuery(filterData);
  149. if (!$scope.loadPontosMoveis) {
  150. return;
  151. }
  152. $scope.loadPontosMoveis = false;
  153. $http.get(API_ENDPOINT + "ponto_movel")
  154. .then(function (result) {
  155. $scope.pontosMoveis = result.data;
  156. loadTable($scope.pontosMoveis);
  157. }, function (err) {
  158. $mdDialog
  159. .show($mdDialog.alert()
  160. .title($scope.res('COMUM_ERRO'))
  161. .content(err.data.message)
  162. .ok($scope.res('COMUM_OK')));
  163. });
  164. }
  165. /**
  166. * @method loadTable
  167. * @param {*} pontosMoveis
  168. */
  169. function loadTable(pontosMoveis) {
  170. $scope.pontosMoveisGrid.data = pontosMoveis;
  171. /*
  172. * When Row of Table is clicked, rowSelectionChanged is invoked
  173. */
  174. if ($scope.gridApi) {
  175. $scope.gridApi.selection.on.rowSelectionChanged(null, function (row) {
  176. $scope.voarPontoMovel(row.entity);
  177. });
  178. resizeTable();
  179. }
  180. }
  181. // Watch the Module Size
  182. $scope.$watch(
  183. function () {
  184. if (angular.element('#modulo-rastreamento')[0] != null) {
  185. return angular.element('#modulo-rastreamento')[0].offsetHeight
  186. }
  187. },
  188. function (value) {
  189. resizeTable();
  190. }
  191. );
  192. $scope.setIconUrl = function (row) {
  193. var incidente = row.entity;
  194. if (incidente.status == "ABERTO") {
  195. return "/assets/images/IncidenteLegenda/s4c_ic_incident_open_fill_subtitle.svg";
  196. } else if (incidente.status == "FECHADO") {
  197. return "/assets/images/IncidenteLegenda/s4c_ic_incident_closed_fill_subtitle.svg";
  198. }
  199. };
  200. $scope.openDetalhamentoFromRow = function (row) {
  201. var incidente = row.entity;
  202. $scope.abrirDetalhamento(incidente);
  203. };
  204. function resizeTable() {
  205. if ($scope.gridApi) {
  206. if (angular.element('#modulo-rastreamento')[0]) {
  207. var gridSize = $scope.gridApi.grid.gridHeight;
  208. var moduleHeight = angular.element('#modulo-rastreamento')[0].clientHeight;
  209. var gridHeight = moduleHeight - 45;
  210. $scope.uiGridHeight = { height: gridHeight + 'px' };
  211. }
  212. }
  213. }
  214. /**
  215. * @method filterTab
  216. */
  217. $scope.filterTab = function (agencia) {
  218. $scope.moduleFilter.agencia = (agencia.nome === $scope.res('COMUM_TODOS')) ? '' : agencia.id;
  219. $scope.searchTable($scope.moduleFilter);
  220. };
  221. /**
  222. * @method searchTable
  223. */
  224. $scope.searchTable = function (filter) {
  225. var filterData = {};
  226. if (filter.nome !== '') {
  227. filterData.nome = filter.nome;
  228. }
  229. var pontosMoveisFiltered = $filter('filter')($scope.pontosMoveis, filterData);
  230. $scope.pontosMoveisGrid.data = pontosMoveisFiltered;
  231. };
  232. $scope.pontosMoveisGrid = {
  233. enableRowSelection: true,
  234. enableRowHeaderSelection: false,
  235. multiSelect: false,
  236. flatEntityAccess: true,
  237. fastWatch: true,
  238. noUnselect: true,
  239. columnDefs: $scope.fields
  240. };
  241. $scope.pontosMoveisGrid.onRegisterApi = function (gridApi) {
  242. $scope.gridApi = gridApi;
  243. };
  244. /**
  245. * @method parseToGrid
  246. * @param {*} incidente
  247. */
  248. function parseToGrid(incidente) {
  249. incidente.statusIcon = (incidente.status === 'ABERTO') ? 'opened' : 'closed';
  250. if (incidente.inicio) {
  251. incidente.inicio = moment(incidente.inicio).format('DD/MM/YYYY - HH:mm');
  252. }
  253. incidente.CategoriaNome = incidente.CategoriaIncidente.nome;
  254. return incidente;
  255. }
  256. /**
  257. * @method verificaMenuCarregado
  258. * @param {*} incidentes
  259. */
  260. function verificaMenuCarregado(incidentes) {
  261. if (!CamadasService.isLoaded) {
  262. CamadasService.isLoaded = true;
  263. setTimeout(function () {
  264. verificaMenuCarregado(incidentes);
  265. }, 1000);
  266. } else {
  267. _updateCamadasService(incidentes);
  268. }
  269. }
  270. /**
  271. * @method _updateCamadasService
  272. * @param {*} incidentes
  273. */
  274. function _updateCamadasService(incidentes) {
  275. var filterData = _getFilterData();
  276. var categorias = filterData.categorias;
  277. var statuses = filterData.statuses;
  278. var itensParaDesativar = [];
  279. _.each(categorias, function (categoria) {
  280. _.each(statuses, function (status) {
  281. if (status.ativo && categoria.ativo) {
  282. CamadasService.ativarSubMenuIncidente(categoria.id);
  283. } else {
  284. itensParaDesativar.push({
  285. categoriaId: categoria.id,
  286. status: status.nome
  287. });
  288. }
  289. });
  290. });
  291. _.each(itensParaDesativar, function (item) {
  292. CamadasService.desativarSubMenuStatusMsi(item.categoriaId, item.status, {
  293. origem: 'filtro'
  294. });
  295. });
  296. }
  297. /**
  298. * @method exportToPdf
  299. */
  300. $scope.exportToPdf = function () {
  301. var ids = $scope.pontosMoveisGrid.data.map(function (incidente) {
  302. return incidente.id;
  303. });
  304. if (ids.length) {
  305. IncidentesService.getPdfReport(ids)
  306. .then(function (data) {
  307. var file = new Blob([data], { type: 'application/pdf' });
  308. var fileURL = URL.createObjectURL(file);
  309. var a = document.createElement("a");
  310. document.body.appendChild(a);
  311. a.style = "display: none";
  312. a.href = fileURL;
  313. a.download = $scope.res('Incidentes') + ".pdf";
  314. a.click();
  315. $mdDialog
  316. .show($mdDialog.alert()
  317. .title($scope.res('COMUM_SUCESSO'))
  318. .content('Arquivo gerado com sucesso.')
  319. .ok($scope.res('COMUM_OK')));
  320. });
  321. }
  322. };
  323. $scope.fieldSelection = false;
  324. /**
  325. * @method toggleFieldSelection
  326. */
  327. $scope.toggleFieldSelection = function () {
  328. $scope.pontosMoveisGrid.columnDefs = $scope.fields.filter(function (column) {
  329. return column.active === true;
  330. });
  331. $scope.fieldSelection = !$scope.fieldSelection;
  332. };
  333. /**
  334. * @method parseIncidente
  335. * @param {*} incidente
  336. */
  337. function parseIncidente(incidente) {
  338. if (incidente.inicio) {
  339. incidente.inicio = moment(moment(incidente.inicio).toDate());
  340. }
  341. if (incidente.fim) {
  342. incidente.fim = moment(moment(incidente.fim).toDate());
  343. }
  344. if (incidente.fim &&
  345. incidente.status === 'FECHADO' &&
  346. incidente.inicio) {
  347. if (moment().dayOfYear() - incidente.fim.dayOfYear() >= 1) {
  348. incidente.icon = '/data-s4c/teste/ic_incidentes_grey_26px.svg';
  349. }
  350. }
  351. if (incidente.status && incidente.status === 'ABERTO') {
  352. incidente.icon = '/data-s4c/teste/ic_incidentes_red_26px.svg';
  353. }
  354. return incidente;
  355. }
  356. /**
  357. * @method _filtrarIncidente
  358. * @param {*} incidente
  359. */
  360. function _filtrarIncidente(incidente) {
  361. return MsiFilter.getInstance('filtro-msi').filtrarIncidente(incidente);
  362. }
  363. /**
  364. * @method _filtrarIncidentes
  365. * @param {*} incidentes
  366. */
  367. function _filtrarIncidentes(incidentes) {
  368. return _.chain(incidentes)
  369. .map(parseIncidente)
  370. .sortBy(function (incidente) {
  371. if (incidente.status === 'ABERTO') {
  372. return 0;
  373. }
  374. if (incidente.fim && moment().dayOfYear() - incidente.fim.dayOfYear() >= 1) {
  375. return 2;
  376. }
  377. return 1;
  378. })
  379. .value();
  380. }
  381. /**
  382. * @method _setQueryStatus
  383. * @param {*} statuses
  384. */
  385. function _setQueryStatus(statuses) {
  386. return { $in: statuses };
  387. }
  388. /**
  389. * @method _setStatuses
  390. * @param {*} statuses
  391. */
  392. function _setStatuses(statuses) {
  393. if (statuses.length) {
  394. var arrFilter = [];
  395. if (statuses.indexOf(1) > -1 || statuses.indexOf(3) > -1) {
  396. arrFilter.push("ABERTO");
  397. }
  398. if (statuses.indexOf(2) > -1) {
  399. arrFilter.push("FECHADO");
  400. }
  401. return arrFilter;
  402. } else {
  403. return ["ABERTO"];
  404. }
  405. }
  406. /**
  407. * @method _setTimeWindow
  408. * @param {*} timeWindow
  409. */
  410. function _setTimeWindow(timeWindow) {
  411. var newTimeWindow = {
  412. start: timeWindow.start,
  413. end: timeWindow.end
  414. };
  415. newTimeWindow.start = moment(newTimeWindow.start).startOf('day').format();
  416. newTimeWindow.end = moment(newTimeWindow.end).endOf('day').format();
  417. return newTimeWindow;
  418. }
  419. /**
  420. * @method _filtrarAtivos
  421. * @param {*} dataArr
  422. * @param {*} filterString
  423. */
  424. function _filtrarAtivos(dataArr, filterString) {
  425. return _.chain(dataArr)
  426. .filter('ativo')
  427. .map(filterString)
  428. .value();
  429. }
  430. /**
  431. * @method _setQueryGravidadeIncidenteId
  432. * @param {*} gravidades
  433. */
  434. function _setQueryGravidadeIncidenteId(gravidades) {
  435. var ativos = _filtrarAtivos(gravidades, 'id');
  436. return (ativos.length) ? { $in: ativos } : null;
  437. }
  438. /**
  439. * @method _setQueryTipoIncidenteId
  440. * @param {*} tipoIncidentes
  441. */
  442. function _setQueryTipoIncidenteId(tipoIncidentes) {
  443. var ativos = _filtrarAtivos(tipoIncidentes, 'id');
  444. return (ativos.length) ? { $in: ativos } : null;
  445. }
  446. /**
  447. * @method _setQueryTimeWindow
  448. * @param {*} timeWindow
  449. */
  450. function _setQueryTimeWindow(timeWindow) {
  451. return {
  452. $between: [
  453. timeWindow.start,
  454. timeWindow.end
  455. ]
  456. };
  457. }
  458. /**
  459. * @method _setQueryCategoria
  460. * @param {*} categorias
  461. */
  462. function _setQueryCategoria(categorias) {
  463. if (categorias.length) {
  464. return { $in: _filtrarAtivos(categorias, 'id') };
  465. }
  466. return;
  467. }
  468. /**
  469. * @method _setQuery
  470. * @param {*} filterData
  471. */
  472. function _setQuery(filterData) {
  473. var data = {};
  474. var timeWindow = _setTimeWindow(filterData.timeWindow, _filtrarAtivos(filterData.statuses, 'id'));
  475. var statuses = _setStatuses(_filtrarAtivos(filterData.statuses, 'id'));
  476. data.status = _setQueryStatus(statuses);
  477. data.CategoriaIncidenteId = _setQueryCategoria(filterData.categorias);
  478. data.GravidadeIncidenteId = _setQueryGravidadeIncidenteId(filterData.gravidades);
  479. data.TipoIncidenteId = _setQueryTipoIncidenteId(filterData.tipoIncidentes);
  480. data.inicio = _setQueryTimeWindow(timeWindow);
  481. //data.limit = 50;
  482. // Deletes invalid filters
  483. for (var filtro in data) {
  484. if (data.hasOwnProperty(filtro) && (data[filtro] === null) || data[filtro] === undefined) {
  485. delete data[filtro];
  486. }
  487. }
  488. return {
  489. where: data,
  490. include: 'CategoriaIncidente'
  491. };
  492. };
  493. /**
  494. * @method setQuery
  495. */
  496. function setQuery() {
  497. var filterData = _getFilterData();
  498. var data = {};
  499. var timeWindow = _setTimeWindow(filterData.timeWindow, _filtrarAtivos(filterData.statuses, 'id'));
  500. var statuses = _setStatuses(_filtrarAtivos(filterData.statuses, 'id'));
  501. data.status = _setQueryStatus(statuses);
  502. data.CategoriaIncidenteId = _setQueryCategoria(filterData.categorias);
  503. data.GravidadeIncidenteId = _setQueryGravidadeIncidenteId(filterData.gravidades);
  504. data.TipoIncidenteId = _setQueryTipoIncidenteId(filterData.tipoIncidentes);
  505. data.inicio = _setQueryTimeWindow(timeWindow);
  506. //data.limit = 50;
  507. // Deletes invalid filters
  508. for (var filtro in data) {
  509. if (data.hasOwnProperty(filtro) && (data[filtro] === null) || data[filtro] === undefined) {
  510. delete data[filtro];
  511. }
  512. }
  513. return {
  514. where: data,
  515. include: {
  516. model: 'GrupoUsuarios',
  517. 'as': 'GruposUsuarios',
  518. include: {
  519. model: 'Usuario'
  520. },
  521. where: {
  522. id: {
  523. $in: _.chain(filterData.gruposUSuarios)
  524. .filter('ativo')
  525. .map('id')
  526. .value()
  527. }
  528. }
  529. },
  530. order: 'inicio DESC'
  531. };
  532. };
  533. /**
  534. * @method _getFilterData
  535. */
  536. function _getFilterData() {
  537. var filter = MsiFilter.getInstance('filtro-msi');
  538. return {
  539. categorias: filter.categorias,
  540. gruposUsuarios: filter.gruposUsuarios,
  541. tipoIncidentes: filter.tipoIncidentes,
  542. statuses: filter.statuses,
  543. gravidades: filter.gravidades,
  544. timeWindow: filter.dataRange
  545. };
  546. }
  547. $scope.incidenteAtivo = -1;
  548. /**
  549. * @method abrirDetalhamento
  550. */
  551. $scope.abrirDetalhamento = function (incidente) {
  552. if (typeof incidente.geojson === 'string') {
  553. incidente.geojson = JSON.parse(incidente.geojson);
  554. }
  555. DetalhamentoManager.abrirIncidente(incidente.id, {
  556. lat: incidente.geojson.coordinates[1],
  557. lng: incidente.geojson.coordinates[0]
  558. });
  559. };
  560. var lastPontoMovel;
  561. /**
  562. * @method voarPontoMovel
  563. */
  564. $scope.voarPontoMovel = function (pontoMovel) {
  565. if (pontoMovel == lastPontoMovel) {
  566. return;
  567. }
  568. lastPontoMovel = pontoMovel;
  569. PontoMovelManager.pontoMovelAtivo = pontoMovel;
  570. CamadasService.ativarMenuDoPontoMovel(pontoMovel.tipo.id);
  571. /*$http.post(API_ENDPOINT + "obterPosicaoAtualER", pontoMovel.idElementoRastreavel)
  572. .then(function(result) {
  573. $scope.elementoRastreavelInfo = result.data;
  574. PontoMovelManager.posicaoAtualER = result.data;
  575. var ponto = {
  576. lat: $scope.elementoRastreavelInfo.latitude,
  577. lng: $scope.elementoRastreavelInfo.longitude
  578. };
  579. MapaManager.desenharPontoMovel(pontoMovel, ponto);
  580. CamadasService.ativarMenuDoPontoMovel(pontoMovel.tipo.id);
  581. if ($scope.elementoRastreavelInfo){
  582. PontoMovelManager.elementoRastreavel = $scope.elementoRastreavelInfo.elementoRastreavel;
  583. }
  584. }, function (err) {
  585. $mdDialog
  586. .show($mdDialog.alert()
  587. .title($scope.res('COMUM_ERRO'))
  588. .content(err.data.message)
  589. .ok($scope.res('COMUM_OK')));
  590. });*/
  591. };
  592. /**
  593. * @method abrirDetalhes
  594. */
  595. $scope.abrirDetalhes = function (incidente) {
  596. MsiService.incidenteDetalhamento.incidente = incidente;
  597. MsiService.state.isVisible = true;
  598. };
  599. $scope.timestamp2string = timestamp2string;
  600. /**
  601. * @method timestamp2string
  602. * @param {*} timestamp
  603. */
  604. function timestamp2string(timestamp) {
  605. if (timestamp === null) {
  606. return;
  607. }
  608. var date = new Date(timestamp);
  609. var mom = moment(date);
  610. var formattedDate = mom.format('DD/MM/YYYY - HH:mm');
  611. return formattedDate;
  612. }
  613. loadPontosMoveis();
  614. /**
  615. * @method gotoIncidente
  616. * @param {*} x
  617. */
  618. function gotoIncidente(x) {
  619. $scope.incidenteAtivo = x;
  620. $anchorScroll();
  621. }
  622. /**
  623. * @method _timeSet
  624. */
  625. function _timeSet() {
  626. return {
  627. start: moment().subtract(1, 'day').startOf('day').format(),
  628. end: moment().endOf('day').format()
  629. }
  630. };
  631. /**
  632. * @method initFilter
  633. */
  634. function initFilter() {
  635. MsiFilter.getInstance('filtro-msi').dataRange = _timeSet();
  636. }
  637. $scope.$apirastreamento = {
  638. gotoIncidente: gotoIncidente,
  639. refreshPontosMoveis: loadPontosMoveis,
  640. setQuery: setQuery,
  641. initFilter: initFilter
  642. };
  643. MainState.registerDirective('rastreamento', $scope.$apirastreamento);
  644. }
  645. function s4cRastreamento() {
  646. return {
  647. restrict: 'EA',
  648. templateUrl: 'app/directives/rastreamento/rastreamento.html',
  649. scope: {},
  650. controller: rastreamentoController
  651. };
  652. }
  653. angular.module('s4c.components.rastreamento', [])
  654. .directive('s4cRastreamento', s4cRastreamento);
  655. })();