Source: components/main/main.controller.js

  1. /**
  2. * @ngdoc main
  3. * @name MainCtrl
  4. * @module s4c.components.main.MainCtrl
  5. *
  6. * @description Principal controller da aplicação. Todos os eventos do menu superior da tela inicial são configurados aqui.
  7. *
  8. *
  9. */
  10. (function () {
  11. 'use strict';
  12. angular.module('s4c.controllers.MainCtrl', [
  13. 's4c.components.busca',
  14. 's4c.components.rotas',
  15. 's4c.components.rotas-unificadas',
  16. 's4c.components.baseConhecimento',
  17. 's4c.components.camadas',
  18. 's4c.components.cameras',
  19. 's4c.components.telegram',
  20. 's4c.components.detalhamento',
  21. 's4c.components.deteccaoImpacto',
  22. 's4c.components.collaboration',
  23. 's4c.components.mapa',
  24. 's4c.components.incidentes',
  25. 's4c.components.tarefas',
  26. 's4c.components.voip',
  27. 's4c.components.zonaObservacao',
  28. 's4c.components.planejamento',
  29. 's4c.components.msi',
  30. 's4c.components.briefingOperacional',
  31. 's4c.components.timeline',
  32. 's4c.components.briefingOperacional',
  33. 's4c.components.terminal',
  34. 's4c.components.detalhamentoRotasOlimpicas',
  35. 's4c.directives.escolhaZona',
  36. 's4c.directives.scroller',
  37. 's4c.directives.twitterArea',
  38. 's4c.directives.timepicker',
  39. 's4c.services.PresetService',
  40. 's4c.services.ParametrosS4C',
  41. 's4c.services.PermissoesService',
  42. 's4c.services.CommService',
  43. 's4c.services.WebSocket',
  44. 's4c.services.MainState',
  45. 's4c.managers',
  46. 'ng-dropdown',
  47. 'datePicker',
  48. 'angular-toasty',
  49. 'color.picker',
  50. 's4c.components.regiao',
  51. 's4c.components.areaAtuacao',
  52. 's4c.services.AuthService',
  53. 's4c.components.rastreamento',
  54. 's4c.components.pontoMovel',
  55. 's4c.components.poi',
  56. 's4c.components.webview',
  57. 's4c.components.video',
  58. 's4c.components.imagem',
  59. 's4c.components.pdf',
  60. 's4c.components.calendar',
  61. 's4c.components.contacts',
  62. 's4c.components.multivis',
  63. 's4c.components.dashboard',
  64. 's4c.components.rdp',
  65. 's4c.components.chartBar',
  66. 's4c.components.chartLine',
  67. 's4c.components.chartPie',
  68. 's4c.components.chartTreeMap',
  69. 's4c.components.hdmi',
  70. 's4c.components.whatsapp'
  71. ])
  72. .constant('FACES', {
  73. 'FACE_FECHADA': {
  74. 'sizeX': 1,
  75. 'sizeY': 1,
  76. 'row': 0,
  77. 'col': 3,
  78. 'name': 'Fechado',
  79. 'template': 'app/components/modulos/face-fechada.html'
  80. }
  81. })
  82. .controller('MainCtrl', MainCtrl)
  83. .directive('compareToo', compareToo)
  84. .directive('safePasswordd', safePasswordd);
  85. /**
  86. * @method compareToo
  87. */
  88. function compareToo() {
  89. return {
  90. require: "ngModel",
  91. scope: {
  92. otherModelValue: "=compareToo"
  93. },
  94. link: function (scope, element, attributes, ngModel) {
  95. ngModel.$validators.compareToo = function (modelValue) {
  96. return modelValue === scope.otherModelValue;
  97. };
  98. scope.$watch("otherModelValue", function () {
  99. ngModel.$validate();
  100. });
  101. }
  102. };
  103. }
  104. /**
  105. * @method safePasswordd
  106. */
  107. function safePasswordd() {
  108. return {
  109. require: "ngModel",
  110. scope: {
  111. username: '=username',
  112. nome: '=nome'
  113. },
  114. /**
  115. * @method safePasswordd
  116. * @param {*} scope
  117. * @param {*} element
  118. * @param {*} attributes
  119. * @param {*} ngModel
  120. */
  121. link: function (scope, element, attributes, ngModel) {
  122. /*
  123. * Valid passwords:
  124. * @a0Abcab
  125. * 0@acanan
  126. */
  127. // Retorno:
  128. // true = tudo OK
  129. /**
  130. * @method ngModel.$validators.safePasswordd
  131. * @param modelValue
  132. */
  133. ngModel.$validators.safePasswordd = function (modelValue) {
  134. // Queremos que seja true:
  135. var checkMinusculas = /(.*[a-z]){1,}/.test(modelValue);
  136. var checkMaiusculas = /(.*[A-Z]){1,}/.test(modelValue);
  137. var checkNumeros = /(.*[0-9]){1,}/.test(modelValue);
  138. var checkCaracteres = /(.*[!@#$&*,.()%^]){1,}/.test(modelValue);
  139. var checkName = true;
  140. var checkUsername = true;
  141. var checks = [
  142. checkMinusculas,
  143. checkMaiusculas,
  144. checkNumeros,
  145. checkCaracteres
  146. ].filter(function (check) {
  147. return check;
  148. });
  149. if (modelValue !== undefined) {
  150. var usernameTester = new RegExp(scope.username, 'i');
  151. checkUsername = !usernameTester.test(modelValue.trim());
  152. }
  153. var nomeSobrenome = scope.nome.split(' ');
  154. for (var i = 0; i < nomeSobrenome.length; i++) {
  155. var nameTester = new RegExp(nomeSobrenome[i], 'i');
  156. checkName = !nameTester.test(modelValue);
  157. if (!checkName) {
  158. break;
  159. }
  160. }
  161. // Pelo menos cumpre 3 das regras
  162. var valido = checks.length >= 3 &&
  163. checkName && checkUsername;
  164. /*checkMinusculas && checkMaiusculas &&
  165. checkNumeros && checkCaracteres*/
  166. return valido;
  167. };
  168. }
  169. };
  170. }
  171. MainCtrl.$inject = [
  172. '$scope',
  173. '$rootScope',
  174. '$timeout',
  175. 'GRIDSTER_OPTIONS_EDICAO',
  176. 'GRIDSTER_OPTIONS_VISUALIZACAO',
  177. 'UserInfo',
  178. 'UserPresets',
  179. '$mdDialog',
  180. 'DetalhamentoService',
  181. '$state',
  182. 'MsiService',
  183. 'CommService',
  184. '$stateParams',
  185. 'toasty',
  186. 'CamadasService',
  187. 'AuthService',
  188. 'MapaService',
  189. 'MainState',
  190. 'MainManager',
  191. 'ModuloTwitterManager',
  192. 'CamerasManager',
  193. 'BuscaManager',
  194. 'MensageriaManager',
  195. 'AvisoOperacionalManager',
  196. 'RotasManager',
  197. 'RotasUnificadasManager',
  198. 'IncidentesManager',
  199. 'BaseConhecimentoManager',
  200. 'FacebookManager',
  201. 'EmailManager',
  202. 'TwitterManager',
  203. 'MSIManager',
  204. 'SubDetalhamentoManager',
  205. 'DetalhamentoManager',
  206. 'ZonaDeObservacaoManager',
  207. 'PlanejamentoManager',
  208. 'DeteccaoImpactoManager',
  209. 'MinhasTarefasManager',
  210. 'TarefaManager',
  211. 'BriefingOperacionalManager',
  212. 'MapaManager',
  213. 'BotoesManager',
  214. 'IncidenteEnterManager',
  215. 'AlarmeDisparadoManager',
  216. 'Preset',
  217. 'PermissoesService',
  218. '$interval',
  219. 'EditPTarefaManager',
  220. 'TerminalManager',
  221. 'BuscaUsuariosTelegramManager',
  222. 'MainService',
  223. 'DetalhamentoRotasOlimpicasManager',
  224. 'HabilitarCamadasManager',
  225. 'localize',
  226. 'Modulo',
  227. 'AreaAtuacaoManager',
  228. 'RastreamentoManager',
  229. 'PontoMovelManager',
  230. 'ZonasDeObservacaoFilter',
  231. 'Usuario',
  232. 'FileUploader',
  233. 'API_ENDPOINT',
  234. '$window',
  235. 'Base',
  236. 'MsiFilter',
  237. '$http',
  238. 'PoiManager',
  239. 'Menu',
  240. 'ParametrosS4C',
  241. 'VoipManager',
  242. 'WebSocket',
  243. 'FileReaderService',
  244. 'VideoStreamService'
  245. ];
  246. /**
  247. * @method MainCtrl
  248. * @param {*} $scope
  249. * @param {*} $rootScope
  250. * @param {*} $timeout
  251. * @param {*} GRIDSTER_OPTIONS_EDICAO
  252. * @param {*} GRIDSTER_OPTIONS_VISUALIZACAO
  253. * @param {*} UserInfo
  254. * @param {*} UserPresets
  255. * @param {*} $mdDialog
  256. * @param {*} DetalhamentoService
  257. * @param {*} $state
  258. * @param {*} MsiService
  259. * @param {*} CommService
  260. * @param {*} $stateParams
  261. * @param {*} toasty
  262. * @param {*} CamadasService
  263. * @param {*} AuthService
  264. * @param {*} MapaService
  265. * @param {*} MainState
  266. * @param {*} MainManager
  267. * @param {*} ModuloTwitterManager
  268. * @param {*} CamerasManager
  269. * @param {*} BuscaManager
  270. * @param {*} MensageriaManager
  271. * @param {*} AvisoOperacionalManager
  272. * @param {*} RotasManager
  273. * @param {*} RotasUnificadasManager
  274. * @param {*} IncidentesManager
  275. * @param {*} BaseConhecimentoManager
  276. * @param {*} FacebookManager
  277. * @param {*} EmailManager
  278. * @param {*} TwitterManager
  279. * @param {*} MSIManager
  280. * @param {*} SubDetalhamentoManager
  281. * @param {*} DetalhamentoManager
  282. * @param {*} ZonaDeObservacaoManager
  283. * @param {*} PlanejamentoManager
  284. * @param {*} DeteccaoImpactoManager
  285. * @param {*} MinhasTarefasManager
  286. * @param {*} TarefaManager
  287. * @param {*} BriefingOperacionalManager
  288. * @param {*} MapaManager
  289. * @param {*} BotoesManager
  290. * @param {*} IncidenteEnterManager
  291. * @param {*} AlarmeDisparadoManager
  292. * @param {*} Preset
  293. * @param {*} PermissoesService
  294. * @param {*} $interval
  295. * @param {*} EditPTarefaManager
  296. * @param {*} TerminalManager
  297. * @param {*} BuscaUsuariosTelegramManager
  298. * @param {*} MainService
  299. * @param {*} DetalhamentoRotasOlimpicasManager
  300. * @param {*} HabilitarCamadasManager
  301. * @param {*} localize
  302. * @param {*} Modulo
  303. * @param {*} AreaAtuacaoManager
  304. * @param {*} RastreamentoManager
  305. * @param {*} PontoMovelManager
  306. * @param {*} ZonasDeObservacaoFilter
  307. * @param {*} Usuario
  308. * @param {*} FileUploader
  309. * @param {*} API_ENDPOINT
  310. * @param {*} $window
  311. * @param {*} Base
  312. * @param {*} MsiFilter
  313. * @param {*} $http
  314. * @param {*} PoiManager
  315. * @param {*} Menu
  316. * @param {*} ParametrosS4C
  317. * @param {*} VoipManager
  318. * @param {*} WebSocket
  319. * @param {*} FileReaderService
  320. * @param {*} VideoStreamService
  321. */
  322. function MainCtrl($scope,
  323. $rootScope,
  324. $timeout,
  325. GRIDSTER_OPTIONS_EDICAO,
  326. GRIDSTER_OPTIONS_VISUALIZACAO,
  327. UserInfo,
  328. UserPresets,
  329. $mdDialog,
  330. DetalhamentoService,
  331. $state,
  332. MsiService,
  333. CommService,
  334. $stateParams,
  335. toasty,
  336. CamadasService,
  337. AuthService,
  338. MapaService,
  339. MainState,
  340. MainManager,
  341. ModuloTwitterManager,
  342. CamerasManager,
  343. BuscaManager,
  344. MensageriaManager,
  345. AvisoOperacionalManager,
  346. RotasManager,
  347. RotasUnificadasManager,
  348. IncidentesManager,
  349. BaseConhecimentoManager,
  350. FacebookManager,
  351. EmailManager,
  352. TwitterManager,
  353. MSIManager,
  354. SubDetalhamentoManager,
  355. DetalhamentoManager,
  356. ZonaDeObservacaoManager,
  357. PlanejamentoManager,
  358. DeteccaoImpactoManager,
  359. MinhasTarefasManager,
  360. TarefaManager,
  361. BriefingOperacionalManager,
  362. MapaManager,
  363. BotoesManager,
  364. IncidenteEnterManager,
  365. AlarmeDisparadoManager,
  366. Preset,
  367. PermissoesService,
  368. $interval,
  369. EditPTarefaManager,
  370. TerminalManager,
  371. BuscaUsuariosTelegramManager,
  372. MainService,
  373. DetalhamentoRotasOlimpicasManager,
  374. HabilitarCamadasManager,
  375. localize,
  376. Modulo,
  377. AreaAtuacaoManager,
  378. RastreamentoManager,
  379. PontoMovelManager,
  380. ZonasDeObservacaoFilter,
  381. Usuario,
  382. FileUploader,
  383. API_ENDPOINT,
  384. $window,
  385. Base,
  386. MsiFilter,
  387. $http,
  388. PoiManager,
  389. Menu,
  390. ParametrosS4C,
  391. VoipManager,
  392. WebSocket,
  393. FileReaderService,
  394. VideoStreamService
  395. ) {
  396. /* Making sure the socket is initialized. */
  397. //CommService.start();
  398. var permissoesAreaAtuacao;
  399. $scope.version = MainState.getVersion();
  400. $interval(function () {
  401. $scope.noError = MainState.noError();
  402. $scope.errorMessage = MainState.getErrorMessage();
  403. }, 1000);
  404. /**
  405. * @method isToShow
  406. * @param label
  407. */
  408. $scope.isToShow = function (label) {
  409. return MainState.isToShow(label);
  410. }
  411. /**
  412. * @method moduleActive
  413. */
  414. $scope.moduleActive = function () {
  415. for (var index in Preset.config.preset.PresetModulos) {
  416. var name = Preset.config.preset.PresetModulos[index].Face ? Preset.config.preset.PresetModulos[index].Face.name : '';
  417. if (Preset.config.preset.PresetModulos[index].name == 'MODULO_DETALHAMENTO' ||
  418. Preset.config.preset.PresetModulos[index].name == $scope.res('MODULO_DETALHAMENTO') ||
  419. name == 'MODULO_DETALHAMENTO' ||
  420. name == $scope.res('MODULO_DETALHAMENTO')
  421. ) {
  422. DetalhamentoManager.ativo = false;
  423. SubDetalhamentoManager.ativo = false;
  424. return true;
  425. }
  426. }
  427. return false;
  428. }
  429. if (!AuthService.user.info.permissoesAreaAtuacao) {
  430. $http.get(API_ENDPOINT + 'area_atuacao/permissoes')
  431. .then(function (permissoes) {
  432. AuthService.getUserInfo().then(function (user) {
  433. user.permissoesAreaAtuacao = permissoes.data;
  434. AuthService.user.info.permissoesAreaAtuacao = permissoes.data;
  435. permissoesAreaAtuacao = permissoes.data;
  436. });
  437. }, function (err) {
  438. p.reject(err);
  439. });
  440. }
  441. $scope.res = $rootScope.res;
  442. $scope.blackList = $rootScope.blackList;
  443. if (moment.locale() == 'en') {
  444. localize.replacejscssfile("assets/i18n/leaflet.draw.pt-br.js", "assets/i18n/leaflet.draw.en-us.js", "js")
  445. } else {
  446. localize.replacejscssfile("assets/i18n/leaflet.draw.en-us.js", "assets/i18n/leaflet.draw.pt-br.js", "js")
  447. }
  448. var flyTo = $stateParams.flyTo;
  449. if (flyTo) {
  450. var data = flyTo.split('|');
  451. var method = data[0];
  452. var id = data[1];
  453. if (method === 'incidente') {
  454. $timeout(function () {
  455. DetalhamentoService.pegarIncidente(id)
  456. .then(function (incidente) {
  457. incidente.geojson = JSON.parse(incidente.geojson);
  458. CamadasService.reloadIncidentes(true);
  459. $scope.IncidentesManager.voarParaIncidente(incidente);
  460. $scope.MapaManager.voarParaObjeto(incidente);
  461. });
  462. }, 5000);
  463. } else if (method === 'zona_observacao') {
  464. $timeout(function () {
  465. CamadasService.exibirZonasDeObservacao();
  466. $scope.DetalhamentoManager.abrirZonaDeObservacao(id);
  467. }, 5000);
  468. }
  469. }
  470. /**
  471. * @method getPermissoes
  472. * @param perms
  473. */
  474. PermissoesService.getPermissoes().then(function (perms) {
  475. $scope.permissoesVisualizacao = perms.permissoesVisualizacao;
  476. $scope.permissoesCriacao = perms.permissoesCriacao;
  477. $scope.permissoesEdicao = perms.permissoesEdicao;
  478. $scope.permissoesRemocao = perms.permissoesRemocao;
  479. $scope.permissoesExtras = perms.permissoesExtras;
  480. if (!_.includes(perms.permissoesCriacao, true)) {
  481. $scope.nenhumaPermissaoCriacao = true;
  482. }
  483. MainState.setPermissoes(perms);
  484. });
  485. MainService.on('logout', logout);
  486. MainService.on('alarmes', function (data) {
  487. if (!data) {
  488. return;
  489. }
  490. // Se o tipo de alarme for de rota
  491. if (data.rota) {
  492. if (!_belongsDataRangeRota(data.alarme)) {
  493. return;
  494. }
  495. }
  496. // Se o tipo de alarme for de Zona de observação
  497. if (data.zonaDeObservacao) {
  498. if (!_belongsDataRange(data.alarme)) {
  499. return;
  500. }
  501. _atualizaDetalhamentoZO(data.zonaDeObservacao.id);
  502. }
  503. var tweetsNovos;
  504. var detalhamentoManager = DetalhamentoManager;
  505. /*
  506. * Se o Detalhamento da Zona de Observação estiver Ativo
  507. * e algum alarme for disparado pertencer a ela,
  508. * o Detalhamento é recarregado
  509. */
  510. /**
  511. * @method _atualizaDetalhamentoZO
  512. * @param {*} id
  513. */
  514. function _atualizaDetalhamentoZO(id) {
  515. var zonaManager = MainState.getManager('ZonaDeObservacaoManager');
  516. if (zonaManager.ativo) {
  517. if (id === zonaManager.data.id) {
  518. DetalhamentoManager.abrirZonaDeObservacao(id);
  519. }
  520. }
  521. }
  522. /**
  523. * @method _belongsDataRangeRota
  524. * @param {*} alarme
  525. */
  526. function _belongsDataRangeRota(alarme) {
  527. var dateNow = moment();
  528. if (!alarme.detalhes) return true;
  529. if (!alarme.detalhes.ranges) return true;
  530. var hasRange = alarme.detalhes.ranges.filter(function (range) {
  531. if (range.start) {
  532. if (!(moment(range.start).isSame(dateNow) || moment(range.start).isBefore(dateNow))) {
  533. return
  534. }
  535. }
  536. if (range.end) {
  537. if (!(moment(range.end).isSame(dateNow) || moment(range.end).isAfter(dateNow))) {
  538. return
  539. }
  540. }
  541. return true;
  542. });
  543. return (hasRange.length > 0);
  544. }
  545. /**
  546. * @method _belongsDataRange
  547. * @param {*} alarme
  548. */
  549. function _belongsDataRange(alarme) {
  550. var dateNow = moment();
  551. if (!alarme.detalhes.start && !alarme.detalhes.end && !alarme.detalhes.ranges) return true;
  552. var fullRange = {
  553. start: moment(alarme.detalhes.start, 'DD/MM/YYYY HH:mm') || null,
  554. end: moment(alarme.detalhes.end, 'DD/MM/YYYY HH:mm') || null
  555. };
  556. if (fullRange.start) {
  557. TarefaManager.close = true;
  558. if (!(fullRange.start.isSame(dateNow) || fullRange.start.isBefore(dateNow))) {
  559. return;
  560. }
  561. }
  562. if (fullRange.end) {
  563. if (!(fullRange.end.isSame(dateNow) || fullRange.end.isAfter(dateNow))) {
  564. return;
  565. }
  566. }
  567. return true;
  568. }
  569. /**
  570. * @method ativarPlanejamento
  571. * @param {*} data
  572. */
  573. var ativarPlanejamento = function (data) {
  574. var planejamento = MainState.getDirective('planejamento');
  575. var usuario = MainState.getManager('UserInfo');
  576. var payload = data.alarme.planejamento;
  577. CamadasService.exibirPlanejamentos();
  578. MapaService.voarPara(data.alarme.planejamento.geometricPOI.coordinates);
  579. if (planejamento.ativo) {
  580. planejamento.fecharPlanejamento();
  581. }
  582. if (PlanejamentoManager.ativo) {
  583. PlanejamentoManager.fecharPlanejamento();
  584. }
  585. PlanejamentoManager.ativo = true;
  586. planejamento.ativo = true;
  587. planejamento.abrirPlanejamento({
  588. draggable: function () { },
  589. undraggable: function () {
  590. },
  591. marker: {
  592. getLatLng: function () {
  593. return L.latLng(
  594. payload.geojson.coordinates[1], payload.geojson.coordinates[0]
  595. );
  596. },
  597. setLatLng: function (lat, lng) {
  598. return L.latLng(lat, lng);
  599. }
  600. },
  601. oldLat: data.alarme.planejamento.geometricPOI.coordinates[1],
  602. oldLng: data.alarme.planejamento.geometricPOI.coordinates[0]
  603. }, payload, usuario);
  604. }
  605. /**
  606. * @method ativarCamadaZO
  607. * @param {*} data
  608. */
  609. var ativarCamadaZO = function (data) {
  610. CamadasService.exibirZonasDeObservacao();
  611. detalhamentoManager.abrirZonaDeObservacao(data.alarme.zonaObservacao.id);
  612. CamadasService.ativarMenuCategoria(data.alarme.detalhes.categoriaId);
  613. CamadasService.ativarSubCategorias(data.alarme.detalhes.categoriaId);
  614. }
  615. /**
  616. * @method ativarZO
  617. * @param {*} data
  618. */
  619. var ativarZO = function (data) {
  620. CamadasService.exibirZonasDeObservacao();
  621. detalhamentoManager.abrirZonaDeObservacao(data.zonaDeObservacao.id);
  622. CamadasService.ativarMenuCategoria(data.alarme.detalhes.categoriaId);
  623. }
  624. /**
  625. * @method tocarSom
  626. * @param {*} arquivo
  627. */
  628. var tocarSom = _.debounce(function (arquivo) {
  629. var som = new Audio(arquivo);
  630. som.play();
  631. }, 1000);
  632. /**
  633. * @method abrirIncidente
  634. * @param {*} data
  635. */
  636. var abrirIncidente = function (data) {
  637. if (!data.alarme.incidente.geojson) {
  638. var latLng = data.alarme.incidente.poiGeometrico.match(/\(([^)]+)\)/)[1].split(' ');
  639. data.alarme.incidente.geojson = {
  640. coordinates: [latLng[0], latLng[1]]
  641. };
  642. } else {
  643. if (typeof data.alarme.incidente.geojson === 'string') {
  644. data.alarme.incidente.geojson = JSON.parse(data.alarme.incidente.geojson);
  645. }
  646. }
  647. CamadasService.reloadIncidentes(true);
  648. IncidentesManager.voarParaIncidente(data.alarme.incidente);
  649. MapaManager.voarParaObjeto(data.alarme.incidente);
  650. detalhamentoManager.abrirIncidente(data.alarme.incidente.id, {
  651. lat: data.alarme.incidente.geojson.coordinates[1],
  652. lng: data.alarme.incidente.geojson.coordinates[0]
  653. });
  654. };
  655. /**
  656. * @method abrirBriefing
  657. * @param {*} data
  658. * @param {*} context
  659. */
  660. var abrirBriefing = function (data, context) {
  661. BriefingOperacionalManager.responderBriefing();
  662. toasty.clear(context.id);
  663. };
  664. /**
  665. * @method fitTweets
  666. * @param {*} data
  667. */
  668. var fitTweets = function (data) {
  669. var tweets = data.tweets;
  670. var coordinates = data.tweets.map(function (tweet) {
  671. var coordinates = tweet.geo.coordinates.slice();
  672. return coordinates;
  673. });
  674. MapaService.fitBounds(coordinates, tweets);
  675. };
  676. var acoesExternas = {
  677. /**
  678. * @method voarParaIncidente
  679. * @param {*} id
  680. */
  681. 'voarParaIncidente': function (id) {
  682. DetalhamentoService.pegarIncidente(id)
  683. .then(function (incidente) {
  684. incidente.geojson = JSON.parse(incidente.geojson);
  685. incidente.geometry = incidente.geojson;
  686. var inc = DetalhamentoManager.abrirIncidente(incidente.id, {
  687. lat: incidente.geojson.coordinates[1],
  688. lng: incidente.geojson.coordinates[0]
  689. });
  690. MainState.getDirective('filtro-msi').voarIncidente(incidente);
  691. });
  692. },
  693. /**
  694. * @method abrirPoi
  695. * @param {*} chaves_estrangeira
  696. */
  697. 'abrirPoi': function (chave_estrangeira) {
  698. DetalhamentoService.pegarPoiPorChaveEstrangeira(chave_estrangeira).then(function (poi) {
  699. var latlng = {
  700. lat: poi.latitude,
  701. lng: poi.longitude
  702. };
  703. DetalhamentoManager.abrirPoi(poi.id, latlng);
  704. CamadasService.ativarMenuCategoria(poi.CategoriumId);
  705. MapaService.voarPara([
  706. poi.longitude,
  707. poi.latitude
  708. ]);
  709. MapaService.piscarAzul(latlng);
  710. });
  711. },
  712. /**
  713. * @method voarPara
  714. * @param {*} coordenadas
  715. */
  716. 'voarPara': function (coordenadas) {
  717. MapaService.voarPara([
  718. coordenadas.longitude,
  719. coordenadas.latitude
  720. ]);
  721. },
  722. 'ligarParaRamal': function (obj) {
  723. call(obj.ramal);
  724. }
  725. }
  726. /**
  727. * @method acoesAlarmeExterno
  728. * @param {*} data
  729. */
  730. var acoesAlarmeExterno = function (data) {
  731. _.each(data.alarme.alarmeExterno.detalhes.acoes, function (acao) {
  732. acoesExternas[acao.nome](acao.parametro)
  733. })
  734. }
  735. /**
  736. * @method voarParaZona
  737. * @param {*} data
  738. */
  739. var voarParaZona = function (data) {
  740. $scope.MapaManager.voarParaObjeto(data.zonaDeObservacao);
  741. };
  742. /**
  743. * @method aceitarVideoChamada
  744. * @param {*} data
  745. */
  746. var aceitarVideoChamada = function (data) {
  747. var url_ = ParametrosS4C.wowzaUrl + '/live/' + data.poiChaveEstrangeira + '.stream/playlist.m3u8';
  748. acoesExternas['voarPara'](data.coordenadas);
  749. acoesExternas['abrirPoi'](data.poiChaveEstrangeira);
  750. //window.open(data.url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=false,resizable=false,width=670,height=512');
  751. window.open("/Cam/rtsp/?url=" + url_, '_blank', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=false,resizable=false,width=' + 670 + ',height=' + 400);
  752. }
  753. var acoes = {
  754. 'TwitterZO': fitTweets,
  755. 'TempoZO': voarParaZona,
  756. 'IncidenteZO': abrirIncidente,
  757. 'Incidente': abrirIncidente,
  758. 'agendarAlertaBriefing': abrirBriefing,
  759. 'Externo': acoesAlarmeExterno,
  760. 'External': acoesAlarmeExterno,
  761. 'AtivarCamadaZO': ativarCamadaZO,
  762. 'CercaVirtualSaidaZO': ativarZO,
  763. 'CercaVirtualEntradaZO': ativarZO,
  764. 'CercaVirtualPermanenciaZO': ativarZO,
  765. 'Planejamento': ativarPlanejamento,
  766. 'VideoChamada': aceitarVideoChamada
  767. };
  768. var som = _.get(data, 'alarme.detalhes.som');
  769. if (som !== undefined) {
  770. tocarSom(som);
  771. }
  772. /**
  773. * Verifica se os tweets passados pelo backend já foram notificados
  774. * ao usuário.
  775. */
  776. if (data.alarme && (data.alarme.tipo === 'Twitter' || data.alarme.tipo == 'TwitterZO')) {
  777. var tweetsAlarmados = localStorage.getItem('tweetsAlarmados');
  778. var alarmados = null;
  779. if (tweetsAlarmados) {
  780. alarmados = tweetsAlarmados.split(',');
  781. // Filtrando para existirem apenas tweets que não estão no
  782. // localStorage
  783. tweetsNovos = _.filter(data.tweets, function (tweet) {
  784. return alarmados.indexOf(tweet.id_str) < 0;
  785. });
  786. if (tweetsNovos.length === 0) {
  787. // Não há novos tweets, retornando
  788. return;
  789. }
  790. // Existem novos tweets, concatenando
  791. alarmados = alarmados.concat(_.map(tweetsNovos, function (tweet) {
  792. return tweet.id_str;
  793. }));
  794. } else {
  795. alarmados = _.map(data.tweets, function (tweet) {
  796. return tweet.id_str;
  797. });
  798. }
  799. if (alarmados.length > 0) {
  800. localStorage.setItem('tweetsAlarmados', alarmados);
  801. }
  802. }
  803. if (data.mensagem) {
  804. if (data.tipo) {
  805. if (data.tipo === 'Briefing') {
  806. var permissoes = _.chain(AuthService.user.info.Perfils)
  807. .map(function (perfil) {
  808. return perfil.PermissaoAcessos;
  809. })
  810. .flatten()
  811. .filter(function (permissao) {
  812. return permissao.modulo === 'Briefing';
  813. })
  814. .value();
  815. if (permissoes.length <= 0) {
  816. // Usuário não tem permissãoo para responder o Briefing
  817. return;
  818. }
  819. data.mensagem += '. ' + $scope('COMUM_CLICK_RESPONDER');
  820. data.alarme = {
  821. tipo: 'Briefing'
  822. };
  823. }
  824. if (data.tipo === 'VideoChamada') {
  825. toasty({
  826. title: 'Chamada de Vídeo',
  827. msg: data.data + '<br/>' + data.mensagem,
  828. showClose: true,
  829. timeout: false,
  830. sound: false,
  831. html: true,
  832. shake: false,
  833. onClick: function () {
  834. acoes[data.tipo](data, this);
  835. }
  836. });
  837. }
  838. }
  839. if (data.alarme) {
  840. if (data.alarme.alarmeExterno) {
  841. toasty({
  842. title: data.alarme.alarmeExterno.titulo,
  843. msg: data.alarme.alarmeExterno.dataHora + '<br/>' + data.alarme.alarmeExterno.mensagem,
  844. showClose: true,
  845. timeout: false,
  846. sound: false,
  847. html: true,
  848. shake: false,
  849. onClick: function () {
  850. acoes[data.alarme.tipo](data, this);
  851. }
  852. });
  853. } else {
  854. if (data.time != null && data.qtdTime != null) {
  855. toasty({
  856. msg: localize.res(data.mensagem) + data.qtdTime + ' ' + localize.res(data.time),
  857. html: true,
  858. onClick: function () {
  859. acoes[data.alarme.tipo](data, this);
  860. }
  861. });
  862. } else {
  863. toasty({
  864. msg: localize.res(data.mensagem),
  865. html: true,
  866. onClick: function () {
  867. acoes[data.alarme.tipo](data, this);
  868. }
  869. });
  870. }
  871. }
  872. }
  873. }
  874. });
  875. ParametrosS4C.showing = false;
  876. /**
  877. * @method addEventListener('keydown')
  878. * @param {*} e
  879. */
  880. window.addEventListener('keydown', function (e) {
  881. if ((e.altKey) && (e.which === 65)) { // Pesquisar (Alt + A)
  882. e.Handled = true;
  883. if (!ParametrosS4C.showing) {
  884. $('.barraModulo').addClass('mostraBarra');
  885. $('.barraModulo .md-toolbar-tools span').addClass('menuFonte');
  886. $('.barraModulo').css('position', 'absolute');
  887. $('.btn-action').removeClass('show');
  888. $('.wrapper').removeClass('topClass');
  889. $('.webViewNav').parent().next().addClass('mt-5');
  890. ParametrosS4C.showing = true;
  891. } else {
  892. $('.barraModulo').removeClass('mostraBarra');
  893. $('.barraModulo .md-toolbar-tools span').removeClass('menuFonte');
  894. // $('.btn-action').addClass('show');
  895. $('.wrapper').addClass('topClass');
  896. $('.webViewNav').parent().next().removeClass('mt-5');
  897. ParametrosS4C.showing = false;
  898. }
  899. }
  900. }, true);
  901. /**
  902. * @method addEventListener(keydown')
  903. * @param {*} e
  904. */
  905. window.addEventListener('keydown', function (e) {
  906. if ((e.altKey) && (e.which === 81)) { // Pesquisar (Alt + Q)
  907. e.Handled = true;
  908. if (!ParametrosS4C.showing) {
  909. $('.menu-superior').addClass('hoverMain');
  910. ParametrosS4C.showing = true;
  911. } else {
  912. $('.menu-superior').removeClass('hoverMain');
  913. ParametrosS4C.showing = false;
  914. }
  915. }
  916. }, true);
  917. /**
  918. * @method addEventListener('DOMContentLoaded')
  919. */
  920. document.body.addEventListener('DOMContentLoaded', function () {
  921. var elems = document.querySelectorAll('.collapsible');
  922. var instances = M.Collapsible.init(elems, options);
  923. });
  924. $timeout(MainState.menuButtonFunction, 2000);
  925. $timeout(function () {
  926. var electron = navigator.userAgent.indexOf("Electron") != -1;
  927. if (!electron) {
  928. $('.menuMain').addClass('hoverMain');
  929. $('.menuMain').removeClass('menuMain');
  930. $('.icone-toolbar img').addClass('png-icon');
  931. $('#mainDiv').addClass('hoverMain');
  932. $('#mainDiv').removeClass('menuMain');
  933. $(".face .wrapper").addClass('topClass');
  934. $(".face .wrapper").css('position', 'absolute');
  935. }
  936. }, 300);
  937. $timeout(function () {
  938. var electron = navigator.userAgent.indexOf("Electron") != -1;
  939. if (!electron) {
  940. $('.barraModulo').addClass('mostraBarra');
  941. $('.barraModulo .md-toolbar-tools span').addClass('menuFonte');
  942. $('.barraModulo').css('position', 'absolute');
  943. $('.btn-action').removeClass('show');
  944. $('.wrapper').removeClass('topClass');
  945. $('.webViewNav').parent().next().addClass('mt-5');
  946. ParametrosS4C.showing = true;
  947. }else{
  948. $('.wrapper').addClass('topClass');
  949. }
  950. }, 2500);
  951. //Função para ter sempre disponível na window a posição do mouse
  952. /**
  953. * @method handler
  954. * @param {*} e
  955. */
  956. function handler(e) {
  957. e = e || window.event;
  958. var pageX = e.pageX;
  959. var pageY = e.pageY;
  960. if (pageX === undefined) {
  961. pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
  962. pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  963. }
  964. window.positionX = pageX;
  965. window.positionY = pageY;
  966. }
  967. // attach handler to the click event of the document
  968. if (document.attachEvent) document.attachEvent('onclick', handler);
  969. else document.addEventListener('click', handler);
  970. /**
  971. * @method errHandler
  972. * @param {*} err
  973. */
  974. let errHandler = function (err) {
  975. alert(err.message);
  976. };
  977. /**
  978. * @method readTextFile
  979. * @param {*} text
  980. */
  981. FileReaderService.readTextFile("/s4c_dir/videoServers.json", function (text) {
  982. var data = JSON.parse(text);
  983. ParametrosS4C.wowzaUrl = data.wowzaUrl;
  984. VideoStreamService.setPlayerOptions({
  985. socket: data.videoServerUrl,
  986. redirectNativeMediaErrors: true,
  987. bufferDuration: 30,
  988. errHandler: errHandler
  989. });
  990. });
  991. /**
  992. * @method $on
  993. * @param {*} e
  994. * @param {*} data
  995. */
  996. $rootScope.$on('s4c:windowResize', function (e, data) {
  997. // Gridster responsivo:
  998. GRIDSTER_OPTIONS_EDICAO.colWidth = parseInt((($(window).width() - 5) / GRIDSTER_OPTIONS_EDICAO.columns).toFixed(), 10);
  999. var electron = navigator.userAgent.indexOf("Electron") != -1;
  1000. if (!electron) {
  1001. GRIDSTER_OPTIONS_EDICAO.rowHeight = parseInt((($(window).height() + 0) / GRIDSTER_OPTIONS_EDICAO.maxRows).toFixed() - 9, 10);
  1002. } else {
  1003. GRIDSTER_OPTIONS_EDICAO.rowHeight = parseInt((($(window).height() + 0) / GRIDSTER_OPTIONS_EDICAO.maxRows).toFixed(), 10);
  1004. }
  1005. });
  1006. MainState.loadGridsterOptions(alterPreset);
  1007. /**
  1008. * @method alterPreset
  1009. */
  1010. function alterPreset(){
  1011. Preset.alterar(_.find(UserPresets, 'padrao') || _.find(UserPresets, 'DepartamentoId'));
  1012. }
  1013. /**
  1014. * @method logout
  1015. */
  1016. function logout() {
  1017. releaseResources();
  1018. AuthService.logout();
  1019. $state.go('inicio');
  1020. if (MainState.getDirective('voip') != null) {
  1021. MainState.getDirective('voip').deslogar();
  1022. }
  1023. }
  1024. setTimeout(function () { MainState.resizeMenuMapa() }, 3000)
  1025. /**
  1026. * @method novoUsuario
  1027. */
  1028. function novoUsuario() {
  1029. $mdDialog.show({
  1030. templateUrl: 'app/components/admin/modulos/usuarios/Usuario/novo.html',
  1031. controller: NovoUsuarioCtrl,
  1032. targetEvent: event
  1033. });
  1034. }
  1035. /**
  1036. * @method hideShare
  1037. */
  1038. function hideShare() {
  1039. $scope.isCancelled = false;
  1040. }
  1041. /**
  1042. * @method showShare
  1043. */
  1044. function showShare() {
  1045. $scope.isCancelled = true;
  1046. }
  1047. $scope.isCancelled = true;
  1048. $scope.renderers = [];
  1049. Preset.setMainRenderes($scope.renderers);
  1050. /**
  1051. * @method share
  1052. */
  1053. $scope.share = function () {
  1054. if (ParametrosS4C.parametros.multivisConfig.length == 0) {
  1055. return;
  1056. }
  1057. if (ParametrosS4C.parametros.multivisConfig.length == 1) {
  1058. var constraint = {
  1059. url: ParametrosS4C.parametros.multivisConfig[0].hostname.replace('http', 'ws').replace('https', 'wss'),
  1060. positionX: $scope.positionX,
  1061. positionY: $scope.positionY
  1062. }
  1063. if (!$scope.renderers[ParametrosS4C.parametros.multivisConfig[0].hostname]) {
  1064. var connection1 = new render.Screenshare(constraint);
  1065. $scope.renderers[ParametrosS4C.parametros.multivisConfig[0].hostname] = connection1;
  1066. }
  1067. hideShare();
  1068. return;
  1069. }
  1070. var confirm = $mdDialog.confirm({
  1071. locals: { render: render, renderers: $scope.renderers },
  1072. templateUrl: 'app/directives/preset/escolhaMultivis.html',
  1073. controller: function ($scope, $mdDialog, render, renderers) {
  1074. $scope.res = $scope.$root.res;
  1075. $scope.multivisSelecionado;
  1076. $scope.multivisList = ParametrosS4C.parametros.multivisConfig;
  1077. $scope.positionX;
  1078. $scope.positionY;
  1079. $scope.rect = document.getElementById("bodyDiv").getBoundingClientRect();
  1080. $scope.ok = function () {
  1081. if (!$scope.multivisSelecionado) {
  1082. return;
  1083. }
  1084. var constraint = {
  1085. url: $scope.multivisSelecionado.hostname.replace('http', 'ws').replace('https', 'wss'),
  1086. positionX: $scope.positionX,
  1087. positionY: $scope.positionY
  1088. }
  1089. if (!renderers[$scope.multivisSelecionado.hostname]) {
  1090. var connection1 = new render.Screenshare(constraint);
  1091. renderers[$scope.multivisSelecionado.hostname] = connection1;
  1092. }
  1093. hideShare();
  1094. $mdDialog.hide();
  1095. }
  1096. $scope.cancelar = function () {
  1097. $mdDialog.hide();
  1098. };
  1099. $scope.rendered = false;
  1100. var interval = $interval(function () {
  1101. if (!$scope.rendered && document.getElementById("escolhaMultivis")) {
  1102. document.getElementById("escolhaMultivis").style.top = (window.positionY + 100) + "px";
  1103. if (window.positionX - 200 > 0) {
  1104. document.getElementById("escolhaMultivis").style.left = (window.positionX - 200) + "px";
  1105. } else {
  1106. document.getElementById("escolhaMultivis").style.left = window.positionX + "px";
  1107. }
  1108. $scope.rendered = true;
  1109. $interval.cancel(interval);
  1110. }
  1111. }, 30);
  1112. },
  1113. parent: angular.element(document.body)
  1114. });
  1115. $mdDialog.show(confirm).then(function () { }, function () { });
  1116. }
  1117. /**
  1118. * @method stopShare
  1119. */
  1120. $scope.stopShare = function () {
  1121. if (ParametrosS4C.parametros.multivisConfig.length == 0) {
  1122. return;
  1123. }
  1124. if (ParametrosS4C.parametros.multivisConfig.length == 1) {
  1125. $scope.multivisSelecionado = ParametrosS4C.parametros.multivisConfig[0];
  1126. if ($scope.renderers[$scope.multivisSelecionado.hostname]) {
  1127. $scope.renderers[$scope.multivisSelecionado.hostname].closeApp($scope.renderers[$scope.multivisSelecionado.hostname]);
  1128. $scope.renderers[$scope.multivisSelecionado.hostname] = null;
  1129. }
  1130. showShare();
  1131. return;
  1132. }
  1133. var confirm = $mdDialog.confirm({
  1134. locals: { renderers: $scope.renderers },
  1135. templateUrl: 'app/directives/preset/escolhaMultivis.html',
  1136. controller: function ($scope, $mdDialog, renderers) {
  1137. $scope.res = $scope.$root.res;
  1138. $scope.multivisSelecionado;
  1139. $scope.multivisList = ParametrosS4C.parametros.multivisConfig;
  1140. $scope.rendered = false;
  1141. var interval = $interval(function () {
  1142. if (!$scope.rendered && document.getElementById("escolhaMultivis")) {
  1143. document.getElementById("escolhaMultivis").style.top = (window.positionY + 100) + "px";
  1144. if (window.positionX - 200 > 0) {
  1145. document.getElementById("escolhaMultivis").style.left = (window.positionX - 200) + "px";
  1146. } else {
  1147. document.getElementById("escolhaMultivis").style.left = window.positionX + "px";
  1148. }
  1149. $scope.rendered = true;
  1150. $interval.cancel(interval);
  1151. }
  1152. }, 30);
  1153. $scope.ok = function () {
  1154. if (!$scope.multivisSelecionado) {
  1155. return;
  1156. }
  1157. if (renderers[$scope.multivisSelecionado.hostname]) {
  1158. renderers[$scope.multivisSelecionado.hostname].closeApp(renderers[$scope.multivisSelecionado.hostname]);
  1159. renderers[$scope.multivisSelecionado.hostname] = null;
  1160. }
  1161. showShare();
  1162. $mdDialog.hide();
  1163. }
  1164. $scope.cancelar = function () {
  1165. $mdDialog.hide();
  1166. };
  1167. },
  1168. parent: angular.element(document.body)
  1169. });
  1170. $mdDialog.show(confirm).then(function () {
  1171. }, function () { });
  1172. }
  1173. /**
  1174. * @method NovoUsuarioCtrl
  1175. * @param {*} $scope
  1176. * @param {*} Usuario
  1177. * @param {*} $mdDialog
  1178. * @param {*} localize
  1179. * @param {*} FileUploader
  1180. * @param {*} API_ENDPOINT
  1181. * @param {*} AuthService
  1182. */
  1183. function NovoUsuarioCtrl($scope, Usuario, $mdDialog, localize, FileUploader, API_ENDPOINT, AuthService) {
  1184. $scope.username = AuthService.user.info.username;
  1185. $scope.name = AuthService.user.info.nome;
  1186. $scope.res = $scope.$root.res;
  1187. /**
  1188. * @method obterPorId
  1189. * @param usuario
  1190. */
  1191. Usuario.obterPorId(AuthService.user.info.id)
  1192. .then(function (usuario) {
  1193. $scope.user = usuario;
  1194. if ($scope.user.urlImagem != null) {
  1195. $scope.hasImage = true;
  1196. } else {
  1197. $scope.hasImage = false;
  1198. }
  1199. });
  1200. /**
  1201. * @method cancelar
  1202. */
  1203. $scope.cancelar = function () {
  1204. $mdDialog.hide();
  1205. };
  1206. /**
  1207. * @method criar
  1208. */
  1209. $scope.criar = function () {
  1210. $scope.cpfExists = false;
  1211. $scope.emailExists = false;
  1212. if ($scope.trocaSenha.$valid) {
  1213. $scope.user.password = $scope.senha;
  1214. } else {
  1215. $scope.user.password = null;
  1216. }
  1217. /**
  1218. * @method atualizarPerfil
  1219. * @param {*} u
  1220. */
  1221. Usuario.atualizarPerfil($scope.user.id, $scope.user).then(function (u) {
  1222. if (!u.id) {
  1223. if (u.Status == 'CPF_USUARIO_EXISTE') {
  1224. $scope.cpfExists = true;
  1225. }
  1226. if (u.Status == 'EMAIL_USUARIO_EXISTE') {
  1227. $scope.emailExists = true;
  1228. }
  1229. return;
  1230. } else {
  1231. toBlob();
  1232. MainState.getManager('UserInfo').nome = u.nome;
  1233. MainState.getManager('UserInfo').cpf = u.cpf;
  1234. /**
  1235. * @method obterShortUsers
  1236. * @param usuarios
  1237. */
  1238. Usuario.obterShortUsers().then(function (usuarios) {
  1239. var usuario_ = _.find(usuarios, function (user) { return user.id === u.id; });
  1240. if (usuario_) {
  1241. usuario_.nome = u.nome;
  1242. }
  1243. });
  1244. $mdDialog
  1245. .show($mdDialog.alert()
  1246. .title($scope.res('COMUM_SUCESSO'))
  1247. .content($scope.res('USUARIO_ATUALIZADO'))
  1248. .ok($scope.res('COMUM_OK')));
  1249. $mdDialog.hide(u);
  1250. }
  1251. });
  1252. };
  1253. /**
  1254. * @method setTimeout
  1255. */
  1256. setTimeout(function () {
  1257. $scope.input = angular.element('#arquivo');
  1258. }, 1000);
  1259. /**
  1260. * @method abrirUpload
  1261. */
  1262. $scope.abrirUpload = function () {
  1263. $scope.input.click();
  1264. }
  1265. var uploader = $scope.uploader = new FileUploader(),
  1266. uploadCallbackQueue = [];
  1267. uploader.clearQueue();
  1268. $scope.uploader.filters.push({
  1269. 'name': 'enforceMaxFileSize',
  1270. 'fn': function (item, evt) {
  1271. var megaByte = parseInt(item.size / 1000000) + "MB";
  1272. if (item.size <= 26214400) {
  1273. return item.size <= 26214400
  1274. } else {
  1275. $mdDialog
  1276. .show($mdDialog.alert()
  1277. .title($scope.res('COMUM_TAMANHOFILEULTRAPASSADO'))
  1278. .content($scope.res('LIMITE_ARQUIVO_ULTRAPASSADO', megaByte))
  1279. .ok($scope.res('COMUM_OK')))
  1280. return item.size <= 26214400
  1281. }
  1282. }
  1283. });
  1284. /**
  1285. * @method
  1286. * @param item
  1287. * @param response
  1288. */
  1289. $scope.uploader.onCompleteItem = function (item, response) {
  1290. $scope.mensagem = response;
  1291. };
  1292. /**
  1293. * @method onAfterAddingFile
  1294. * @param Item
  1295. * @param evt
  1296. * @param arquivo
  1297. */
  1298. $scope.uploader.onAfterAddingFile = function (item, evt, arquivo) {
  1299. item.novoNome = item.file.name;
  1300. enviarArquivo();
  1301. }
  1302. /**
  1303. * @method exit
  1304. * @param {*} filename
  1305. */
  1306. function ext(filename) {
  1307. var index = _.lastIndexOf(filename, '.');
  1308. return filename.substring(index, filename.length);
  1309. }
  1310. /**
  1311. * @method onBeforeUploadItem
  1312. * @param Item
  1313. */
  1314. $scope.uploader.onBeforeUploadItem = function (item) {
  1315. item.url = uploader.url;
  1316. var token = window.sessionStorage.getItem('s4cToken');
  1317. var tokenObj = JSON.parse(token);
  1318. item.headers = {
  1319. 'Authorization': 'Bearer ' + tokenObj.access_token
  1320. };
  1321. item.file.name = item.novoNome + ext(item.file.name);
  1322. };
  1323. /**
  1324. * @method onProgressItem
  1325. * @param fileItem
  1326. * @param progress
  1327. */
  1328. $scope.uploader.onProgressItem = function (fileItem, progress) {
  1329. console.info('onProgressItem', fileItem, progress);
  1330. };
  1331. /**
  1332. * @method onCompleteAll
  1333. * @param {*} result
  1334. */
  1335. $scope.uploader.onCompleteAll = function (result) {
  1336. _.each(uploadCallbackQueue, function (callback) {
  1337. callback();
  1338. });
  1339. };
  1340. /**
  1341. * @method mostrarImagem
  1342. */
  1343. $scope.mostrarImagem = function () {
  1344. $('#arquivo').each(function (index) {
  1345. if ($('#arquivo').eq(index).val() != "") {
  1346. $scope.readURL(this);
  1347. }
  1348. });
  1349. }
  1350. /**
  1351. * @method removeImage
  1352. */
  1353. $scope.removeImage = function () {
  1354. $scope.hasImage = false;
  1355. }
  1356. /**
  1357. * @method readURL
  1358. * @param input
  1359. */
  1360. $scope.readURL = function (input) {
  1361. if (input.files && input.files[0]) {
  1362. $scope.hasImage = true;
  1363. var reader = new FileReader();
  1364. reader.onload = function (e) {
  1365. $("#renderCropper_perfil").empty();
  1366. var img = $('<img />', {
  1367. id: 'image',
  1368. src: e.target.result,
  1369. style: 'width: 100%'
  1370. }).appendTo($('#renderCropper_perfil'));
  1371. var cropper = new Cropper(img[0], {
  1372. aspectRatio: 1,
  1373. crop: function (e) {
  1374. document.getElementById('editarX').value = e.detail.x;
  1375. document.getElementById('editarY').value = e.detail.y;
  1376. document.getElementById('editarWidth').value = e.detail.width;
  1377. document.getElementById('editarHeight').value = e.detail.height;
  1378. },
  1379. zoomable: true,
  1380. scalable: true,
  1381. movable: true,
  1382. background: false,
  1383. viewMode: 1
  1384. });
  1385. };
  1386. reader.readAsDataURL(input.files[0]);
  1387. }
  1388. }
  1389. /**
  1390. * @method enviarArquivo
  1391. */
  1392. function enviarArquivo() {
  1393. $scope.mostrarImagem();
  1394. }
  1395. $scope.uploader.alias = 'arquivo';
  1396. $scope.uploader.removeAfterUpload = true;
  1397. /**
  1398. * @method toBlob
  1399. */
  1400. function toBlob() {
  1401. var canvas = document.createElement('canvas');
  1402. var ctx = canvas.getContext('2d');
  1403. canvas.height = document.getElementById('editarHeight').value;
  1404. canvas.width = document.getElementById('editarWidth').value;
  1405. if (!document.getElementById('image') || !$scope.hasImage) {
  1406. return;
  1407. }
  1408. ctx.drawImage(document.getElementById('image'), document.getElementById('editarX').value, document.getElementById('editarY').value, canvas.width, canvas.height, 10, 10, canvas.width, canvas.height);
  1409. if (canvas.toBlob) {
  1410. canvas.toBlob(function (blob) {
  1411. var formData = new FormData();
  1412. var token = window.sessionStorage.getItem('s4cToken');
  1413. var tokenObj = JSON.parse(token);
  1414. formData.append('arquivo', blob, "avatar.png");
  1415. $.ajax('/usuarios/' + $scope.user.id, {
  1416. method: "POST",
  1417. data: formData,
  1418. processData: false,
  1419. contentType: false,
  1420. headers: {
  1421. 'Authorization': 'Bearer ' + tokenObj.access_token
  1422. },
  1423. success: function (data) {
  1424. MainState.getManager('UserInfo').urlImagem = data.imgUrl;
  1425. $('.imagem-usuario').attr("src", data.imgUrl);
  1426. },
  1427. error: function () {
  1428. console.log('Upload error');
  1429. }
  1430. });
  1431. });
  1432. }
  1433. }
  1434. }
  1435. /**
  1436. * @method onunload
  1437. */
  1438. window.onunload = function () {
  1439. if (MainState.getDirective('voip') != null) {
  1440. MainState.getDirective('voip').deslogar();
  1441. }
  1442. releaseResources();
  1443. }
  1444. /**
  1445. * @method onclose
  1446. */
  1447. window.onclose = function () {
  1448. if (MainState.getDirective('voip') != null) {
  1449. MainState.getDirective('voip').deslogar();
  1450. }
  1451. releaseResources();
  1452. }
  1453. $scope.MainManager = {
  1454. 'usuarioAtivo': UserInfo
  1455. };
  1456. /**
  1457. * @method atualizarRotas
  1458. */
  1459. $scope.atualizarRotas = function () {
  1460. var rotas = $scope.$directives.rotas || {};
  1461. rotas.atualizarRotas();
  1462. };
  1463. $scope.notificacaoManager = {
  1464. 'contarNofificacao': MensageriaManager.notificacao
  1465. };
  1466. $scope.BotoesManager = {
  1467. 'abrirTwitter': TwitterManager.abrir,
  1468. 'abrirFacebook': FacebookManager.abrir,
  1469. 'abrirMensageria': MensageriaManager.abrir,
  1470. 'abrirAvisoOperacional': AvisoOperacionalManager.abrir
  1471. };
  1472. $scope.CamadasManager = {
  1473. 'categoriasSelecionadas': []
  1474. };
  1475. $scope.disable = false;
  1476. $scope.showDeleteIcon = true;
  1477. /**
  1478. * @method visualizarPreset
  1479. */
  1480. $scope.visualizarPreset = function () {
  1481. var atualPreset = Preset.config.preset;
  1482. $scope.showDeleteIcon = true;
  1483. $scope.disable = true;
  1484. Preset.salvar().then(function (preset) {
  1485. if (preset.status == 403) {
  1486. toasty({
  1487. msg: preset.message
  1488. });
  1489. atualPreset = Preset.config.preset;
  1490. Preset.editar();
  1491. } else {
  1492. if (atualPreset.id === undefined) {
  1493. atualPreset.id = preset.id;
  1494. atualPreset.nome = preset.nome;
  1495. $scope.presets.push(atualPreset);
  1496. }
  1497. Preset.editar();
  1498. }
  1499. $scope.disable = false;
  1500. }, function (err) {
  1501. if (err.status == 422) {
  1502. $mdDialog
  1503. .show($mdDialog.alert()
  1504. .title('Erro')
  1505. .content($scope.res(err.message.message))
  1506. .ok('OK'));
  1507. }
  1508. });
  1509. };
  1510. /**
  1511. * @method editarPreset
  1512. */
  1513. $scope.editarPreset = function () {
  1514. // Pegar permissões de usuário
  1515. var permissoes = $scope.permissoesExtras,
  1516. isPresetDeAgencia = Preset.isPresetDeAgencia();
  1517. // Verificar se user tem permissão para modificar preset de grupo
  1518. if (!permissoes.alterarPresetAgencia && isPresetDeAgencia) {
  1519. toasty({
  1520. msg: $scope.res('COMUM_MSG_ALERT_EDITAR_PRESET')
  1521. });
  1522. return false;
  1523. }
  1524. if (_.keys(MainState.detalhamentosAtivos).length > 0) {
  1525. var confirm = $mdDialog.confirm()
  1526. .title($scope.res('COMUM_ATENCAO'))
  1527. .content($scope.res('COMUM_MSG_ALERT_MODO_EDICAO'))
  1528. .ariaLabel($scope.res('COMUM_CONFIRMAR_EDICAO'))
  1529. .ok($scope.res('COMUM_SIM'))
  1530. .cancel($scope.res('COMUM_CANCELAR'));
  1531. $mdDialog
  1532. .show(confirm)
  1533. .then(function () {
  1534. _.each(MainState.detalhamentosAtivos, function (detalhamento) {
  1535. detalhamento.fechar();
  1536. })
  1537. Preset.editar();
  1538. });
  1539. } else {
  1540. Preset.editar();
  1541. }
  1542. };
  1543. /**
  1544. * @method releaseResources
  1545. */
  1546. function releaseResources() {
  1547. CommService.stop();
  1548. closeModals();
  1549. VideoStreamService.closeAll();
  1550. CamadasService.clearReloadNodes();
  1551. Menu.clearPromise();
  1552. Preset.stopAllShare();
  1553. DetalhamentoManager.fecharTodos();
  1554. Preset.rollBackEmptyModules();
  1555. }
  1556. /**
  1557. * @method alterarPreset
  1558. * @param {*} preset
  1559. */
  1560. function alterarPreset(preset) {
  1561. const alterarPresetFinal = new Promise((resolve)=>{
  1562. Preset.alterar(preset);
  1563. setTimeout(()=>{resolve()},200)
  1564. });
  1565. alterarPresetFinal.then(()=> $('.wrapper').addClass('topClass'))
  1566. }
  1567. /**
  1568. * @method desenharPoligono
  1569. * @param {*} e
  1570. * @param {*} data
  1571. */
  1572. function desenharPoligono(e, data) {
  1573. $scope.RotasManager.desenharPoligono(data);
  1574. }
  1575. $rootScope.$on('mapa:desenharPoligono', desenharPoligono);
  1576. /**
  1577. * @method saveMapPosition
  1578. */
  1579. function saveMapPosition() {
  1580. MapaService.obterPontoCentral()
  1581. .then(function (center) {
  1582. MapaService.pegarZoom(function (zoom) {
  1583. var jsonObject = {};
  1584. jsonObject.lat = center.lat;
  1585. jsonObject.lng = center.lng;
  1586. jsonObject.zoom = zoom;
  1587. Preset.saveMapPosition(Preset.config.preset.id, jsonObject);
  1588. $mdDialog.show($mdDialog.alert()
  1589. .title($scope.res('COMUM_SUCESSO'))
  1590. .content($scope.res('MSG_PRESET_ATUALIZADO'))
  1591. .ok($scope.res('COMUM_OK')));
  1592. });
  1593. });
  1594. }
  1595. /**
  1596. * @method novoPreset
  1597. * @param {*} duplicarPreset
  1598. */
  1599. function novoPreset(duplicarPreset) {
  1600. var presetModulos = Preset.config.preset ? angular.copy(Preset.config.preset.PresetModulos) : [],
  1601. presetAntigo = Preset.obter(),
  1602. novoPreset = Preset.novo(),
  1603. presetNomes = _.map($scope.presets, 'nome');
  1604. $mdDialog.show({
  1605. templateUrl: 'app/directives/preset/dialog.html',
  1606. controller: function ($scope) {
  1607. $scope.res = $scope.$root.res;
  1608. $scope.titulo = ((duplicarPreset) ? $scope.res('MSG_SALVAR_NOVO_PRESET') : 'Preset');
  1609. $scope.erroNomeExistente = false;
  1610. $scope.erroNome = false;
  1611. $scope.preset = {
  1612. nome: ''
  1613. };
  1614. $scope.ok = function () {
  1615. if ($scope.preset.nome.length === 0) {
  1616. $scope.erroNome = true;
  1617. $scope.erroNomeExistente = false;
  1618. return false;
  1619. }
  1620. if ($scope.preset.nome && _.indexOf(presetNomes, $scope.preset.nome) !== -1) {
  1621. $scope.erroNomeExistente = true;
  1622. $scope.erroNome = false;
  1623. return false;
  1624. }
  1625. $mdDialog.hide($scope.preset.nome);
  1626. };
  1627. $scope.cancelar = function () {
  1628. Preset.alterar(presetAntigo)
  1629. $mdDialog.cancel();
  1630. };
  1631. },
  1632. clickOutsideToClose: false,
  1633. escapeToClose: false,
  1634. }).then(function (nome) {
  1635. Preset.renomear(nome);
  1636. if (duplicarPreset && duplicarPreset === true) {
  1637. novoPreset.PresetModulos = presetModulos;
  1638. Preset.obterMeus().then(function (meus) {
  1639. $scope.presets = meus;
  1640. $scope.presets.push(novoPreset);
  1641. });
  1642. }
  1643. novoPreset.padrao = false;
  1644. $scope.presets.push(novoPreset);
  1645. $scope.alterarPreset(novoPreset);
  1646. });
  1647. }
  1648. /**
  1649. * @method renomearPreset
  1650. */
  1651. function renomearPreset() {
  1652. var presetNomes = _.map($scope.presets, 'nome');
  1653. $mdDialog.show({
  1654. templateUrl: 'app/directives/preset/dialog.html',
  1655. controller: function ($scope) {
  1656. $scope.res = $scope.$root.res;
  1657. $scope.preset = Preset.obter();
  1658. $scope.ok = function () {
  1659. if (_.indexOf(presetNomes, $scope.preset.nome) !== -1) {
  1660. $scope.erroNomeExistente = true;
  1661. return false;
  1662. }
  1663. $mdDialog.hide($scope.preset.nome);
  1664. };
  1665. $scope.cancelar = function () {
  1666. $mdDialog.cancel();
  1667. }
  1668. },
  1669. clickOutsideToClose: false,
  1670. escapeToClose: false
  1671. }).then(function (nome) {
  1672. Preset.renomear(nome);
  1673. });
  1674. }
  1675. /**
  1676. * @method excluirPreset
  1677. * @param {*} e
  1678. * @param {*} preset
  1679. */
  1680. function excluirPreset(e, preset) {
  1681. PermissoesService.getPermissoes().then(function (perms) {
  1682. $scope.permissoesVisualizacao = perms.permissoesVisualizacao;
  1683. $scope.permissoesCriacao = perms.permissoesCriacao;
  1684. $scope.permissoesEdicao = perms.permissoesEdicao;
  1685. $scope.permissoesRemocao = perms.permissoesRemocao;
  1686. $scope.permissoesExtras = perms.permissoesExtras;
  1687. if (!$scope.permissoesRemocao.presetPublico) {
  1688. // Usuário não tem permissãoo para remover preset
  1689. $mdDialog
  1690. .show($mdDialog.alert()
  1691. .title($scope.res('COMUM_ERRO'))
  1692. .content($scope.res('PRESET_SEM_PERMISSAO_REMOVER'))
  1693. .ok($scope.res('COMUM_OK')));
  1694. return;
  1695. }
  1696. });
  1697. var confirm = $mdDialog.confirm()
  1698. .title($scope.res('MSG_DESEJA_EXCLUIR'))
  1699. .ariaLabel($scope.res('MSG_EXCLUIR_PRESET'))
  1700. .ok($scope.res('COMUM_SIM'))
  1701. .cancel($scope.res('COMUM_NAO'));
  1702. $mdDialog.show(confirm).then(function () {
  1703. Preset.remover(preset).then(function () {
  1704. var presetIndex = $scope.presets.indexOf(preset);
  1705. $scope.presets.splice(presetIndex, 1);
  1706. //Alterar para o preset padrão ou o primeiro da lista, caso tenha excluído o preset atual
  1707. if (preset === Preset.obter()) {
  1708. Preset.alterar(_.find($scope.presets, 'padrao') || _.find($scope.presets, 'DepartamentoId'));
  1709. }
  1710. $mdDialog
  1711. .show($mdDialog.alert()
  1712. .title($scope.res('COMUM_EXCLUIDO'))
  1713. .content($scope.res('PRESET_EXCLUIDO_SUCESSO'))
  1714. .ok($scope.res('COMUM_OK')));
  1715. }, function () {
  1716. $mdDialog
  1717. .show($mdDialog.alert()
  1718. .title($scope.res('COMUM_ERRO'))
  1719. .content($scope.res('MSG_ERRO_PRESET_EXCLUIR'))
  1720. .ok($scope.res('COMUM_OK')));
  1721. });
  1722. });
  1723. e.stopPropagation();
  1724. }
  1725. /**
  1726. * @method togglePresetPadrao
  1727. * @param {*} preset
  1728. */
  1729. function _togglePresetPadrao(preset) {
  1730. preset.padrao = !preset.padrao;
  1731. Preset.salvar(preset).then(angular.noop, function () {
  1732. $mdDialog
  1733. .show($mdDialog.alert()
  1734. .title($scope.res('COMUM_ERRO'))
  1735. .content($scope.res('COMUM_MSG_ERRO_PRESET'))
  1736. .ok($scope.res('COMUM_OK')));
  1737. });
  1738. }
  1739. var alteracaoEmAndamento = false;
  1740. /**
  1741. * @method togglePresetPadrao
  1742. * @param {*} e
  1743. * @param {*} preset
  1744. */
  1745. function togglePresetPadrao(e, preset) {
  1746. var antigoPresetPadrao = _.find($scope.presets, 'padrao');
  1747. if (antigoPresetPadrao && antigoPresetPadrao != preset) {
  1748. alteracaoEmAndamento = true;
  1749. antigoPresetPadrao.padrao = false;
  1750. Preset.salvar(antigoPresetPadrao).then(function () {
  1751. _togglePresetPadrao(preset);
  1752. alteracaoEmAndamento = false;
  1753. }, function () {
  1754. $mdDialog
  1755. .show($mdDialog.alert()
  1756. .title($scope.res('COMUM_ERRO'))
  1757. .content($scope.res('COMUM_MSG_ERRO_PRESET'))
  1758. .ok($scope.res('COMUM_OK')));
  1759. })
  1760. } else if (alteracaoEmAndamento == false){
  1761. _togglePresetPadrao(preset);
  1762. }
  1763. e.stopPropagation();
  1764. }
  1765. /**
  1766. * @method meusPresets
  1767. */
  1768. function meusPresets() {
  1769. return _.reject($scope.presets, 'DepartamentoId');
  1770. }
  1771. /**
  1772. * @method presetAgencia
  1773. */
  1774. function presetAgencia() {
  1775. return _.find($scope.presets, 'DepartamentoId')
  1776. }
  1777. $scope.optionDropdownActive = false;
  1778. $scope.abrirScroller = function () {
  1779. var params = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=false,resizable=false,width=' + screen.width + ',height=100';
  1780. var windowRef = window.open('/#/scroller', 'Scroller', params);
  1781. windowRef.aberto = true;
  1782. windowRef.onclose = function () {
  1783. windowRef.aberto = false;
  1784. }
  1785. };
  1786. /**
  1787. * @method updateMessage
  1788. */
  1789. function updateMessage() {
  1790. var msg = getCookie();
  1791. document.cookie = "cookie-msg-s4c=; path=/";
  1792. if (msg && msg.indexOf(":") != -1) {
  1793. var comando = msg.split(":")[0];
  1794. var id = msg.split(":")[1];
  1795. if (comando === "voarParaIncidente") {
  1796. DetalhamentoService.pegarIncidente(id)
  1797. .then(function (incidente) {
  1798. incidente.geojson = JSON.parse(incidente.geojson);
  1799. incidente.geometry = incidente.geojson;
  1800. incidente.filtro = $scope.res('TITULO_DASHBOARD');
  1801. MainState.getDirective('filtro-msi').addIncidente(incidente);
  1802. });
  1803. }
  1804. }
  1805. $timeout(updateMessage, 500);
  1806. }
  1807. /**
  1808. * @method getCookie
  1809. */
  1810. function getCookie() {
  1811. var cname = "cookie-msg-s4c=";
  1812. var ca = document.cookie.split(';');
  1813. for (var i = 0; i < ca.length; i++) {
  1814. var c = ca[i];
  1815. while (c.charAt(0) == ' ') c = c.substring(1, c.length);
  1816. if (c.indexOf(cname) == 0) {
  1817. return c.substring(cname.length, c.length);
  1818. }
  1819. }
  1820. return null;
  1821. }
  1822. FileReaderService.readTextFile("/s4c_dir/dashboard.json", function (text) {
  1823. var data = JSON.parse(text);
  1824. $scope.url = data.url_dashboard;
  1825. });
  1826. /**
  1827. * @method abrirDashboard
  1828. */
  1829. $scope.abrirDashboard = function () {
  1830. var params = 'toolbar=no,location=no,status=no,menubar=no,scrollbars=false,resizable=false,width=1200,height=800';
  1831. var win = window.open('', 'TPID', params);
  1832. win.document.body.innerHTML = '<body style="margin:0px;padding:0px;overflow:hidden"><iframe src="' + $scope.url + '" sandbox="allow-same-origin allow-scripts allow-forms allow-modals"' +
  1833. 'scroll="no" frameborder="0" style="overflow:hidden;height:98%;width:100%"></iframe></body>';
  1834. $timeout(updateMessage(), 500);
  1835. };
  1836. /**
  1837. * @method abrirPop
  1838. */
  1839. $scope.abrirPop = function () {
  1840. $mdDialog.show({
  1841. controller: popConsultaCtrl,
  1842. templateUrl: 'app/components/pop/popConsulta.html',
  1843. parent: document.body,
  1844. locals: {
  1845. res: $scope.res
  1846. }
  1847. });
  1848. }
  1849. /**
  1850. * @method popConsultaCtrl
  1851. * @param {*} $scope
  1852. * @param {*} Base
  1853. */
  1854. function popConsultaCtrl($scope, Base) {
  1855. $scope.res = $scope.$root.res;
  1856. $scope.tipoIncidenteSelecionado = null;
  1857. $scope.popPerfis = {};
  1858. Base.obter('tipo_incidentes/getByTipoIncidenteAndPerfilInPop').then(function (resultado_tipo) {
  1859. ordenaArray(resultado_tipo);
  1860. $scope.tipos = resultado_tipo;
  1861. angular.forEach($scope.tipos, function (tipo) {
  1862. tipo.ativo = false;
  1863. });
  1864. $scope.tiposPesquisa = resultado_tipo;
  1865. });
  1866. /**
  1867. * @method ordenaArray
  1868. * @param {*} array
  1869. */
  1870. function ordenaArray(array) {
  1871. array = array.sort(function (a, b) {
  1872. return a.nome > b.nome ? 1 : a.nome < b.nome ? -1 : 0
  1873. });
  1874. }
  1875. /**
  1876. * @method selecionaTipoIncidente
  1877. * @param {*} tipoIncidente
  1878. */
  1879. function selecionaTipoIncidente(tipoIncidente) {
  1880. if (tipoIncidente.ativo) {
  1881. return;
  1882. }
  1883. /**
  1884. * @method .map
  1885. * @param tipoIncidente
  1886. */
  1887. $scope.tipos = _.map($scope.tipos, function (tipoIncidente) {
  1888. tipoIncidente.ativo = false;
  1889. return tipoIncidente;
  1890. });
  1891. tipoIncidente.ativo = true;
  1892. $scope.tipoIncidenteSelecionado = tipoIncidente;
  1893. getPopPerfisByUserAndTipoIncidente($scope.tipoIncidenteSelecionado);
  1894. }
  1895. /**
  1896. * @method getPopPerfisByUserAndTipoIncidente
  1897. * @param {*} tipoIncidente
  1898. */
  1899. function getPopPerfisByUserAndTipoIncidente(tipoIncidente) {
  1900. Base.obter('pop_perfis/getPopPerfisByUserAndTipoIncidente/' + tipoIncidente.id).then(function (resultado) {
  1901. $scope.popPerfis = resultado;
  1902. $scope.showResults = true;
  1903. });
  1904. }
  1905. /**
  1906. * @method executeSearchTipoIncidente
  1907. * @param {*} textoTipoIncidente
  1908. */
  1909. function executeSearchTipoIncidente(textoTipoIncidente) {
  1910. $scope.tipos = [];
  1911. var texto = textoTipoIncidente.toLowerCase();
  1912. angular.forEach($scope.tiposPesquisa, function (tipoPesquisa) {
  1913. var nome = tipoPesquisa.nome.toLowerCase();
  1914. if (nome.indexOf(texto) !== -1) {
  1915. $scope.tipos.push(tipoPesquisa);
  1916. }
  1917. });
  1918. }
  1919. /**
  1920. * @method fechar
  1921. */
  1922. function fechar() {
  1923. $mdDialog.hide();
  1924. }
  1925. angular.extend($scope, {
  1926. selecionaTipoIncidente: selecionaTipoIncidente,
  1927. executeSearchTipoIncidente: executeSearchTipoIncidente,
  1928. fechar: fechar
  1929. });
  1930. }
  1931. $scope.showingElements = {
  1932. 'documento_button': false,
  1933. 'briefing_button': false,
  1934. 'share_button': false,
  1935. 'preset_button': false
  1936. };
  1937. /**
  1938. * @method toggleSelect
  1939. * @param elementId
  1940. * @param id
  1941. */
  1942. $scope.toggleSelect = function (elementId, id) {
  1943. if (elementId != 'documento_button') {
  1944. $scope.showingElements['documento_button'] = false;
  1945. }
  1946. if (elementId == 'documento_button') {
  1947. if (!id) {
  1948. $('.menu-adicionar').toggleClass(' open ');
  1949. } else {
  1950. if (id !== 'dropdown-demo-menu') {
  1951. $('.menu-adicionar').removeClass(' open ');
  1952. $('#' + id).toggleClass(' open ');
  1953. } else {
  1954. if ($('#' + id).hasClass('open')) {
  1955. $('#' + id).removeClass(' open ');
  1956. } else {
  1957. $('#' + id).addClass(' open ');
  1958. }
  1959. }
  1960. }
  1961. }
  1962. if (elementId != 'briefing_button') {
  1963. $scope.showingElements['briefing_button'] = false;
  1964. }
  1965. if (elementId != 'share_button') {
  1966. $scope.showingElements['share_button'] = false;
  1967. }
  1968. if (elementId != 'preset_button') {
  1969. $scope.showingElements['preset_button'] = false;
  1970. }
  1971. $scope.showingElements[elementId] = !$scope.showingElements[elementId];
  1972. if ($scope.showingElements[elementId]) {
  1973. $window.onclick = function (event) {
  1974. event.stopPropagation();
  1975. var clickedElement = event.target;
  1976. if (!clickedElement) {
  1977. return;
  1978. }
  1979. };
  1980. } else {
  1981. $window.onclick = null;
  1982. }
  1983. }
  1984. /**
  1985. * @method showAlarmes
  1986. */
  1987. function showAlarmes() {
  1988. ZonasDeObservacaoFilter.getInstance('zonas-de-observacao-filter').trigger('alarmesConfigurados');
  1989. TarefaManager.closePush();
  1990. }
  1991. AuthService.user.info.showFilters = false;
  1992. AuthService.user.info.filterNames = "";
  1993. AuthService.user.info.areaInterna = true;
  1994. /**
  1995. * @method openAreaDialog
  1996. */
  1997. function openAreaDialog() {
  1998. $mdDialog.show({
  1999. templateUrl: 'app/directives/area-atuacao/trocar_area_atuacao.html',
  2000. controller: function ($scope, Modulo, AuthService) {
  2001. $scope.areaInterna = AuthService.user.info.areaInterna;
  2002. document.body.style.overflow = 'hidden';
  2003. $scope.res = $scope.$root.res;
  2004. if (AuthService.user.info.permissoesAreaAtuacao) {
  2005. $scope.permissoesArea = AuthService.user.info.permissoesAreaAtuacao;
  2006. } else {
  2007. $scope.permissoesArea = permissoesAreaAtuacao;
  2008. AuthService.user.info.permissoesAreaAtuacao = permissoesAreaAtuacao;
  2009. }
  2010. $scope.permissoesArea = $scope.permissoesArea.sort(function (perm1, perm2) {
  2011. return perm1.nomeArea > perm2.nomeArea ? 1 : perm1.nomeArea < perm2.nomeArea ? -1 : 0
  2012. });
  2013. /**
  2014. * @method each
  2015. * @param permissao
  2016. */
  2017. _.each($scope.permissoesArea, function (permissao) {
  2018. if (!permissao.regiaoArray) {
  2019. return;
  2020. }
  2021. permissao.regiaoArray = permissao.regiaoArray.sort(function (regiao1, regiao2) {
  2022. return regiao1.nomeRegiao > regiao2.nomeRegiao ? 1 : regiao1.nomeRegiao < regiao2.nomeRegiao ? -1 : 0
  2023. });
  2024. });
  2025. $scope.ok = function () {
  2026. var filtro = { regioes: $scope.permissoesArea, areaInterna: $scope.areaInterna };
  2027. //Altera o filtro deste usuário no servidor
  2028. Base.salvar('area_atuacao/filtrar', filtro).then(function () {
  2029. reloadFrontendInfo();
  2030. });
  2031. AuthService.user.info.filterNames = "";
  2032. for (var index in $scope.permissoesArea) {
  2033. for (var index2 in $scope.permissoesArea[index].regiaoArray) {
  2034. if ($scope.permissoesArea[index].regiaoArray[index2].check) {
  2035. AuthService.user.info.showFilters = true;
  2036. AuthService.user.info.filterNames += $scope.permissoesArea[index].regiaoArray[index2].nomeRegiao + ' - ';
  2037. }
  2038. }
  2039. }
  2040. AuthService.user.info.filterNames = AuthService.user.info.filterNames.substring(0, AuthService.user.info.filterNames.length - 3);
  2041. if (AuthService.user.info.filterNames.length > 80) {
  2042. AuthService.user.info.filterNames = AuthService.user.info.filterNames.substring(0, 80);
  2043. AuthService.user.info.filterNames += ' ...';
  2044. }
  2045. AuthService.user.info.areaInterna = $scope.areaInterna;
  2046. $mdDialog.hide();
  2047. document.body.style.overflow = 'auto';
  2048. };
  2049. /**
  2050. * @method cancelar
  2051. */
  2052. $scope.cancelar = function () {
  2053. $mdDialog.cancel();
  2054. document.body.style.overflow = 'auto';
  2055. }
  2056. /**
  2057. * @method selectAllChild
  2058. * @param permissao
  2059. */
  2060. $scope.selectAllChild = function (permissao) {
  2061. _.each(permissao.regiaoArray, function (regiao) {
  2062. if (!permissao.check) {
  2063. regiao.check = true;
  2064. } else {
  2065. regiao.check = false;
  2066. }
  2067. });
  2068. }
  2069. /**
  2070. * @method unselectParent
  2071. * @param regiao
  2072. * @param permissao
  2073. */
  2074. $scope.unselectParent = function (regiao, permissao) {
  2075. if (regiao.check) {
  2076. permissao.check = false;
  2077. }
  2078. }
  2079. }
  2080. }).then(function () {
  2081. });
  2082. }
  2083. /**
  2084. * @method removeFilters
  2085. */
  2086. function removeFilters() {
  2087. for (var index in AuthService.user.info.permissoesAreaAtuacao) {
  2088. for (var index2 in AuthService.user.info.permissoesAreaAtuacao[index].regiaoArray) {
  2089. AuthService.user.info.permissoesAreaAtuacao[index].check = false;
  2090. AuthService.user.info.permissoesAreaAtuacao[index].regiaoArray[index2].check = false;
  2091. }
  2092. }
  2093. var filtro = { regioes: AuthService.user.info.permissoesAreaAtuacao, areaInterna: false };
  2094. //Altera o filtro deste usuário no servidor
  2095. Base.salvar('area_atuacao/filtrar', filtro).then(function () {
  2096. reloadFrontendInfo();
  2097. AuthService.user.info.showFilters = false;
  2098. });
  2099. }
  2100. /**
  2101. * @method reloadFrontendInfo
  2102. */
  2103. function reloadFrontendInfo() {
  2104. Modulo.reInitModules();
  2105. CamadasService.reloadNodes();
  2106. RotasUnificadasManager.reloadRotas();
  2107. if (MainState.getDirective('filtro-msi') && !MainState.getDirective('filtro-msi').msiFechado()) {
  2108. MsiFilter.getInstance('filtro-msi').trigger('filterChanged', 'origem');
  2109. }
  2110. if (MainState.getDirective('moduloPoi')) {
  2111. MainState.getDirective('moduloPoi').reloadPois();
  2112. }
  2113. }
  2114. //Atualizar o relógio
  2115. $interval(function () {
  2116. $scope.horario = moment().format('HH:mm');
  2117. }, 60000);
  2118. function showAdminDiv() {
  2119. closeModals();
  2120. VideoStreamService.closeAll();
  2121. DetalhamentoManager.fecharTodos();
  2122. $state.go('admin.main');
  2123. Preset.rollBackEmptyModules();
  2124. releaseResources();
  2125. }
  2126. /**
  2127. * @method hasPermission
  2128. */
  2129. $scope.hasPermission = function () {
  2130. if (!AuthService.user.info) {
  2131. return;
  2132. }
  2133. return AuthService.user.info.superuser || _isLdapAdmin(AuthService.user.info.ldapPerfis);
  2134. }
  2135. /**
  2136. * @method _isLdapAdmin
  2137. * @param {*} ldapPerfis
  2138. */
  2139. function _isLdapAdmin(ldapPerfis) {
  2140. var isAdmin = false;
  2141. if (ldapPerfis != null && ldapPerfis.length > 0) {
  2142. var i = 0;
  2143. for (; i < ldapPerfis.length; i++) {
  2144. if (ldapPerfis[i].contains("ADMIN")) {
  2145. isAdmin = true;
  2146. }
  2147. }
  2148. }
  2149. return isAdmin;
  2150. }
  2151. /**
  2152. * @method franquias
  2153. */
  2154. $scope.franquias = function () {
  2155. getCookie();
  2156. FileReaderService.readTextFile("/s4c_dir/url_s4s.json", function (text) {
  2157. var data = JSON.parse(text);
  2158. $window.location.href = data.url_s4s;
  2159. });
  2160. }
  2161. $scope.isElectron = navigator.userAgent.indexOf("Electron") != -1
  2162. /**
  2163. * @method reboot
  2164. */
  2165. $scope.reboot = function () {
  2166. MainState.reboot(true, logout);
  2167. }
  2168. /**
  2169. * @method updateCockpit
  2170. */
  2171. $scope.updateCockpit = function () {
  2172. MainState.reboot();
  2173. }
  2174. /**
  2175. * @method shutdown
  2176. */
  2177. $scope.shutdown = function () {
  2178. MainState.shutdown(true, logout);
  2179. }
  2180. /**
  2181. * @method multivisManager
  2182. */
  2183. $scope.multivisManager = function () {
  2184. getCookie();
  2185. FileReaderService.readTextFile("/s4c_dir/url_s4s.json", function (text) {
  2186. var data = JSON.parse(text);
  2187. $window.location.href = data.url_multivismanager;
  2188. });
  2189. }
  2190. /**
  2191. * @method getCookie
  2192. */
  2193. function getCookie() {
  2194. try {
  2195. var tokenObj = JSON.parse($window.sessionStorage.getItem('s4cToken'));
  2196. document.cookie = "token=" + tokenObj.access_token;
  2197. } catch (erro) {
  2198. document.cookie = "token=" + $window.sessionStorage.getItem('s4cToken');
  2199. }
  2200. }
  2201. angular.extend($scope, {
  2202. $directives: {},
  2203. presetConfig: Preset.config,
  2204. buscaAtiva: false,
  2205. seletorAtivo: false,
  2206. buscaResults: [],
  2207. textoBusca: '',
  2208. criandoPreset: false,
  2209. detalhamentoAtivo: false,
  2210. usuario: UserInfo,
  2211. presets: UserPresets,
  2212. AuthService: AuthService,
  2213. showAdminDiv: showAdminDiv,
  2214. modais: {
  2215. baseConhecimento: false,
  2216. detalhamento: false,
  2217. editorRotas: false,
  2218. scroller: false,
  2219. planejamento: false,
  2220. tarefa: false,
  2221. twitter: false
  2222. },
  2223. menu: {
  2224. isOpen: false
  2225. },
  2226. //Managers:
  2227. MsiDetalhamentoManager: MsiService,
  2228. // Métodos:
  2229. renomearPreset: renomearPreset,
  2230. novoPreset: novoPreset,
  2231. alterarPreset: alterarPreset,
  2232. logout: logout,
  2233. excluirPreset: excluirPreset,
  2234. togglePresetPadrao: togglePresetPadrao,
  2235. meusPresets: meusPresets,
  2236. presetAgencia: presetAgencia,
  2237. showAlarmes: showAlarmes,
  2238. novoUsuario: novoUsuario,
  2239. saveMapPosition: saveMapPosition,
  2240. openAreaDialog: openAreaDialog,
  2241. removeFilters: removeFilters,
  2242. noError: $scope.noError,
  2243. errorMessage: $scope.errorMessage,
  2244. version: $scope.version
  2245. });
  2246. // Registrando managers no scope
  2247. $scope.DetalhamentoManager = DetalhamentoManager;
  2248. $scope.ModuloTwitterManager = ModuloTwitterManager;
  2249. $scope.CamerasManager = CamerasManager;
  2250. $scope.BuscaManager = BuscaManager;
  2251. $scope.MensageriaManager = MensageriaManager;
  2252. $scope.AvisoOperacionalManager = AvisoOperacionalManager;
  2253. $scope.RotasManager = RotasManager;
  2254. $scope.RotasUnificadasManager = RotasUnificadasManager;
  2255. $scope.BriefingOperacionalManager = BriefingOperacionalManager;
  2256. $scope.MapaManager = MapaManager;
  2257. $scope.IncidentesManager = IncidentesManager;
  2258. $scope.BaseConhecimentoManager = BaseConhecimentoManager;
  2259. $scope.TwitterManager = TwitterManager;
  2260. $scope.MSIManager = MSIManager;
  2261. $scope.SubDetalhamentoManager = SubDetalhamentoManager;
  2262. $scope.ZonaDeObservacaoManager = ZonaDeObservacaoManager;
  2263. $scope.PlanejamentoManager = PlanejamentoManager;
  2264. $scope.DeteccaoImpactoManager = DeteccaoImpactoManager;
  2265. $scope.MinhasTarefasManager = MinhasTarefasManager;
  2266. $scope.VoipManager = VoipManager;
  2267. $scope.TarefaManager = TarefaManager;
  2268. $scope.FacebookManager = FacebookManager;
  2269. $scope.EmailManager = EmailManager;
  2270. $scope.IncidenteEnterManager = IncidenteEnterManager;
  2271. $scope.AlarmeDisparadoManager = AlarmeDisparadoManager;
  2272. $scope.EditPTarefaManager = EditPTarefaManager;
  2273. $scope.TerminalManager = TerminalManager;
  2274. $scope.BuscaUsuariosTelegramManager = BuscaUsuariosTelegramManager;
  2275. $scope.DetalhamentoRotasOlimpicasManager = DetalhamentoRotasOlimpicasManager;
  2276. $scope.HabilitarCamadasManager = HabilitarCamadasManager;
  2277. $scope.AreaAtuacaoManager = AreaAtuacaoManager;
  2278. $scope.RastreamentoManager = RastreamentoManager;
  2279. $scope.PontoMovelManager = PontoMovelManager;
  2280. $scope.PoiManager = PoiManager;
  2281. /*
  2282. * Registrando managers no Service
  2283. */
  2284. var managersList = [
  2285. 'MainManager',
  2286. 'ModuloTwitterManager',
  2287. 'CamerasManager',
  2288. 'BuscaManager',
  2289. 'MensageriaManager',
  2290. 'TelegramManager',
  2291. 'RotasManager',
  2292. 'RotasUnificadasManager',
  2293. 'IncidentesManager',
  2294. 'BaseConhecimentoManager',
  2295. 'FacebookManager',
  2296. 'EmailManager',
  2297. 'TwitterManager',
  2298. 'MSIManager',
  2299. 'SubDetalhamentoManager',
  2300. 'DetalhamentoManager',
  2301. 'ZonaDeObservacaoManager',
  2302. 'PlanejamentoManager',
  2303. 'DeteccaoImpactoManager',
  2304. 'MinhasTarefasManager',
  2305. 'TarefaManager',
  2306. 'BriefingOperacionalManager',
  2307. 'MapaManager',
  2308. 'BotoesManager',
  2309. 'IncidenteEnterManager',
  2310. 'AlarmeDisparadoManager',
  2311. 'EditPTarefaManager',
  2312. 'TerminalManager',
  2313. 'BuscaUsuariosTelegramManager',
  2314. 'DetalhamentoRotasOlimpicasManager',
  2315. 'HabilitarCamadasManager',
  2316. 'AreaAtuacaoManager',
  2317. 'RastreamentoManager',
  2318. 'PontoMovelManager',
  2319. 'PoiManager',
  2320. 'VoipManager'
  2321. ];
  2322. var managers = [];
  2323. /**
  2324. * @method forEach
  2325. * @param manager
  2326. */
  2327. managersList.forEach(function (manager) {
  2328. if ($scope.hasOwnProperty(manager)) {
  2329. MainState.registerManager(manager, $scope[manager]);
  2330. managers.push($scope[manager]);
  2331. }
  2332. });
  2333. DetalhamentoManager.setManagers(managers);
  2334. MainState.registerManager('UserInfo', UserInfo);
  2335. /*
  2336. * Removendo managers do Service:
  2337. */
  2338. $scope.$on('$destroy', function () {
  2339. managersList.forEach(function (manager) {
  2340. MainState.unregisterManager(manager);
  2341. });
  2342. });
  2343. }
  2344. }());