Source: components/admin/controllers/auditorias.controller.js

/**
 * @ngdoc controller
 * @name AdminAuditoriaCtrl
 * @module s4c.components.admin.controllers.AdminAuditoriaCtrl
 *
 * @description
 * `AdminAuditoriaCtrl` Controller da tela de Auditoria do módulo de administração
 * 
 * 
 */
(function () {
    'use strict';

    AdminAuditoriaCtrl.$inject = [
        '$scope',
        '$http',
        '$mdDialog',
        'API_ENDPOINT',
        'ngFileReader',
        '$rootScope',
        'Usuario'
    ];

    angular.module('s4c.controllers.AdminAuditoriaCtrl', [
        's4c.services.Categoria',
        's4c.directives.ngFileReader'
    ]).controller('AdminAuditoriaCtrl', AdminAuditoriaCtrl);

    function AdminAuditoriaCtrl($scope, $http, $mdDialog, API_ENDPOINT, ngFileReader, $rootScope, Usuario) {

        $scope.res = $rootScope.res;

        var basicColumns = [{
            headerName: $scope.res('AUDITORIA_DATA'),
            //width: 150,
            field: "dtEntry",
            editable: false,
            volatile: true,
            colId: "dataFieldId"
        }, {
            headerName: $scope.res('AUDITORIA_ACAO'),
            // width: 200,
            editable: false,
            cellRenderer: controlAcao,
            suppressMenu: true,
            suppressSorting: true
        }, {
            headerName: $scope.res('AUDITORIA_TIPO_OBJETO'),
            // width: 400,
            editable: false,
            cellRenderer: controlTipoObjeto,
            suppressMenu: true,
            suppressSorting: true
        }, {
            headerName: $scope.res('LOGIN_USUARIO'),
            //width: 250,
            field: "usuario",
            editable: false,
            volatile: true
        }, {
            headerName: $scope.res('MSI_DETALHES'),
            //  width: 150,
            editable: false,
            cellTemplate: controlDetalhes,
            suppressMenu: true,
            suppressSorting: true
        }
        ];


        /**
         * @method controlDetalhes
         * @param {*} row 
         */
        function controlDetalhes(row) {
            var html;
            if (row.entity.mensagem && row.entity.mensagem.indexOf(' [') > 0) {
                html = '<div style="text-align: center;">' +
                    '<a href="javascript:;" ng-click="exibirDetalhes(' + "'" + row.entity.id + "'" + ');"><img src="/assets/icons/search-icon-24px.png"></img></a></div>';
            }
            else {
                html = '<div style="text-align: center;"></div>';
            }

            return html;
        }

        /**
         * @method controlTipoObjeto
         * 
         * @param {*} params 
         */
        function controlTipoObjeto(params) {
            return '<div style="text-align: left;"><a>' + $scope.res(params.data.tipoObjeto) + '</a></div>';
        }

        /**
         * @method controlAcao
         * 
         * @param {*} params 
         */
        function controlAcao(params) {
            return '<div style="text-align: left;"><a>' + $scope.res('AUDITORIA_' + params.data.acao) + '</a></div>';
        }

        $scope.gridOptions = {
            rowSelection: 'multiple',
            enableSorting: true,
            columnDefs: [{
                name: $scope.res('AUDITORIA_DATA'),
                //width: 150,
                field: "dtEntry",
                editable: false,
                volatile: true,
                colId: "dataFieldId"
            }, {
                name: $scope.res('AUDITORIA_ACAO'),
                // width: 200,
                field: "acao",
                editable: false,
                cellRenderer: controlAcao,
                suppressMenu: true,
                suppressSorting: true
            }, {
                name: $scope.res('AUDITORIA_TIPO_OBJETO'),
                // width: 400,
                field: "tipoObjeto",
                editable: false,
                cellRenderer: controlTipoObjeto,
                suppressMenu: true,
                suppressSorting: true
            }, {
                name: $scope.res('LOGIN_USUARIO'),
                //width: 250,
                field: "usuario",
                editable: false,
                volatile: true
            }, {
                name: $scope.res('MSI_DETALHES'),
                //  width: 150,
                editable: false,
                field: "detalhes",
                cellTemplate: '<div style="text-align: center;"><a href="javascript:;" ng-show="grid.appScope.exibirCampoDetalhes(row)" ng-click="grid.appScope.exibirDetalhes(row);"><img src="/assets/icons/search-icon-24px.png"></img></a></div>',
                suppressMenu: true,
                suppressSorting: true
            }
            ],
            angularCompileHeaders: true,
            angularCompileRows: true,
            //headerCellRenderer: headerCellRendererFunction,
            pinnedColumnCount: 0,
            enableColResize: true,
            rowGroupPanelShow: 'always',
            pivotPanelShow: 'always',
            paginationPageSizes: [5, 10, 25],
            pagination: true,
            paginationPageSize: 30,
            enableRangeSelection: true,
            enableFilter: true,
            suppressHorizontalScroll: true,
            groupSelectsChildren: true,
            localeText: {
                // for filter panel
                page: $scope.res('COMUM_PAGINA'),
                more: $scope.res('AUDITORIA_PAGINA_MAIS'),
                to: $scope.res('AUDITORIA_PARA'),
                of: $scope.res('AUDITORIA_DE'),
                next: $scope.res('COMUM_PROXIMO'),
                last: $scope.res('AUDITORIA_ULTIMO'),
                first: $scope.res('AUDITORIA_PRIMEIRO'),
                previous: $scope.res('COMUM_ANTERIOR'),
                loadingOoo: $scope.res('AUDITORIA_CARREGANDO')
            }
        };


        $scope.gridOptions.onRegisterApi = function (gridApi) {
            $scope.gridApi = gridApi;
        };


        /**
         * @method headerCellRendererFunction
         * @param {*} params 
         */
        function headerCellRendererFunction(params) {
            var eHeader = document.createElement('span');
            var eTitle = document.createTextNode(params.colDef.headerName);

            eHeader.appendChild(eTitle);

            if (params.colDef.headerName == '') {
                eHeader.style.textAlign = 'center';
                eHeader.style.verticalAlign = 'center';
            } else {

                var eEdit = document.createElement('md-icon');

                eEdit.setAttribute('class', 'menu-icon');
                eEdit.setAttribute('style', 'float: right');
                eEdit.setAttribute('md-svg-icon', 'menu:edit');
                eEdit.setAttribute('alt', 'editar');
                eEdit.setAttribute('ng-click', 'definirValorDaColuna($event, this,"' + params.colDef.field + '")');

                eHeader.appendChild(eEdit);
            }


            return eHeader.outerHTML;
        }

        /**
         * @method definirValorDaColuna
         * 
         * @param {*} event 
         * @param {*} domNode 
         * @param {*} field 
         */
        function definirValorDaColuna(event, domNode, field) {
            event.stopPropagation();
            $mdDialog.show({
                controller: function ($scope, res) {
                    $scope.res = res;
                    $scope.ok = function () {
                        $mdDialog.hide($scope.coluna.valor);
                    };

                    $scope.cancelar = $mdDialog.cancel;
                },
                templateUrl: 'app/components/admin/modulos/manutencao/pois/definirValorDaColuna.html',
                locals: {
                    res: $scope.res
                },
                parent: domNode
            }).then(function (valor) {
                _.each($scope.gridOptions.rowData, function (row) {
                    row[field] = valor;
                });
                $scope.gridOptions.api.refreshView();
            });
        }

        /**
         * @method carregarTiposObjeto
         */
        function carregarTiposObjeto() {
            $http.get(API_ENDPOINT + "audit_entry/tipos_objeto")
                .then(function (result) {
                    $scope.tiposObjeto = result.data;
                }, function (err) {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_ERRO'))
                            .content(err.data.message)
                            .ok($scope.res('COMUM_OK')));
                });
        }

        /**
         * @method carregarUsuarios
         */
        function carregarUsuarios() {
            Usuario.obterShortUsers()
                .then(function (result) {
                    $scope.usuarios = result;
                }, function (err) {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_ERRO'))
                            .content(err.data.message)
                            .ok($scope.res('COMUM_OK')));
                });
        }

        /**
         * @method pesquisar
         */
        function pesquisar() {
            var filter = {};
            filter.usuario = $scope.usuarioFiltro;
            filter.acao = $scope.acao;
            filter.tipoObjeto = $scope.tipoObjeto;
            filter.dtInicioStr = $scope.dtInicio;
            filter.dtFimStr = $scope.dtFim;

            if ($scope.gridOptions != null && $scope.gridOptions.api != null && $scope.gridOptions.api.getSortModel() != null) {
                filter.order = $scope.gridOptions.api.getSortModel()[0].sort;
            }

            $http.post(API_ENDPOINT + "audit_entry/pesquisar", filter)
                .then(function (result) {
                    if (result.data.length == 1000) {
                        $("#limite_pesquisa").show();
                    } else {
                        $("#limite_pesquisa").hide();
                    }

                    $scope.gridOptions.data = result.data;


                }, function (err) {
                    $mdDialog
                        .show($mdDialog.alert()
                            .title($scope.res('COMUM_ERRO'))
                            .content(err.data.message)
                            .ok($scope.res('COMUM_OK')));
                });
        }

        var objetoColumns = [{
            name: $scope.res('COMUM_ATRIBUTO'),
            //width: 150,
            field: "key",
            editable: false,
            volatile: true
        }, {
            name: $scope.res('COMUM_VALOR'),
            //width: 250,
            field: "value",
            editable: false,
            volatile: true
        }
        ];

        $scope.gridObjetoOptions = {
            rowSelection: 'multiple',
            rowData: [],
            enableSorting: true,
            columnDefs: objetoColumns,
            angularCompileHeaders: true,
            angularCompileRows: true,
            pinnedColumnCount: 0,
            enableColResize: true,
            suppressHorizontalScroll: true
        };

        /**
         * @method controlValorAtributo
         * 
         * @param {*} params 
         */
        function controlValorAtributo(params) {
            return '<div style="text-align: left;" title=' + "'" + params.data.value + "'" + '><a>' + params.data.value + '</a></div>';
        }


        /**
         * @method exibirCampoDetalhes
         * @param {*} row
         */
        $scope.exibirCampoDetalhes = function (row) {
            if (row.entity.mensagem && row.entity.mensagem.indexOf(' [') > 0) {
                return true;
            } else {
                return false;
            }
        }

        /**
         * @method exibirDetalhes
         * @param {*} row
         */        
        $scope.exibirDetalhes = function (row) {
            var listObjetos = mapAtributos(row.entity.mensagem);

            if (listObjetos.length > 0) {
                //$scope.gridObjetoOptions.rowData = listObjetos;
                $scope.gridObjetoOptions.data = listObjetos;
            }
            else {
                $mdDialog
                    .show($mdDialog.alert()
                        .title($scope.res(audit.tipoObjeto))
                        .content($scope.res('AUDITORIA_FORMATO_TIPO_OBJETO'))
                        .ok($scope.res('COMUM_OK')));
                return;
            }

            $mdDialog.show({
                scope: $scope.$new(),
                template: '<md-dialog draggable>' +
                    '<md-title style="padding: 20px 0px 0px 20px;">' + $scope.res(row.entity.tipoObjeto) + '</md-title>' +
                    '<br>' +
                    '<div style="color: black;" flex md-theme="s4c-light">' +

                    ' <div ui-grid="gridObjetoOptions" class="grid">' +
                    ' </div>' +
                    '  <div class="md-actions">' +
                    '    <md-button ng-click="fechar()">' + $scope.res('COMUM_OK') + '</md-button>' +
                    '  </div>' +

                    '  </div>' +
                    '</md-dialog>',
                controller: function ($scope, $mdDialog) {
                    $scope.fechar = function () {
                        $mdDialog.hide();
                    }
                }
            });
        }

        /**
         * 
         * @method mapAtributos
         * 
         * @param {*} mensagem
         */
        function mapAtributos(mensagem) {
            var listObjetos = [];
            var listAtributosObjeto = [];
            var indexMarkerInit = mensagem.indexOf(' [');
            var indexMarkerEnd;

            if (indexMarkerInit >= 0) {
                //var nameObjectAttribute = mensagem.substring(0, indexMarkerInit);
                var i = -1;
                while (i++ < mensagem.length) {
                    i = mensagem.indexOf(']', i);
                    if (i < 0) {
                        break;
                    }
                    else {
                        indexMarkerEnd = i;
                    }
                }

                var content = mensagem.substring(indexMarkerInit + 2, indexMarkerEnd);
                listAtributosObjeto = mapAtributos(content);

                var atributos = content.split(', ');
                //var keys = Object.keys(objetoPersistido);
                _.each(atributos, function (atributo) {
                    var map = atributo.split('=', 2);
                    if (!verificaSeAtributoExiste(listAtributosObjeto, map)) {
                        if (map[1] != null && map[1] != "null" && isPrimitive(map[1])) {
                            listObjetos.push({ "key": map[0], "value": map[1] });
                        } else if (map[1] == null) {
                            listObjetos.push({ "key": map[0], "value": "" });
                        }

                    }
                });
            }

            return listObjetos;
        }

        /**
         * @method isPrimitive
         * 
         * @param {*} test 
         */
        function isPrimitive(test) {
            return (test !== Object(test));
        };

        /**
         * 
         * @method verificaSeAtributoExiste
         * 
         * @param {*} listAtributosObjeto 
         * @param {*} map 
         */
        function verificaSeAtributoExiste(listAtributosObjeto, map) {
            var flag = false;

            _.each(listAtributosObjeto, function (atributo) {
                if (atributo.key == map[0] && atributo.value == map[1]) {
                    flag = true;
                }
            });

            return flag;
        }

        $(function () {
            carregarTiposObjeto();
            carregarUsuarios();
            pesquisar();

        });

        angular.extend($scope, {
            definirValorDaColuna: definirValorDaColuna,
            pesquisar: pesquisar
        });

    }

}());