From c9d5440d4410e56cf74af9a8106e348ad9326da6 Mon Sep 17 00:00:00 2001 From: WILLIAM Date: Tue, 23 Jul 2019 16:49:52 -0300 Subject: [PATCH] =?UTF-8?q?Desafio=20edi=C3=A7=C3=B5es=20e=20exclus=C3=B5e?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../brewer/pom.xml | 304 + .../algaworks/brewer/config/JPAConfig.java | 63 + .../algaworks/brewer/config/MailConfig.java | 45 + .../brewer/config/SecurityConfig.java | 66 + .../brewer/config/ServiceConfig.java | 20 + .../algaworks/brewer/config/WebConfig.java | 154 + .../brewer/config/init/AppInitializer.java | 44 + .../config/init/SecurityInitializer.java | 26 + .../brewer/controller/CervejasController.java | 105 + .../brewer/controller/CidadesController.java | 114 + .../brewer/controller/ClientesController.java | 120 + .../brewer/controller/ErrosController.java | 20 + .../brewer/controller/EstilosController.java | 102 + .../brewer/controller/FotosController.java | 44 + .../controller/SegurancaController.java | 25 + .../brewer/controller/UsuariosController.java | 110 + .../brewer/controller/VendasController.java | 207 + .../controller/converter/CidadeConverter.java | 21 + .../controller/converter/EstadoConverter.java | 21 + .../controller/converter/EstiloConverter.java | 21 + .../controller/converter/GrupoConverter.java | 21 + .../ControllerAdviceExceptionHandler.java | 17 + .../brewer/controller/page/PageWrapper.java | 87 + .../controller/validator/VendaValidator.java | 48 + .../com/algaworks/brewer/dto/CervejaDTO.java | 75 + .../com/algaworks/brewer/dto/FotoDTO.java | 29 + .../com/algaworks/brewer/mail/Mailer.java | 93 + .../com/algaworks/brewer/model/Cerveja.java | 246 + .../com/algaworks/brewer/model/Cidade.java | 95 + .../com/algaworks/brewer/model/Cliente.java | 163 + .../com/algaworks/brewer/model/Endereco.java | 86 + .../com/algaworks/brewer/model/Estado.java | 72 + .../com/algaworks/brewer/model/Estilo.java | 78 + .../com/algaworks/brewer/model/Grupo.java | 80 + .../com/algaworks/brewer/model/ItemVenda.java | 104 + .../com/algaworks/brewer/model/Origem.java | 18 + .../com/algaworks/brewer/model/Permissao.java | 64 + .../com/algaworks/brewer/model/Sabor.java | 21 + .../algaworks/brewer/model/StatusVenda.java | 19 + .../algaworks/brewer/model/TipoPessoa.java | 56 + .../com/algaworks/brewer/model/Usuario.java | 160 + .../algaworks/brewer/model/UsuarioGrupo.java | 47 + .../brewer/model/UsuarioGrupoId.java | 69 + .../com/algaworks/brewer/model/Venda.java | 254 + .../ClienteGroupSequenceProvider.java | 28 + .../model/validation/group/CnpjGroup.java | 5 + .../model/validation/group/CpfGroup.java | 5 + .../algaworks/brewer/repository/Cervejas.java | 12 + .../algaworks/brewer/repository/Cidades.java | 22 + .../algaworks/brewer/repository/Clientes.java | 17 + .../algaworks/brewer/repository/Estados.java | 9 + .../algaworks/brewer/repository/Estilos.java | 16 + .../algaworks/brewer/repository/Grupos.java | 9 + .../algaworks/brewer/repository/Usuarios.java | 17 + .../algaworks/brewer/repository/Vendas.java | 10 + .../repository/filter/CervejaFilter.java | 75 + .../repository/filter/CidadeFilter.java | 26 + .../repository/filter/ClienteFilter.java | 30 + .../repository/filter/EstiloFilter.java | 15 + .../repository/filter/UsuarioFilter.java | 37 + .../brewer/repository/filter/VendaFilter.java | 85 + .../helper/cerveja/CervejasImpl.java | 98 + .../helper/cerveja/CervejasQueries.java | 18 + .../repository/helper/cidade/CidadesImpl.java | 62 + .../helper/cidade/CidadesQueries.java | 13 + .../helper/cliente/ClientesImpl.java | 64 + .../helper/cliente/ClientesQueries.java | 13 + .../repository/helper/estilo/EstilosImpl.java | 57 + .../helper/estilo/EstilosQueries.java | 13 + .../helper/usuario/UsuariosImpl.java | 113 + .../helper/usuario/UsuariosQueries.java | 22 + .../repository/helper/venda/VendasImpl.java | 103 + .../helper/venda/VendasQueries.java | 15 + .../repository/paginacao/PaginacaoUtil.java | 28 + .../security/AppUserDetailsService.java | 42 + .../brewer/security/UsuarioSistema.java | 25 + .../service/CadastroCervejaService.java | 47 + .../brewer/service/CadastroCidadeService.java | 41 + .../service/CadastroClienteService.java | 61 + .../brewer/service/CadastroEstiloService.java | 42 + .../service/CadastroUsuarioService.java | 67 + .../brewer/service/CadastroVendaService.java | 57 + .../brewer/service/StatusUsuario.java | 23 + .../event/cerveja/CervejaListener.java | 20 + .../event/cerveja/CervejaSalvaEvent.java | 27 + .../CpfCnpjClienteJaCadastradoException.java | 11 + .../EmailUsuarioJaCadastradoException.java | 11 + .../ImpossivelExcluirEntidadeException.java | 11 + .../NomeCidadeJaCadastradaException.java | 11 + .../NomeEstiloJaCadastradoException.java | 11 + .../SenhaObrigatoriaUsuarioException.java | 11 + .../brewer/session/TabelaItensVenda.java | 99 + .../brewer/session/TabelasItensSession.java | 52 + .../algaworks/brewer/storage/FotoStorage.java | 19 + .../brewer/storage/FotoStorageRunnable.java | 27 + .../storage/local/FotoStorageLocal.java | 129 + .../brewer/thymeleaf/BrewerDialect.java | 33 + .../ClassForErrorAttributeTagProcessor.java | 32 + .../processor/MenuAttributeTagProcessor.java | 44 + .../processor/MessageElementTagProcessor.java | 32 + .../processor/OrderElementTagProcessor.java | 38 + .../PaginationElementTagProcessor.java | 36 + .../validation/AtributoConfirmacao.java | 30 + .../com/algaworks/brewer/validation/SKU.java | 25 + .../AtributoConfirmacaoValidator.java | 52 + .../V01__criar_tabelas_estilo_e_cerveja.sql | 23 + ...r_coluna_quantidade_estoque_em_cerveja.sql | 2 + ..._colunas_foto_e_contentType_na_cerveja.sql | 3 + .../V04__adicionar_cidade_e_estado.sql | 40 + .../V05__adicionar_tabela_cliente.sql | 14 + .../V06__alterar_cpf_cnpj_para_not_null.sql | 2 + ...__criar_tabela_usuario_grupo_permissao.sql | 34 + ...terando_ativo_do_usuario_para_not_null.sql | 2 + .../db/migration/V09__inserir_grupos.sql | 2 + .../V10__inserir_usuario_administrador.sql | 1 + ..._permissoes_e_relacionar_usuario_admin.sql | 8 + .../V12__criar_tabela_venda_e_item_venda.sql | 24 + .../V13__inserir_role_cancelar_venda.sql | 3 + .../resources/env/mail-homolog.properties | 2 + .../main/resources/env/mail-local.properties | 2 + .../brewer/src/main/resources/log4j2.xml | 19 + .../src/main/resources/messages.properties | 3 + .../resources/static/images/cerveja-mock.png | Bin 0 -> 5088 bytes .../main/resources/static/images/favicon.png | Bin 0 -> 1633 bytes .../resources/static/images/logo-gray.png | Bin 0 -> 1352 bytes .../src/main/resources/static/images/logo.png | Bin 0 -> 1243 bytes .../resources/static/images/mini-loading.gif | Bin 0 -> 771 bytes .../javascripts/brewer.dialogo-excluir.js | 62 + .../resources/static/javascripts/brewer.js | 119 + .../static/javascripts/cerveja.upload-foto.js | 80 + .../cliente.combo-estado-cidade.js | 103 + .../javascripts/cliente.mascara-cpf-cnpj.js | 38 + .../javascripts/cliente.pesquisa-rapida.js | 84 + .../javascripts/estilo.cadastro-rapido.js | 64 + .../static/javascripts/multiselecao.js | 66 + .../javascripts/venda.autocomplete-itens.js | 49 + .../static/javascripts/venda.botoes-submit.js | 36 + .../resources/static/javascripts/venda.js | 61 + .../static/javascripts/venda.tabela-itens.js | 96 + .../vendors/bootstrap-datepicker.min.js | 10 + .../vendors/bootstrap-datepicker.pt-BR.min.js | 1 + .../vendors/bootstrap-switch.min.js | 22 + .../javascripts/vendors/handlebars.min.js | 29 + .../vendors/jquery.easy-autocomplete.min.js | 10 + .../javascripts/vendors/jquery.mask.min.js | 15 + .../vendors/jquery.maskMoney.min.js | 9 + .../static/javascripts/vendors/numeral.min.js | 8 + .../static/javascripts/vendors/pt-br.min.js | 6 + .../static/javascripts/vendors/uikit.min.js | 3 + .../static/javascripts/vendors/upload.min.js | 2 + .../static/layout/images/logo-gray.png | Bin 0 -> 4153 bytes .../resources/static/layout/images/logo.png | Bin 0 -> 5004 bytes .../static/layout/javascripts/algaworks.js | 86 + .../layout/javascripts/algaworks.min.js | 1 + .../static/layout/javascripts/vendors.js | 13808 ++++++++++++++++ .../static/layout/javascripts/vendors.min.js | 5 + .../static/layout/stylesheets/algaworks.css | 642 + .../layout/stylesheets/algaworks.min.css | 1 + .../static/layout/stylesheets/application.css | 48 + .../static/layout/stylesheets/vendors.css | 10143 ++++++++++++ .../static/layout/stylesheets/vendors.min.css | 12 + .../layout/vendors/bootstrap/bootstrap.js | 2363 +++ .../fonts/glyphicons-halflings-regular.eot | Bin 0 -> 20127 bytes .../fonts/glyphicons-halflings-regular.svg | 288 + .../fonts/glyphicons-halflings-regular.ttf | Bin 0 -> 45404 bytes .../fonts/glyphicons-halflings-regular.woff | Bin 0 -> 23424 bytes .../fonts/glyphicons-halflings-regular.woff2 | Bin 0 -> 18028 bytes .../font-awesome/fonts/4.4.0/index.html | 58 + .../font-awesome/fonts/FontAwesome.otf | Bin 0 -> 123112 bytes .../fonts/fontawesome-webfont.eot | Bin 0 -> 75220 bytes .../fonts/fontawesome-webfont.svg | 685 + .../fonts/fontawesome-webfont.ttf | Bin 0 -> 150920 bytes .../fonts/fontawesome-webfont.woff | Bin 0 -> 89076 bytes .../fonts/fontawesome-webfont.woff2 | Bin 0 -> 70728 bytes .../static/layout/vendors/jquery/jquery.js | 9842 +++++++++++ .../jquery.stickytableheaders.js | 316 + .../vendors/sweetalert/sweetalert-dev.js | 1285 ++ .../layout/vendors/sweetalert/sweetalert.css | 932 ++ .../resources/static/stylesheets/brewer.css | 332 + .../bootstrap-datepicker.standalone.min.css | 9 + .../vendors/bootstrap-switch.min.css | 22 + .../vendors/easy-autocomplete.min.css | 11 + .../vendors/easy-autocomplete.themes.min.css | 11 + .../static/stylesheets/vendors/upload.min.css | 2 + .../src/main/resources/templates/403.html | 25 + .../src/main/resources/templates/404.html | 24 + .../src/main/resources/templates/500.html | 24 + .../src/main/resources/templates/Login.html | 61 + .../templates/cerveja/CadastroCerveja.html | 169 + .../templates/cerveja/PesquisaCervejas.html | 147 + .../templates/cidade/CadastroCidade.html | 60 + .../templates/cidade/PesquisaCidades.html | 96 + .../templates/cliente/CadastroCliente.html | 136 + .../templates/cliente/PesquisaClientes.html | 98 + .../cliente/PesquisaRapidaClientes.html | 39 + .../templates/estilo/CadastroEstilo.html | 57 + .../estilo/CadastroRapidoEstilo.html | 35 + .../templates/estilo/PesquisaEstilos.html | 85 + .../templates/fragments/MensagemSucesso.html | 10 + .../fragments/MensagensErroValidacao.html | 12 + .../templates/fragments/Ordenacao.html | 15 + .../templates/fragments/Paginacao.html | 26 + .../resources/templates/hbs/FotoCerveja.html | 12 + .../hbs/TabelaPesquisaRapidaClientes.html | 27 + .../hbs/TemplateAutocompleteCerveja.html | 15 + .../templates/layout/LayoutPadrao.html | 59 + .../templates/layout/LayoutSimples.html | 28 + .../layout/fragments/BarraNavegacao.html | 35 + .../templates/layout/fragments/Footer.html | 13 + .../layout/fragments/MenuLateral.html | 74 + .../resources/templates/mail/ResumoVenda.html | 82 + .../templates/usuario/CadastroUsuario.html | 107 + .../templates/usuario/PesquisaUsuarios.html | 145 + .../templates/venda/CadastroVenda.html | 197 + .../templates/venda/PesquisaVendas.html | 132 + .../templates/venda/TabelaItensVenda.html | 39 + .../brewer/src/main/webapp/.gitkeep | 0 .../src/main/webapp/META-INF/context.xml | 15 + .../brewer/src/main/webapp/WEB-INF/web.xml | 20 + .../brewer/src/test/java/.gitkeep | 0 .../brewer/session/TabelaItensVendaTest.java | 106 + .../brewer/src/test/resources/.gitkeep | 0 222 files changed, 50121 insertions(+) create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/pom.xml create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/JPAConfig.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/MailConfig.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/SecurityConfig.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/ServiceConfig.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/WebConfig.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/AppInitializer.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/SecurityInitializer.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CervejasController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CidadesController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ClientesController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ErrosController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/EstilosController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/FotosController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/SegurancaController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/UsuariosController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/VendasController.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/CidadeConverter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstadoConverter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstiloConverter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/GrupoConverter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/handler/ControllerAdviceExceptionHandler.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/page/PageWrapper.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/validator/VendaValidator.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/CervejaDTO.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/FotoDTO.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/mail/Mailer.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cerveja.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cidade.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cliente.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Endereco.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estado.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estilo.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Grupo.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/ItemVenda.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Origem.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Permissao.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Sabor.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/StatusVenda.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/TipoPessoa.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Usuario.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupo.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupoId.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Venda.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/ClienteGroupSequenceProvider.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CnpjGroup.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CpfGroup.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cervejas.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cidades.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Clientes.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estados.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estilos.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Grupos.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Usuarios.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Vendas.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CervejaFilter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CidadeFilter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/ClienteFilter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/EstiloFilter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/UsuarioFilter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/VendaFilter.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasImpl.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasQueries.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesImpl.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesQueries.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesImpl.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesQueries.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosImpl.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosQueries.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosImpl.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosQueries.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasImpl.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasQueries.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/paginacao/PaginacaoUtil.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/AppUserDetailsService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/UsuarioSistema.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCervejaService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCidadeService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroClienteService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroEstiloService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroUsuarioService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroVendaService.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/StatusUsuario.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaListener.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaSalvaEvent.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/CpfCnpjClienteJaCadastradoException.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/EmailUsuarioJaCadastradoException.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/ImpossivelExcluirEntidadeException.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeCidadeJaCadastradaException.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeEstiloJaCadastradoException.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/SenhaObrigatoriaUsuarioException.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelaItensVenda.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelasItensSession.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorage.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorageRunnable.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/local/FotoStorageLocal.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/BrewerDialect.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/ClassForErrorAttributeTagProcessor.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MenuAttributeTagProcessor.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MessageElementTagProcessor.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/OrderElementTagProcessor.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/PaginationElementTagProcessor.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/AtributoConfirmacao.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/SKU.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/validator/AtributoConfirmacaoValidator.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V01__criar_tabelas_estilo_e_cerveja.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V02__criar_coluna_quantidade_estoque_em_cerveja.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V03__criar_colunas_foto_e_contentType_na_cerveja.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V04__adicionar_cidade_e_estado.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V05__adicionar_tabela_cliente.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V06__alterar_cpf_cnpj_para_not_null.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V07__criar_tabela_usuario_grupo_permissao.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V08__alterando_ativo_do_usuario_para_not_null.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V09__inserir_grupos.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V10__inserir_usuario_administrador.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V11__inserir_permissoes_e_relacionar_usuario_admin.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V12__criar_tabela_venda_e_item_venda.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V13__inserir_role_cancelar_venda.sql create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-homolog.properties create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-local.properties create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/log4j2.xml create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/messages.properties create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/cerveja-mock.png create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/favicon.png create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/logo-gray.png create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/logo.png create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/mini-loading.gif create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.dialogo-excluir.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cerveja.upload-foto.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.combo-estado-cidade.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.mascara-cpf-cnpj.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.pesquisa-rapida.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/estilo.cadastro-rapido.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/multiselecao.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.autocomplete-itens.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.botoes-submit.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.tabela-itens.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.pt-BR.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-switch.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/handlebars.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.easy-autocomplete.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.mask.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.maskMoney.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/numeral.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/pt-br.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/uikit.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/upload.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/images/logo-gray.png create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/images/logo.png create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/algaworks.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/algaworks.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/vendors.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/vendors.min.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/stylesheets/algaworks.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/stylesheets/algaworks.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/stylesheets/application.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/stylesheets/vendors.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/stylesheets/vendors.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/bootstrap/bootstrap.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/bootstrap/fonts/glyphicons-halflings-regular.eot create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/bootstrap/fonts/glyphicons-halflings-regular.svg create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/bootstrap/fonts/glyphicons-halflings-regular.ttf create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/bootstrap/fonts/glyphicons-halflings-regular.woff create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/bootstrap/fonts/glyphicons-halflings-regular.woff2 create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/4.4.0/index.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/FontAwesome.otf create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/fontawesome-webfont.eot create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/fontawesome-webfont.svg create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/fontawesome-webfont.ttf create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/fontawesome-webfont.woff create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/font-awesome/fonts/fontawesome-webfont.woff2 create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/jquery/jquery.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/stickytableheaders/jquery.stickytableheaders.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/sweetalert/sweetalert-dev.js create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/vendors/sweetalert/sweetalert.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/stylesheets/brewer.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/stylesheets/vendors/bootstrap-datepicker.standalone.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/stylesheets/vendors/bootstrap-switch.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/stylesheets/vendors/easy-autocomplete.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/stylesheets/vendors/easy-autocomplete.themes.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/stylesheets/vendors/upload.min.css create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/403.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/404.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/500.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/Login.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cerveja/CadastroCerveja.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cerveja/PesquisaCervejas.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cidade/CadastroCidade.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cidade/PesquisaCidades.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cliente/CadastroCliente.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cliente/PesquisaClientes.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/cliente/PesquisaRapidaClientes.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/estilo/CadastroEstilo.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/estilo/CadastroRapidoEstilo.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/estilo/PesquisaEstilos.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/fragments/MensagemSucesso.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/fragments/MensagensErroValidacao.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/fragments/Ordenacao.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/fragments/Paginacao.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/hbs/FotoCerveja.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/hbs/TabelaPesquisaRapidaClientes.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/hbs/TemplateAutocompleteCerveja.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/layout/LayoutPadrao.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/layout/LayoutSimples.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/layout/fragments/BarraNavegacao.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/layout/fragments/Footer.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/layout/fragments/MenuLateral.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/mail/ResumoVenda.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/usuario/CadastroUsuario.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/usuario/PesquisaUsuarios.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/venda/CadastroVenda.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/venda/PesquisaVendas.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/templates/venda/TabelaItensVenda.html create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/webapp/.gitkeep create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/webapp/META-INF/context.xml create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/webapp/WEB-INF/web.xml create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/test/java/.gitkeep create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/test/java/com/algaworks/brewer/session/TabelaItensVendaTest.java create mode 100644 25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/test/resources/.gitkeep diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/pom.xml b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/pom.xml new file mode 100644 index 00000000..17c971de --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/pom.xml @@ -0,0 +1,304 @@ + + + 4.0.0 + + com.algaworks + brewer + 1.0.0-SNAPSHOT + + war + + + UTF-8 + UTF-8 + + false + + 1.8 + 3.2 + 4.0.2 + 5.1.39 + + + 4.3.0.RELEASE + + + 3.1.0 + + + 3.0.0.RELEASE + + + 5.2.4.Final + + + 2.0.0 + + + 2.6 + 1.7.21 + + + 5.1.0.Final + + + 1.10.2.RELEASE + + + 2.7.5 + + + + 0.4.8 + + + 2.0.1 + + + 19.0 + + + 1.9.2 + + + 4.1.1.RELEASE + + + 3.0.0.RELEASE + + + 4.12 + + + 1.5.6 + + + + + + maven-compiler-plugin + ${maven-compiler-pluging.version} + + ${java.version} + ${java.version} + + + + + org.flywaydb + flyway-maven-plugin + ${flyway-maven-plugin.version} + + com.mysql.jdbc.Driver + + + + + + + + + org.springframework + spring-framework-bom + ${spring-framework.version} + pom + import + + + + + + + + org.springframework + spring-webmvc + compile + + + commons-logging + commons-logging + + + + + + + javax.servlet + javax.servlet-api + ${servlet.version} + provided + + + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + compile + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + compile + + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + compile + + + + + nz.net.ultraq.thymeleaf + thymeleaf-layout-dialect + ${thymeleaf-layout-dialect.version} + + + + + org.apache.logging.log4j + log4j-slf4j-impl + ${log4j.version} + + + org.apache.logging.log4j + log4j-api + ${log4j.version} + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + + + org.slf4j + jcl-over-slf4j + ${jcl-over-slf4j.version} + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + compile + + + + + org.hibernate + hibernate-java8 + ${hibernate.version} + compile + + + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + provided + + + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + compile + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-core.version} + compile + + + + + net.coobird + thumbnailator + ${thumbnailator.version} + compile + + + + + com.github.mxab.thymeleaf.extras + thymeleaf-extras-data-attribute + ${thymeleaf-extras-data-attribute.version} + compile + + + + + com.google.guava + guava + ${guava.version} + compile + + + + + org.springframework + spring-context-support + compile + + + + + commons-beanutils + commons-beanutils + ${commons-beanutils.version} + compile + + + + + org.springframework.security + spring-security-web + ${spring-security.version} + compile + + + org.springframework.security + spring-security-config + ${spring-security.version} + compile + + + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + ${thymeleaf-extras-springsecurity.version} + compile + + + + + junit + junit + ${junit.version} + test + + + + + com.sun.mail + javax.mail + ${javax.mail.version} + compile + + + + + \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/JPAConfig.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/JPAConfig.java new file mode 100644 index 00000000..16e216f6 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/JPAConfig.java @@ -0,0 +1,63 @@ +package com.algaworks.brewer.config; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.Database; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.repository.Cervejas; + +@Configuration +@ComponentScan(basePackageClasses = Cervejas.class) +@EnableJpaRepositories(basePackageClasses = Cervejas.class, enableDefaultTransactions = false) +@EnableTransactionManagement +@ComponentScan(basePackageClasses = Cervejas.class) +public class JPAConfig { + + @Bean + public DataSource dataSource() { + JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup(); + dataSourceLookup.setResourceRef(true); + return dataSourceLookup.getDataSource("jdbc/brewerDB"); + } + + @Bean + public JpaVendorAdapter jpaVendorAdapter() { + HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); + adapter.setDatabase(Database.MYSQL); + adapter.setShowSql(false); + adapter.setGenerateDdl(false); + adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); + return adapter; + } + + @Bean + public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setDataSource(dataSource); + factory.setJpaVendorAdapter(jpaVendorAdapter); + factory.setPackagesToScan(Cerveja.class.getPackage().getName()); + factory.afterPropertiesSet(); + return factory.getObject(); + } + + @Bean + public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/MailConfig.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/MailConfig.java new file mode 100644 index 00000000..5bbbd417 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/MailConfig.java @@ -0,0 +1,45 @@ +package com.algaworks.brewer.config; + +import java.util.Properties; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.JavaMailSenderImpl; + +import com.algaworks.brewer.mail.Mailer; + +@Configuration +@ComponentScan(basePackageClasses = Mailer.class) +@PropertySource({ "classpath:env/mail-${ambiente:local}.properties" }) +@PropertySource(value = { "file://${HOME}/.brewer-mail.properties" }, ignoreResourceNotFound = true) +public class MailConfig { + + @Autowired + private Environment env; + + @Bean + public JavaMailSender mailSender() { + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost("smtp.sendgrid.net"); + mailSender.setPort(587); + mailSender.setUsername(env.getProperty("username")); + mailSender.setPassword(env.getProperty("password")); + + Properties props = new Properties(); + props.put("mail.transport.protocol", "smtp"); + props.put("mail.smtp.auth", true); + props.put("mail.smtp.starttls.enable", true); + props.put("mail.debug", false); + props.put("mail.smtp.connectiontimeout", 10000); // miliseconds + + mailSender.setJavaMailProperties(props); + + return mailSender; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/SecurityConfig.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/SecurityConfig.java new file mode 100644 index 00000000..bba35c2b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/SecurityConfig.java @@ -0,0 +1,66 @@ +package com.algaworks.brewer.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; + +import com.algaworks.brewer.security.AppUserDetailsService; + +@EnableWebSecurity +@ComponentScan(basePackageClasses = AppUserDetailsService.class) +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); + } + + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring() + .antMatchers("/layout/**") + .antMatchers("/images/**"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/cidades/nova").hasRole("CADASTRAR_CIDADE") + .antMatchers("/usuarios/**").hasRole("CADASTRAR_USUARIO") + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login") + .permitAll() + .and() + .logout() + .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) + .and() + .exceptionHandling() + .accessDeniedPage("/403") + .and() + .sessionManagement() + .invalidSessionUrl("/login"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/ServiceConfig.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/ServiceConfig.java new file mode 100644 index 00000000..f93be098 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/ServiceConfig.java @@ -0,0 +1,20 @@ +package com.algaworks.brewer.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import com.algaworks.brewer.service.CadastroCervejaService; +import com.algaworks.brewer.storage.FotoStorage; +import com.algaworks.brewer.storage.local.FotoStorageLocal; + +@Configuration +@ComponentScan(basePackageClasses = CadastroCervejaService.class) +public class ServiceConfig { + + @Bean + public FotoStorage fotoStorage() { + return new FotoStorageLocal(); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/WebConfig.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/WebConfig.java new file mode 100644 index 00000000..075f55f3 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/WebConfig.java @@ -0,0 +1,154 @@ +package com.algaworks.brewer.config; + +import java.math.BigDecimal; +import java.time.format.DateTimeFormatter; +import java.util.Locale; +import java.util.concurrent.TimeUnit; + +import org.springframework.beans.BeansException; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.guava.GuavaCacheManager; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.data.repository.support.DomainClassConverter; +import org.springframework.data.web.config.EnableSpringDataWebSupport; +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; +import org.springframework.format.number.NumberStyleFormatter; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.i18n.FixedLocaleResolver; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import com.algaworks.brewer.controller.CervejasController; +import com.algaworks.brewer.controller.converter.CidadeConverter; +import com.algaworks.brewer.controller.converter.EstadoConverter; +import com.algaworks.brewer.controller.converter.EstiloConverter; +import com.algaworks.brewer.controller.converter.GrupoConverter; +import com.algaworks.brewer.session.TabelasItensSession; +import com.algaworks.brewer.thymeleaf.BrewerDialect; +import com.github.mxab.thymeleaf.extras.dataattribute.dialect.DataAttributeDialect; +import com.google.common.cache.CacheBuilder; + +import nz.net.ultraq.thymeleaf.LayoutDialect; + +@Configuration +@ComponentScan(basePackageClasses = { CervejasController.class, TabelasItensSession.class }) +@EnableWebMvc +@EnableSpringDataWebSupport +@EnableCaching +@EnableAsync +public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { + + private ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + @Bean + public ViewResolver viewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine()); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } + + @Bean + public TemplateEngine templateEngine() { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setEnableSpringELCompiler(true); + engine.setTemplateResolver(templateResolver()); + + engine.addDialect(new LayoutDialect()); + engine.addDialect(new BrewerDialect()); + engine.addDialect(new DataAttributeDialect()); + engine.addDialect(new SpringSecurityDialect()); + return engine; + } + + private ITemplateResolver templateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("classpath:/templates/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); + } + + @Bean + public FormattingConversionService mvcConversionService() { + DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService(); +// conversionService.addConverter(new EstiloConverter()); + conversionService.addConverter(new CidadeConverter()); + conversionService.addConverter(new EstadoConverter()); + conversionService.addConverter(new GrupoConverter()); + + NumberStyleFormatter bigDecimalFormatter = new NumberStyleFormatter("#,##0.00"); + conversionService.addFormatterForFieldType(BigDecimal.class, bigDecimalFormatter); + + NumberStyleFormatter integerFormatter = new NumberStyleFormatter("#,##0"); + conversionService.addFormatterForFieldType(Integer.class, integerFormatter); + + // API de Datas do Java 8 + DateTimeFormatterRegistrar dateTimeFormatter = new DateTimeFormatterRegistrar(); + dateTimeFormatter.setDateFormatter(DateTimeFormatter.ofPattern("dd/MM/yyyy")); + dateTimeFormatter.setTimeFormatter(DateTimeFormatter.ofPattern("HH:mm")); + dateTimeFormatter.registerFormatters(conversionService); + + return conversionService; + } + + @Bean + public LocaleResolver localeResolver() { + return new FixedLocaleResolver(new Locale("pt", "BR")); + } + + @Bean + public CacheManager cacheManager() { + CacheBuilder cacheBuilder = CacheBuilder.newBuilder() + .maximumSize(3) + .expireAfterAccess(20, TimeUnit.SECONDS); + + GuavaCacheManager cacheManager = new GuavaCacheManager(); + cacheManager.setCacheBuilder(cacheBuilder); + return cacheManager; + } + + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource bundle = new ReloadableResourceBundleMessageSource(); + bundle.setBasename("classpath:/messages"); + bundle.setDefaultEncoding("UTF-8"); // http://www.utf8-chartable.de/ + return bundle; + } + + @Bean + public DomainClassConverter domainClassConverter() { + return new DomainClassConverter(mvcConversionService()); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/AppInitializer.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/AppInitializer.java new file mode 100644 index 00000000..4250674d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/AppInitializer.java @@ -0,0 +1,44 @@ +package com.algaworks.brewer.config.init; + +import javax.servlet.Filter; +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletRegistration.Dynamic; + +import org.springframework.web.filter.HttpPutFormContentFilter; +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +import com.algaworks.brewer.config.JPAConfig; +import com.algaworks.brewer.config.MailConfig; +import com.algaworks.brewer.config.SecurityConfig; +import com.algaworks.brewer.config.ServiceConfig; +import com.algaworks.brewer.config.WebConfig; + +public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { JPAConfig.class, ServiceConfig.class, SecurityConfig.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return new Class[] { WebConfig.class, MailConfig.class }; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + + @Override + protected Filter[] getServletFilters() { + HttpPutFormContentFilter httpPutFormContentFilter = new HttpPutFormContentFilter(); + return new Filter[] { httpPutFormContentFilter }; + } + + @Override + protected void customizeRegistration(Dynamic registration) { + registration.setMultipartConfig(new MultipartConfigElement("")); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/SecurityInitializer.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/SecurityInitializer.java new file mode 100644 index 00000000..e8ef25f3 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/config/init/SecurityInitializer.java @@ -0,0 +1,26 @@ +package com.algaworks.brewer.config.init; + +import java.util.EnumSet; + +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; +import javax.servlet.SessionTrackingMode; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; +import org.springframework.web.filter.CharacterEncodingFilter; + +public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { + + @Override + protected void beforeSpringSecurityFilterChain(ServletContext servletContext) { +// servletContext.getSessionCookieConfig().setMaxAge(20); + servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); + + FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("encodingFilter", + new CharacterEncodingFilter()); + characterEncodingFilter.setInitParameter("encoding", "UTF-8"); + characterEncodingFilter.setInitParameter("forceEncoding", "true"); + characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*"); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CervejasController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CervejasController.java new file mode 100644 index 00000000..38fdf5d8 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CervejasController.java @@ -0,0 +1,105 @@ +package com.algaworks.brewer.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import com.algaworks.brewer.controller.page.PageWrapper; +import com.algaworks.brewer.dto.CervejaDTO; +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.model.Origem; +import com.algaworks.brewer.model.Sabor; +import com.algaworks.brewer.repository.Cervejas; +import com.algaworks.brewer.repository.Estilos; +import com.algaworks.brewer.repository.filter.CervejaFilter; +import com.algaworks.brewer.service.CadastroCervejaService; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; + +@Controller +@RequestMapping("/cervejas") +public class CervejasController { + + @Autowired + private Estilos estilos; + + @Autowired + private CadastroCervejaService cadastroCervejaService; + + @Autowired + private Cervejas cervejas; + + @RequestMapping("/nova") + public ModelAndView nova(Cerveja cerveja) { + ModelAndView mv = new ModelAndView("cerveja/CadastroCerveja"); + mv.addObject("sabores", Sabor.values()); + mv.addObject("estilos", estilos.findAll()); + mv.addObject("origens", Origem.values()); + return mv; + } + + @RequestMapping(value = { "/nova", "{\\d+}" }, method = RequestMethod.POST) + public ModelAndView salvar(@Valid Cerveja cerveja, BindingResult result, Model model, RedirectAttributes attributes) { + if (result.hasErrors()) { + return nova(cerveja); + } + + cadastroCervejaService.salvar(cerveja); + attributes.addFlashAttribute("mensagem", "Cerveja salva com sucesso!"); + return new ModelAndView("redirect:/cervejas/nova"); + } + + @GetMapping + public ModelAndView pesquisar(CervejaFilter cervejaFilter, BindingResult result + , @PageableDefault(size = 2) Pageable pageable, HttpServletRequest httpServletRequest) { + ModelAndView mv = new ModelAndView("cerveja/PesquisaCervejas"); + mv.addObject("estilos", estilos.findAll()); + mv.addObject("sabores", Sabor.values()); + mv.addObject("origens", Origem.values()); + + PageWrapper paginaWrapper = new PageWrapper<>(cervejas.filtrar(cervejaFilter, pageable) + , httpServletRequest); + mv.addObject("pagina", paginaWrapper); + return mv; + } + + @RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + public @ResponseBody List pesquisar(String skuOuNome) { + return cervejas.porSkuOuNome(skuOuNome); + } + + @DeleteMapping("/{codigo}") + public @ResponseBody ResponseEntity excluir(@PathVariable("codigo") Cerveja cerveja) { + try { + cadastroCervejaService.excluir(cerveja); + } catch (ImpossivelExcluirEntidadeException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + return ResponseEntity.ok().build(); + } + + @GetMapping("/{codigo}") + public ModelAndView editar(@PathVariable("codigo") Cerveja cerveja) { + ModelAndView mv = nova(cerveja); + mv.addObject(cerveja); + return mv; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CidadesController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CidadesController.java new file mode 100644 index 00000000..a67fec6c --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/CidadesController.java @@ -0,0 +1,114 @@ +package com.algaworks.brewer.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import com.algaworks.brewer.controller.page.PageWrapper; +import com.algaworks.brewer.model.Cidade; +import com.algaworks.brewer.repository.Cidades; +import com.algaworks.brewer.repository.Estados; +import com.algaworks.brewer.repository.filter.CidadeFilter; +import com.algaworks.brewer.service.CadastroCidadeService; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.service.exception.NomeCidadeJaCadastradaException; + +@Controller +@RequestMapping("/cidades") +public class CidadesController { + + @Autowired + private Cidades cidades; + + @Autowired + private Estados estados; + + @Autowired + private CadastroCidadeService cadastroCidadeService; + + @GetMapping("/nova") + public ModelAndView nova(Cidade cidade) { + ModelAndView mv = new ModelAndView("cidade/CadastroCidade"); + mv.addObject("estados", estados.findAll()); + return mv; + } + + @Cacheable(value = "cidades", key = "#codigoEstado") + @RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) + public @ResponseBody List pesquisarPorCodigoEstado( + @RequestParam(name = "estado", defaultValue = "-1") Long codigoEstado) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { } + return cidades.findByEstadoCodigo(codigoEstado); + } + + @PostMapping({"/nova", "/nova/{codgo}"}) + @CacheEvict(value = "cidades", key = "#cidade.estado.codigo", condition = "#cidade.temEstado()") + public ModelAndView salvar(@Valid Cidade cidade, Model model, BindingResult result, RedirectAttributes attributes) { + if (result.hasErrors()) { + return nova(cidade); + } + + try { + cadastroCidadeService.salvar(cidade); + } catch (NomeCidadeJaCadastradaException e) { + result.rejectValue("nome", e.getMessage(), e.getMessage()); + return nova(cidade); + } + + attributes.addFlashAttribute("mensagem", "Cidade salva com sucesso!"); + return new ModelAndView("redirect:/cidades/nova"); + } + + @GetMapping + public ModelAndView pesquisar(CidadeFilter cidadeFilter, BindingResult result + , @PageableDefault(size = 10) Pageable pageable, HttpServletRequest httpServletRequest) { + ModelAndView mv = new ModelAndView("cidade/PesquisaCidades"); + mv.addObject("estados", estados.findAll()); + + PageWrapper paginaWrapper = new PageWrapper<>(cidades.filtrar(cidadeFilter, pageable) + , httpServletRequest); + mv.addObject("pagina", paginaWrapper); + return mv; + } + + @DeleteMapping("/{codigo}") + public ResponseEntity excluir(@PathVariable("codigo") Cidade cidade) { + try { + this.cadastroCidadeService.excluir(cidade); + } catch (ImpossivelExcluirEntidadeException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + return ResponseEntity.ok().build(); + } + + @GetMapping("/{codigo}") + public ModelAndView atualizar(@PathVariable("codigo") Cidade cidade) { + ModelAndView mv = this.nova(cidade); + mv.addObject(this.cidades.findByCodigoFetchingEstado(cidade.getCodigo())); + return mv; + } +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ClientesController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ClientesController.java new file mode 100644 index 00000000..0176624a --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ClientesController.java @@ -0,0 +1,120 @@ +package com.algaworks.brewer.controller; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.util.StringUtils; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import com.algaworks.brewer.controller.page.PageWrapper; +import com.algaworks.brewer.model.Cliente; +import com.algaworks.brewer.model.TipoPessoa; +import com.algaworks.brewer.repository.Clientes; +import com.algaworks.brewer.repository.Estados; +import com.algaworks.brewer.repository.filter.ClienteFilter; +import com.algaworks.brewer.service.CadastroClienteService; +import com.algaworks.brewer.service.exception.CpfCnpjClienteJaCadastradoException; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; + +@Controller +@RequestMapping("/clientes") +public class ClientesController { + + @Autowired + private Estados estados; + + @Autowired + private CadastroClienteService cadastroClienteService; + + @Autowired + private Clientes clientes; + + @RequestMapping("/novo") + public ModelAndView novo(Cliente cliente) { + ModelAndView mv = new ModelAndView("cliente/CadastroCliente"); + mv.addObject("tiposPessoa", TipoPessoa.values()); + mv.addObject("estados", estados.findAll()); + return mv; + } + + @PostMapping({"/novo", "{\\d+}"}) + public ModelAndView salvar(@Valid Cliente cliente, BindingResult result, RedirectAttributes attributes) { + if (result.hasErrors()) { + return novo(cliente); + } + + try { + cadastroClienteService.salvar(cliente); + } catch (CpfCnpjClienteJaCadastradoException e) { + result.rejectValue("cpfOuCnpj", e.getMessage(), e.getMessage()); + return novo(cliente); + } + + attributes.addFlashAttribute("mensagem", "Cliente salvo com sucesso!"); + return new ModelAndView("redirect:/clientes/novo"); + } + + @GetMapping + public ModelAndView pesquisar(ClienteFilter clienteFilter, BindingResult result + , @PageableDefault(size = 3) Pageable pageable, HttpServletRequest httpServletRequest) { + ModelAndView mv = new ModelAndView("cliente/PesquisaClientes"); + mv.addObject("tiposPessoa", TipoPessoa.values()); + + PageWrapper paginaWrapper = new PageWrapper<>(clientes.filtrar(clienteFilter, pageable) + , httpServletRequest); + mv.addObject("pagina", paginaWrapper); + return mv; + } + + @RequestMapping(consumes = { MediaType.APPLICATION_JSON_VALUE }) + public @ResponseBody List pesquisar(String nome) { + validarTamanhoNome(nome); + return clientes.findByNomeStartingWithIgnoreCase(nome); + } + + private void validarTamanhoNome(String nome) { + if (StringUtils.isEmpty(nome) || nome.length() < 3) { + throw new IllegalArgumentException(); + } + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity tratarIllegalArgumentException(IllegalArgumentException e) { + return ResponseEntity.badRequest().build(); + } + + @GetMapping("/{codigo}") + public ModelAndView editar(@PathVariable("codigo") Cliente cliente) { + ModelAndView mv = this.novo(cliente); + this.cadastroClienteService.comporDadosEndereco(cliente); + mv.addObject(cliente); + return mv; + } + + @DeleteMapping("/{codigo}") + public ResponseEntity excluir(@PathVariable("codigo") Cliente cliente) { + try { + this.cadastroClienteService.excluir(cliente); + } catch (ImpossivelExcluirEntidadeException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + return ResponseEntity.ok().build(); + } +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ErrosController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ErrosController.java new file mode 100644 index 00000000..1d3769b3 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/ErrosController.java @@ -0,0 +1,20 @@ +package com.algaworks.brewer.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class ErrosController { + + @GetMapping("/404") + public String paginaNaoEncontrada() { + return "404"; + } + + @RequestMapping("/500") + public String erroServidor() { + return "500"; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/EstilosController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/EstilosController.java new file mode 100644 index 00000000..b2594afa --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/EstilosController.java @@ -0,0 +1,102 @@ +package com.algaworks.brewer.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import com.algaworks.brewer.controller.page.PageWrapper; +import com.algaworks.brewer.model.Estilo; +import com.algaworks.brewer.repository.Estilos; +import com.algaworks.brewer.repository.filter.EstiloFilter; +import com.algaworks.brewer.service.CadastroEstiloService; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.service.exception.NomeEstiloJaCadastradoException; + +@Controller +@RequestMapping("/estilos") +public class EstilosController { + + @Autowired + private CadastroEstiloService cadastroEstiloService; + + @Autowired + private Estilos estilos; + + @RequestMapping("/novo") + public ModelAndView novo(Estilo estilo) { + return new ModelAndView("estilo/CadastroEstilo"); + } + + @RequestMapping(value = { "/novo", "{\\d+}" }, method = RequestMethod.POST) + public ModelAndView cadastrar(@Valid Estilo estilo, Model model, BindingResult result, + RedirectAttributes attributes) { + if (result.hasErrors()) { + return novo(estilo); + } + + try { + cadastroEstiloService.salvar(estilo); + } catch (NomeEstiloJaCadastradoException e) { + result.rejectValue("nome", e.getMessage(), e.getMessage()); + return novo(estilo); + } + + attributes.addFlashAttribute("mensagem", "Estilo salvo com sucesso"); + return new ModelAndView("redirect:/estilos/novo"); + } + + @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE }) + public @ResponseBody ResponseEntity salvar(@RequestBody @Valid Estilo estilo, BindingResult result) { + if (result.hasErrors()) { + return ResponseEntity.badRequest().body(result.getFieldError("nome").getDefaultMessage()); + } + + estilo = cadastroEstiloService.salvar(estilo); + return ResponseEntity.ok(estilo); + } + + @GetMapping + public ModelAndView pesquisar(EstiloFilter estiloFilter, BindingResult result, + @PageableDefault(size = 2) Pageable pageable, HttpServletRequest httpServletRequest) { + ModelAndView mv = new ModelAndView("estilo/PesquisaEstilos"); + + PageWrapper paginaWrapper = new PageWrapper<>(estilos.filtrar(estiloFilter, pageable), + httpServletRequest); + mv.addObject("pagina", paginaWrapper); + return mv; + } + + @GetMapping("/{codigo}") + public ModelAndView editar(@PathVariable("codigo") Estilo estilo) { + ModelAndView mv = this.novo(estilo); + mv.addObject(estilo); + return mv; + } + + @DeleteMapping("/{codigo}") + public ResponseEntity excluir(@PathVariable("codigo") Estilo estilo) { + try { + this.cadastroEstiloService.excluir(estilo); + } catch (ImpossivelExcluirEntidadeException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + return ResponseEntity.ok().build(); + } +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/FotosController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/FotosController.java new file mode 100644 index 00000000..681fe0d1 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/FotosController.java @@ -0,0 +1,44 @@ +package com.algaworks.brewer.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.multipart.MultipartFile; + +import com.algaworks.brewer.dto.FotoDTO; +import com.algaworks.brewer.storage.FotoStorage; +import com.algaworks.brewer.storage.FotoStorageRunnable; + +@RestController +@RequestMapping("/fotos") +public class FotosController { + + @Autowired + private FotoStorage fotoStorage; + + @PostMapping + public DeferredResult upload(@RequestParam("files[]") MultipartFile[] files) { + DeferredResult resultado = new DeferredResult<>(); + + Thread thread = new Thread(new FotoStorageRunnable(files, resultado, fotoStorage)); + thread.start(); + + return resultado; + } + + @GetMapping("/temp/{nome:.*}") + public byte[] recuperarFotoTemporaria(@PathVariable String nome) { + return fotoStorage.recuperarFotoTemporaria(nome); + } + + @GetMapping("/{nome:.*}") + public byte[] recuperar(@PathVariable String nome) { + return fotoStorage.recuperar(nome); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/SegurancaController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/SegurancaController.java new file mode 100644 index 00000000..90b9ad05 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/SegurancaController.java @@ -0,0 +1,25 @@ +package com.algaworks.brewer.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.userdetails.User; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SegurancaController { + + @GetMapping("/login") + public String login(@AuthenticationPrincipal User user) { + if (user != null) { + return "redirect:/cervejas"; + } + + return "Login"; + } + + @GetMapping("/403") + public String acessoNegado() { + return "403"; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/UsuariosController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/UsuariosController.java new file mode 100644 index 00000000..daf7acd0 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/UsuariosController.java @@ -0,0 +1,110 @@ +package com.algaworks.brewer.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import com.algaworks.brewer.controller.page.PageWrapper; +import com.algaworks.brewer.model.Usuario; +import com.algaworks.brewer.repository.Grupos; +import com.algaworks.brewer.repository.Usuarios; +import com.algaworks.brewer.repository.filter.UsuarioFilter; +import com.algaworks.brewer.service.CadastroUsuarioService; +import com.algaworks.brewer.service.StatusUsuario; +import com.algaworks.brewer.service.exception.EmailUsuarioJaCadastradoException; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.service.exception.SenhaObrigatoriaUsuarioException; + +@Controller +@RequestMapping("/usuarios") +public class UsuariosController { + + @Autowired + private CadastroUsuarioService cadastroUsuarioService; + + @Autowired + private Grupos grupos; + + @Autowired + private Usuarios usuarios; + + @RequestMapping("/novo") + public ModelAndView novo(Usuario usuario) { + ModelAndView mv = new ModelAndView("usuario/CadastroUsuario"); + mv.addObject("grupos", grupos.findAll()); + return mv; + } + + @PostMapping({ "/novo", "{\\+d}" }) + public ModelAndView salvar(@Valid Usuario usuario, BindingResult result, RedirectAttributes attributes) { + if (result.hasErrors()) { + return novo(usuario); + } + + try { + cadastroUsuarioService.salvar(usuario); + } catch (EmailUsuarioJaCadastradoException e) { + result.rejectValue("email", e.getMessage(), e.getMessage()); + return novo(usuario); + } catch (SenhaObrigatoriaUsuarioException e) { + result.rejectValue("senha", e.getMessage(), e.getMessage()); + return novo(usuario); + } + + attributes.addFlashAttribute("mensagem", "Usuário salvo com sucesso"); + return new ModelAndView("redirect:/usuarios/novo"); + } + + @GetMapping + public ModelAndView pesquisar(UsuarioFilter usuarioFilter + , @PageableDefault(size = 3) Pageable pageable, HttpServletRequest httpServletRequest) { + ModelAndView mv = new ModelAndView("/usuario/PesquisaUsuarios"); + mv.addObject("grupos", grupos.findAll()); + + PageWrapper paginaWrapper = new PageWrapper<>(usuarios.filtrar(usuarioFilter, pageable) + , httpServletRequest); + mv.addObject("pagina", paginaWrapper); + return mv; + } + + @PutMapping("/status") + @ResponseStatus(HttpStatus.OK) + public void atualizarStatus(@RequestParam("codigos[]") Long[] codigos, @RequestParam("status") StatusUsuario statusUsuario) { + cadastroUsuarioService.alterarStatus(codigos, statusUsuario); + } + + @GetMapping("/{codigo}") + public ModelAndView editar(@PathVariable Long codigo) { + Usuario usuario = usuarios.buscarComGrupos(codigo); + ModelAndView mv = novo(usuario); + mv.addObject(usuario); + return mv; + } + + @DeleteMapping("/{codigo}") + public ResponseEntity excluir(@PathVariable("codigo") Usuario usuario) { + try { + cadastroUsuarioService.excluir(usuario); + } catch (ImpossivelExcluirEntidadeException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + return ResponseEntity.ok().build(); + } +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/VendasController.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/VendasController.java new file mode 100644 index 00000000..ba9decd5 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/VendasController.java @@ -0,0 +1,207 @@ +package com.algaworks.brewer.controller; + +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.stereotype.Controller; +import org.springframework.util.StringUtils; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import com.algaworks.brewer.controller.page.PageWrapper; +import com.algaworks.brewer.controller.validator.VendaValidator; +import com.algaworks.brewer.mail.Mailer; +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.model.ItemVenda; +import com.algaworks.brewer.model.StatusVenda; +import com.algaworks.brewer.model.TipoPessoa; +import com.algaworks.brewer.model.Venda; +import com.algaworks.brewer.repository.Cervejas; +import com.algaworks.brewer.repository.Vendas; +import com.algaworks.brewer.repository.filter.VendaFilter; +import com.algaworks.brewer.security.UsuarioSistema; +import com.algaworks.brewer.service.CadastroVendaService; +import com.algaworks.brewer.session.TabelasItensSession; + +@Controller +@RequestMapping("/vendas") +public class VendasController { + + @Autowired + private Cervejas cervejas; + + @Autowired + private TabelasItensSession tabelaItens; + + @Autowired + private CadastroVendaService cadastroVendaService; + + @Autowired + private VendaValidator vendaValidator; + + @Autowired + private Vendas vendas; + + @Autowired + private Mailer mailer; + + @InitBinder("venda") + public void inicializarValidador(WebDataBinder binder) { + binder.setValidator(vendaValidator); + } + + @GetMapping("/nova") + public ModelAndView nova(Venda venda) { + ModelAndView mv = new ModelAndView("venda/CadastroVenda"); + + setUuid(venda); + + mv.addObject("itens", venda.getItens()); + mv.addObject("valorFrete", venda.getValorFrete()); + mv.addObject("valorDesconto", venda.getValorDesconto()); + mv.addObject("valorTotalItens", tabelaItens.getValorTotal(venda.getUuid())); + + return mv; + } + + @PostMapping(value = "/nova", params = "salvar") + public ModelAndView salvar(Venda venda, BindingResult result, RedirectAttributes attributes, @AuthenticationPrincipal UsuarioSistema usuarioSistema) { + validarVenda(venda, result); + if (result.hasErrors()) { + return nova(venda); + } + + venda.setUsuario(usuarioSistema.getUsuario()); + + cadastroVendaService.salvar(venda); + attributes.addFlashAttribute("mensagem", "Venda salva com sucesso"); + return new ModelAndView("redirect:/vendas/nova"); + } + + @PostMapping(value = "/nova", params = "emitir") + public ModelAndView emitir(Venda venda, BindingResult result, RedirectAttributes attributes, @AuthenticationPrincipal UsuarioSistema usuarioSistema) { + validarVenda(venda, result); + if (result.hasErrors()) { + return nova(venda); + } + + venda.setUsuario(usuarioSistema.getUsuario()); + + cadastroVendaService.emitir(venda); + attributes.addFlashAttribute("mensagem", "Venda emitida com sucesso"); + return new ModelAndView("redirect:/vendas/nova"); + } + + @PostMapping(value = "/nova", params = "enviarEmail") + public ModelAndView enviarEmail(Venda venda, BindingResult result, RedirectAttributes attributes, @AuthenticationPrincipal UsuarioSistema usuarioSistema) { + validarVenda(venda, result); + if (result.hasErrors()) { + return nova(venda); + } + + venda.setUsuario(usuarioSistema.getUsuario()); + + venda = cadastroVendaService.salvar(venda); + mailer.enviar(venda); + + attributes.addFlashAttribute("mensagem", String.format("Venda nº %d salva com sucesso e e-mail enviado", venda.getCodigo())); + return new ModelAndView("redirect:/vendas/nova"); + } + + @PostMapping("/item") + public ModelAndView adicionarItem(Long codigoCerveja, String uuid) { + Cerveja cerveja = cervejas.findOne(codigoCerveja); + tabelaItens.adicionarItem(uuid, cerveja, 1); + return mvTabelaItensVenda(uuid); + } + + @PutMapping("/item/{codigoCerveja}") + public ModelAndView alterarQuantidadeItem(@PathVariable("codigoCerveja") Cerveja cerveja + , Integer quantidade, String uuid) { + tabelaItens.alterarQuantidadeItens(uuid, cerveja, quantidade); + return mvTabelaItensVenda(uuid); + } + + @DeleteMapping("/item/{uuid}/{codigoCerveja}") + public ModelAndView excluirItem(@PathVariable("codigoCerveja") Cerveja cerveja + , @PathVariable String uuid) { + tabelaItens.excluirItem(uuid, cerveja); + return mvTabelaItensVenda(uuid); + } + + @GetMapping + public ModelAndView pesquisar(VendaFilter vendaFilter, + @PageableDefault(size = 10) Pageable pageable, HttpServletRequest httpServletRequest) { + ModelAndView mv = new ModelAndView("/venda/PesquisaVendas"); + mv.addObject("todosStatus", StatusVenda.values()); + mv.addObject("tiposPessoa", TipoPessoa.values()); + + PageWrapper paginaWrapper = new PageWrapper<>(vendas.filtrar(vendaFilter, pageable) + , httpServletRequest); + mv.addObject("pagina", paginaWrapper); + return mv; + } + + @GetMapping("/{codigo}") + public ModelAndView editar(@PathVariable Long codigo) { + Venda venda = vendas.buscarComItens(codigo); + + setUuid(venda); + for (ItemVenda item : venda.getItens()) { + tabelaItens.adicionarItem(venda.getUuid(), item.getCerveja(), item.getQuantidade()); + } + + ModelAndView mv = nova(venda); + mv.addObject(venda); + return mv; + } + + @PostMapping(value = "/nova", params = "cancelar") + public ModelAndView cancelar(Venda venda, BindingResult result + , RedirectAttributes attributes, @AuthenticationPrincipal UsuarioSistema usuarioSistema) { + try { + cadastroVendaService.cancelar(venda); + } catch (AccessDeniedException e) { + return new ModelAndView("/403"); + } + + attributes.addFlashAttribute("mensagem", "Venda cancelada com sucesso"); + return new ModelAndView("redirect:/vendas/" + venda.getCodigo()); + } + + private ModelAndView mvTabelaItensVenda(String uuid) { + ModelAndView mv = new ModelAndView("venda/TabelaItensVenda"); + mv.addObject("itens", tabelaItens.getItens(uuid)); + mv.addObject("valorTotal", tabelaItens.getValorTotal(uuid)); + return mv; + } + + private void validarVenda(Venda venda, BindingResult result) { + venda.adicionarItens(tabelaItens.getItens(venda.getUuid())); + venda.calcularValorTotal(); + + vendaValidator.validate(venda, result); + } + + private void setUuid(Venda venda) { + if (StringUtils.isEmpty(venda.getUuid())) { + venda.setUuid(UUID.randomUUID().toString()); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/CidadeConverter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/CidadeConverter.java new file mode 100644 index 00000000..51d97146 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/CidadeConverter.java @@ -0,0 +1,21 @@ +package com.algaworks.brewer.controller.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Cidade; + +public class CidadeConverter implements Converter { + + @Override + public Cidade convert(String codigo) { + if (!StringUtils.isEmpty(codigo)) { + Cidade cidade = new Cidade(); + cidade.setCodigo(Long.valueOf(codigo)); + return cidade; + } + + return null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstadoConverter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstadoConverter.java new file mode 100644 index 00000000..ad0e9ba2 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstadoConverter.java @@ -0,0 +1,21 @@ +package com.algaworks.brewer.controller.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Estado; + +public class EstadoConverter implements Converter { + + @Override + public Estado convert(String codigo) { + if (!StringUtils.isEmpty(codigo)) { + Estado estado = new Estado(); + estado.setCodigo(Long.valueOf(codigo)); + return estado; + } + + return null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstiloConverter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstiloConverter.java new file mode 100644 index 00000000..d989c40f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/EstiloConverter.java @@ -0,0 +1,21 @@ +package com.algaworks.brewer.controller.converter; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Estilo; + +public class EstiloConverter implements Converter { + + @Override + public Estilo convert(String codigo) { + if (!StringUtils.isEmpty(codigo)) { + Estilo estilo = new Estilo(); + estilo.setCodigo(Long.valueOf(codigo)); + return estilo; + } + + return null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/GrupoConverter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/GrupoConverter.java new file mode 100644 index 00000000..55154ea0 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/converter/GrupoConverter.java @@ -0,0 +1,21 @@ +package com.algaworks.brewer.controller.converter; + +import org.springframework.core.convert.converter.Converter; +import org.thymeleaf.util.StringUtils; + +import com.algaworks.brewer.model.Grupo; + +public class GrupoConverter implements Converter { + + @Override + public Grupo convert(String codigo) { + if (!StringUtils.isEmpty(codigo)) { + Grupo grupo = new Grupo(); + grupo.setCodigo(Long.valueOf(codigo)); + return grupo; + } + + return null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/handler/ControllerAdviceExceptionHandler.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/handler/ControllerAdviceExceptionHandler.java new file mode 100644 index 00000000..377211fe --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/handler/ControllerAdviceExceptionHandler.java @@ -0,0 +1,17 @@ +package com.algaworks.brewer.controller.handler; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import com.algaworks.brewer.service.exception.NomeEstiloJaCadastradoException; + +@ControllerAdvice +public class ControllerAdviceExceptionHandler { + + @ExceptionHandler(NomeEstiloJaCadastradoException.class) + public ResponseEntity handleNomeEstiloJaCadastradoException(NomeEstiloJaCadastradoException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/page/PageWrapper.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/page/PageWrapper.java new file mode 100644 index 00000000..febfd159 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/page/PageWrapper.java @@ -0,0 +1,87 @@ +package com.algaworks.brewer.controller.page; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Order; +import org.springframework.web.util.UriComponentsBuilder; + +public class PageWrapper { + + private Page page; + private UriComponentsBuilder uriBuilder; + + public PageWrapper(Page page, HttpServletRequest httpServletRequest) { + this.page = page; + String httpUrl = httpServletRequest.getRequestURL().append( + httpServletRequest.getQueryString() != null ? "?" + httpServletRequest.getQueryString() : "") + .toString().replaceAll("\\+", "%20").replaceAll("excluido", ""); + this.uriBuilder = UriComponentsBuilder.fromHttpUrl(httpUrl); + } + + public List getConteudo() { + return page.getContent(); + } + + public boolean isVazia() { + return page.getContent().isEmpty(); + } + + public int getAtual() { + return page.getNumber(); + } + + public boolean isPrimeira() { + return page.isFirst(); + } + + public boolean isUltima() { + return page.isLast(); + } + + public int getTotal() { + return page.getTotalPages(); + } + + public String urlParaPagina(int pagina) { + return uriBuilder.replaceQueryParam("page", pagina).build(true).encode().toUriString(); + } + + public String urlOrdenada(String propriedade) { + UriComponentsBuilder uriBuilderOrder = UriComponentsBuilder + .fromUriString(uriBuilder.build(true).encode().toUriString()); + + String valorSort = String.format("%s,%s", propriedade, inverterDirecao(propriedade)); + + return uriBuilderOrder.replaceQueryParam("sort", valorSort).build(true).encode().toUriString(); + } + + public String inverterDirecao(String propriedade) { + String direcao = "asc"; + + Order order = page.getSort() != null ? page.getSort().getOrderFor(propriedade) : null; + if (order != null) { + direcao = Sort.Direction.ASC.equals(order.getDirection()) ? "desc" : "asc"; + } + + return direcao; + } + + public boolean descendente(String propriedade) { + return inverterDirecao(propriedade).equals("asc"); + } + + public boolean ordenada(String propriedade) { + Order order = page.getSort() != null ? page.getSort().getOrderFor(propriedade) : null; + + if (order == null) { + return false; + } + + return page.getSort().getOrderFor(propriedade) != null ? true : false; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/validator/VendaValidator.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/validator/VendaValidator.java new file mode 100644 index 00000000..904f1bf1 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/controller/validator/VendaValidator.java @@ -0,0 +1,48 @@ +package com.algaworks.brewer.controller.validator; + +import java.math.BigDecimal; + +import org.springframework.stereotype.Component; +import org.springframework.validation.Errors; +import org.springframework.validation.ValidationUtils; +import org.springframework.validation.Validator; + +import com.algaworks.brewer.model.Venda; + +@Component +public class VendaValidator implements Validator { + + @Override + public boolean supports(Class clazz) { + return Venda.class.isAssignableFrom(clazz); + } + + @Override + public void validate(Object target, Errors errors) { + ValidationUtils.rejectIfEmpty(errors, "cliente.codigo", "", "Selecione um cliente na pesquisa rápida"); + + Venda venda = (Venda) target; + validarSeInformouApenasHorarioEntrega(errors, venda); + validarSeInformouItens(errors, venda); + validarValorTotalNegativo(errors, venda); + } + + private void validarValorTotalNegativo(Errors errors, Venda venda) { + if (venda.getValorTotal().compareTo(BigDecimal.ZERO) < 0) { + errors.reject("", "Valor total não pode ser negativo"); + } + } + + private void validarSeInformouItens(Errors errors, Venda venda) { + if (venda.getItens().isEmpty()) { + errors.reject("", "Adicione pelo menos uma cerveja na venda"); + } + } + + private void validarSeInformouApenasHorarioEntrega(Errors errors, Venda venda) { + if (venda.getHorarioEntrega() != null && venda.getDataEntrega() == null) { + errors.rejectValue("dataEntrega", "", "Informe uma data da entrega para um horário"); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/CervejaDTO.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/CervejaDTO.java new file mode 100644 index 00000000..6f59d8aa --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/CervejaDTO.java @@ -0,0 +1,75 @@ +package com.algaworks.brewer.dto; + +import java.math.BigDecimal; + +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Origem; + +public class CervejaDTO { + + private Long codigo; + private String sku; + private String nome; + private String origem; + private BigDecimal valor; + private String foto; + + public CervejaDTO(Long codigo, String sku, String nome, Origem origem, BigDecimal valor, String foto) { + this.codigo = codigo; + this.sku = sku; + this.nome = nome; + this.origem = origem.getDescricao(); + this.valor = valor; + this.foto = StringUtils.isEmpty(foto) ? "cerveja-mock.png" : foto; + } + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getOrigem() { + return origem; + } + + public void setOrigem(String origem) { + this.origem = origem; + } + + public BigDecimal getValor() { + return valor; + } + + public void setValor(BigDecimal valor) { + this.valor = valor; + } + + public String getFoto() { + return foto; + } + + public void setFoto(String foto) { + this.foto = foto; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/FotoDTO.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/FotoDTO.java new file mode 100644 index 00000000..6ff1ea7d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/dto/FotoDTO.java @@ -0,0 +1,29 @@ +package com.algaworks.brewer.dto; + +public class FotoDTO { + + private String nome; + private String contentType; + + public FotoDTO(String nome, String contentType) { + this.nome = nome; + this.contentType = contentType; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/mail/Mailer.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/mail/Mailer.java new file mode 100644 index 00000000..feb9317e --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/mail/Mailer.java @@ -0,0 +1,93 @@ +package com.algaworks.brewer.mail; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; + +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.model.ItemVenda; +import com.algaworks.brewer.model.Venda; +import com.algaworks.brewer.storage.FotoStorage; + +@Component +public class Mailer { + + private static Logger logger = LoggerFactory.getLogger(Mailer.class); + + @Autowired + private JavaMailSender mailSender; + + @Autowired + private TemplateEngine thymeleaf; + + @Autowired + private FotoStorage fotoStorage; + + @Async + public void enviar(Venda venda) { + Context context = new Context(new Locale("pt", "BR")); + + context.setVariable("venda", venda); + context.setVariable("logo", "logo"); + + Map fotos = new HashMap<>(); + boolean adicionarMockCerveja = false; + for (ItemVenda item : venda.getItens()) { + Cerveja cerveja = item.getCerveja(); + if (cerveja.temFoto()) { + String cid = "foto-" + cerveja.getCodigo(); + context.setVariable(cid, cid); + + fotos.put(cid, cerveja.getFoto() + "|" + cerveja.getContentType()); + } else { + adicionarMockCerveja = true; + context.setVariable("mockCerveja", "mockCerveja"); + } + } + + try { + String email = thymeleaf.process("mail/ResumoVenda", context); + + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); + helper.setFrom("teste@algaworks.com"); + helper.setTo(venda.getCliente().getEmail()); + helper.setSubject(String.format("Brewer - Venda nº %d", venda.getCodigo())); + helper.setText(email, true); + + helper.addInline("logo", new ClassPathResource("static/images/logo-gray.png")); + + if (adicionarMockCerveja) { + helper.addInline("mockCerveja", new ClassPathResource("static/images/cerveja-mock.png")); + } + + for (String cid : fotos.keySet()) { + String[] fotoContentType = fotos.get(cid).split("\\|"); + String foto = fotoContentType[0]; + String contentType = fotoContentType[1]; + byte[] arrayFoto = fotoStorage.recuperarThumbnail(foto); + helper.addInline(cid, new ByteArrayResource(arrayFoto), contentType); + } + + mailSender.send(mimeMessage); + } catch (MessagingException e) { + logger.error("Erro enviando e-mail", e); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cerveja.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cerveja.java new file mode 100644 index 00000000..57383f8d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cerveja.java @@ -0,0 +1,246 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.validation.constraints.DecimalMax; +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.Max; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +import org.hibernate.validator.constraints.NotBlank; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.validation.SKU; + +@Entity +@Table(name = "cerveja") +public class Cerveja implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + @SKU + @NotBlank(message = "SKU é obrigatório") + private String sku; + + @NotBlank(message = "Nome é obrigatório") + private String nome; + + @NotBlank(message = "A descrição é obrigatória") + @Size(max = 50, message = "O tamanho da descrição deve estar entre 1 e 50") + private String descricao; + + @NotNull(message = "Valor é obrigatório") + @DecimalMin(value = "0.50", message = "O valor da cerveja deve ser maior que R$0,50") + @DecimalMax(value = "9999999.99", message = "O valor da cerveja deve ser menor que R$9.999.999,99") + private BigDecimal valor; + + @NotNull(message = "O teor alcóolico é obrigatório") + @DecimalMax(value = "100.0", message = "O valor do teor alcóolico deve ser menor que 100") + @Column(name = "teor_alcoolico") + private BigDecimal teorAlcoolico; + + @NotNull(message = "A comissão é obrigatória") + @DecimalMax(value = "100.0", message = "A comissão deve ser igual ou menor que 100") + private BigDecimal comissao; + + @NotNull(message = "A quantidade em estoque é obrigatória") + @Max(value = 9999, message = "A quantidade em estoque deve ser menor que 9.999") + @Column(name = "quantidade_estoque") + private Integer quantidadeEstoque; + + @NotNull(message = "A origem é obrigatória") + @Enumerated(EnumType.STRING) + private Origem origem; + + @NotNull(message = "O sabor é obrigatório") + @Enumerated(EnumType.STRING) + private Sabor sabor; + + @NotNull(message = "O estilo é obrigatório") + @ManyToOne + @JoinColumn(name = "codigo_estilo") + private Estilo estilo; + + private String foto; + + @Column(name = "content_type") + private String contentType; + + @Transient + private boolean novaFoto; + + @PrePersist + @PreUpdate + private void prePersistUpdate() { + sku = sku.toUpperCase(); + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getDescricao() { + return descricao; + } + + public void setDescricao(String descricao) { + this.descricao = descricao; + } + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public BigDecimal getValor() { + return valor; + } + + public void setValor(BigDecimal valor) { + this.valor = valor; + } + + public BigDecimal getTeorAlcoolico() { + return teorAlcoolico; + } + + public void setTeorAlcoolico(BigDecimal teorAlcoolico) { + this.teorAlcoolico = teorAlcoolico; + } + + public BigDecimal getComissao() { + return comissao; + } + + public void setComissao(BigDecimal comissao) { + this.comissao = comissao; + } + + public Integer getQuantidadeEstoque() { + return quantidadeEstoque; + } + + public void setQuantidadeEstoque(Integer quantidadeEstoque) { + this.quantidadeEstoque = quantidadeEstoque; + } + + public Origem getOrigem() { + return origem; + } + + public void setOrigem(Origem origem) { + this.origem = origem; + } + + public Sabor getSabor() { + return sabor; + } + + public void setSabor(Sabor sabor) { + this.sabor = sabor; + } + + public Estilo getEstilo() { + return estilo; + } + + public void setEstilo(Estilo estilo) { + this.estilo = estilo; + } + + public String getFoto() { + return foto; + } + + public void setFoto(String foto) { + this.foto = foto; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public String getFotoOuMock() { + return !StringUtils.isEmpty(foto) ? foto : "cerveja-mock.png"; + } + + public boolean temFoto() { + return !StringUtils.isEmpty(this.foto); + } + + public boolean isNova() { + return codigo == null; + } + + public boolean isNovaFoto() { + return novaFoto; + } + + public void setNovaFoto(boolean novaFoto) { + this.novaFoto = novaFoto; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Cerveja other = (Cerveja) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cidade.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cidade.java new file mode 100644 index 00000000..3d00dc16 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cidade.java @@ -0,0 +1,95 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +import org.hibernate.validator.constraints.NotBlank; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@Entity +@Table(name = "cidade") +public class Cidade implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + @NotBlank(message = "Nome é obrigatório") + private String nome; + + @NotNull(message = "Estado é obrigatório") + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "codigo_estado") + @JsonIgnore + private Estado estado; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public Estado getEstado() { + return estado; + } + + public void setEstado(Estado estado) { + this.estado = estado; + } + + public boolean temEstado() { + return estado != null; + } + + public boolean isNova() { + return this.codigo == null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Cidade other = (Cidade) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cliente.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cliente.java new file mode 100644 index 00000000..7fd0fb12 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Cliente.java @@ -0,0 +1,163 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.PostLoad; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.validation.constraints.NotNull; + +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotBlank; +import org.hibernate.validator.constraints.br.CNPJ; +import org.hibernate.validator.constraints.br.CPF; +import org.hibernate.validator.group.GroupSequenceProvider; + +import com.algaworks.brewer.model.validation.ClienteGroupSequenceProvider; +import com.algaworks.brewer.model.validation.group.CnpjGroup; +import com.algaworks.brewer.model.validation.group.CpfGroup; +import com.fasterxml.jackson.annotation.JsonIgnore; + +@Entity +@Table(name = "cliente") +@GroupSequenceProvider(ClienteGroupSequenceProvider.class) +public class Cliente implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + @NotBlank(message = "Nome é obrigatório") + private String nome; + + @NotNull(message = "Tipo pessoa é obrigatório") + @Enumerated(EnumType.STRING) + @Column(name = "tipo_pessoa") + private TipoPessoa tipoPessoa; + + @NotBlank(message = "CPF/CNPJ é obrigatório") + @CPF(groups = CpfGroup.class) + @CNPJ(groups = CnpjGroup.class) + @Column(name = "cpf_cnpj") + private String cpfOuCnpj; + + private String telefone; + + @Email(message = "E-mail inválido") + private String email; + + @JsonIgnore + @Embedded + private Endereco endereco; + + @PrePersist @PreUpdate + private void prePersistPreUpdate() { + this.cpfOuCnpj = TipoPessoa.removerFormatacao(this.cpfOuCnpj); + } + + @PostLoad + private void postLoad() { + this.cpfOuCnpj = this.tipoPessoa.formatar(this.cpfOuCnpj); + } + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public TipoPessoa getTipoPessoa() { + return tipoPessoa; + } + + public void setTipoPessoa(TipoPessoa tipoPessoa) { + this.tipoPessoa = tipoPessoa; + } + + public String getCpfOuCnpj() { + return cpfOuCnpj; + } + + public void setCpfOuCnpj(String cpfOuCnpj) { + this.cpfOuCnpj = cpfOuCnpj; + } + + public String getTelefone() { + return telefone; + } + + public void setTelefone(String telefone) { + this.telefone = telefone; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public Endereco getEndereco() { + return endereco; + } + + public void setEndereco(Endereco endereco) { + this.endereco = endereco; + } + + public String getCpfOuCnpjSemFormatacao() { + return TipoPessoa.removerFormatacao(this.cpfOuCnpj); + } + + public boolean isNovo() { + return this.codigo == null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Cliente other = (Cliente) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Endereco.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Endereco.java new file mode 100644 index 00000000..8b6f21d8 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Endereco.java @@ -0,0 +1,86 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; + +import javax.persistence.Embeddable; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Transient; + +@Embeddable +public class Endereco implements Serializable { + + private static final long serialVersionUID = 1L; + + private String logradouro; + + private String numero; + + private String complemento; + + private String cep; + + @ManyToOne + @JoinColumn(name = "codigo_cidade") + private Cidade cidade; + + @Transient + private Estado estado; + + public String getLogradouro() { + return logradouro; + } + + public void setLogradouro(String logradouro) { + this.logradouro = logradouro; + } + + public String getNumero() { + return numero; + } + + public void setNumero(String numero) { + this.numero = numero; + } + + public String getComplemento() { + return complemento; + } + + public void setComplemento(String complemento) { + this.complemento = complemento; + } + + public String getCep() { + return cep; + } + + public void setCep(String cep) { + this.cep = cep; + } + + public Cidade getCidade() { + return cidade; + } + + public void setCidade(Cidade cidade) { + this.cidade = cidade; + } + + public Estado getEstado() { + return estado; + } + + public void setEstado(Estado estado) { + this.estado = estado; + } + + public String getNomeCidadeSiglaEstado() { + if (this.cidade != null) { + return this.cidade.getNome() + "/" + this.cidade.getEstado().getSigla(); + } + + return null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estado.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estado.java new file mode 100644 index 00000000..be8ba5d7 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estado.java @@ -0,0 +1,72 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "estado") +public class Estado implements Serializable { + + private static final long serialVersionUID = 1L; + + private Long codigo; + private String nome; + private String sigla; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getSigla() { + return sigla; + } + + public void setSigla(String sigla) { + this.sigla = sigla; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Estado other = (Estado) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estilo.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estilo.java new file mode 100644 index 00000000..349a53ea --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Estilo.java @@ -0,0 +1,78 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.validation.constraints.Size; + +import org.hibernate.validator.constraints.NotBlank; + +@Entity +@Table(name = "estilo") +public class Estilo implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + @NotBlank(message = "O nome é obrigatório") + @Size(max = 20, message = "O tamanho do nome não pode ser maior que {max} caracteres") + private String nome; + + @OneToMany(mappedBy = "estilo") + private List cervejas; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public boolean isNovo() { + return this.codigo == null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Estilo other = (Estilo) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Grupo.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Grupo.java new file mode 100644 index 00000000..6583fe5b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Grupo.java @@ -0,0 +1,80 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "grupo") +public class Grupo implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + private String nome; + + @ManyToMany + @JoinTable(name = "grupo_permissao", joinColumns = @JoinColumn(name = "codigo_grupo"), inverseJoinColumns = @JoinColumn(name = "codigo_permissao")) + private List permissoes; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public List getPermissoes() { + return permissoes; + } + + public void setPermissoes(List permissoes) { + this.permissoes = permissoes; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Grupo other = (Grupo) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/ItemVenda.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/ItemVenda.java new file mode 100644 index 00000000..c9091c55 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/ItemVenda.java @@ -0,0 +1,104 @@ +package com.algaworks.brewer.model; + +import java.math.BigDecimal; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "item_venda") +public class ItemVenda { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + private Integer quantidade; + + @Column(name = "valor_unitario") + private BigDecimal valorUnitario; + + @ManyToOne + @JoinColumn(name = "codigo_cerveja") + private Cerveja cerveja; + + @ManyToOne + @JoinColumn(name = "codigo_venda") + private Venda venda; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public Integer getQuantidade() { + return quantidade; + } + + public void setQuantidade(Integer quantidade) { + this.quantidade = quantidade; + } + + public BigDecimal getValorUnitario() { + return valorUnitario; + } + + public void setValorUnitario(BigDecimal valorUnitario) { + this.valorUnitario = valorUnitario; + } + + public Cerveja getCerveja() { + return cerveja; + } + + public void setCerveja(Cerveja cerveja) { + this.cerveja = cerveja; + } + + public BigDecimal getValorTotal() { + return valorUnitario.multiply(new BigDecimal(quantidade)); + } + + public Venda getVenda() { + return venda; + } + + public void setVenda(Venda venda) { + this.venda = venda; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ItemVenda other = (ItemVenda) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Origem.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Origem.java new file mode 100644 index 00000000..9a582f27 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Origem.java @@ -0,0 +1,18 @@ +package com.algaworks.brewer.model; + +public enum Origem { + + NACIONAL("Nacional"), + INTERNACIONAL("Internacional"); + + private String descricao; + + Origem(String descricao) { + this.descricao = descricao; + } + + public String getDescricao() { + return descricao; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Permissao.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Permissao.java new file mode 100644 index 00000000..fdb94d4c --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Permissao.java @@ -0,0 +1,64 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "permissao") +public class Permissao implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + private String nome; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Permissao other = (Permissao) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Sabor.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Sabor.java new file mode 100644 index 00000000..1ff02623 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Sabor.java @@ -0,0 +1,21 @@ +package com.algaworks.brewer.model; + +public enum Sabor { + + ADOCICADA("Adocicada"), + AMARGA("Amarga"), + FORTE("Forte"), + FRUTADA("Frutada"), + SUAVE("Suave"); + + private String descricao; + + Sabor(String descricao) { + this.descricao = descricao; + } + + public String getDescricao() { + return descricao; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/StatusVenda.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/StatusVenda.java new file mode 100644 index 00000000..8d074504 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/StatusVenda.java @@ -0,0 +1,19 @@ +package com.algaworks.brewer.model; + +public enum StatusVenda { + + ORCAMENTO("Orçamento"), + EMITIDA("Emitida"), + CANCELADA("Cancelada"); + + private String descricao; + + StatusVenda(String descricao) { + this.descricao = descricao; + } + + public String getDescricao() { + return descricao; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/TipoPessoa.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/TipoPessoa.java new file mode 100644 index 00000000..248d2d23 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/TipoPessoa.java @@ -0,0 +1,56 @@ +package com.algaworks.brewer.model; + +import com.algaworks.brewer.model.validation.group.CnpjGroup; +import com.algaworks.brewer.model.validation.group.CpfGroup; + +public enum TipoPessoa { + + FISICA("Física", "CPF", "000.000.000-00", CpfGroup.class) { + @Override + public String formatar(String cpfOuCnpj) { + return cpfOuCnpj.replaceAll("(\\d{3})(\\d{3})(\\d{3})", "$1.$2.$3-"); + } + }, + + JURIDICA("Jurídica", "CNPJ", "00.000.000/0000-00", CnpjGroup.class) { + @Override + public String formatar(String cpfOuCnpj) { + return cpfOuCnpj.replaceAll("(\\d{2})(\\d{3})(\\d{3})(\\d{4})", "$1.$2.$3/$4-"); + } + }; + + private String descricao; + private String documento; + private String mascara; + private Class grupo; + + TipoPessoa(String descricao, String documento, String mascara, Class grupo) { + this.descricao = descricao; + this.documento = documento; + this.mascara = mascara; + this.grupo = grupo; + } + + public abstract String formatar(String cpfOuCnpj); + + public String getDescricao() { + return descricao; + } + + public String getDocumento() { + return documento; + } + + public String getMascara() { + return mascara; + } + + public Class getGrupo() { + return grupo; + } + + public static String removerFormatacao(String cpfOuCnpj) { + return cpfOuCnpj.replaceAll("\\.|-|/", ""); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Usuario.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Usuario.java new file mode 100644 index 00000000..cb0da53b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Usuario.java @@ -0,0 +1,160 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; +import java.time.LocalDate; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.validation.constraints.Size; + +import org.hibernate.annotations.DynamicUpdate; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotBlank; + +import com.algaworks.brewer.validation.AtributoConfirmacao; + +@AtributoConfirmacao(atributo = "senha", atributoConfirmacao = "confirmacaoSenha" + , message = "Confirmação da senha não confere") +@Entity +@Table(name = "usuario") +@DynamicUpdate +public class Usuario implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + @NotBlank(message = "Nome é obrigatório") + private String nome; + + @NotBlank(message = "E-mail é obrigatório") + @Email(message = "E-mail inválido") + private String email; + + private String senha; + + @Transient + private String confirmacaoSenha; + + private Boolean ativo; + + @Size(min = 1, message = "Selecione pelo menos um grupo") + @ManyToMany + @JoinTable(name = "usuario_grupo", joinColumns = @JoinColumn(name = "codigo_usuario") + , inverseJoinColumns = @JoinColumn(name = "codigo_grupo")) + private List grupos; + + @Column(name = "data_nascimento") + private LocalDate dataNascimento; + + @PreUpdate + private void preUpdate() { + this.confirmacaoSenha = senha; + } + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getSenha() { + return senha; + } + + public void setSenha(String senha) { + this.senha = senha; + } + + public Boolean getAtivo() { + return ativo; + } + + public void setAtivo(Boolean ativo) { + this.ativo = ativo; + } + + public LocalDate getDataNascimento() { + return dataNascimento; + } + + public void setDataNascimento(LocalDate dataNascimento) { + this.dataNascimento = dataNascimento; + } + + public List getGrupos() { + return grupos; + } + + public void setGrupos(List grupos) { + this.grupos = grupos; + } + + public String getConfirmacaoSenha() { + return confirmacaoSenha; + } + + public void setConfirmacaoSenha(String confirmacaoSenha) { + this.confirmacaoSenha = confirmacaoSenha; + } + + public boolean isNovo() { + return codigo == null; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Usuario other = (Usuario) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupo.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupo.java new file mode 100644 index 00000000..ac6b12f5 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupo.java @@ -0,0 +1,47 @@ +package com.algaworks.brewer.model; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name = "usuario_grupo") +public class UsuarioGrupo { + + @EmbeddedId + private UsuarioGrupoId id; + + public UsuarioGrupoId getId() { + return id; + } + + public void setId(UsuarioGrupoId id) { + this.id = id; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UsuarioGrupo other = (UsuarioGrupo) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupoId.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupoId.java new file mode 100644 index 00000000..b7a33a5d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/UsuarioGrupoId.java @@ -0,0 +1,69 @@ +package com.algaworks.brewer.model; + +import java.io.Serializable; + +import javax.persistence.Embeddable; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Embeddable +public class UsuarioGrupoId implements Serializable { + + private static final long serialVersionUID = 1L; + + @ManyToOne + @JoinColumn(name = "codigo_usuario") + private Usuario usuario; + + @ManyToOne + @JoinColumn(name = "codigo_grupo") + private Grupo grupo; + + public Usuario getUsuario() { + return usuario; + } + + public void setUsuario(Usuario usuario) { + this.usuario = usuario; + } + + public Grupo getGrupo() { + return grupo; + } + + public void setGrupo(Grupo grupo) { + this.grupo = grupo; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((grupo == null) ? 0 : grupo.hashCode()); + result = prime * result + ((usuario == null) ? 0 : usuario.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UsuarioGrupoId other = (UsuarioGrupoId) obj; + if (grupo == null) { + if (other.grupo != null) + return false; + } else if (!grupo.equals(other.grupo)) + return false; + if (usuario == null) { + if (other.usuario != null) + return false; + } else if (!usuario.equals(other.usuario)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Venda.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Venda.java new file mode 100644 index 00000000..8f71eb72 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/Venda.java @@ -0,0 +1,254 @@ +package com.algaworks.brewer.model; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.persistence.Transient; + +import org.hibernate.annotations.DynamicUpdate; + +@Entity +@Table(name = "venda") +@DynamicUpdate +public class Venda { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long codigo; + + @Column(name = "data_criacao") + private LocalDateTime dataCriacao; + + @Column(name = "valor_frete") + private BigDecimal valorFrete; + + @Column(name = "valor_desconto") + private BigDecimal valorDesconto; + + @Column(name = "valor_total") + private BigDecimal valorTotal = BigDecimal.ZERO; + + private String observacao; + + @Column(name = "data_hora_entrega") + private LocalDateTime dataHoraEntrega; + + @ManyToOne + @JoinColumn(name = "codigo_cliente") + private Cliente cliente; + + @ManyToOne + @JoinColumn(name = "codigo_usuario") + private Usuario usuario; + + @Enumerated(EnumType.STRING) + private StatusVenda status = StatusVenda.ORCAMENTO; + + @OneToMany(mappedBy = "venda", cascade = CascadeType.ALL, orphanRemoval = true) + private List itens = new ArrayList<>(); + + @Transient + private String uuid; + + @Transient + private LocalDate dataEntrega; + + @Transient + private LocalTime horarioEntrega; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public LocalDateTime getDataCriacao() { + return dataCriacao; + } + + public void setDataCriacao(LocalDateTime dataCriacao) { + this.dataCriacao = dataCriacao; + } + + public BigDecimal getValorFrete() { + return valorFrete; + } + + public void setValorFrete(BigDecimal valorFrete) { + this.valorFrete = valorFrete; + } + + public BigDecimal getValorDesconto() { + return valorDesconto; + } + + public void setValorDesconto(BigDecimal valorDesconto) { + this.valorDesconto = valorDesconto; + } + + public BigDecimal getValorTotal() { + return valorTotal; + } + + public void setValorTotal(BigDecimal valorTotal) { + this.valorTotal = valorTotal; + } + + public String getObservacao() { + return observacao; + } + + public void setObservacao(String observacao) { + this.observacao = observacao; + } + + public LocalDateTime getDataHoraEntrega() { + return dataHoraEntrega; + } + + public void setDataHoraEntrega(LocalDateTime dataHoraEntrega) { + this.dataHoraEntrega = dataHoraEntrega; + } + + public Cliente getCliente() { + return cliente; + } + + public void setCliente(Cliente cliente) { + this.cliente = cliente; + } + + public Usuario getUsuario() { + return usuario; + } + + public void setUsuario(Usuario usuario) { + this.usuario = usuario; + } + + public StatusVenda getStatus() { + return status; + } + + public void setStatus(StatusVenda status) { + this.status = status; + } + + public List getItens() { + return itens; + } + + public void setItens(List itens) { + this.itens = itens; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public LocalDate getDataEntrega() { + return dataEntrega; + } + + public void setDataEntrega(LocalDate dataEntrega) { + this.dataEntrega = dataEntrega; + } + + public LocalTime getHorarioEntrega() { + return horarioEntrega; + } + + public void setHorarioEntrega(LocalTime horarioEntrega) { + this.horarioEntrega = horarioEntrega; + } + + public boolean isNova() { + return codigo == null; + } + + public void adicionarItens(List itens) { + this.itens = itens; + this.itens.forEach(i -> i.setVenda(this)); + } + + public BigDecimal getValorTotalItens() { + return getItens().stream() + .map(ItemVenda::getValorTotal) + .reduce(BigDecimal::add) + .orElse(BigDecimal.ZERO); + } + + public void calcularValorTotal() { + this.valorTotal = calcularValorTotal(getValorTotalItens(), getValorFrete(), getValorDesconto()); + } + + public Long getDiasCriacao() { + LocalDate inicio = dataCriacao != null ? dataCriacao.toLocalDate() : LocalDate.now(); + return ChronoUnit.DAYS.between(inicio, LocalDate.now()); + } + + public boolean isSalvarPermitido() { + return !status.equals(StatusVenda.CANCELADA); + } + + public boolean isSalvarProibido() { + return !isSalvarPermitido(); + } + + private BigDecimal calcularValorTotal(BigDecimal valorTotalItens, BigDecimal valorFrete, BigDecimal valorDesconto) { + BigDecimal valorTotal = valorTotalItens + .add(Optional.ofNullable(valorFrete).orElse(BigDecimal.ZERO)) + .subtract(Optional.ofNullable(valorDesconto).orElse(BigDecimal.ZERO)); + return valorTotal; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Venda other = (Venda) obj; + if (codigo == null) { + if (other.codigo != null) + return false; + } else if (!codigo.equals(other.codigo)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/ClienteGroupSequenceProvider.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/ClienteGroupSequenceProvider.java new file mode 100644 index 00000000..87380f69 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/ClienteGroupSequenceProvider.java @@ -0,0 +1,28 @@ +package com.algaworks.brewer.model.validation; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider; + +import com.algaworks.brewer.model.Cliente; + +public class ClienteGroupSequenceProvider implements DefaultGroupSequenceProvider { + + @Override + public List> getValidationGroups(Cliente cliente) { + List> grupos = new ArrayList<>(); + grupos.add(Cliente.class); + + if (isPessoaSelecionada(cliente)) { + grupos.add(cliente.getTipoPessoa().getGrupo()); + } + + return grupos; + } + + private boolean isPessoaSelecionada(Cliente cliente) { + return cliente != null && cliente.getTipoPessoa() != null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CnpjGroup.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CnpjGroup.java new file mode 100644 index 00000000..1fcadb6f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CnpjGroup.java @@ -0,0 +1,5 @@ +package com.algaworks.brewer.model.validation.group; + +public interface CnpjGroup { + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CpfGroup.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CpfGroup.java new file mode 100644 index 00000000..d40f7c83 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/model/validation/group/CpfGroup.java @@ -0,0 +1,5 @@ +package com.algaworks.brewer.model.validation.group; + +public interface CpfGroup { + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cervejas.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cervejas.java new file mode 100644 index 00000000..437dc775 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cervejas.java @@ -0,0 +1,12 @@ +package com.algaworks.brewer.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.repository.helper.cerveja.CervejasQueries; + +@Repository +public interface Cervejas extends JpaRepository, CervejasQueries { + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cidades.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cidades.java new file mode 100644 index 00000000..8515bcfa --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Cidades.java @@ -0,0 +1,22 @@ +package com.algaworks.brewer.repository; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import com.algaworks.brewer.model.Cidade; +import com.algaworks.brewer.model.Estado; +import com.algaworks.brewer.repository.helper.cidade.CidadesQueries; + +public interface Cidades extends JpaRepository, CidadesQueries { + + public List findByEstadoCodigo(Long codigoEstado); + + public Optional findByNomeAndEstado(String nome, Estado estado); + + @Query("select c from Cidade c join fetch c.estado where c.codigo = :codigo") + public Cidade findByCodigoFetchingEstado(@Param("codigo") Long codigo); +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Clientes.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Clientes.java new file mode 100644 index 00000000..1bbb6d09 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Clientes.java @@ -0,0 +1,17 @@ +package com.algaworks.brewer.repository; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.algaworks.brewer.model.Cliente; +import com.algaworks.brewer.repository.helper.cliente.ClientesQueries; + +public interface Clientes extends JpaRepository, ClientesQueries { + + public Optional findByCpfOuCnpj(String cpfOuCnpj); + + public List findByNomeStartingWithIgnoreCase(String nome); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estados.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estados.java new file mode 100644 index 00000000..ce9fa3ef --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estados.java @@ -0,0 +1,9 @@ +package com.algaworks.brewer.repository; + +import com.algaworks.brewer.model.Estado; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface Estados extends JpaRepository { + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estilos.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estilos.java new file mode 100644 index 00000000..a342c525 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Estilos.java @@ -0,0 +1,16 @@ +package com.algaworks.brewer.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.algaworks.brewer.model.Estilo; +import com.algaworks.brewer.repository.helper.estilo.EstilosQueries; + +@Repository +public interface Estilos extends JpaRepository, EstilosQueries { + + public Optional findByNomeIgnoreCase(String nome); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Grupos.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Grupos.java new file mode 100644 index 00000000..fa1e5a47 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Grupos.java @@ -0,0 +1,9 @@ +package com.algaworks.brewer.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.algaworks.brewer.model.Grupo; + +public interface Grupos extends JpaRepository { + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Usuarios.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Usuarios.java new file mode 100644 index 00000000..c9969b57 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Usuarios.java @@ -0,0 +1,17 @@ +package com.algaworks.brewer.repository; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.algaworks.brewer.model.Usuario; +import com.algaworks.brewer.repository.helper.usuario.UsuariosQueries; + +public interface Usuarios extends JpaRepository, UsuariosQueries { + + public Optional findByEmail(String email); + + public List findByCodigoIn(Long[] codigos); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Vendas.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Vendas.java new file mode 100644 index 00000000..ddb36b6f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/Vendas.java @@ -0,0 +1,10 @@ +package com.algaworks.brewer.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.algaworks.brewer.model.Venda; +import com.algaworks.brewer.repository.helper.venda.VendasQueries; + +public interface Vendas extends JpaRepository, VendasQueries { + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CervejaFilter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CervejaFilter.java new file mode 100644 index 00000000..43a18e6e --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CervejaFilter.java @@ -0,0 +1,75 @@ +package com.algaworks.brewer.repository.filter; + +import java.math.BigDecimal; + +import com.algaworks.brewer.model.Estilo; +import com.algaworks.brewer.model.Origem; +import com.algaworks.brewer.model.Sabor; + +public class CervejaFilter { + + private String sku; + private String nome; + private Estilo estilo; + private Sabor sabor; + private Origem origem; + private BigDecimal valorDe; + private BigDecimal valorAte; + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public Estilo getEstilo() { + return estilo; + } + + public void setEstilo(Estilo estilo) { + this.estilo = estilo; + } + + public Sabor getSabor() { + return sabor; + } + + public void setSabor(Sabor sabor) { + this.sabor = sabor; + } + + public Origem getOrigem() { + return origem; + } + + public void setOrigem(Origem origem) { + this.origem = origem; + } + + public BigDecimal getValorDe() { + return valorDe; + } + + public void setValorDe(BigDecimal valorDe) { + this.valorDe = valorDe; + } + + public BigDecimal getValorAte() { + return valorAte; + } + + public void setValorAte(BigDecimal valorAte) { + this.valorAte = valorAte; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CidadeFilter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CidadeFilter.java new file mode 100644 index 00000000..d8aff60f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/CidadeFilter.java @@ -0,0 +1,26 @@ +package com.algaworks.brewer.repository.filter; + +import com.algaworks.brewer.model.Estado; + +public class CidadeFilter { + + private Estado estado; + private String nome; + + public Estado getEstado() { + return estado; + } + + public void setEstado(Estado estado) { + this.estado = estado; + } + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/ClienteFilter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/ClienteFilter.java new file mode 100644 index 00000000..7ba55d7f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/ClienteFilter.java @@ -0,0 +1,30 @@ +package com.algaworks.brewer.repository.filter; + +import com.algaworks.brewer.model.TipoPessoa; + +public class ClienteFilter { + + private String nome; + private String cpfOuCnpj; + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getCpfOuCnpj() { + return cpfOuCnpj; + } + + public void setCpfOuCnpj(String cpfOuCnpj) { + this.cpfOuCnpj = cpfOuCnpj; + } + + public Object getCpfOuCnpjSemFormatacao() { + return TipoPessoa.removerFormatacao(this.cpfOuCnpj); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/EstiloFilter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/EstiloFilter.java new file mode 100644 index 00000000..fae7d1a5 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/EstiloFilter.java @@ -0,0 +1,15 @@ +package com.algaworks.brewer.repository.filter; + +public class EstiloFilter { + + private String nome; + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/UsuarioFilter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/UsuarioFilter.java new file mode 100644 index 00000000..756c28ea --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/UsuarioFilter.java @@ -0,0 +1,37 @@ +package com.algaworks.brewer.repository.filter; + +import java.util.List; + +import com.algaworks.brewer.model.Grupo; + +public class UsuarioFilter { + + private String nome; + private String email; + private List grupos; + + public String getNome() { + return nome; + } + + public void setNome(String nome) { + this.nome = nome; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public List getGrupos() { + return grupos; + } + + public void setGrupos(List grupos) { + this.grupos = grupos; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/VendaFilter.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/VendaFilter.java new file mode 100644 index 00000000..59b476fc --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/filter/VendaFilter.java @@ -0,0 +1,85 @@ +package com.algaworks.brewer.repository.filter; + +import java.math.BigDecimal; +import java.time.LocalDate; + +import com.algaworks.brewer.model.StatusVenda; + +public class VendaFilter { + + private Long codigo; + private StatusVenda status; + + private LocalDate desde; + private LocalDate ate; + private BigDecimal valorMinimo; + private BigDecimal valorMaximo; + + private String nomeCliente; + private String cpfOuCnpjCliente; + + public Long getCodigo() { + return codigo; + } + + public void setCodigo(Long codigo) { + this.codigo = codigo; + } + + public StatusVenda getStatus() { + return status; + } + + public void setStatus(StatusVenda status) { + this.status = status; + } + + public LocalDate getDesde() { + return desde; + } + + public void setDesde(LocalDate desde) { + this.desde = desde; + } + + public LocalDate getAte() { + return ate; + } + + public void setAte(LocalDate ate) { + this.ate = ate; + } + + public BigDecimal getValorMinimo() { + return valorMinimo; + } + + public void setValorMinimo(BigDecimal valorMinimo) { + this.valorMinimo = valorMinimo; + } + + public BigDecimal getValorMaximo() { + return valorMaximo; + } + + public void setValorMaximo(BigDecimal valorMaximo) { + this.valorMaximo = valorMaximo; + } + + public String getNomeCliente() { + return nomeCliente; + } + + public void setNomeCliente(String nomeCliente) { + this.nomeCliente = nomeCliente; + } + + public String getCpfOuCnpjCliente() { + return cpfOuCnpjCliente; + } + + public void setCpfOuCnpjCliente(String cpfOuCnpjCliente) { + this.cpfOuCnpjCliente = cpfOuCnpjCliente; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasImpl.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasImpl.java new file mode 100644 index 00000000..173701d6 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasImpl.java @@ -0,0 +1,98 @@ +package com.algaworks.brewer.repository.helper.cerveja; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.dto.CervejaDTO; +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.repository.filter.CervejaFilter; +import com.algaworks.brewer.repository.paginacao.PaginacaoUtil; + +public class CervejasImpl implements CervejasQueries { + + @PersistenceContext + private EntityManager manager; + + @Autowired + private PaginacaoUtil paginacaoUtil; + + @SuppressWarnings("unchecked") + @Override + @Transactional(readOnly = true) + public Page filtrar(CervejaFilter filtro, Pageable pageable) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Cerveja.class); + + paginacaoUtil.preparar(criteria, pageable); + adicionarFiltro(filtro, criteria); + + return new PageImpl<>(criteria.list(), pageable, total(filtro)); + } + + private Long total(CervejaFilter filtro) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Cerveja.class); + adicionarFiltro(filtro, criteria); + criteria.setProjection(Projections.rowCount()); + return (Long) criteria.uniqueResult(); + } + + private void adicionarFiltro(CervejaFilter filtro, Criteria criteria) { + if (filtro != null) { + if (!StringUtils.isEmpty(filtro.getSku())) { + criteria.add(Restrictions.eq("sku", filtro.getSku())); + } + + if (!StringUtils.isEmpty(filtro.getNome())) { + criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE)); + } + + if (isEstiloPresente(filtro)) { + criteria.add(Restrictions.eq("estilo", filtro.getEstilo())); + } + + if (filtro.getSabor() != null) { + criteria.add(Restrictions.eq("sabor", filtro.getSabor())); + } + + if (filtro.getOrigem() != null) { + criteria.add(Restrictions.eq("origem", filtro.getOrigem())); + } + + if (filtro.getValorDe() != null) { + criteria.add(Restrictions.ge("valor", filtro.getValorDe())); + } + + if (filtro.getValorAte() != null) { + criteria.add(Restrictions.le("valor", filtro.getValorAte())); + } + } + } + + private boolean isEstiloPresente(CervejaFilter filtro) { + return filtro.getEstilo() != null && filtro.getEstilo().getCodigo() != null; + } + + @Override + public List porSkuOuNome(String skuOuNome) { + String jpql = "select new com.algaworks.brewer.dto.CervejaDTO(codigo, sku, nome, origem, valor, foto) " + + "from Cerveja where lower(sku) like lower(:skuOuNome) or lower(nome) like lower(:skuOuNome)"; + List cervejasFiltradas = manager.createQuery(jpql, CervejaDTO.class) + .setParameter("skuOuNome", skuOuNome + "%") + .getResultList(); + return cervejasFiltradas; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasQueries.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasQueries.java new file mode 100644 index 00000000..9e516340 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cerveja/CervejasQueries.java @@ -0,0 +1,18 @@ +package com.algaworks.brewer.repository.helper.cerveja; + +import java.util.List; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.algaworks.brewer.dto.CervejaDTO; +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.repository.filter.CervejaFilter; + +public interface CervejasQueries { + + public Page filtrar(CervejaFilter filtro, Pageable pageable); + + public List porSkuOuNome(String skuOuNome); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesImpl.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesImpl.java new file mode 100644 index 00000000..81342b6d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesImpl.java @@ -0,0 +1,62 @@ +package com.algaworks.brewer.repository.helper.cidade; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Cidade; +import com.algaworks.brewer.repository.filter.CidadeFilter; +import com.algaworks.brewer.repository.paginacao.PaginacaoUtil; + +public class CidadesImpl implements CidadesQueries { + + @PersistenceContext + private EntityManager manager; + + @Autowired + private PaginacaoUtil paginacaoUtil; + + @SuppressWarnings("unchecked") + @Override + @Transactional(readOnly = true) + public Page filtrar(CidadeFilter filtro, Pageable pageable) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Cidade.class); + + paginacaoUtil.preparar(criteria, pageable); + adicionarFiltro(filtro, criteria); + criteria.createAlias("estado", "e"); + + return new PageImpl<>(criteria.list(), pageable, total(filtro)); + } + + private Long total(CidadeFilter filtro) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Cidade.class); + adicionarFiltro(filtro, criteria); + criteria.setProjection(Projections.rowCount()); + return (Long) criteria.uniqueResult(); + } + + private void adicionarFiltro(CidadeFilter filtro, Criteria criteria) { + if (filtro != null) { + if (filtro.getEstado() != null) { + criteria.add(Restrictions.eq("estado", filtro.getEstado())); + } + + if (!StringUtils.isEmpty(filtro.getNome())) { + criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE)); + } + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesQueries.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesQueries.java new file mode 100644 index 00000000..422f79d1 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cidade/CidadesQueries.java @@ -0,0 +1,13 @@ +package com.algaworks.brewer.repository.helper.cidade; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.algaworks.brewer.model.Cidade; +import com.algaworks.brewer.repository.filter.CidadeFilter; + +public interface CidadesQueries { + + public Page filtrar(CidadeFilter filtro, Pageable pageable); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesImpl.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesImpl.java new file mode 100644 index 00000000..24f42536 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesImpl.java @@ -0,0 +1,64 @@ +package com.algaworks.brewer.repository.helper.cliente; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.hibernate.sql.JoinType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Cliente; +import com.algaworks.brewer.repository.filter.ClienteFilter; +import com.algaworks.brewer.repository.paginacao.PaginacaoUtil; + +public class ClientesImpl implements ClientesQueries { + + @PersistenceContext + private EntityManager manager; + + @Autowired + private PaginacaoUtil paginacaoUtil; + + @SuppressWarnings("unchecked") + @Override + @Transactional(readOnly = true) + public Page filtrar(ClienteFilter filtro, Pageable pageable) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Cliente.class); + + paginacaoUtil.preparar(criteria, pageable); + adicionarFiltro(filtro, criteria); + criteria.createAlias("endereco.cidade", "c", JoinType.LEFT_OUTER_JOIN); + criteria.createAlias("c.estado", "e", JoinType.LEFT_OUTER_JOIN); + + return new PageImpl<>(criteria.list(), pageable, total(filtro)); + } + + private Long total(ClienteFilter filtro) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Cliente.class); + adicionarFiltro(filtro, criteria); + criteria.setProjection(Projections.rowCount()); + return (Long) criteria.uniqueResult(); + } + + private void adicionarFiltro(ClienteFilter filtro, Criteria criteria) { + if (filtro != null) { + if (!StringUtils.isEmpty(filtro.getNome())) { + criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE)); + } + + if (!StringUtils.isEmpty(filtro.getCpfOuCnpj())) { + criteria.add(Restrictions.eq("cpfOuCnpj", filtro.getCpfOuCnpjSemFormatacao())); + } + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesQueries.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesQueries.java new file mode 100644 index 00000000..dcd84d69 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/cliente/ClientesQueries.java @@ -0,0 +1,13 @@ +package com.algaworks.brewer.repository.helper.cliente; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.algaworks.brewer.model.Cliente; +import com.algaworks.brewer.repository.filter.ClienteFilter; + +public interface ClientesQueries { + + public Page filtrar(ClienteFilter filtro, Pageable pageable); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosImpl.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosImpl.java new file mode 100644 index 00000000..e4095372 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosImpl.java @@ -0,0 +1,57 @@ +package com.algaworks.brewer.repository.helper.estilo; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Estilo; +import com.algaworks.brewer.repository.filter.EstiloFilter; +import com.algaworks.brewer.repository.paginacao.PaginacaoUtil; + +public class EstilosImpl implements EstilosQueries { + + @PersistenceContext + private EntityManager manager; + + @Autowired + private PaginacaoUtil paginacaoUtil; + + @SuppressWarnings("unchecked") + @Override + @Transactional(readOnly = true) + public Page filtrar(EstiloFilter filtro, Pageable pageable) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Estilo.class); + + paginacaoUtil.preparar(criteria, pageable); + adicionarFiltro(filtro, criteria); + + return new PageImpl<>(criteria.list(), pageable, total(filtro)); + } + + private Long total(EstiloFilter filtro) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Estilo.class); + adicionarFiltro(filtro, criteria); + criteria.setProjection(Projections.rowCount()); + return (Long) criteria.uniqueResult(); + } + + private void adicionarFiltro(EstiloFilter filtro, Criteria criteria) { + if (filtro != null) { + if (!StringUtils.isEmpty(filtro.getNome())) { + criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE)); + } + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosQueries.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosQueries.java new file mode 100644 index 00000000..929a701f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/estilo/EstilosQueries.java @@ -0,0 +1,13 @@ +package com.algaworks.brewer.repository.helper.estilo; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.algaworks.brewer.model.Estilo; +import com.algaworks.brewer.repository.filter.EstiloFilter; + +public interface EstilosQueries { + + public Page filtrar(EstiloFilter filtro, Pageable pageable); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosImpl.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosImpl.java new file mode 100644 index 00000000..ce0ee01b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosImpl.java @@ -0,0 +1,113 @@ +package com.algaworks.brewer.repository.helper.usuario; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.hibernate.Criteria; +import org.hibernate.Hibernate; +import org.hibernate.Session; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.DetachedCriteria; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.hibernate.criterion.Subqueries; +import org.hibernate.sql.JoinType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Grupo; +import com.algaworks.brewer.model.Usuario; +import com.algaworks.brewer.model.UsuarioGrupo; +import com.algaworks.brewer.repository.filter.UsuarioFilter; +import com.algaworks.brewer.repository.paginacao.PaginacaoUtil; + +public class UsuariosImpl implements UsuariosQueries { + + @PersistenceContext + private EntityManager manager; + + @Autowired + private PaginacaoUtil paginacaoUtil; + + @Override + public Optional porEmailEAtivo(String email) { + return manager + .createQuery("from Usuario where lower(email) = lower(:email) and ativo = true", Usuario.class) + .setParameter("email", email).getResultList().stream().findFirst(); + } + + @Override + public List permissoes(Usuario usuario) { + return manager.createQuery( + "select distinct p.nome from Usuario u inner join u.grupos g inner join g.permissoes p where u = :usuario", String.class) + .setParameter("usuario", usuario) + .getResultList(); + } + + @SuppressWarnings("unchecked") + @Transactional(readOnly = true) + @Override + public Page filtrar(UsuarioFilter filtro, Pageable pageable) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Usuario.class); + + paginacaoUtil.preparar(criteria, pageable); + adicionarFiltro(filtro, criteria); + + List filtrados = criteria.list(); + filtrados.forEach(u -> Hibernate.initialize(u.getGrupos())); + return new PageImpl<>(filtrados, pageable, total(filtro)); + } + + @Transactional(readOnly = true) + @Override + public Usuario buscarComGrupos(Long codigo) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Usuario.class); + criteria.createAlias("grupos", "g", JoinType.LEFT_OUTER_JOIN); + criteria.add(Restrictions.eq("codigo", codigo)); + criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + return (Usuario) criteria.uniqueResult(); + } + + private Long total(UsuarioFilter filtro) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Usuario.class); + adicionarFiltro(filtro, criteria); + criteria.setProjection(Projections.rowCount()); + return (Long) criteria.uniqueResult(); + } + + private void adicionarFiltro(UsuarioFilter filtro, Criteria criteria) { + if (filtro != null) { + if (!StringUtils.isEmpty(filtro.getNome())) { + criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE)); + } + + if (!StringUtils.isEmpty(filtro.getEmail())) { + criteria.add(Restrictions.ilike("email", filtro.getEmail(), MatchMode.START)); + } + + if (filtro.getGrupos() != null && !filtro.getGrupos().isEmpty()) { + List subqueries = new ArrayList<>(); + for (Long codigoGrupo : filtro.getGrupos().stream().mapToLong(Grupo::getCodigo).toArray()) { + DetachedCriteria dc = DetachedCriteria.forClass(UsuarioGrupo.class); + dc.add(Restrictions.eq("id.grupo.codigo", codigoGrupo)); + dc.setProjection(Projections.property("id.usuario")); + + subqueries.add(Subqueries.propertyIn("codigo", dc)); + } + + Criterion[] criterions = new Criterion[subqueries.size()]; + criteria.add(Restrictions.and(subqueries.toArray(criterions))); + } + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosQueries.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosQueries.java new file mode 100644 index 00000000..883e95d6 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/usuario/UsuariosQueries.java @@ -0,0 +1,22 @@ +package com.algaworks.brewer.repository.helper.usuario; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.algaworks.brewer.model.Usuario; +import com.algaworks.brewer.repository.filter.UsuarioFilter; + +public interface UsuariosQueries { + + public Optional porEmailEAtivo(String email); + + public List permissoes(Usuario usuario); + + public Page filtrar(UsuarioFilter filtro, Pageable pageable); + + public Usuario buscarComGrupos(Long codigo); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasImpl.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasImpl.java new file mode 100644 index 00000000..dd06f1e0 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasImpl.java @@ -0,0 +1,103 @@ +package com.algaworks.brewer.repository.helper.venda; + +import java.time.LocalDateTime; +import java.time.LocalTime; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.hibernate.sql.JoinType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.TipoPessoa; +import com.algaworks.brewer.model.Venda; +import com.algaworks.brewer.repository.filter.VendaFilter; +import com.algaworks.brewer.repository.paginacao.PaginacaoUtil; + +public class VendasImpl implements VendasQueries { + + @PersistenceContext + private EntityManager manager; + + @Autowired + private PaginacaoUtil paginacaoUtil; + + @SuppressWarnings("unchecked") + @Transactional(readOnly = true) + @Override + public Page filtrar(VendaFilter filtro, Pageable pageable) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Venda.class); + paginacaoUtil.preparar(criteria, pageable); + adicionarFiltro(filtro, criteria); + + return new PageImpl<>(criteria.list(), pageable, total(filtro)); + } + + @Transactional(readOnly = true) + @Override + public Venda buscarComItens(Long codigo) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Venda.class); + criteria.createAlias("itens", "i", JoinType.LEFT_OUTER_JOIN); + criteria.add(Restrictions.eq("codigo", codigo)); + criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + return (Venda) criteria.uniqueResult(); + } + + private Long total(VendaFilter filtro) { + Criteria criteria = manager.unwrap(Session.class).createCriteria(Venda.class); + adicionarFiltro(filtro, criteria); + criteria.setProjection(Projections.rowCount()); + return (Long) criteria.uniqueResult(); + } + + private void adicionarFiltro(VendaFilter filtro, Criteria criteria) { + criteria.createAlias("cliente", "c"); + + if (filtro != null) { + if (!StringUtils.isEmpty(filtro.getCodigo())) { + criteria.add(Restrictions.eq("codigo", filtro.getCodigo())); + } + + if (filtro.getStatus() != null) { + criteria.add(Restrictions.eq("status", filtro.getStatus())); + } + + if (filtro.getDesde() != null) { + LocalDateTime desde = LocalDateTime.of(filtro.getDesde(), LocalTime.of(0, 0)); + criteria.add(Restrictions.ge("dataCriacao", desde)); + } + + if (filtro.getAte() != null) { + LocalDateTime ate = LocalDateTime.of(filtro.getAte(), LocalTime.of(23, 59)); + criteria.add(Restrictions.le("dataCriacao", ate)); + } + + if (filtro.getValorMinimo() != null) { + criteria.add(Restrictions.ge("valorTotal", filtro.getValorMinimo())); + } + + if (filtro.getValorMaximo() != null) { + criteria.add(Restrictions.le("valorTotal", filtro.getValorMaximo())); + } + + if (!StringUtils.isEmpty(filtro.getNomeCliente())) { + criteria.add(Restrictions.ilike("c.nome", filtro.getNomeCliente(), MatchMode.ANYWHERE)); + } + + if (!StringUtils.isEmpty(filtro.getCpfOuCnpjCliente())) { + criteria.add(Restrictions.eq("c.cpfOuCnpj", TipoPessoa.removerFormatacao(filtro.getCpfOuCnpjCliente()))); + } + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasQueries.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasQueries.java new file mode 100644 index 00000000..b98c0684 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/helper/venda/VendasQueries.java @@ -0,0 +1,15 @@ +package com.algaworks.brewer.repository.helper.venda; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.algaworks.brewer.model.Venda; +import com.algaworks.brewer.repository.filter.VendaFilter; + +public interface VendasQueries { + + public Page filtrar(VendaFilter filtro, Pageable pageable); + + public Venda buscarComItens(Long codigo); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/paginacao/PaginacaoUtil.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/paginacao/PaginacaoUtil.java new file mode 100644 index 00000000..af63c390 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/repository/paginacao/PaginacaoUtil.java @@ -0,0 +1,28 @@ +package com.algaworks.brewer.repository.paginacao; + +import org.hibernate.Criteria; +import org.hibernate.criterion.Order; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Component; + +@Component +public class PaginacaoUtil { + + public void preparar(Criteria criteria, Pageable pageable) { + int paginaAtual = pageable.getPageNumber(); + int totalRegistrosPorPagina = pageable.getPageSize(); + int primeiroRegistro = paginaAtual * totalRegistrosPorPagina; + + criteria.setFirstResult(primeiroRegistro); + criteria.setMaxResults(totalRegistrosPorPagina); + + Sort sort = pageable.getSort(); + if (sort != null) { + Sort.Order order = sort.iterator().next(); + String property = order.getProperty(); + criteria.addOrder(order.isAscending() ? Order.asc(property) : Order.desc(property)); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/AppUserDetailsService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/AppUserDetailsService.java new file mode 100644 index 00000000..d1189d2d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/AppUserDetailsService.java @@ -0,0 +1,42 @@ +package com.algaworks.brewer.security; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import com.algaworks.brewer.model.Usuario; +import com.algaworks.brewer.repository.Usuarios; + +@Service +public class AppUserDetailsService implements UserDetailsService { + + @Autowired + private Usuarios usuarios; + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + Optional usuarioOptional = usuarios.porEmailEAtivo(email); + Usuario usuario = usuarioOptional.orElseThrow(() -> new UsernameNotFoundException("Usuário e/ou senha incorretos")); + return new UsuarioSistema(usuario, getPermissoes(usuario)); + } + + private Collection getPermissoes(Usuario usuario) { + Set authorities = new HashSet<>(); + + List permissoes = usuarios.permissoes(usuario); + permissoes.forEach(p -> authorities.add(new SimpleGrantedAuthority(p.toUpperCase()))); + + return authorities; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/UsuarioSistema.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/UsuarioSistema.java new file mode 100644 index 00000000..3da3a412 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/security/UsuarioSistema.java @@ -0,0 +1,25 @@ +package com.algaworks.brewer.security; + +import java.util.Collection; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; + +import com.algaworks.brewer.model.Usuario; + +public class UsuarioSistema extends User { + + private static final long serialVersionUID = 1L; + + private Usuario usuario; + + public UsuarioSistema(Usuario usuario, Collection authorities) { + super(usuario.getEmail(), usuario.getSenha(), authorities); + this.usuario = usuario; + } + + public Usuario getUsuario() { + return usuario; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCervejaService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCervejaService.java new file mode 100644 index 00000000..2f405c44 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCervejaService.java @@ -0,0 +1,47 @@ +package com.algaworks.brewer.service; + +import javax.persistence.PersistenceException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.repository.Cervejas; +import com.algaworks.brewer.service.event.cerveja.CervejaSalvaEvent; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.storage.FotoStorage; + +@Service +public class CadastroCervejaService { + + @Autowired + private Cervejas cervejas; + + @Autowired + private ApplicationEventPublisher publisher; + + @Autowired + private FotoStorage fotoStorage; + + @Transactional + public void salvar(Cerveja cerveja) { + cervejas.save(cerveja); + + publisher.publishEvent(new CervejaSalvaEvent(cerveja)); + } + + @Transactional + public void excluir(Cerveja cerveja) { + try { + String foto = cerveja.getFoto(); + cervejas.delete(cerveja); + cervejas.flush(); + fotoStorage.excluir(foto); + } catch (PersistenceException e) { + throw new ImpossivelExcluirEntidadeException("Impossível apagar cerveja. Já foi usada em alguma venda."); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCidadeService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCidadeService.java new file mode 100644 index 00000000..68225605 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroCidadeService.java @@ -0,0 +1,41 @@ +package com.algaworks.brewer.service; + +import java.util.Optional; + +import javax.persistence.PersistenceException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.algaworks.brewer.model.Cidade; +import com.algaworks.brewer.repository.Cidades; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.service.exception.NomeCidadeJaCadastradaException; + +@Service +public class CadastroCidadeService { + + @Autowired + private Cidades cidades; + + @Transactional + public void salvar(Cidade cidade) { + Optional cidadeExistente = cidades.findByNomeAndEstado(cidade.getNome(), cidade.getEstado()); + if (cidadeExistente.isPresent()) { + throw new NomeCidadeJaCadastradaException("Nome de cidade já cadastrado"); + } + + cidades.save(cidade); + } + + @Transactional + public void excluir(Cidade cidade) { + try { + this.cidades.delete(cidade); + this.cidades.flush(); + } catch (PersistenceException e) { + throw new ImpossivelExcluirEntidadeException("Impossível apagar cidade. O registro está sendo usado."); + } + } +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroClienteService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroClienteService.java new file mode 100644 index 00000000..dbb52304 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroClienteService.java @@ -0,0 +1,61 @@ +package com.algaworks.brewer.service; + +import javax.persistence.PersistenceException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.algaworks.brewer.model.Cidade; +import com.algaworks.brewer.model.Cliente; +import com.algaworks.brewer.repository.Cidades; +import com.algaworks.brewer.repository.Clientes; +import com.algaworks.brewer.service.exception.CpfCnpjClienteJaCadastradoException; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; + +@Service +public class CadastroClienteService { + + @Autowired + private Clientes clientes; + + @Autowired + private Cidades cidades; + + @Transactional + public void salvar(Cliente cliente) { + if (cliente.isNovo()) { + this.clientes.findByCpfOuCnpj(cliente.getCpfOuCnpjSemFormatacao()) + .ifPresent(c -> { + throw new CpfCnpjClienteJaCadastradoException("CPF/CNPJ já cadastrado"); + }); + } + + this.clientes.save(cliente); + } + + @Transactional(readOnly = true) + public void comporDadosEndereco(Cliente cliente) { + if (cliente.getEndereco() == null + || cliente.getEndereco().getCidade() == null + || cliente.getEndereco().getCidade().getCodigo() == null) { + return; + } + + Cidade cidade = this.cidades.findByCodigoFetchingEstado(cliente.getEndereco().getCidade().getCodigo()); + + cliente.getEndereco().setCidade(cidade); + cliente.getEndereco().setEstado(cidade.getEstado()); + } + + @Transactional + public void excluir(Cliente cliente) { + try { + this.clientes.delete(cliente); + this.clientes.flush(); + } catch (PersistenceException e) { + throw new ImpossivelExcluirEntidadeException("Impossível apagar cliente. Já está atrelado a alguma venda."); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroEstiloService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroEstiloService.java new file mode 100644 index 00000000..9732cc88 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroEstiloService.java @@ -0,0 +1,42 @@ +package com.algaworks.brewer.service; + +import java.util.Optional; + +import javax.persistence.PersistenceException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.algaworks.brewer.model.Estilo; +import com.algaworks.brewer.repository.Estilos; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.service.exception.NomeEstiloJaCadastradoException; + +@Service +public class CadastroEstiloService { + + @Autowired + private Estilos estilos; + + @Transactional + public Estilo salvar(Estilo estilo) { + Optional estiloOptional = estilos.findByNomeIgnoreCase(estilo.getNome()); + if (estiloOptional.isPresent()) { + throw new NomeEstiloJaCadastradoException("Nome do estilo já cadastrado"); + } + + return estilos.saveAndFlush(estilo); + } + + @Transactional + public void excluir(Estilo estilo) { + try { + this.estilos.delete(estilo); + this.estilos.flush(); + } catch (PersistenceException e) { + throw new ImpossivelExcluirEntidadeException("Impossível apagar estilo. Já está atrelado a alguma cerveja."); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroUsuarioService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroUsuarioService.java new file mode 100644 index 00000000..37466902 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroUsuarioService.java @@ -0,0 +1,67 @@ +package com.algaworks.brewer.service; + +import java.util.Optional; + +import javax.persistence.PersistenceException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Usuario; +import com.algaworks.brewer.repository.Usuarios; +import com.algaworks.brewer.service.exception.EmailUsuarioJaCadastradoException; +import com.algaworks.brewer.service.exception.ImpossivelExcluirEntidadeException; +import com.algaworks.brewer.service.exception.SenhaObrigatoriaUsuarioException; + +@Service +public class CadastroUsuarioService { + + @Autowired + private Usuarios usuarios; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Transactional + public void salvar(Usuario usuario) { + Optional usuarioExistente = usuarios.findByEmail(usuario.getEmail()); + if (usuarioExistente.isPresent() && !usuarioExistente.get().equals(usuario)) { + throw new EmailUsuarioJaCadastradoException("E-mail já cadastrado"); + } + + if (usuario.isNovo() && StringUtils.isEmpty(usuario.getSenha())) { + throw new SenhaObrigatoriaUsuarioException("Senha é obrigatória para novo usuário"); + } + + if (usuario.isNovo() || !StringUtils.isEmpty(usuario.getSenha())) { + usuario.setSenha(this.passwordEncoder.encode(usuario.getSenha())); + } else if (StringUtils.isEmpty(usuario.getSenha())) { + usuario.setSenha(usuarioExistente.get().getSenha()); + } + usuario.setConfirmacaoSenha(usuario.getSenha()); + + if (!usuario.isNovo() && usuario.getAtivo() == null) { + usuario.setAtivo(usuarioExistente.get().getAtivo()); + } + + usuarios.save(usuario); + } + + @Transactional + public void alterarStatus(Long[] codigos, StatusUsuario statusUsuario) { + statusUsuario.executar(codigos, usuarios); + } + + @Transactional + public void excluir(Usuario usuario) { + try { + this.usuarios.delete(usuario); + this.usuarios.flush(); + } catch (PersistenceException e) { + throw new ImpossivelExcluirEntidadeException("Impossível apagar usuário."); + } + } +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroVendaService.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroVendaService.java new file mode 100644 index 00000000..ab08e994 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/CadastroVendaService.java @@ -0,0 +1,57 @@ +package com.algaworks.brewer.service; + +import java.time.LocalDateTime; +import java.time.LocalTime; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.algaworks.brewer.model.StatusVenda; +import com.algaworks.brewer.model.Venda; +import com.algaworks.brewer.repository.Vendas; + +@Service +public class CadastroVendaService { + + @Autowired + private Vendas vendas; + + @Transactional + public Venda salvar(Venda venda) { + if (venda.isSalvarProibido()) { + throw new RuntimeException("Usuário tentando salvar uma venda proibida"); + } + + if (venda.isNova()) { + venda.setDataCriacao(LocalDateTime.now()); + } else { + Venda vendaExistente = vendas.findOne(venda.getCodigo()); + venda.setDataCriacao(vendaExistente.getDataCriacao()); + } + + if (venda.getDataEntrega() != null) { + venda.setDataHoraEntrega(LocalDateTime.of(venda.getDataEntrega() + , venda.getHorarioEntrega() != null ? venda.getHorarioEntrega() : LocalTime.NOON)); + } + + return vendas.saveAndFlush(venda); + } + + @Transactional + public void emitir(Venda venda) { + venda.setStatus(StatusVenda.EMITIDA); + salvar(venda); + } + + @PreAuthorize("#venda.usuario == principal.usuario or hasRole('CANCELAR_VENDA')") + @Transactional + public void cancelar(Venda venda) { + Venda vendaExistente = vendas.findOne(venda.getCodigo()); + + vendaExistente.setStatus(StatusVenda.CANCELADA); + vendas.save(vendaExistente); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/StatusUsuario.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/StatusUsuario.java new file mode 100644 index 00000000..f21b128c --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/StatusUsuario.java @@ -0,0 +1,23 @@ +package com.algaworks.brewer.service; + +import com.algaworks.brewer.repository.Usuarios; + +public enum StatusUsuario { + + ATIVAR { + @Override + public void executar(Long[] codigos, Usuarios usuarios) { + usuarios.findByCodigoIn(codigos).forEach(u -> u.setAtivo(true)); + } + }, + + DESATIVAR { + @Override + public void executar(Long[] codigos, Usuarios usuarios) { + usuarios.findByCodigoIn(codigos).forEach(u -> u.setAtivo(false)); + } + }; + + public abstract void executar(Long[] codigos, Usuarios usuarios); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaListener.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaListener.java new file mode 100644 index 00000000..1f05cb48 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaListener.java @@ -0,0 +1,20 @@ +package com.algaworks.brewer.service.event.cerveja; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; + +import com.algaworks.brewer.storage.FotoStorage; + +@Component +public class CervejaListener { + + @Autowired + private FotoStorage fotoStorage; + + @EventListener(condition = "#evento.temFoto() and #evento.novaFoto") + public void cervejaSalva(CervejaSalvaEvent evento) { + fotoStorage.salvar(evento.getCerveja().getFoto()); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaSalvaEvent.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaSalvaEvent.java new file mode 100644 index 00000000..7720bcbf --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/event/cerveja/CervejaSalvaEvent.java @@ -0,0 +1,27 @@ +package com.algaworks.brewer.service.event.cerveja; + +import org.springframework.util.StringUtils; + +import com.algaworks.brewer.model.Cerveja; + +public class CervejaSalvaEvent { + + private Cerveja cerveja; + + public CervejaSalvaEvent(Cerveja cerveja) { + this.cerveja = cerveja; + } + + public Cerveja getCerveja() { + return cerveja; + } + + public boolean temFoto() { + return !StringUtils.isEmpty(cerveja.getFoto()); + } + + public boolean isNovaFoto() { + return cerveja.isNovaFoto(); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/CpfCnpjClienteJaCadastradoException.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/CpfCnpjClienteJaCadastradoException.java new file mode 100644 index 00000000..c1b29d6d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/CpfCnpjClienteJaCadastradoException.java @@ -0,0 +1,11 @@ +package com.algaworks.brewer.service.exception; + +public class CpfCnpjClienteJaCadastradoException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public CpfCnpjClienteJaCadastradoException(String message) { + super(message); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/EmailUsuarioJaCadastradoException.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/EmailUsuarioJaCadastradoException.java new file mode 100644 index 00000000..b0fd6295 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/EmailUsuarioJaCadastradoException.java @@ -0,0 +1,11 @@ +package com.algaworks.brewer.service.exception; + +public class EmailUsuarioJaCadastradoException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public EmailUsuarioJaCadastradoException(String message) { + super(message); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/ImpossivelExcluirEntidadeException.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/ImpossivelExcluirEntidadeException.java new file mode 100644 index 00000000..7b7fc5a9 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/ImpossivelExcluirEntidadeException.java @@ -0,0 +1,11 @@ +package com.algaworks.brewer.service.exception; + +public class ImpossivelExcluirEntidadeException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ImpossivelExcluirEntidadeException(String msg) { + super(msg); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeCidadeJaCadastradaException.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeCidadeJaCadastradaException.java new file mode 100644 index 00000000..209ee036 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeCidadeJaCadastradaException.java @@ -0,0 +1,11 @@ +package com.algaworks.brewer.service.exception; + +public class NomeCidadeJaCadastradaException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public NomeCidadeJaCadastradaException(String message) { + super(message); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeEstiloJaCadastradoException.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeEstiloJaCadastradoException.java new file mode 100644 index 00000000..c3a09599 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/NomeEstiloJaCadastradoException.java @@ -0,0 +1,11 @@ +package com.algaworks.brewer.service.exception; + +public class NomeEstiloJaCadastradoException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public NomeEstiloJaCadastradoException(String message) { + super(message); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/SenhaObrigatoriaUsuarioException.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/SenhaObrigatoriaUsuarioException.java new file mode 100644 index 00000000..3de779ad --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/service/exception/SenhaObrigatoriaUsuarioException.java @@ -0,0 +1,11 @@ +package com.algaworks.brewer.service.exception; + +public class SenhaObrigatoriaUsuarioException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public SenhaObrigatoriaUsuarioException(String message) { + super(message); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelaItensVenda.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelaItensVenda.java new file mode 100644 index 00000000..8a48ee0c --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelaItensVenda.java @@ -0,0 +1,99 @@ +package com.algaworks.brewer.session; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.IntStream; + +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.model.ItemVenda; + +class TabelaItensVenda { + + private String uuid; + private List itens = new ArrayList<>(); + + public TabelaItensVenda(String uuid) { + this.uuid = uuid; + } + + public BigDecimal getValorTotal() { + return itens.stream() + .map(ItemVenda::getValorTotal) + .reduce(BigDecimal::add) + .orElse(BigDecimal.ZERO); + } + + public void adicionarItem(Cerveja cerveja, Integer quantidade) { + Optional itemVendaOptional = buscarItemPorCerveja(cerveja); + + ItemVenda itemVenda = null; + if (itemVendaOptional.isPresent()) { + itemVenda = itemVendaOptional.get(); + itemVenda.setQuantidade(itemVenda.getQuantidade() + quantidade); + } else { + itemVenda = new ItemVenda(); + itemVenda.setCerveja(cerveja); + itemVenda.setQuantidade(quantidade); + itemVenda.setValorUnitario(cerveja.getValor()); + itens.add(0, itemVenda); + } + } + + public void alterarQuantidadeItens(Cerveja cerveja, Integer quantidade) { + ItemVenda itemVenda = buscarItemPorCerveja(cerveja).get(); + itemVenda.setQuantidade(quantidade); + } + + public void excluirItem(Cerveja cerveja) { + int indice = IntStream.range(0, itens.size()) + .filter(i -> itens.get(i).getCerveja().equals(cerveja)) + .findAny().getAsInt(); + itens.remove(indice); + } + + public int total() { + return itens.size(); + } + + public List getItens() { + return itens; + } + + private Optional buscarItemPorCerveja(Cerveja cerveja) { + return itens.stream() + .filter(i -> i.getCerveja().equals(cerveja)) + .findAny(); + } + + public String getUuid() { + return uuid; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TabelaItensVenda other = (TabelaItensVenda) obj; + if (uuid == null) { + if (other.uuid != null) + return false; + } else if (!uuid.equals(other.uuid)) + return false; + return true; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelasItensSession.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelasItensSession.java new file mode 100644 index 00000000..acd96823 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/session/TabelasItensSession.java @@ -0,0 +1,52 @@ +package com.algaworks.brewer.session; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.springframework.stereotype.Component; +import org.springframework.web.context.annotation.SessionScope; + +import com.algaworks.brewer.model.Cerveja; +import com.algaworks.brewer.model.ItemVenda; + +@SessionScope +@Component +public class TabelasItensSession { + + private Set tabelas = new HashSet<>(); + + public void adicionarItem(String uuid, Cerveja cerveja, int quantidade) { + TabelaItensVenda tabela = buscarTabelaPorUuid(uuid); + tabela.adicionarItem(cerveja, quantidade); + tabelas.add(tabela); + } + + public void alterarQuantidadeItens(String uuid, Cerveja cerveja, Integer quantidade) { + TabelaItensVenda tabela = buscarTabelaPorUuid(uuid); + tabela.alterarQuantidadeItens(cerveja, quantidade); + } + + public void excluirItem(String uuid, Cerveja cerveja) { + TabelaItensVenda tabela = buscarTabelaPorUuid(uuid); + tabela.excluirItem(cerveja); + } + + public List getItens(String uuid) { + return buscarTabelaPorUuid(uuid).getItens(); + } + + public Object getValorTotal(String uuid) { + return buscarTabelaPorUuid(uuid).getValorTotal(); + } + + private TabelaItensVenda buscarTabelaPorUuid(String uuid) { + TabelaItensVenda tabela = tabelas.stream() + .filter(t -> t.getUuid().equals(uuid)) + .findAny() + .orElse(new TabelaItensVenda(uuid)); + return tabela; + } + + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorage.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorage.java new file mode 100644 index 00000000..e0e744ef --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorage.java @@ -0,0 +1,19 @@ +package com.algaworks.brewer.storage; + +import org.springframework.web.multipart.MultipartFile; + +public interface FotoStorage { + + public String salvarTemporariamente(MultipartFile[] files); + + public byte[] recuperarFotoTemporaria(String nome); + + public void salvar(String foto); + + public byte[] recuperar(String foto); + + public byte[] recuperarThumbnail(String fotoCerveja); + + public void excluir(String foto); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorageRunnable.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorageRunnable.java new file mode 100644 index 00000000..d7821f00 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/FotoStorageRunnable.java @@ -0,0 +1,27 @@ +package com.algaworks.brewer.storage; + +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.multipart.MultipartFile; + +import com.algaworks.brewer.dto.FotoDTO; + +public class FotoStorageRunnable implements Runnable { + + private MultipartFile[] files; + private DeferredResult resultado; + private FotoStorage fotoStorage; + + public FotoStorageRunnable(MultipartFile[] files, DeferredResult resultado, FotoStorage fotoStorage) { + this.files = files; + this.resultado = resultado; + this.fotoStorage = fotoStorage; + } + + @Override + public void run() { + String nomeFoto = this.fotoStorage.salvarTemporariamente(files); + String contentType = files[0].getContentType(); + resultado.setResult(new FotoDTO(nomeFoto, contentType)); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/local/FotoStorageLocal.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/local/FotoStorageLocal.java new file mode 100644 index 00000000..e4c8dda1 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/storage/local/FotoStorageLocal.java @@ -0,0 +1,129 @@ +package com.algaworks.brewer.storage.local; + +import static java.nio.file.FileSystems.getDefault; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.multipart.MultipartFile; + +import com.algaworks.brewer.storage.FotoStorage; + +import net.coobird.thumbnailator.Thumbnails; +import net.coobird.thumbnailator.name.Rename; + +public class FotoStorageLocal implements FotoStorage { + + private static final Logger logger = LoggerFactory.getLogger(FotoStorageLocal.class); + private static final String THUMBNAIL_PREFIX = "thumbnail."; + + private Path local; + private Path localTemporario; + + public FotoStorageLocal() { + this(getDefault().getPath(System.getenv("HOME"), ".brewerfotos")); + } + + public FotoStorageLocal(Path path) { + this.local = path; + criarPastas(); + } + + @Override + public String salvarTemporariamente(MultipartFile[] files) { + String novoNome = null; + if (files != null && files.length > 0) { + MultipartFile arquivo = files[0]; + novoNome = renomearArquivo(arquivo.getOriginalFilename()); + try { + arquivo.transferTo(new File(this.localTemporario.toAbsolutePath().toString() + getDefault().getSeparator() + novoNome)); + } catch (IOException e) { + throw new RuntimeException("Erro salvando a foto na pasta temporária", e); + } + } + + return novoNome; + } + + @Override + public byte[] recuperarFotoTemporaria(String nome) { + try { + return Files.readAllBytes(this.localTemporario.resolve(nome)); + } catch (IOException e) { + throw new RuntimeException("Erro lendo a foto temporária", e); + } + } + + @Override + public void salvar(String foto) { + try { + Files.move(this.localTemporario.resolve(foto), this.local.resolve(foto)); + } catch (IOException e) { + throw new RuntimeException("Erro movendo a foto para destino final", e); + } + + try { + Thumbnails.of(this.local.resolve(foto).toString()).size(40, 68).toFiles(Rename.PREFIX_DOT_THUMBNAIL); + } catch (IOException e) { + throw new RuntimeException("Erro gerando thumbnail", e); + } + } + + @Override + public byte[] recuperar(String nome) { + try { + return Files.readAllBytes(this.local.resolve(nome)); + } catch (IOException e) { + throw new RuntimeException("Erro lendo a foto", e); + } + } + + @Override + public byte[] recuperarThumbnail(String fotoCerveja) { + return recuperar(THUMBNAIL_PREFIX + fotoCerveja); + } + + @Override + public void excluir(String foto) { + try { + Files.deleteIfExists(this.local.resolve(foto)); + Files.deleteIfExists(this.local.resolve(THUMBNAIL_PREFIX + foto)); + } catch (IOException e) { + logger.warn(String.format("Erro apagando foto '%s'. Mensagem: %s", foto, e.getMessage())); + } + + } + + private void criarPastas() { + try { + Files.createDirectories(this.local); + this.localTemporario = getDefault().getPath(this.local.toString(), "temp"); + Files.createDirectories(this.localTemporario); + + if (logger.isDebugEnabled()) { + logger.debug("Pastas criadas para salvar fotos."); + logger.debug("Pasta default: " + this.local.toAbsolutePath()); + logger.debug("Pasta temporária: " + this.localTemporario.toAbsolutePath()); + } + } catch (IOException e) { + throw new RuntimeException("Erro criando pasta para salvar foto", e); + } + } + + private String renomearArquivo(String nomeOriginal) { + String novoNome = UUID.randomUUID().toString() + "_" + nomeOriginal; + + if (logger.isDebugEnabled()) { + logger.debug(String.format("Nome original: %s, novo nome: %s", nomeOriginal, novoNome)); + } + + return novoNome; + + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/BrewerDialect.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/BrewerDialect.java new file mode 100644 index 00000000..e60bf981 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/BrewerDialect.java @@ -0,0 +1,33 @@ +package com.algaworks.brewer.thymeleaf; + +import java.util.HashSet; +import java.util.Set; + +import org.thymeleaf.dialect.AbstractProcessorDialect; +import org.thymeleaf.processor.IProcessor; +import org.thymeleaf.standard.StandardDialect; + +import com.algaworks.brewer.thymeleaf.processor.ClassForErrorAttributeTagProcessor; +import com.algaworks.brewer.thymeleaf.processor.MenuAttributeTagProcessor; +import com.algaworks.brewer.thymeleaf.processor.MessageElementTagProcessor; +import com.algaworks.brewer.thymeleaf.processor.OrderElementTagProcessor; +import com.algaworks.brewer.thymeleaf.processor.PaginationElementTagProcessor; + +public class BrewerDialect extends AbstractProcessorDialect { + + public BrewerDialect() { + super("AlgaWorks Brewer", "brewer", StandardDialect.PROCESSOR_PRECEDENCE); + } + + @Override + public Set getProcessors(String dialectPrefix) { + final Set processadores = new HashSet<>(); + processadores.add(new ClassForErrorAttributeTagProcessor(dialectPrefix)); + processadores.add(new MessageElementTagProcessor(dialectPrefix)); + processadores.add(new OrderElementTagProcessor(dialectPrefix)); + processadores.add(new PaginationElementTagProcessor(dialectPrefix)); + processadores.add(new MenuAttributeTagProcessor(dialectPrefix)); + return processadores; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/ClassForErrorAttributeTagProcessor.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/ClassForErrorAttributeTagProcessor.java new file mode 100644 index 00000000..63c65dff --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/ClassForErrorAttributeTagProcessor.java @@ -0,0 +1,32 @@ +package com.algaworks.brewer.thymeleaf.processor; + +import org.thymeleaf.context.ITemplateContext; +import org.thymeleaf.engine.AttributeName; +import org.thymeleaf.model.IProcessableElementTag; +import org.thymeleaf.processor.element.AbstractAttributeTagProcessor; +import org.thymeleaf.processor.element.IElementTagStructureHandler; +import org.thymeleaf.spring4.util.FieldUtils; +import org.thymeleaf.templatemode.TemplateMode; + +public class ClassForErrorAttributeTagProcessor extends AbstractAttributeTagProcessor { + + private static final String NOME_ATRIBUTO = "classforerror"; + private static final int PRECEDENCIA = 1000; + + public ClassForErrorAttributeTagProcessor(String dialectPrefix) { + super(TemplateMode.HTML, dialectPrefix, null, false, NOME_ATRIBUTO, true, PRECEDENCIA, true); + } + + @Override + protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, + String attributeValue, IElementTagStructureHandler structureHandler) { + + boolean temErro = FieldUtils.hasErrors(context, attributeValue); + + if (temErro) { + String classesExistentes = tag.getAttributeValue("class"); + structureHandler.setAttribute("class", classesExistentes + " has-error"); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MenuAttributeTagProcessor.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MenuAttributeTagProcessor.java new file mode 100644 index 00000000..e70c576f --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MenuAttributeTagProcessor.java @@ -0,0 +1,44 @@ +package com.algaworks.brewer.thymeleaf.processor; + +import javax.servlet.http.HttpServletRequest; + +import org.thymeleaf.IEngineConfiguration; +import org.thymeleaf.context.ITemplateContext; +import org.thymeleaf.context.IWebContext; +import org.thymeleaf.engine.AttributeName; +import org.thymeleaf.model.IProcessableElementTag; +import org.thymeleaf.processor.element.AbstractAttributeTagProcessor; +import org.thymeleaf.processor.element.IElementTagStructureHandler; +import org.thymeleaf.standard.expression.IStandardExpression; +import org.thymeleaf.standard.expression.IStandardExpressionParser; +import org.thymeleaf.standard.expression.StandardExpressions; +import org.thymeleaf.templatemode.TemplateMode; + +public class MenuAttributeTagProcessor extends AbstractAttributeTagProcessor { + + private static final String NOME_ATRIBUTO = "menu"; + private static final int PRECEDENCIA = 1000; + + public MenuAttributeTagProcessor(String dialectPrefix) { + super(TemplateMode.HTML, dialectPrefix, null, false, NOME_ATRIBUTO, true, PRECEDENCIA, true); + } + + @Override + protected void doProcess(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName, + String attributeValue, IElementTagStructureHandler structureHandler) { + + IEngineConfiguration configuration = context.getConfiguration(); + IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); + IStandardExpression expression = parser.parseExpression(context, attributeValue); + String menu = (String) expression.execute(context); + + HttpServletRequest request = ((IWebContext) context).getRequest(); + String uri = request.getRequestURI(); + + if (uri.matches(menu)) { + String classesExistentes = tag.getAttributeValue("class"); + structureHandler.setAttribute("class", classesExistentes + " is-active"); + } + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MessageElementTagProcessor.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MessageElementTagProcessor.java new file mode 100644 index 00000000..696e63f5 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/MessageElementTagProcessor.java @@ -0,0 +1,32 @@ +package com.algaworks.brewer.thymeleaf.processor; + +import org.thymeleaf.context.ITemplateContext; +import org.thymeleaf.model.IModel; +import org.thymeleaf.model.IModelFactory; +import org.thymeleaf.model.IProcessableElementTag; +import org.thymeleaf.processor.element.AbstractElementTagProcessor; +import org.thymeleaf.processor.element.IElementTagStructureHandler; +import org.thymeleaf.templatemode.TemplateMode; + +public class MessageElementTagProcessor extends AbstractElementTagProcessor { + + private static final String NOME_TAG = "message"; + private static final int PRECEDENCIA = 1000; + + public MessageElementTagProcessor(String dialectPrefix) { + super(TemplateMode.HTML, dialectPrefix, NOME_TAG, true, null, false, PRECEDENCIA); + } + + @Override + protected void doProcess(ITemplateContext context, IProcessableElementTag tag, + IElementTagStructureHandler structureHandler) { + IModelFactory modelFactory = context.getModelFactory(); + + IModel model = modelFactory.createModel(); + model.add(modelFactory.createStandaloneElementTag("th:block", "th:replace", "fragments/MensagemSucesso :: alert")); + model.add(modelFactory.createStandaloneElementTag("th:block", "th:replace", "fragments/MensagensErroValidacao :: alert")); + + structureHandler.replaceWith(model, true); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/OrderElementTagProcessor.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/OrderElementTagProcessor.java new file mode 100644 index 00000000..3014e457 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/OrderElementTagProcessor.java @@ -0,0 +1,38 @@ +package com.algaworks.brewer.thymeleaf.processor; + +import org.thymeleaf.context.ITemplateContext; +import org.thymeleaf.model.IAttribute; +import org.thymeleaf.model.IModel; +import org.thymeleaf.model.IModelFactory; +import org.thymeleaf.model.IProcessableElementTag; +import org.thymeleaf.processor.element.AbstractElementTagProcessor; +import org.thymeleaf.processor.element.IElementTagStructureHandler; +import org.thymeleaf.templatemode.TemplateMode; + +public class OrderElementTagProcessor extends AbstractElementTagProcessor { + + private static final String NOME_TAG = "order"; + private static final int PRECEDENCIA = 1000; + + public OrderElementTagProcessor(String dialectPrefix) { + super(TemplateMode.HTML, dialectPrefix, NOME_TAG, true, null, false, PRECEDENCIA); + } + + @Override + protected void doProcess(ITemplateContext context, IProcessableElementTag tag, + IElementTagStructureHandler structureHandler) { + IModelFactory modelFactory = context.getModelFactory(); + + IAttribute page = tag.getAttribute("page"); + IAttribute field = tag.getAttribute("field"); + IAttribute text = tag.getAttribute("text"); + + IModel model = modelFactory.createModel(); + model.add(modelFactory.createStandaloneElementTag("th:block" + , "th:replace" + , String.format("fragments/Ordenacao :: order (%s, %s, '%s')", page.getValue(), field.getValue(), text.getValue()))); + + structureHandler.replaceWith(model, true); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/PaginationElementTagProcessor.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/PaginationElementTagProcessor.java new file mode 100644 index 00000000..aae58c68 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/thymeleaf/processor/PaginationElementTagProcessor.java @@ -0,0 +1,36 @@ +package com.algaworks.brewer.thymeleaf.processor; + +import org.thymeleaf.context.ITemplateContext; +import org.thymeleaf.model.IAttribute; +import org.thymeleaf.model.IModel; +import org.thymeleaf.model.IModelFactory; +import org.thymeleaf.model.IProcessableElementTag; +import org.thymeleaf.processor.element.AbstractElementTagProcessor; +import org.thymeleaf.processor.element.IElementTagStructureHandler; +import org.thymeleaf.templatemode.TemplateMode; + +public class PaginationElementTagProcessor extends AbstractElementTagProcessor { + + private static final String NOME_TAG = "pagination"; + private static final int PRECEDENCIA = 1000; + + public PaginationElementTagProcessor(String dialectPrefix) { + super(TemplateMode.HTML, dialectPrefix, NOME_TAG, true, null, false, PRECEDENCIA); + } + + @Override + protected void doProcess(ITemplateContext context, IProcessableElementTag tag, + IElementTagStructureHandler structureHandler) { + IModelFactory modelFactory = context.getModelFactory(); + + IAttribute page = tag.getAttribute("page"); + + IModel model = modelFactory.createModel(); + model.add(modelFactory.createStandaloneElementTag("th:block" + , "th:replace" + , String.format("fragments/Paginacao :: pagination (%s)", page.getValue()))); + + structureHandler.replaceWith(model, true); + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/AtributoConfirmacao.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/AtributoConfirmacao.java new file mode 100644 index 00000000..f10448e3 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/AtributoConfirmacao.java @@ -0,0 +1,30 @@ +package com.algaworks.brewer.validation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.OverridesAttribute; +import javax.validation.Payload; +import javax.validation.constraints.Pattern; + +import com.algaworks.brewer.validation.validator.AtributoConfirmacaoValidator; + +@Target({ ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = { AtributoConfirmacaoValidator.class }) +public @interface AtributoConfirmacao { + + @OverridesAttribute(constraint = Pattern.class, name = "message") + String message() default "Atributos não conferem"; + + Class[] groups() default {}; + Class[] payload() default {}; + + String atributo(); + + String atributoConfirmacao(); + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/SKU.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/SKU.java new file mode 100644 index 00000000..4d77c0c1 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/SKU.java @@ -0,0 +1,25 @@ +package com.algaworks.brewer.validation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.OverridesAttribute; +import javax.validation.Payload; +import javax.validation.constraints.Pattern; + +@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = {}) +@Pattern(regexp = "([a-zA-Z]{2}\\d{4})?") +public @interface SKU { + + @OverridesAttribute(constraint = Pattern.class, name = "message") + String message() default "SKU deve seguir o padrão XX9999"; + + Class[] groups() default {}; + Class[] payload() default {}; + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/validator/AtributoConfirmacaoValidator.java b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/validator/AtributoConfirmacaoValidator.java new file mode 100644 index 00000000..1cd8dbea --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/java/com/algaworks/brewer/validation/validator/AtributoConfirmacaoValidator.java @@ -0,0 +1,52 @@ +package com.algaworks.brewer.validation.validator; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder; + +import org.apache.commons.beanutils.BeanUtils; + +import com.algaworks.brewer.validation.AtributoConfirmacao; + +public class AtributoConfirmacaoValidator implements ConstraintValidator { + + private String atributo; + private String atributoConfirmacao; + + @Override + public void initialize(AtributoConfirmacao constraintAnnotation) { + this.atributo = constraintAnnotation.atributo(); + this.atributoConfirmacao = constraintAnnotation.atributoConfirmacao(); + } + + @Override + public boolean isValid(Object object, ConstraintValidatorContext context) { + boolean valido = false; + try { + Object valorAtributo = BeanUtils.getProperty(object, this.atributo); + Object valorAtributoConfirmacao = BeanUtils.getProperty(object, this.atributoConfirmacao); + + valido = ambosSaoNull(valorAtributo, valorAtributoConfirmacao) || ambosSaoIguais(valorAtributo, valorAtributoConfirmacao); + } catch (Exception e) { + throw new RuntimeException("Erro recuperando valores dos atributos", e); + } + + if (!valido) { + context.disableDefaultConstraintViolation(); + String mensagem = context.getDefaultConstraintMessageTemplate(); + ConstraintViolationBuilder violationBuilder = context.buildConstraintViolationWithTemplate(mensagem); + violationBuilder.addPropertyNode(atributoConfirmacao).addConstraintViolation(); + } + + return valido; + } + + private boolean ambosSaoIguais(Object valorAtributo, Object valorAtributoConfirmacao) { + return valorAtributo != null && valorAtributo.equals(valorAtributoConfirmacao); + } + + private boolean ambosSaoNull(Object valorAtributo, Object valorAtributoConfirmacao) { + return valorAtributo == null && valorAtributoConfirmacao == null; + } + +} diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V01__criar_tabelas_estilo_e_cerveja.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V01__criar_tabelas_estilo_e_cerveja.sql new file mode 100644 index 00000000..689ef07a --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V01__criar_tabelas_estilo_e_cerveja.sql @@ -0,0 +1,23 @@ +CREATE TABLE estilo ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + nome VARCHAR(50) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE cerveja ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + sku VARCHAR(50) NOT NULL, + nome VARCHAR(80) NOT NULL, + descricao TEXT NOT NULL, + valor DECIMAL(10, 2) NOT NULL, + teor_alcoolico DECIMAL(10, 2) NOT NULL, + comissao DECIMAL(10, 2) NOT NULL, + sabor VARCHAR(50) NOT NULL, + origem VARCHAR(50) NOT NULL, + codigo_estilo BIGINT(20) NOT NULL, + FOREIGN KEY (codigo_estilo) REFERENCES estilo(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO estilo VALUES (0, 'Amber Lager'); +INSERT INTO estilo VALUES (0, 'Dark Lager'); +INSERT INTO estilo VALUES (0, 'Pale Lager'); +INSERT INTO estilo VALUES (0, 'Pilsner'); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V02__criar_coluna_quantidade_estoque_em_cerveja.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V02__criar_coluna_quantidade_estoque_em_cerveja.sql new file mode 100644 index 00000000..7989afdf --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V02__criar_coluna_quantidade_estoque_em_cerveja.sql @@ -0,0 +1,2 @@ +ALTER TABLE cerveja + ADD quantidade_estoque INTEGER; \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V03__criar_colunas_foto_e_contentType_na_cerveja.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V03__criar_colunas_foto_e_contentType_na_cerveja.sql new file mode 100644 index 00000000..25519d7d --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V03__criar_colunas_foto_e_contentType_na_cerveja.sql @@ -0,0 +1,3 @@ +ALTER TABLE cerveja + ADD foto VARCHAR(100), + ADD content_type VARCHAR(100); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V04__adicionar_cidade_e_estado.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V04__adicionar_cidade_e_estado.sql new file mode 100644 index 00000000..56054956 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V04__adicionar_cidade_e_estado.sql @@ -0,0 +1,40 @@ +CREATE TABLE estado ( + codigo BIGINT(20) PRIMARY KEY, + nome VARCHAR(50) NOT NULL, + sigla VARCHAR(2) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE cidade ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + nome VARCHAR(50) NOT NULL, + codigo_estado BIGINT(20) NOT NULL, + FOREIGN KEY (codigo_estado) REFERENCES estado(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO estado (codigo, nome, sigla) VALUES (1,'Acre', 'AC'); +INSERT INTO estado (codigo, nome, sigla) VALUES (2,'Bahia', 'BA'); +INSERT INTO estado (codigo, nome, sigla) VALUES (3,'Goiás', 'GO'); +INSERT INTO estado (codigo, nome, sigla) VALUES (4,'Minas Gerais', 'MG'); +INSERT INTO estado (codigo, nome, sigla) VALUES (5,'Santa Catarina', 'SC'); +INSERT INTO estado (codigo, nome, sigla) VALUES (6,'São Paulo', 'SP'); + + +INSERT INTO cidade (nome, codigo_estado) VALUES ('Rio Branco', 1); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Cruzeiro do Sul', 1); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Salvador', 2); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Porto Seguro', 2); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Santana', 2); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Goiânia', 3); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Itumbiara', 3); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Novo Brasil', 3); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Belo Horizonte', 4); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Uberlândia', 4); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Montes Claros', 4); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Florianópolis', 5); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Criciúma', 5); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Camboriú', 5); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Lages', 5); +INSERT INTO cidade (nome, codigo_estado) VALUES ('São Paulo', 6); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Ribeirão Preto', 6); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Campinas', 6); +INSERT INTO cidade (nome, codigo_estado) VALUES ('Santos', 6); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V05__adicionar_tabela_cliente.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V05__adicionar_tabela_cliente.sql new file mode 100644 index 00000000..abe49eb2 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V05__adicionar_tabela_cliente.sql @@ -0,0 +1,14 @@ +CREATE TABLE cliente ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + nome VARCHAR(80) NOT NULL, + tipo_pessoa VARCHAR(15) NOT NULL, + cpf_cnpj VARCHAR(30), + telefone VARCHAR(20), + email VARCHAR(50) NOT NULL, + logradouro VARCHAR(50), + numero VARCHAR(15), + complemento VARCHAR(20), + cep VARCHAR(15), + codigo_cidade BIGINT(20), + FOREIGN KEY (codigo_cidade) REFERENCES cidade(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V06__alterar_cpf_cnpj_para_not_null.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V06__alterar_cpf_cnpj_para_not_null.sql new file mode 100644 index 00000000..34cfc86a --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V06__alterar_cpf_cnpj_para_not_null.sql @@ -0,0 +1,2 @@ +ALTER TABLE cliente + MODIFY cpf_cnpj VARCHAR(30) NOT NULL; \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V07__criar_tabela_usuario_grupo_permissao.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V07__criar_tabela_usuario_grupo_permissao.sql new file mode 100644 index 00000000..59f8c0eb --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V07__criar_tabela_usuario_grupo_permissao.sql @@ -0,0 +1,34 @@ +CREATE TABLE usuario ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + nome VARCHAR(50) NOT NULL, + email VARCHAR(50) NOT NULL, + senha VARCHAR(120) NOT NULL, + ativo BOOLEAN DEFAULT true, + data_nascimento DATE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE grupo ( + codigo BIGINT(20) PRIMARY KEY, + nome VARCHAR(50) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE permissao ( + codigo BIGINT(20) PRIMARY KEY, + nome VARCHAR(50) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE usuario_grupo ( + codigo_usuario BIGINT(20) NOT NULL, + codigo_grupo BIGINT(20) NOT NULL, + PRIMARY KEY (codigo_usuario, codigo_grupo), + FOREIGN KEY (codigo_usuario) REFERENCES usuario(codigo), + FOREIGN KEY (codigo_grupo) REFERENCES grupo(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE grupo_permissao ( + codigo_grupo BIGINT(20) NOT NULL, + codigo_permissao BIGINT(20) NOT NULL, + PRIMARY KEY (codigo_grupo, codigo_permissao), + FOREIGN KEY (codigo_grupo) REFERENCES grupo(codigo), + FOREIGN KEY (codigo_permissao) REFERENCES permissao(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V08__alterando_ativo_do_usuario_para_not_null.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V08__alterando_ativo_do_usuario_para_not_null.sql new file mode 100644 index 00000000..d9c562e8 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V08__alterando_ativo_do_usuario_para_not_null.sql @@ -0,0 +1,2 @@ +ALTER TABLE usuario + MODIFY ativo BOOLEAN DEFAULT true NOT NULL; \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V09__inserir_grupos.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V09__inserir_grupos.sql new file mode 100644 index 00000000..eb68d7f5 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V09__inserir_grupos.sql @@ -0,0 +1,2 @@ +INSERT INTO grupo (codigo, nome) VALUES (1, 'Administrador'); +INSERT INTO grupo (codigo, nome) VALUES (2, 'Vendedor'); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V10__inserir_usuario_administrador.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V10__inserir_usuario_administrador.sql new file mode 100644 index 00000000..b1d105d7 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V10__inserir_usuario_administrador.sql @@ -0,0 +1 @@ +INSERT INTO usuario (nome, email, senha, ativo) VALUES ('Admin', 'admin@brewer.com', '$2a$10$g.wT4R0Wnfel1jc/k84OXuwZE02BlACSLfWy6TycGPvvEKvIm86SG', 1) \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V11__inserir_permissoes_e_relacionar_usuario_admin.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V11__inserir_permissoes_e_relacionar_usuario_admin.sql new file mode 100644 index 00000000..b33e241b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V11__inserir_permissoes_e_relacionar_usuario_admin.sql @@ -0,0 +1,8 @@ +INSERT INTO permissao VALUES (1, 'ROLE_CADASTRAR_CIDADE'); +INSERT INTO permissao VALUES (2, 'ROLE_CADASTRAR_USUARIO'); + +INSERT INTO grupo_permissao (codigo_grupo, codigo_permissao) VALUES (1, 1); +INSERT INTO grupo_permissao (codigo_grupo, codigo_permissao) VALUES (1, 2); + +INSERT INTO usuario_grupo (codigo_usuario, codigo_grupo) VALUES ( + (SELECT codigo FROM usuario WHERE email = 'admin@brewer.com'), 1); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V12__criar_tabela_venda_e_item_venda.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V12__criar_tabela_venda_e_item_venda.sql new file mode 100644 index 00000000..db1a8768 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V12__criar_tabela_venda_e_item_venda.sql @@ -0,0 +1,24 @@ +CREATE TABLE venda ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + data_criacao DATETIME NOT NULL, + valor_frete DECIMAL(10,2), + valor_desconto DECIMAL(10,2), + valor_total DECIMAL(10,2) NOT NULL, + status VARCHAR(30) NOT NULL, + observacao VARCHAR(200), + data_hora_entrega DATETIME, + codigo_cliente BIGINT(20) NOT NULL, + codigo_usuario BIGINT(20) NOT NULL, + FOREIGN KEY (codigo_cliente) REFERENCES cliente(codigo), + FOREIGN KEY (codigo_usuario) REFERENCES usuario(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE item_venda ( + codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT, + quantidade INTEGER NOT NULL, + valor_unitario DECIMAL(10,2) NOT NULL, + codigo_cerveja BIGINT(20) NOT NULL, + codigo_venda BIGINT(20) NOT NULL, + FOREIGN KEY (codigo_cerveja) REFERENCES cerveja(codigo), + FOREIGN KEY (codigo_venda) REFERENCES venda(codigo) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V13__inserir_role_cancelar_venda.sql b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V13__inserir_role_cancelar_venda.sql new file mode 100644 index 00000000..715f49a7 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/db/migration/V13__inserir_role_cancelar_venda.sql @@ -0,0 +1,3 @@ +INSERT INTO permissao VALUES (3, 'ROLE_CANCELAR_VENDA'); + +INSERT INTO grupo_permissao (codigo_grupo, codigo_permissao) VALUES (1, 3); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-homolog.properties b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-homolog.properties new file mode 100644 index 00000000..2d0567de --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-homolog.properties @@ -0,0 +1,2 @@ +username=algaworkshomolog +password=8888888 \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-local.properties b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-local.properties new file mode 100644 index 00000000..3c672c59 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/env/mail-local.properties @@ -0,0 +1,2 @@ +username=algaworksteste +password=12345678 \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/log4j2.xml b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/log4j2.xml new file mode 100644 index 00000000..d41f4241 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/log4j2.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/messages.properties b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/messages.properties new file mode 100644 index 00000000..b8f80175 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/messages.properties @@ -0,0 +1,3 @@ +typeMismatch.java.time.LocalDate = {0} inv\u00E1lida + +usuario.dataNascimento = Data de nascimento \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/cerveja-mock.png b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/cerveja-mock.png new file mode 100644 index 0000000000000000000000000000000000000000..122a8609c542a37759da5dfebed3e8c585755921 GIT binary patch literal 5088 zcmcIoc{G&$+n=SejGd7XWy?%N5|S_(dr#aL(kN@|Sh6dGiEJTTmTWWDL1?PUk}VGs z3XidmrI4Yr?@907^ZT9myyt!X`JMNi_daLNeP7?@n(wuKuIn2Em>KaP#gGsPgvZ2K z-x7Q?AP^{#gAM$0zU^BIfe4kD=%2^m&Hg_A!TPXCBVxHr>t)nU=*Yq5mtjv0+HGDT zQWg1MVCA^PF84k}@QigB$V+l?9iuto4=x`R9YFzkj1SxOO+LP6TXE}Ew^FO6Rdr55 z1pfJO&ZB+dn;Uz3hi81mT@@fh5G80f+wBMka|i+Qax_CpAD)nq{N|i6_3G)tkC5QC z{kJRI_Ts8*KPkvm_D1-CtrolI>;`Vy*G^n@V~2!cTL{(DIC>+VJ_Ka2U8*ce<4OL3 zTpqxw4dy~vki$Vc&AxkIzGj+g2exqCX9Pdnor|#*L%-LK_VPq$f)f|P3F5&zsEQSN&@&}{5?3vA zN>}eh>O})@t3E=PNVki7cWn!2iSig+Rt zLDVRkT)b7=mw=*w zUxH$2Kuyv{5PuJ({5=r)CEuTnb$^!;-bso2>k5MxMdgY10W{ZvFpnRvEy?OG@yply zaOX**rle8DN0PBMnCH?1@6%v((W0obc+PPgG&{W^+6lL{@8Sj;$b8Al?>6o6E@1mS)Y2}ZY9@&VvBS`3^!8C!8F zX~DPfEPH9Z1>fxNxi+-mNS2LAgxCT_9Uu>ubEr9Ml|JaZP#QG~+OSHR!QxPpl|nKC z>^{YNleI!G?wYtE+@T{BI*&|7?4SR#K{-lNHZKFOn z&XWQk`ze4FATZZ{tnln*3-Uw(vs3>y4LD~(?rhDF=~rbSk&GZAy?9%Bzs%E})em6S z#R&kYHE=H|aI~LgKrg6vb;lbY?2ue0 zT#_hFkToQU88NEybd?jOc!RPO9>jv$V4=sia6v`T$yyCbffa=m$96mS3%mEe>yrZG zy-2Oz2UzN$U^W-(DcFYg8f<<@2qD>2D168y28~3^6az21U*elG# zFqrKLG{EciME|(R@vq~8LWVh4(15aS54`jo?mY(z-6#ty8W5ZY$oBX+X+%ZxA<*CX zg%Aq{!gWw+t3R9PDhgf6Q0fJx^|82sqKd?E7057*;|JGHfd7zs*C}Z%JW4*;e(K4qx@!s`pBNECqBe2;Z!W;#s?7MNCK5$88cx02#h$83ewhp# zC>As7DSIltp=?(D@G@KkrjbEx>LZ1CP}UrU&nQY)o!JGzy(7 z_%VV|0*0Y28fXC?dSDe%)CpN%IPAFJq8kdC$`Xw=CVigQ)4;Y^k?+>^@+2;!&`vcR ze{cAAa*@+3#BRK*u|lJ$_Az6V>?aC1R-QjB6h4Cf>@l8zm$zP+rC_1;*Nr4f&B{<{ zG=Tj?lFn^Wks2_03NxtV7o4o<8oqW$ieYTuNAfON$`Lfx79>Wr+8zyJ+G@!$ObC4> z*h#s8+a`W`;7`fKFWK6S%sjayTzX}}?kK@B$Gp{|UshNg4H;@B1hf(+1lW&391Wj6 z$(DxC2FlxzC1aMVx#n~6b7eF3WgS=wpOC9xYc^i~^bKV#nL$%iFOu|@8TNB^(1na& z5^bB7Z3rZDVqR)xrzEsyY|zg6y(rD*R4g*}$Kal!qNe;{?AvVHuVt++9OfLSHHYy zxw%$CpMo?HPfwp}%$z%xQd{D8qm@u1SFr+)PEE8cc5LLU>M8qKbtX)F192jV=VR>Z z`Nf8QP%=O6MW(~61U(H$hn}7utzY(A6~iQrrS$_-^@&&t?KOO<>lTzeI(IX`HyA=_38RO)g(a@=Ks>zz|)FP#wl|ytnZdq~d^x*3$Ue@00uM2`3fS1#jnU!-z zYPWQi$dj2ynEyP*kd-4zbU9W?cz^p@PPi7P(Mq{U^0?%;iPC6+GM*brLyrvoNn%bx z?e6Y>EZ8ymJ_n{OwI+{vEOjUWQ=4X7*Y@1&O2j?wHPkZ%T@7U3VK2teJ-kPje9;jr3%Jp8JKZUe4rQ$Mf{g&J`G%ji)9ec0hO;yCtS(v<{xTOzun$+D0xBl{(%Ho(U|r@Z6m4gSX$$I z(C_nW`*b2XOU?K(?6I`1d5e@sak5c!KB7_ zOw54`QlqbOSA=%^;WrnB9d&%qoCCW1b?QykfH={6%B0b0gCFl$@MX^Cym}rU{!@$gWPFhfBZHrKH{F?hs2WzVZnkJ`TUtM~#P=D}WA{G(BdzcdI+C{E zvec{{>+80blv{GB$3iUCnBzV+pXML=r~K*rTDW>`B2o7O7e~Mb_8we<}>{UUnFUZ5tBpEKPYB_SL~h zuB@h%xvUqYUMlnyE@EK6pGJT3c=)BGM1FM0yCxTMMZq@f$yqe*NtXGp_-y2Sg%u?9 z9)T|d1XhGdu`XEgSvnZzqRgJcHVmCpUQ+gwy6%~|flxiv5jsV3`du7ak|(&lV66d= zCU{L-$UC& z8*L2nOvC6m(ycYH-y{jkZ`D%frLM@c#x{Jq(o!(HJ8F3j943|3;wdoULEo{g^efS$ z?hl#bQN^sNT{(Vj+(VzPT-l2F+X7$inI1+Qj~k;+U}tjQdAy^Z7{dVj_mBMWv#;F0 z^i9JVeE^wy#GG}fEyPZ&Py9&`?fOF<+XDBU^r6#em0Y8BF4rYJiOgxX(;mG|+OPF= zxpfWlv$ibB*!bzKVVmo30OhE!y644HG2^T8G7IUcti;+CG~mr~@mnKUFBDsU`H@)^ z96Wajg_iHDKKRg|t>SE`0jWjTZv0VjDaTup>WoVuuT|&J>H}0+ANMogo}6_HnXuK` zQ@xL)M9H`uI%E{Uo6wiHpyC#9zBp7SmM%F3{zt_RpnI>~tWDpMOc# zh?efs4j2E00nFUHxtnn;f7ver&5FJ<&iU8|b*}NS)^4JUbEwU_DJdC;{^JfBn2z36 zBgE6KS?V)o42wqE&jH&X98h@9j^-p!B z@$KG%F*z0E3rorHa`~u-~XB)evsS6DbZ<&dQ%}#>r{k!>YJKtxa#C|9WvCe>mu>CYwoyV@Jue>uSHD;JP4V> z!Tv%|x;92tKZbTg|A_qc7UA+B3-I|?u+8z4{?LPWMe~P_wt@|tM9rglUWk}$&&rDj zV{^-O%E&$_imF{(o9+r35`E}8Y=3Hq`Ii%l3a{rJ;{J(TV(j($2s~z!GiKVQNaCtp z%mZBoGGT3gF|Uq2ECIjMVFokDv`R=>wDPJz`_ES74ra%&JImkAtLpuT7iiuZ!+N0> zuEPFD$Bal~q#z~AV!K=&!>9i)ikeh2mr_;e%{RsEzZd-zpUA)fGTuEHU7ckk5mw%x zI`Hku(F{e`HVmO5J zOQHcu?(?9z^Ftl<>Fc2Z+s$>g!k^9tG(~Qe1waV(p<5Ag#-!B_ch1bmz*e58iEUuy z??(Io7B>GQit;Vtev)<2*w6semY-Q@j@PORUC~P@p{b$YC zEN`RODmzP=o9Bqml6P(6-qQqX?F+GJ2t4&++ zHIGs0wwu(#AgY|zdNp@)@og5{^J@ZV4P`YRCihN852i<};fVnmLRSC6+x)oqdtw7~ zu)Q0n@c>hs#jx%Hy2M=PAeHr}4SBu5YoYOV@pW!t=vKO~c%8(HKJDEK$q|!91xGtR zHNafBqC&eLtBu!ZI*fvmmw2ghNvs$zw5>c!)8e5Fyb ziQ>uHQHBs)twGZiorlS*3|=q|S4R=P*ms_ava#M?4hzw=_|XT$Yy$7;+lg2nW=IL< z^evUhp!M?hF&q~LkUR-f^VA-c+x3j6zbiRl&I;PEwWI4%u=kp|8K*=lV}4kluYQ;LnSefEo;et31HCy!$Tyt#vz7?|l->N!66FQz9>s{jB1 literal 0 HcmV?d00001 diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/favicon.png b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/images/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..8275ea65a744405d8bca90528cfce6080b2ebcd2 GIT binary patch literal 1633 zcmV-n2A=teP)7p7di;kVqu(qKb=)0RYT2&vRum z8OY^w6c-nxy}iBB@Aq$FSvC@hL`;!L#3;rk5{WX8$Mc@Y<9Sc7*VozY_RiDd`t+TfH*Yoopz7=EzcCt( zdYY#F_wV0_#bWvE0D>TZVHlK`m&5P(b9e9FE$Zm#I4mYFDJk*FWU^#995!v-xUsFF zq2a?@w{AhDQekLl=t@gViz}1KNO$hs`LWGrd%v`_6f&7C`=?$hLI|SKDC~Co4yja{ z06;{mt*!mOt*s3XhXXd7O?&U&J=*1Rp|Pf+U0q#`l9CdzEITkUF_8%b0$93qDeCI# zke8Q-6)RT!AjW4hnd0{L_HUg|=SBb+A0NlFXU}p>6eTt~Iy&CjvSrI{0H~;_7&I6R zjs5-or3!^&{^7%iTh(ecTrL+bUc88wmKMZfG0dMoA5~RV0Dx#TDzV$`izE`syFAYy zd;IuueraiGsJpxS&7z_rGBqgxR905zu7TFp);h7>)YP;g6bk)3I5>#P%1TJ3QUrrR zXti2w-@YA!AV8^9Vq#(f*REZIUav=9UY<}^R_3)>EMBwOJa*u~feXXK!^-{p_rI%F ztAC2e2w;IOePDG1qcKJMPi$#>5$QAgj%hJN~J<97DGCnMnORV%F4&%`llv*|DgpgREP(uE*_mTNsA%FJ8P@<8(UF)z!88`0?YrRVvj0W)MYD zplLeM*Vp$}G#b?dz~;@H&!0PYuKxDz+i*IaP$(2wzkWT8Mq?HrI|Dq=W9{0tTikAU zUpk#GExZ;RWGvc)?5nFUn*xb)P+ZwjKb2!5~tp6z0vFH?1sZ0TwM< z1gTWo58yY3Ve)922FtQw80Ifll3eBI=TABuj(v|FJ*rG5lOz-hB?uv3)YjJaysB@U zfB6#T+*+*b;P!mZJ0uF^D}6n%QV{!=m8pKZqk0D60SYXH>D zI9D^s;c&E>}#}Pv0$z&1$kW40p znfm^Uf4TC}G)-ul&i-DtYE|=p3NY1_O68!(<9XwM0m#qKzkA}ui3L+Pqgh)6RaI3d z{eJ(a!C+7afZeodQ_yO)-cc%*Ij7=T1K6-(L!ZfH8mOtM832HV3l}1hNMK}SBUs{xDxNCO!AoAwLP5<5Q% zCzgun#LjYqpP-Gg5>eRAitD1Q?pU02=AGPkUy{kN3gi6Yao;=l>)i8s?|qfk)m0p7 zz$xHK;A)@(jDa74+kp$f{lI4=5JE_i58zO#R3^Tw?!Ac!KLdUSz63r1ZUgQFo&b&j z8^Cq{0cjfsf{yB+IfjM8U_kYy(R=_Xy|# zojt7MKf^4q&$6rqbdj~L6RooboJ55GA@B|GEk)rQR)I&fd>iqMpJp(ygm?|W(7hWP zN^2kr+HYte!ngMcRDs74D|`re0eEA|V4ncb0WSjA1NZHc854dVxFv*8L97CDuh?%G zyZ2sPSq1(8u4H#{-86b}0fu@Zgq0A&NWVLXLSTO?z}7hqAq?Zn8lshxh$p;;Sm{w< zyJWy?5kY+gY%RdddV)R#T1bA_uP6u~L;)S(S>PI_JqFx5W3a!0mw=mqOThP9&O#@I zFrM9PU%`xOl&Y*DVdMhvm(qTnW6&z_I&c_K#^=COND`lhehIy$rMHqM;%OuD{Lo?2 zgWAXr!*)_VCSz_3373V~8{xE;#~iJWcz9F!?g4|SzMW;+7)h>cTE7w*nI+z&0_+^H z4crXefP|P?r~p?1hmibnFYxNDP9@ggCbts5zzuyi$#cV+J}9lL@3xcLBF|4~->&Op z_X;{){8hn`WCs$Ln50z#NKB<xevSvyN)tImgT#CxQU_j2SEq)x8 z9$o=0@~eyi5{vz~ar^kNS9fy`qqcSOP&r1t(-g47SJ~ED!_qpiemOkgu=YQs-+NJ} z-w7qRYbCH44I=D#k+D*JZZMiDWJpojD~LiY2kiO`6GE7J$+)NjjsPDc$=J57zm>Gz zxqQpAtc@hBv3|FhyaTdCI}0XQyJ0o75s&DRC+@aBJtlKU3rU(5S}cjj24DiTt!|w> z7fprU0^4q?S9TS#2&xoM%cn}(4#_RA3v@N^$LNzzz=az`a=|v4%mEEoZ)1*>epYEC zrLQGu_HI0PwXe?s1uw|5tl{pqjOK5FZ5@RixMSfxAlv zO5r?kBk+qSmi?U2P}4}o!xC?p7yk4*El%6PYsCCHrcQp90qGnw&kva;U}PQ=|B^HX zd=1<&Cu1P@Mn{1kcEij8iVCnC@Fws)`Hp59wt@GN|HcQ{BmMzAY3P)%7}qqiIbW+Vq~B&XCg*A3W9;j8j6WCsBoaDyBL`{lb$9s zso4&K-UbRgmna7(?4EcW-g$R_gRbKB_VjyiW_C|b_x{kl_o}O_tE;-Js%ILKh_DWv z23`a10~)|Sa2|L9xC}fC{J?Fjghr!r;Cn54Zxf9FHgEy>5%?B(9C!+N6}SiJ11J6k zU5^JOH6@)+Ix4WCa%|oL#=03TUh`(o0T&c@;W9$sH-RrL=>W%2 zQY)ii=N2&7QMX>SzIJN=HQ)+xH_OHKraiANF~+e4oC0R{Jpe}b-dRE3tqx!3J}^x? z*9ivs0C)xXoRDN60hBTu9v~R%Ct$pSGVf*RQ=m&I1pcp>Gd=_d41l+Q`;GQ8@K}wo z>%d3A!@v#ToIUF>Anb(W1m9G%T<01gj9dn;8ST#ngsuT!06V~0;Cn*3T8B{yy=%{S zm$ZQm>l+hJWIq|#Gy1OaHk1CY@zi14T8yUA1PqxEk4>AiXL`x>Om%44GwT3P6u(IN zOwvh7=Q2ri5ll*wP@IJ8l2n|8$0hT4$(l><+X|(w%Sgu{sjpBL`dm#FWn$g@y{Nye zq8ldb+m3Ze;TN$>gfO&2i2rr?%lNy%S4Mk!fpMLvZ2+6r04COQ7!eY;%fQA%$SDnb zwyDocZNe_~&=4m_r@4+Z;88-}o0+a%=HYx~`dwye4uEic?f_2KDDU_i_y)KL+zY%; zdD4y(Yn5@fD*8qQ=Zpw>q($L~K{UQ^^R+p+;Oycn;6~h{2puDekeG(jk?{>U7;56M zmCb$YIpP9n5PmDVNGM^U+yQY+%wd8HyvDJG!w0x)eKhLUBs`yOZ$esu`bi%E6G?q^P|12|Iig zeUo{Q5#M```~=)(zPf zu@`;s+TwD*g1V8@U0&zde!|y|=JX3#Q-u?Dji+o(jF`7&JbTJJpq0qzDdT{K5vRa2 zOT@KHz(c?v3-Wgfv9vlKE{`@v46lmQe({>Ic#dfj^!8kl%Q1_ ~NwO_yO%;SvZ5MdNYf|QNy-I*%yJaj+uTdt+qbZ z4E`Fzb8m}I&!N8OKmWEcCmrLs^Hs&3i)mt@hQVdcqghkaBs*D}tG_lKew4?rTjzIZ z9tSone1TS+TR7tu^CunG)Y7Jg#sw#)sG9C!c0I%LEzP)9;hqRf&)s$D8d5Db{TBs% zgl0~5QQ91luq4Q9tJgt4QLbaxZvAaKeCM9!oy85dg4k>TdBSVqjHub_PG=PO&J-rx z7oYTuF+kH|tG-UK+EkUhDjYx?zW?T|lx>+aOQm zzL$v$zBLo4Cj=G&tw{H}dW?tlTkS)SY4<#NS92z*EY-MMB6Ftp`R=*=*Ev7cS+X%W zMCur^FdlokL}1Y+&aasU2J4#EOuNlnb9CmqgLCGTSY!1BD42pkHY^XidQ5=>YQx%` z*%Pm9D!CkBu&tMWm(%-ejACVWGS2RX5=QOJ$1*tr7F}F+*-OA+Ly&Isg|AEuUYicA z#%IG6kPXkHt{zk2M6zK@Vu^4Q(1zE$?yY6M!^&jQ+2^E?!p7{g*|X6}vuRC3p@jk0 W117c83?+LXEZI4G$p&LV25SKE>nb+@ literal 0 HcmV?d00001 diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.dialogo-excluir.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.dialogo-excluir.js new file mode 100644 index 00000000..63e3befd --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.dialogo-excluir.js @@ -0,0 +1,62 @@ +Brewer = Brewer || {}; + +Brewer.DialogoExcluir = (function() { + + function DialogoExcluir() { + this.exclusaoBtn = $('.js-exclusao-btn') + } + + DialogoExcluir.prototype.iniciar = function() { + this.exclusaoBtn.on('click', onExcluirClicado.bind(this)); + + if (window.location.search.indexOf('excluido') > -1) { + swal('Pronto!', 'Excluído com sucesso!', 'success'); + } + } + + function onExcluirClicado(evento) { + event.preventDefault(); + var botaoClicado = $(evento.currentTarget); + var url = botaoClicado.data('url'); + var objeto = botaoClicado.data('objeto'); + + swal({ + title: 'Tem certeza?', + text: 'Excluir "' + objeto + '"? Você não poderá recuperar depois.', + showCancelButton: true, + confirmButtonColor: '#DD6B55', + confirmButtonText: 'Sim, exclua agora!', + closeOnConfirm: false + }, onExcluirConfirmado.bind(this, url)); + } + + function onExcluirConfirmado(url) { + $.ajax({ + url: url, + method: 'DELETE', + success: onExcluidoSucesso.bind(this), + error: onErroExcluir.bind(this) + }); + } + + function onExcluidoSucesso() { + var urlAtual = window.location.href; + var separador = urlAtual.indexOf('?') > -1 ? '&' : '?'; + var novaUrl = urlAtual.indexOf('excluido') > -1 ? urlAtual : urlAtual + separador + 'excluido'; + + window.location = novaUrl; + } + + function onErroExcluir(e) { + console.log('ahahahah', e.responseText); + swal('Oops!', e.responseText, 'error'); + } + + return DialogoExcluir; + +}()); + +$(function() { + var dialogo = new Brewer.DialogoExcluir(); + dialogo.iniciar(); +}); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.js new file mode 100644 index 00000000..ad2cc350 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/brewer.js @@ -0,0 +1,119 @@ +var Brewer = Brewer || {}; + +Brewer.MaskMoney = (function() { + + function MaskMoney() { + this.decimal = $('.js-decimal'); + this.plain = $('.js-plain'); + } + + MaskMoney.prototype.enable = function() { + this.decimal.maskMoney({ decimal: ',', thousands: '.' }); + this.plain.maskMoney({ precision: 0, thousands: '.' }); + } + + return MaskMoney; + +}()); + +Brewer.MaskPhoneNumber = (function() { + + function MaskPhoneNumber() { + this.inputPhoneNumber = $('.js-phone-number'); + } + + MaskPhoneNumber.prototype.enable = function() { + var maskBehavior = function (val) { + return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; + }; + + var options = { + onKeyPress: function(val, e, field, options) { + field.mask(maskBehavior.apply({}, arguments), options); + } + }; + + this.inputPhoneNumber.mask(maskBehavior, options); + } + + return MaskPhoneNumber; + +}()); + +Brewer.MaskCep = (function() { + + function MaskCep() { + this.inputCep = $('.js-cep'); + } + + MaskCep.prototype.enable = function() { + this.inputCep.mask('00.000-000'); + } + + return MaskCep; + +}()); + +Brewer.MaskDate = (function() { + + function MaskDate() { + this.inputDate = $('.js-date'); + } + + MaskDate.prototype.enable = function() { + this.inputDate.mask('00/00/0000'); + this.inputDate.datepicker({ + orientation: 'bottom', + language: 'pt-BR', + autoclose: true + }); + } + + return MaskDate; + +}()); + +Brewer.Security = (function() { + + function Security() { + this.token = $('input[name=_csrf]').val(); + this.header = $('input[name=_csrf_header]').val(); + } + + Security.prototype.enable = function() { + $(document).ajaxSend(function(event, jqxhr, settings) { + jqxhr.setRequestHeader(this.header, this.token); + }.bind(this)); + } + + return Security; + +}()); + +numeral.language('pt-br'); + +Brewer.formatarMoeda = function(valor) { + return numeral(valor).format('0,0.00'); +} + +Brewer.recuperarValor = function(valorFormatado) { + return numeral().unformat(valorFormatado); +} + +$(function() { + var maskMoney = new Brewer.MaskMoney(); + maskMoney.enable(); + + var maskPhoneNumber = new Brewer.MaskPhoneNumber(); + maskPhoneNumber.enable(); + + var maskCep = new Brewer.MaskCep(); + maskCep.enable(); + + var maskDate = new Brewer.MaskDate(); + maskDate.enable(); + + var security = new Brewer.Security(); + security.enable(); + +}); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cerveja.upload-foto.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cerveja.upload-foto.js new file mode 100644 index 00000000..33d79e97 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cerveja.upload-foto.js @@ -0,0 +1,80 @@ +var Brewer = Brewer || {}; + +Brewer.UploadFoto = (function() { + + function UploadFoto() { + this.inputNomeFoto = $('input[name=foto]'); + this.inputContentType = $('input[name=contentType]'); + this.novaFoto = $('input[name=novaFoto]'); + + this.htmlFotoCervejaTemplate = $('#foto-cerveja').html(); + this.template = Handlebars.compile(this.htmlFotoCervejaTemplate); + + this.containerFotoCerveja = $('.js-container-foto-cerveja'); + + this.uploadDrop = $('#upload-drop'); + } + + UploadFoto.prototype.iniciar = function () { + var settings = { + type: 'json', + filelimit: 1, + allow: '*.(jpg|jpeg|png)', + action: this.containerFotoCerveja.data('url-fotos'), + complete: onUploadCompleto.bind(this), + beforeSend: adicionarCsrfToken + } + + UIkit.uploadSelect($('#upload-select'), settings); + UIkit.uploadDrop(this.uploadDrop, settings); + + if (this.inputNomeFoto.val()) { + renderizarFoto.call(this, { nome: this.inputNomeFoto.val(), contentType: this.inputContentType.val()}); + } + } + + function onUploadCompleto(resposta) { + this.novaFoto.val('true'); + renderizarFoto.call(this, resposta); + } + + function renderizarFoto(resposta) { + this.inputNomeFoto.val(resposta.nome); + this.inputContentType.val(resposta.contentType); + + this.uploadDrop.addClass('hidden'); + + var foto = ''; + if (this.novaFoto.val() == 'true') { + foto = 'temp/'; + } + foto += resposta.nome; + + var htmlFotoCerveja = this.template({foto: foto}); + this.containerFotoCerveja.append(htmlFotoCerveja); + + $('.js-remove-foto').on('click', onRemoverFoto.bind(this)); + } + + function onRemoverFoto() { + $('.js-foto-cerveja').remove(); + this.uploadDrop.removeClass('hidden'); + this.inputNomeFoto.val(''); + this.inputContentType.val(''); + this.novaFoto.val('false'); + } + + function adicionarCsrfToken(xhr) { + var token = $('input[name=_csrf]').val(); + var header = $('input[name=_csrf_header]').val(); + xhr.setRequestHeader(header, token); + } + + return UploadFoto; + +})(); + +$(function() { + var uploadFoto = new Brewer.UploadFoto(); + uploadFoto.iniciar(); +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.combo-estado-cidade.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.combo-estado-cidade.js new file mode 100644 index 00000000..dd68ab75 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.combo-estado-cidade.js @@ -0,0 +1,103 @@ +var Brewer = Brewer || {}; + +Brewer.ComboEstado = (function() { + + function ComboEstado() { + this.combo = $('#estado'); + this.emitter = $({}); + this.on = this.emitter.on.bind(this.emitter); + } + + ComboEstado.prototype.iniciar = function() { + this.combo.on('change', onEstadoAlterado.bind(this)); + } + + function onEstadoAlterado() { + this.emitter.trigger('alterado', this.combo.val()); + } + + return ComboEstado; + +}()); + +Brewer.ComboCidade = (function() { + + function ComboCidade(comboEstado) { + this.comboEstado = comboEstado; + this.combo = $('#cidade'); + this.imgLoading = $('.js-img-loading'); + this.inputHiddenCidadeSelecionada = $('#inputHiddenCidadeSelecionada'); + } + + ComboCidade.prototype.iniciar = function() { + reset.call(this); + this.comboEstado.on('alterado', onEstadoAlterado.bind(this)); + var codigoEstado = this.comboEstado.combo.val(); + inicializarCidades.call(this, codigoEstado); + } + + function onEstadoAlterado(evento, codigoEstado) { + this.inputHiddenCidadeSelecionada.val(''); + inicializarCidades.call(this, codigoEstado); + } + + function inicializarCidades(codigoEstado) { + if (codigoEstado) { + var resposta = $.ajax({ + url: this.combo.data('url'), + method: 'GET', + contentType: 'application/json', + data: { 'estado': codigoEstado }, + beforeSend: iniciarRequisicao.bind(this), + complete: finalizarRequisicao.bind(this) + }); + resposta.done(onBuscarCidadesFinalizado.bind(this)); + } else { + reset.call(this); + } + } + + function onBuscarCidadesFinalizado(cidades) { + var options = []; + cidades.forEach(function(cidade) { + options.push(''); + }); + + this.combo.html(options.join('')); + this.combo.removeAttr('disabled'); + + var codigoCidadeSelecionada = this.inputHiddenCidadeSelecionada.val(); + if (codigoCidadeSelecionada) { + this.combo.val(codigoCidadeSelecionada); + } + } + + function reset() { + this.combo.html(''); + this.combo.val(''); + this.combo.attr('disabled', 'disabled'); + } + + function iniciarRequisicao() { + reset.call(this); + this.imgLoading.show(); + } + + function finalizarRequisicao() { + this.imgLoading.hide(); + } + + return ComboCidade; + +}()); + +$(function() { + + var comboEstado = new Brewer.ComboEstado(); + comboEstado.iniciar(); + + var comboCidade = new Brewer.ComboCidade(comboEstado); + comboCidade.iniciar(); + +}); + diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.mascara-cpf-cnpj.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.mascara-cpf-cnpj.js new file mode 100644 index 00000000..6b95b71e --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.mascara-cpf-cnpj.js @@ -0,0 +1,38 @@ +var Brewer = Brewer || {}; + +Brewer.MascaraCpfCnpj = (function() { + + function MascaraCpfCnpj() { + this.radioTipoPessoa = $('.js-radio-tipo-pessoa'); + this.labelCpfCnpj = $('[for=cpfOuCnpj]'); + this.inputCpfCnpj = $('#cpfOuCnpj'); + } + + MascaraCpfCnpj.prototype.iniciar = function() { + this.radioTipoPessoa.on('change', onTipoPessoaAlterado.bind(this)); + var tipoPessoaSelecionada = this.radioTipoPessoa.filter(':checked')[0]; + if (tipoPessoaSelecionada) { + aplicarMascara.call(this, $(tipoPessoaSelecionada)); + } + } + + function onTipoPessoaAlterado(evento) { + var tipoPessoaSelecionada = $(evento.currentTarget); + aplicarMascara.call(this, tipoPessoaSelecionada); + this.inputCpfCnpj.val(''); + } + + function aplicarMascara(tipoPessoaSelecionada) { + this.labelCpfCnpj.text(tipoPessoaSelecionada.data('documento')); + this.inputCpfCnpj.mask(tipoPessoaSelecionada.data('mascara')); + this.inputCpfCnpj.removeAttr('disabled'); + } + + return MascaraCpfCnpj; + +}()); + +$(function() { + var mascaraCpfCnpj = new Brewer.MascaraCpfCnpj(); + mascaraCpfCnpj.iniciar(); +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.pesquisa-rapida.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.pesquisa-rapida.js new file mode 100644 index 00000000..d72629c4 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/cliente.pesquisa-rapida.js @@ -0,0 +1,84 @@ +Brewer = Brewer || {}; + +Brewer.PesquisaRapidaCliente = (function() { + + function PesquisaRapidaCliente() { + this.pesquisaRapidaClientesModal = $('#pesquisaRapidaClientes'); + this.nomeInput = $('#nomeClienteModal'); + this.pesquisaRapidaBtn = $('.js-pesquisa-rapida-clientes-btn'); + this.containerTabelaPesquisa = $('#containerTabelaPesquisaRapidaClientes'); + this.htmlTabelaPesquisa = $('#tabela-pesquisa-rapida-cliente').html(); + this.template = Handlebars.compile(this.htmlTabelaPesquisa); + this.mensagemErro = $('.js-mensagem-erro'); + } + + PesquisaRapidaCliente.prototype.iniciar = function() { + this.pesquisaRapidaBtn.on('click', onPesquisaRapidaClicado.bind(this)); + this.pesquisaRapidaClientesModal.on('shown.bs.modal', onModalShow.bind(this)); + + } + + function onModalShow() { + this.nomeInput.focus(); + } + + function onPesquisaRapidaClicado(event) { + event.preventDefault(); + + $.ajax({ + url: this.pesquisaRapidaClientesModal.find('form').attr('action'), + method: 'GET', + contentType: 'application/json', + data: { + nome: this.nomeInput.val() + }, + success: onPesquisaConcluida.bind(this), + error: onErroPesquisa.bind(this) + }); + } + + function onPesquisaConcluida(resultado) { + this.mensagemErro.addClass('hidden'); + + var html = this.template(resultado); + this.containerTabelaPesquisa.html(html); + + var tabelaClientePesquisaRapida = new Brewer.TabelaClientePesquisaRapida(this.pesquisaRapidaClientesModal); + tabelaClientePesquisaRapida.iniciar(); + } + + function onErroPesquisa() { + this.mensagemErro.removeClass('hidden'); + } + + return PesquisaRapidaCliente; + +}()); + +Brewer.TabelaClientePesquisaRapida = (function() { + + function TabelaClientePesquisaRapida(modal) { + this.modalCliente = modal; + this.cliente = $('.js-cliente-pesquisa-rapida'); + } + + TabelaClientePesquisaRapida.prototype.iniciar = function() { + this.cliente.on('click', onClienteSelecionado.bind(this)); + } + + function onClienteSelecionado(evento) { + this.modalCliente.modal('hide'); + + var clienteSelecionado = $(evento.currentTarget); + $('#nomeCliente').val(clienteSelecionado.data('nome')); + $('#codigoCliente').val(clienteSelecionado.data('codigo')); + } + + return TabelaClientePesquisaRapida; + +}()); + +$(function() { + var pesquisaRapidaCliente = new Brewer.PesquisaRapidaCliente(); + pesquisaRapidaCliente.iniciar(); +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/estilo.cadastro-rapido.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/estilo.cadastro-rapido.js new file mode 100644 index 00000000..f6329354 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/estilo.cadastro-rapido.js @@ -0,0 +1,64 @@ +var Brewer = Brewer || {}; + +Brewer.EstiloCadastroRapido = (function() { + + function EstiloCadastroRapido() { + this.modal = $('#modalCadastroRapidoEstilo'); + this.botaoSalvar = this.modal.find('.js-modal-cadastro-estilo-salvar-btn'); + this.form = this.modal.find('form'); + this.url = this.form.attr('action'); + this.inputNomeEstilo = $('#nomeEstilo'); + this.containerMensagemErro = $('.js-mensagem-cadastro-rapido-estilo'); + } + + EstiloCadastroRapido.prototype.iniciar = function() { + this.form.on('submit', function(event) { event.preventDefault() }); + this.modal.on('shown.bs.modal', onModalShow.bind(this)); + this.modal.on('hide.bs.modal', onModalClose.bind(this)) + this.botaoSalvar.on('click', onBotaoSalvarClick.bind(this)); + } + + function onModalShow() { + this.inputNomeEstilo.focus(); + } + + function onModalClose() { + this.inputNomeEstilo.val(''); + this.containerMensagemErro.addClass('hidden'); + this.form.find('.form-group').removeClass('has-error'); + } + + function onBotaoSalvarClick() { + var nomeEstilo = this.inputNomeEstilo.val().trim(); + $.ajax({ + url: this.url, + method: 'POST', + contentType: 'application/json', + data: JSON.stringify({ nome: nomeEstilo }), + error: onErroSalvandoEstilo.bind(this), + success: onEstiloSalvo.bind(this) + }); + } + + function onErroSalvandoEstilo(obj) { + var mensagemErro = obj.responseText; + this.containerMensagemErro.removeClass('hidden'); + this.containerMensagemErro.html('' + mensagemErro + ''); + this.form.find('.form-group').addClass('has-error'); + } + + function onEstiloSalvo(estilo) { + var comboEstilo = $('#estilo'); + comboEstilo.append(''); + comboEstilo.val(estilo.codigo); + this.modal.modal('hide'); + } + + return EstiloCadastroRapido; + +}()); + +$(function() { + var estiloCadastroRapido = new Brewer.EstiloCadastroRapido(); + estiloCadastroRapido.iniciar(); +}); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/multiselecao.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/multiselecao.js new file mode 100644 index 00000000..3044a043 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/multiselecao.js @@ -0,0 +1,66 @@ +Brewer = Brewer || {}; + +Brewer.MultiSelecao = (function() { + + function MultiSelecao() { + this.statusBtn = $('.js-status-btn'); + this.selecaoCheckbox = $('.js-selecao'); + this.selecaoTodosCheckbox = $('.js-selecao-todos'); + } + + MultiSelecao.prototype.iniciar = function() { + this.statusBtn.on('click', onStatusBtnClicado.bind(this)); + this.selecaoTodosCheckbox.on('click', onSelecaoTodosClicado.bind(this)); + this.selecaoCheckbox.on('click', onSelecaoClicado.bind(this)); + } + + function onStatusBtnClicado(event) { + var botaoClicado = $(event.currentTarget); + var status = botaoClicado.data('status'); + var url = botaoClicado.data('url'); + + var checkBoxSelecionados = this.selecaoCheckbox.filter(':checked'); + var codigos = $.map(checkBoxSelecionados, function(c) { + return $(c).data('codigo'); + }); + + if (codigos.length > 0) { + $.ajax({ + url: url, + method: 'PUT', + data: { + codigos: codigos, + status: status + }, + success: function() { + window.location.reload(); + } + }); + + } + } + + function onSelecaoTodosClicado() { + var status = this.selecaoTodosCheckbox.prop('checked'); + this.selecaoCheckbox.prop('checked', status); + statusBotaoAcao.call(this, status); + } + + function onSelecaoClicado() { + var selecaoCheckboxChecados = this.selecaoCheckbox.filter(':checked'); + this.selecaoTodosCheckbox.prop('checked', selecaoCheckboxChecados.length >= this.selecaoCheckbox.length); + statusBotaoAcao.call(this, selecaoCheckboxChecados.length); + } + + function statusBotaoAcao(ativar) { + ativar ? this.statusBtn.removeClass('disabled') : this.statusBtn.addClass('disabled'); + } + + return MultiSelecao; + +}()); + +$(function() { + var multiSelecao = new Brewer.MultiSelecao(); + multiSelecao.iniciar(); +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.autocomplete-itens.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.autocomplete-itens.js new file mode 100644 index 00000000..955bc5df --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.autocomplete-itens.js @@ -0,0 +1,49 @@ +Brewer = Brewer || {}; + +Brewer.Autocomplete = (function() { + + function Autocomplete() { + this.skuOuNomeInput = $('.js-sku-nome-cerveja-input'); + var htmlTemplateAutocomplete = $('#template-autocomplete-cerveja').html(); + this.template = Handlebars.compile(htmlTemplateAutocomplete); + this.emitter = $({}); + this.on = this.emitter.on.bind(this.emitter); + } + + Autocomplete.prototype.iniciar = function() { + var options = { + url: function(skuOuNome) { + return this.skuOuNomeInput.data('url') + '?skuOuNome=' + skuOuNome; + }.bind(this), + getValue: 'nome', + minCharNumber: 3, + requestDelay: 300, + ajaxSettings: { + contentType: 'application/json' + }, + template: { + type: 'custom', + method: template.bind(this) + }, + list: { + onChooseEvent: onItemSelecionado.bind(this) + } + }; + + this.skuOuNomeInput.easyAutocomplete(options); + } + + function onItemSelecionado() { + this.emitter.trigger('item-selecionado', this.skuOuNomeInput.getSelectedItemData()); + this.skuOuNomeInput.val(''); + this.skuOuNomeInput.focus(); + } + + function template(nome, cerveja) { + cerveja.valorFormatado = Brewer.formatarMoeda(cerveja.valor); + return this.template(cerveja); + } + + return Autocomplete + +}()); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.botoes-submit.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.botoes-submit.js new file mode 100644 index 00000000..7407fac2 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.botoes-submit.js @@ -0,0 +1,36 @@ +Brewer = Brewer || {}; + +Brewer.BotaoSubmit = (function() { + + function BotaoSubmit() { + this.submitBtn = $('.js-submit-btn'); + this.formulario = $('.js-formulario-principal'); + } + + BotaoSubmit.prototype.iniciar = function() { + this.submitBtn.on('click', onSubmit.bind(this)); + } + + function onSubmit(evento) { + evento.preventDefault(); + + var botaoClicado = $(evento.target); + var acao = botaoClicado.data('acao'); + + var acaoInput = $(''); + acaoInput.attr('name', acao); + + this.formulario.append(acaoInput); + this.formulario.submit(); + } + + return BotaoSubmit + +}()); + +$(function() { + + var botaoSubmit = new Brewer.BotaoSubmit(); + botaoSubmit.iniciar(); + +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.js new file mode 100644 index 00000000..56145c99 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.js @@ -0,0 +1,61 @@ +Brewer.Venda = (function() { + + function Venda(tabelaItens) { + this.tabelaItens = tabelaItens; + this.valorTotalBox = $('.js-valor-total-box'); + this.valorFreteInput = $('#valorFrete'); + this.valorDescontoInput = $('#valorDesconto'); + this.valorTotalBoxContainer = $('.js-valor-total-box-container'); + + this.valorTotalItens = this.tabelaItens.valorTotal(); + this.valorFrete = this.valorFreteInput.data('valor'); + this.valorDesconto = this.valorDescontoInput.data('valor'); + } + + Venda.prototype.iniciar = function() { + this.tabelaItens.on('tabela-itens-atualizada', onTabelaItensAtualizada.bind(this)); + this.valorFreteInput.on('keyup', onValorFreteAlterado.bind(this)); + this.valorDescontoInput.on('keyup', onValorDescontoAlterado.bind(this)); + + this.tabelaItens.on('tabela-itens-atualizada', onValoresAlterados.bind(this)); + this.valorFreteInput.on('keyup', onValoresAlterados.bind(this)); + this.valorDescontoInput.on('keyup', onValoresAlterados.bind(this)); + + onValoresAlterados.call(this); + } + + function onTabelaItensAtualizada(evento, valorTotalItens) { + this.valorTotalItens = valorTotalItens == null ? 0 : valorTotalItens; + } + + function onValorFreteAlterado(evento) { + this.valorFrete = Brewer.recuperarValor($(evento.target).val()); + } + + function onValorDescontoAlterado(evento) { + this.valorDesconto = Brewer.recuperarValor($(evento.target).val()); + } + + function onValoresAlterados() { + var valorTotal = numeral(this.valorTotalItens) + numeral(this.valorFrete) - numeral(this.valorDesconto); + this.valorTotalBox.html(Brewer.formatarMoeda(valorTotal)); + + this.valorTotalBoxContainer.toggleClass('negativo', valorTotal < 0); + } + + return Venda; + +}()); + +$(function() { + + var autocomplete = new Brewer.Autocomplete(); + autocomplete.iniciar(); + + var tabelaItens = new Brewer.TabelaItens(autocomplete); + tabelaItens.iniciar(); + + var venda = new Brewer.Venda(tabelaItens); + venda.iniciar(); + +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.tabela-itens.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.tabela-itens.js new file mode 100644 index 00000000..dce2f162 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/venda.tabela-itens.js @@ -0,0 +1,96 @@ +Brewer.TabelaItens = (function() { + + function TabelaItens(autocomplete) { + this.autocomplete = autocomplete; + this.tabelaCervejasContainer = $('.js-tabela-cervejas-container'); + this.uuid = $('#uuid').val(); + this.emitter = $({}); + this.on = this.emitter.on.bind(this.emitter); + } + + TabelaItens.prototype.iniciar = function() { + this.autocomplete.on('item-selecionado', onItemSelecionado.bind(this)); + + bindQuantidade.call(this); + bindTabelaItem.call(this); + } + + TabelaItens.prototype.valorTotal = function() { + return this.tabelaCervejasContainer.data('valor'); + } + + function onItemSelecionado(evento, item) { + var resposta = $.ajax({ + url: 'item', + method: 'POST', + data: { + codigoCerveja: item.codigo, + uuid: this.uuid + } + }); + + resposta.done(onItemAtualizadoNoServidor.bind(this)); + } + + function onItemAtualizadoNoServidor(html) { + this.tabelaCervejasContainer.html(html); + + bindQuantidade.call(this); + + var tabelaItem = bindTabelaItem.call(this); + this.emitter.trigger('tabela-itens-atualizada', tabelaItem.data('valor-total')); + } + + function onQuantidadeItemAlterado(evento) { + var input = $(evento.target); + var quantidade = input.val(); + + if (quantidade <= 0) { + input.val(1); + quantidade = 1; + } + + var codigoCerveja = input.data('codigo-cerveja'); + + var resposta = $.ajax({ + url: 'item/' + codigoCerveja, + method: 'PUT', + data: { + quantidade: quantidade, + uuid: this.uuid + } + }); + + resposta.done(onItemAtualizadoNoServidor.bind(this)); + } + + function onDoubleClick(evento) { + $(this).toggleClass('solicitando-exclusao'); + } + + function onExclusaoItemClick(evento) { + var codigoCerveja = $(evento.target).data('codigo-cerveja'); + var resposta = $.ajax({ + url: 'item/' + this.uuid + '/' + codigoCerveja, + method: 'DELETE' + }); + + resposta.done(onItemAtualizadoNoServidor.bind(this)); + } + + function bindQuantidade() { + var quantidadeItemInput = $('.js-tabela-cerveja-quantidade-item'); + quantidadeItemInput.on('change', onQuantidadeItemAlterado.bind(this)); + quantidadeItemInput.maskMoney({ precision: 0, thousands: '' }); + } + + function bindTabelaItem() { + var tabelaItem = $('.js-tabela-item'); + tabelaItem.on('dblclick', onDoubleClick); + $('.js-exclusao-item-btn').on('click', onExclusaoItemClick.bind(this)); + return tabelaItem; + } + + return TabelaItens; + +}()); diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.min.js new file mode 100644 index 00000000..4ba060f6 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.min.js @@ -0,0 +1,10 @@ +/*! + * Datepicker for Bootstrap v1.7.0-dev (https://github.com/eternicode/bootstrap-datepicker) + * + * Copyright 2012 Stefan Petre + * Improvements by Andrew Rowls + * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0) + */ + +!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a,b){function c(){return new Date(Date.UTC.apply(Date,arguments))}function d(){var a=new Date;return c(a.getFullYear(),a.getMonth(),a.getDate())}function e(a,b){return a.getUTCFullYear()===b.getUTCFullYear()&&a.getUTCMonth()===b.getUTCMonth()&&a.getUTCDate()===b.getUTCDate()}function f(a){return function(){return this[a].apply(this,arguments)}}function g(a){return a&&!isNaN(a.getTime())}function h(b,c){function d(a,b){return b.toLowerCase()}var e,f=a(b).data(),g={},h=new RegExp("^"+c.toLowerCase()+"([A-Z])");c=new RegExp("^"+c.toLowerCase());for(var i in f)c.test(i)&&(e=i.replace(h,d),g[e]=f[i]);return g}function i(b){var c={};if(q[b]||(b=b.split("-")[0],q[b])){var d=q[b];return a.each(p,function(a,b){b in d&&(c[b]=d[b])}),c}}var j=function(){var b={get:function(a){return this.slice(a)[0]},contains:function(a){for(var b=a&&a.valueOf(),c=0,d=this.length;d>c;c++)if(0<=this[c].valueOf()-b&&this[c].valueOf()-b<864e5)return c;return-1},remove:function(a){this.splice(a,1)},replace:function(b){b&&(a.isArray(b)||(b=[b]),this.clear(),this.push.apply(this,b))},clear:function(){this.length=0},copy:function(){var a=new j;return a.replace(this),a}};return function(){var c=[];return c.push.apply(c,arguments),a.extend(c,b),c}}(),k=function(b,c){a.data(b,"datepicker",this),this._process_options(c),this.dates=new j,this.viewDate=this.o.defaultViewDate,this.focusDate=null,this.element=a(b),this.isInput=this.element.is("input"),this.inputField=this.isInput?this.element:this.element.find("input"),this.component=this.element.hasClass("date")?this.element.find(".add-on, .input-group-addon, .btn"):!1,this.component&&0===this.component.length&&(this.component=!1),this.isInline=!this.component&&this.element.is("div"),this.picker=a(r.template),this._check_template(this.o.templates.leftArrow)&&this.picker.find(".prev").html(this.o.templates.leftArrow),this._check_template(this.o.templates.rightArrow)&&this.picker.find(".next").html(this.o.templates.rightArrow),this._buildEvents(),this._attachEvents(),this.isInline?this.picker.addClass("datepicker-inline").appendTo(this.element):this.picker.addClass("datepicker-dropdown dropdown-menu"),this.o.rtl&&this.picker.addClass("datepicker-rtl"),this.o.calendarWeeks&&this.picker.find(".datepicker-days .datepicker-switch, thead .datepicker-title, tfoot .today, tfoot .clear").attr("colspan",function(a,b){return Number(b)+1}),this._allow_update=!1,this.setStartDate(this._o.startDate),this.setEndDate(this._o.endDate),this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled),this.setDaysOfWeekHighlighted(this.o.daysOfWeekHighlighted),this.setDatesDisabled(this.o.datesDisabled),this.setViewMode(this.o.startView),this.fillDow(),this.fillMonths(),this._allow_update=!0,this.update(),this.isInline&&this.show()};k.prototype={constructor:k,_resolveViewName:function(b){return a.each(r.viewModes,function(c,d){return b===c||-1!==a.inArray(b,d.names)?(b=c,!1):void 0}),b},_resolveDaysOfWeek:function(b){return a.isArray(b)||(b=b.split(/[,\s]*/)),a.map(b,Number)},_check_template:function(c){try{if(c===b||""===c)return!1;if((c.match(/[<>]/g)||[]).length<=0)return!0;var d=a(c);return d.length>0}catch(e){return!1}},_process_options:function(b){this._o=a.extend({},this._o,b);var e=this.o=a.extend({},this._o),f=e.language;q[f]||(f=f.split("-")[0],q[f]||(f=o.language)),e.language=f,e.startView=this._resolveViewName(e.startView),e.minViewMode=this._resolveViewName(e.minViewMode),e.maxViewMode=this._resolveViewName(e.maxViewMode),e.startView=Math.max(this.o.minViewMode,Math.min(this.o.maxViewMode,e.startView)),e.multidate!==!0&&(e.multidate=Number(e.multidate)||!1,e.multidate!==!1&&(e.multidate=Math.max(0,e.multidate))),e.multidateSeparator=String(e.multidateSeparator),e.weekStart%=7,e.weekEnd=(e.weekStart+6)%7;var g=r.parseFormat(e.format);e.startDate!==-(1/0)&&(e.startDate?e.startDate instanceof Date?e.startDate=this._local_to_utc(this._zero_time(e.startDate)):e.startDate=r.parseDate(e.startDate,g,e.language,e.assumeNearbyYear):e.startDate=-(1/0)),e.endDate!==1/0&&(e.endDate?e.endDate instanceof Date?e.endDate=this._local_to_utc(this._zero_time(e.endDate)):e.endDate=r.parseDate(e.endDate,g,e.language,e.assumeNearbyYear):e.endDate=1/0),e.daysOfWeekDisabled=this._resolveDaysOfWeek(e.daysOfWeekDisabled||[]),e.daysOfWeekHighlighted=this._resolveDaysOfWeek(e.daysOfWeekHighlighted||[]),e.datesDisabled=e.datesDisabled||[],a.isArray(e.datesDisabled)||(e.datesDisabled=[e.datesDisabled]),e.datesDisabled=a.map(e.datesDisabled,function(a){return r.parseDate(a,g,e.language,e.assumeNearbyYear)});var h=String(e.orientation).toLowerCase().split(/\s+/g),i=e.orientation.toLowerCase();if(h=a.grep(h,function(a){return/^auto|left|right|top|bottom$/.test(a)}),e.orientation={x:"auto",y:"auto"},i&&"auto"!==i)if(1===h.length)switch(h[0]){case"top":case"bottom":e.orientation.y=h[0];break;case"left":case"right":e.orientation.x=h[0]}else i=a.grep(h,function(a){return/^left|right$/.test(a)}),e.orientation.x=i[0]||"auto",i=a.grep(h,function(a){return/^top|bottom$/.test(a)}),e.orientation.y=i[0]||"auto";else;if(e.defaultViewDate){var j=e.defaultViewDate.year||(new Date).getFullYear(),k=e.defaultViewDate.month||0,l=e.defaultViewDate.day||1;e.defaultViewDate=c(j,k,l)}else e.defaultViewDate=d()},_events:[],_secondaryEvents:[],_applyEvents:function(a){for(var c,d,e,f=0;ff?(this.picker.addClass("datepicker-orient-right"),n+=m-b):this.picker.addClass("datepicker-orient-left");var p,q=this.o.orientation.y;if("auto"===q&&(p=-g+o-c,q=0>p?"bottom":"top"),this.picker.addClass("datepicker-orient-"+q),"top"===q?o-=c+parseInt(this.picker.css("padding-top")):o+=l,this.o.rtl){var r=f-(n+m);this.picker.css({top:o,right:r,zIndex:j})}else this.picker.css({top:o,left:n,zIndex:j});return this},_allow_update:!0,update:function(){if(!this._allow_update)return this;var b=this.dates.copy(),c=[],d=!1;return arguments.length?(a.each(arguments,a.proxy(function(a,b){b instanceof Date&&(b=this._local_to_utc(b)),c.push(b)},this)),d=!0):(c=this.isInput?this.element.val():this.element.data("date")||this.inputField.val(),c=c&&this.o.multidate?c.split(this.o.multidateSeparator):[c],delete this.element.data().date),c=a.map(c,a.proxy(function(a){return r.parseDate(a,this.o.format,this.o.language,this.o.assumeNearbyYear)},this)),c=a.grep(c,a.proxy(function(a){return!this.dateWithinRange(a)||!a},this),!0),this.dates.replace(c),this.dates.length?this.viewDate=new Date(this.dates.get(-1)):this.viewDatethis.o.endDate?this.viewDate=new Date(this.o.endDate):this.viewDate=this.o.defaultViewDate,d?(this.setValue(),this.element.change()):this.dates.length&&String(b)!==String(this.dates)&&d&&(this._trigger("changeDate"),this.element.change()),!this.dates.length&&b.length&&(this._trigger("clearDate"),this.element.change()),this.fill(),this},fillDow:function(){var b=this.o.weekStart,c="";for(this.o.calendarWeeks&&(c+=' ');b";c+="",this.picker.find(".datepicker-days thead").append(c)},fillMonths:function(){for(var a=this._utc_to_local(this.viewDate),b="",c=0;12>c;){var d=a&&a.getMonth()===c?" focused":"";b+=''+q[this.o.language].monthsShort[c++]+""}this.picker.find(".datepicker-months td").html(b)},setRange:function(b){b&&b.length?this.range=a.map(b,function(a){return a.valueOf()}):delete this.range,this.fill()},getClassNames:function(b){var c=[],f=this.viewDate.getUTCFullYear(),g=this.viewDate.getUTCMonth(),h=d();return b.getUTCFullYear()f||b.getUTCFullYear()===f&&b.getUTCMonth()>g)&&c.push("new"),this.focusDate&&b.valueOf()===this.focusDate.valueOf()&&c.push("focused"),this.o.todayHighlight&&e(b,h)&&c.push("today"),-1!==this.dates.contains(b)&&c.push("active"),this.dateWithinRange(b)||c.push("disabled"),this.dateIsDisabled(b)&&c.push("disabled","disabled-date"),-1!==a.inArray(b.getUTCDay(),this.o.daysOfWeekHighlighted)&&c.push("highlighted"),this.range&&(b>this.range[0]&&br;r+=1)s=[d],t=null,-1===r?s.push("old"):10===r&&s.push("new"),-1!==a.inArray(q,n)&&s.push("active"),(o>q||q>p)&&s.push("disabled"),q===this.viewDate.getFullYear()&&s.push("focused"),j!==a.noop&&(u=j(new Date(q,0,1)),u===b?u={}:"boolean"==typeof u?u={enabled:u}:"string"==typeof u&&(u={classes:u}),u.enabled===!1&&s.push("disabled"),u.classes&&(s=s.concat(u.classes.split(/\s+/))),u.tooltip&&(t=u.tooltip)),k+='"+q+"",q+=f;l.find("td").html(k)},fill:function(){var d,e,f=new Date(this.viewDate),g=f.getUTCFullYear(),h=f.getUTCMonth(),i=this.o.startDate!==-(1/0)?this.o.startDate.getUTCFullYear():-(1/0),j=this.o.startDate!==-(1/0)?this.o.startDate.getUTCMonth():-(1/0),k=this.o.endDate!==1/0?this.o.endDate.getUTCFullYear():1/0,l=this.o.endDate!==1/0?this.o.endDate.getUTCMonth():1/0,m=q[this.o.language].today||q.en.today||"",n=q[this.o.language].clear||q.en.clear||"",o=q[this.o.language].titleFormat||q.en.titleFormat;if(!isNaN(g)&&!isNaN(h)){this.picker.find(".datepicker-days .datepicker-switch").text(r.formatDate(f,o,this.o.language)),this.picker.find("tfoot .today").text(m).toggle(this.o.todayBtn!==!1),this.picker.find("tfoot .clear").text(n).toggle(this.o.clearBtn!==!1),this.picker.find("thead .datepicker-title").text(this.o.title).toggle(""!==this.o.title),this.updateNavArrows(),this.fillMonths();var p=c(g,h,0),s=p.getUTCDate();p.setUTCDate(s-(p.getUTCDay()-this.o.weekStart+7)%7);var t=new Date(p);p.getUTCFullYear()<100&&t.setUTCFullYear(p.getUTCFullYear()),t.setUTCDate(t.getUTCDate()+42),t=t.valueOf();for(var u,v,w=[];p.valueOf()"),this.o.calendarWeeks)){var x=new Date(+p+(this.o.weekStart-u-7)%7*864e5),y=new Date(Number(x)+(11-x.getUTCDay())%7*864e5),z=new Date(Number(z=c(y.getUTCFullYear(),0,1))+(11-z.getUTCDay())%7*864e5),A=(y-z)/864e5/7+1;w.push(''+A+"")}v=this.getClassNames(p),v.push("day"),this.o.beforeShowDay!==a.noop&&(e=this.o.beforeShowDay(this._utc_to_local(p)),e===b?e={}:"boolean"==typeof e?e={enabled:e}:"string"==typeof e&&(e={classes:e}),e.enabled===!1&&v.push("disabled"),e.classes&&(v=v.concat(e.classes.split(/\s+/))),e.tooltip&&(d=e.tooltip)),v=a.unique(v),w.push('"+p.getUTCDate()+""),d=null,u===this.o.weekEnd&&w.push(""),p.setUTCDate(p.getUTCDate()+1)}this.picker.find(".datepicker-days tbody").html(w.join(""));var B=q[this.o.language].monthsTitle||q.en.monthsTitle||"Months",C=this.picker.find(".datepicker-months").find(".datepicker-switch").text(this.o.maxViewMode<2?B:g).end().find("tbody span").removeClass("active");if(a.each(this.dates,function(a,b){b.getUTCFullYear()===g&&C.eq(b.getUTCMonth()).addClass("active")}),(i>g||g>k)&&C.addClass("disabled"),g===i&&C.slice(0,j).addClass("disabled"),g===k&&C.slice(l+1).addClass("disabled"),this.o.beforeShowMonth!==a.noop){var D=this;a.each(C,function(c,d){var e=new Date(g,c,1),f=D.o.beforeShowMonth(e);f===b?f={}:"boolean"==typeof f?f={enabled:f}:"string"==typeof f&&(f={classes:f}),f.enabled!==!1||a(d).hasClass("disabled")||a(d).addClass("disabled"),f.classes&&a(d).addClass(f.classes),f.tooltip&&a(d).prop("title",f.tooltip)})}this._fill_yearsView(".datepicker-years","year",10,1,g,i,k,this.o.beforeShowYear),this._fill_yearsView(".datepicker-decades","decade",100,10,g,i,k,this.o.beforeShowDecade),this._fill_yearsView(".datepicker-centuries","century",1e3,100,g,i,k,this.o.beforeShowCentury)}},updateNavArrows:function(){if(this._allow_update){var a,b,c=new Date(this.viewDate),d=c.getUTCFullYear(),e=c.getUTCMonth();switch(this.viewMode){case 0:a=this.o.startDate!==-(1/0)&&d<=this.o.startDate.getUTCFullYear()&&e<=this.o.startDate.getUTCMonth(),b=this.o.endDate!==1/0&&d>=this.o.endDate.getUTCFullYear()&&e>=this.o.endDate.getUTCMonth();break;case 1:case 2:case 3:case 4:a=this.o.startDate!==-(1/0)&&d<=this.o.startDate.getUTCFullYear(),b=this.o.endDate!==1/0&&d>=this.o.endDate.getUTCFullYear()}this.picker.find(".prev").toggleClass("disabled",a),this.picker.find(".next").toggleClass("disabled",b)}},click:function(b){b.preventDefault(),b.stopPropagation();var e,f,g,h,i;e=a(b.target),e.hasClass("datepicker-switch")&&this.setViewMode(this.viewMode+1),e.hasClass("today")&&!e.hasClass("day")&&(this.setViewMode(0),this._setDate(d(),"linked"===this.o.todayBtn?null:"view")),e.hasClass("clear")&&this.clearDates(),e.hasClass("disabled")||(e.hasClass("day")&&(g=Number(e.text()),h=this.viewDate.getUTCFullYear(),i=this.viewDate.getUTCMonth(),(e.hasClass("old")||e.hasClass("new"))&&(f=e.hasClass("old")?-1:1,i=(i+f+12)%12,(-1===f&&11===i||1===f&&0===i)&&(h+=f,this._trigger("changeYear",this.viewDate)),this._trigger("changeMonth",this.viewDate)),this._setDate(c(h,i,g))),(e.hasClass("month")||e.hasClass("year")||e.hasClass("decade")||e.hasClass("century"))&&(this.viewDate.setUTCDate(1),g=1,1===this.viewMode?(i=e.parent().find("span").index(e),h=this.viewDate.getUTCFullYear(),this.viewDate.setUTCMonth(i)):(i=0,h=Number(e.text()),this.viewDate.setUTCFullYear(h)),this._trigger(r.viewModes[this.viewMode-1].e,this.viewDate),this.viewMode===this.o.minViewMode?this._setDate(c(h,i,g)):(this.setViewMode(this.viewMode-1),this.fill()))),this.picker.is(":visible")&&this._focused_from&&this._focused_from.focus(),delete this._focused_from},navArrowsClick:function(b){var c=a(b.target),d=c.hasClass("prev")?-1:1;0!==this.viewMode&&(d*=12*r.viewModes[this.viewMode].navStep),this.viewDate=this.moveMonth(this.viewDate,d),this._trigger(r.viewModes[this.viewMode].e,this.viewDate),this.fill()},_toggle_multidate:function(a){var b=this.dates.contains(a);if(a||this.dates.clear(),-1!==b?(this.o.multidate===!0||this.o.multidate>1||this.o.toggleActive)&&this.dates.remove(b):this.o.multidate===!1?(this.dates.clear(),this.dates.push(a)):this.dates.push(a),"number"==typeof this.o.multidate)for(;this.dates.length>this.o.multidate;)this.dates.remove(0)},_setDate:function(a,b){b&&"date"!==b||this._toggle_multidate(a&&new Date(a)),b&&"view"!==b||(this.viewDate=a&&new Date(a)),this.fill(),this.setValue(),b&&"view"===b||this._trigger("changeDate"),this.inputField.trigger("change"),!this.o.autoclose||b&&"date"!==b||this.hide()},moveDay:function(a,b){var c=new Date(a);return c.setUTCDate(a.getUTCDate()+b),c},moveWeek:function(a,b){return this.moveDay(a,7*b)},moveMonth:function(a,b){if(!g(a))return this.o.defaultViewDate;if(!b)return a;var c,d,e=new Date(a.valueOf()),f=e.getUTCDate(),h=e.getUTCMonth(),i=Math.abs(b);if(b=b>0?1:-1,1===i)d=-1===b?function(){return e.getUTCMonth()===h}:function(){return e.getUTCMonth()!==c},c=h+b,e.setUTCMonth(c),c=(c+12)%12;else{for(var j=0;i>j;j++)e=this.moveMonth(e,b);c=e.getUTCMonth(),e.setUTCDate(f),d=function(){return c!==e.getUTCMonth()}}for(;d();)e.setUTCDate(--f),e.setUTCMonth(c);return e},moveYear:function(a,b){return this.moveMonth(a,12*b)},moveAvailableDate:function(a,b,c){do{if(a=this[c](a,b),!this.dateWithinRange(a))return!1;c="moveDay"}while(this.dateIsDisabled(a));return a},weekOfDateIsDisabled:function(b){return-1!==a.inArray(b.getUTCDay(),this.o.daysOfWeekDisabled)},dateIsDisabled:function(b){return this.weekOfDateIsDisabled(b)||a.grep(this.o.datesDisabled,function(a){return e(b,a)}).length>0},dateWithinRange:function(a){return a>=this.o.startDate&&a<=this.o.endDate},keydown:function(a){if(!this.picker.is(":visible"))return void((40===a.keyCode||27===a.keyCode)&&(this.show(),a.stopPropagation()));var b,c,d=!1,e=this.focusDate||this.viewDate;switch(a.keyCode){case 27:this.focusDate?(this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill()):this.hide(),a.preventDefault(),a.stopPropagation();break;case 37:case 38:case 39:case 40:if(!this.o.keyboardNavigation||7===this.o.daysOfWeekDisabled.length)break;b=37===a.keyCode||38===a.keyCode?-1:1,0===this.viewMode?a.ctrlKey?(c=this.moveAvailableDate(e,b,"moveYear"),c&&this._trigger("changeYear",this.viewDate)):a.shiftKey?(c=this.moveAvailableDate(e,b,"moveMonth"),c&&this._trigger("changeMonth",this.viewDate)):37===a.keyCode||39===a.keyCode?c=this.moveAvailableDate(e,b,"moveDay"):this.weekOfDateIsDisabled(e)||(c=this.moveAvailableDate(e,b,"moveWeek")):1===this.viewMode?((38===a.keyCode||40===a.keyCode)&&(b=4*b),c=this.moveAvailableDate(e,b,"moveMonth")):2===this.viewMode&&((38===a.keyCode||40===a.keyCode)&&(b=4*b),c=this.moveAvailableDate(e,b,"moveYear")),c&&(this.focusDate=this.viewDate=c,this.setValue(),this.fill(),a.preventDefault());break;case 13:if(!this.o.forceParse)break;e=this.focusDate||this.dates.get(-1)||this.viewDate,this.o.keyboardNavigation&&(this._toggle_multidate(e),d=!0),this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.setValue(),this.fill(),this.picker.is(":visible")&&(a.preventDefault(),a.stopPropagation(),this.o.autoclose&&this.hide());break;case 9:this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill(),this.hide()}d&&(this.dates.length?this._trigger("changeDate"):this._trigger("clearDate"),this.inputField.trigger("change"))},setViewMode:function(a){this.viewMode=a,this.picker.children("div").hide().filter(".datepicker-"+r.viewModes[this.viewMode].clsName).show(),this.updateNavArrows()}};var l=function(b,c){a.data(b,"datepicker",this),this.element=a(b),this.inputs=a.map(c.inputs,function(a){return a.jquery?a[0]:a}),delete c.inputs,this.keepEmptyValues=c.keepEmptyValues,delete c.keepEmptyValues,n.call(a(this.inputs),c).on("changeDate",a.proxy(this.dateUpdated,this)),this.pickers=a.map(this.inputs,function(b){return a.data(b,"datepicker")}),this.updateDates()};l.prototype={updateDates:function(){this.dates=a.map(this.pickers,function(a){return a.getUTCDate()}),this.updateRanges()},updateRanges:function(){var b=a.map(this.dates,function(a){return a.valueOf()});a.each(this.pickers,function(a,c){c.setRange(b)})},dateUpdated:function(c){if(!this.updating){this.updating=!0;var d=a.data(c.target,"datepicker");if(d!==b){var e=d.getUTCDate(),f=this.keepEmptyValues,g=a.inArray(c.target,this.inputs),h=g-1,i=g+1,j=this.inputs.length;if(-1!==g){if(a.each(this.pickers,function(a,b){b.getUTCDate()||b!==d&&f||b.setUTCDate(e)}),e=0&&ethis.dates[i])for(;j>i&&e>this.dates[i];)this.pickers[i++].setUTCDate(e);this.updateDates(),delete this.updating}}}},destroy:function(){a.map(this.pickers,function(a){a.destroy()}),delete this.element.data().datepicker},remove:f("destroy")};var m=a.fn.datepicker,n=function(c){var d=Array.apply(null,arguments);d.shift();var e;if(this.each(function(){var b=a(this),f=b.data("datepicker"),g="object"==typeof c&&c;if(!f){var j=h(this,"date"),m=a.extend({},o,j,g),n=i(m.language),p=a.extend({},o,n,j,g);b.hasClass("input-daterange")||p.inputs?(a.extend(p,{inputs:p.inputs||b.find("input").toArray()}),f=new l(this,p)):f=new k(this,p),b.data("datepicker",f)}"string"==typeof c&&"function"==typeof f[c]&&(e=f[c].apply(f,d))}),e===b||e instanceof k||e instanceof l)return this;if(this.length>1)throw new Error("Using only allowed for the collection of a single element ("+c+" function)");return e};a.fn.datepicker=n;var o=a.fn.datepicker.defaults={assumeNearbyYear:!1,autoclose:!1,beforeShowDay:a.noop,beforeShowMonth:a.noop,beforeShowYear:a.noop,beforeShowDecade:a.noop,beforeShowCentury:a.noop,calendarWeeks:!1,clearBtn:!1,toggleActive:!1,daysOfWeekDisabled:[],daysOfWeekHighlighted:[],datesDisabled:[],endDate:1/0,forceParse:!0,format:"mm/dd/yyyy",keepEmptyValues:!1,keyboardNavigation:!0,language:"en",minViewMode:0,maxViewMode:4,multidate:!1,multidateSeparator:",",orientation:"auto",rtl:!1,startDate:-(1/0),startView:0,todayBtn:!1,todayHighlight:!1,weekStart:0,disableTouchKeyboard:!1,enableOnReadonly:!0,showOnFocus:!0,zIndexOffset:10,container:"body",immediateUpdates:!1,dateCells:!1,title:"",templates:{leftArrow:"«",rightArrow:"»"}},p=a.fn.datepicker.locale_opts=["format","rtl","weekStart"];a.fn.datepicker.Constructor=k;var q=a.fn.datepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],today:"Today",clear:"Clear",titleFormat:"MM yyyy"}},r={viewModes:[{names:["days","month"],clsName:"days",e:"changeMonth"},{names:["months","year"],clsName:"months",e:"changeYear",navStep:1},{names:["years","decade"],clsName:"years",e:"changeDecade",navStep:10},{names:["decades","century"],clsName:"decades",e:"changeCentury",navStep:100},{names:["centuries","millennium"],clsName:"centuries",e:"changeMillennium",navStep:1e3}],validParts:/dd?|DD?|mm?|MM?|yy(?:yy)?/g,nonpunctuation:/[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,parseFormat:function(a){if("function"==typeof a.toValue&&"function"==typeof a.toDisplay)return a;var b=a.replace(this.validParts,"\x00").split("\x00"),c=a.match(this.validParts);if(!b||!b.length||!c||0===c.length)throw new Error("Invalid date format.");return{separators:b,parts:c}},parseDate:function(e,f,g,h){function i(a,b){return b===!0&&(b=10),100>a&&(a+=2e3,a>(new Date).getFullYear()+b&&(a-=100)),a}function j(){var a=this.slice(0,s[n].length),b=s[n].slice(0,a.length);return a.toLowerCase()===b.toLowerCase()}if(!e)return b;if(e instanceof Date)return e;if("string"==typeof f&&(f=r.parseFormat(f)),f.toValue)return f.toValue(e,f,g);var l,m,n,o,p=/([\-+]\d+)([dmwy])/,s=e.match(/([\-+]\d+)([dmwy])/g),t={d:"moveDay",m:"moveMonth",w:"moveWeek",y:"moveYear"},u={yesterday:"-1d",today:"+0d",tomorrow:"+1d"};if(/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(e)){for(e=new Date,n=0;nb;)b+=12;for(b%=12,a.setUTCMonth(b);a.getUTCMonth()!==b;)a.setUTCDate(a.getUTCDate()-1);return a},d:function(a,b){return a.setUTCDate(b)}};z.yy=z.yyyy,z.M=z.MM=z.mm=z.m,z.dd=z.d,e=d();var A=f.parts.slice();if(s.length!==A.length&&(A=a(A).filter(function(b,c){return-1!==a.inArray(c,y)}).toArray()),s.length===A.length){var B;for(n=0,B=A.length;B>n;n++){if(v=parseInt(s[n],10),l=A[n],isNaN(v))switch(l){case"MM":w=a(q[g].months).filter(j),v=a.inArray(w[0],q[g].months)+1;break;case"M":w=a(q[g].monthsShort).filter(j),v=a.inArray(w[0],q[g].monthsShort)+1}x[l]=v}var C,D;for(n=0;n=g;g++)f.length&&b.push(f.shift()),b.push(e[c.parts[g]]);return b.join("")},headTemplate:'«»',contTemplate:'',footTemplate:''};r.template='
'+r.headTemplate+""+r.footTemplate+'
'+r.headTemplate+r.contTemplate+r.footTemplate+'
'+r.headTemplate+r.contTemplate+r.footTemplate+'
'+r.headTemplate+r.contTemplate+r.footTemplate+'
'+r.headTemplate+r.contTemplate+r.footTemplate+"
", +a.fn.datepicker.DPGlobal=r,a.fn.datepicker.noConflict=function(){return a.fn.datepicker=m,this},a.fn.datepicker.version="1.7.0-dev",a(document).on("focus.datepicker.data-api click.datepicker.data-api",'[data-provide="datepicker"]',function(b){var c=a(this);c.data("datepicker")||(b.preventDefault(),n.call(c,"show"))}),a(function(){n.call(a('[data-provide="datepicker-inline"]'))})}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.pt-BR.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.pt-BR.min.js new file mode 100644 index 00000000..2d3f8afd --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-datepicker.pt-BR.min.js @@ -0,0 +1 @@ +!function(a){a.fn.datepicker.dates["pt-BR"]={days:["Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado"],daysShort:["Dom","Seg","Ter","Qua","Qui","Sex","Sáb"],daysMin:["Do","Se","Te","Qu","Qu","Se","Sa"],months:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],monthsShort:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"],today:"Hoje",monthsTitle:"Meses",clear:"Limpar",format:"dd/mm/yyyy"}}(jQuery); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-switch.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-switch.min.js new file mode 100644 index 00000000..9849658b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/bootstrap-switch.min.js @@ -0,0 +1,22 @@ +/* ======================================================================== + * bootstrap-switch - v3.3.2 + * http://www.bootstrap-switch.org + * ======================================================================== + * Copyright 2012-2013 Mattia Larentis + * + * ======================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ======================================================================== + */ + +(function(){var t=[].slice;!function(e,i){"use strict";var n;return n=function(){function t(t,i){null==i&&(i={}),this.$element=e(t),this.options=e.extend({},e.fn.bootstrapSwitch.defaults,{state:this.$element.is(":checked"),size:this.$element.data("size"),animate:this.$element.data("animate"),disabled:this.$element.is(":disabled"),readonly:this.$element.is("[readonly]"),indeterminate:this.$element.data("indeterminate"),inverse:this.$element.data("inverse"),radioAllOff:this.$element.data("radio-all-off"),onColor:this.$element.data("on-color"),offColor:this.$element.data("off-color"),onText:this.$element.data("on-text"),offText:this.$element.data("off-text"),labelText:this.$element.data("label-text"),handleWidth:this.$element.data("handle-width"),labelWidth:this.$element.data("label-width"),baseClass:this.$element.data("base-class"),wrapperClass:this.$element.data("wrapper-class")},i),this.prevOptions={},this.$wrapper=e("
",{"class":function(t){return function(){var e;return e=[""+t.options.baseClass].concat(t._getClasses(t.options.wrapperClass)),e.push(t.options.state?t.options.baseClass+"-on":t.options.baseClass+"-off"),null!=t.options.size&&e.push(t.options.baseClass+"-"+t.options.size),t.options.disabled&&e.push(t.options.baseClass+"-disabled"),t.options.readonly&&e.push(t.options.baseClass+"-readonly"),t.options.indeterminate&&e.push(t.options.baseClass+"-indeterminate"),t.options.inverse&&e.push(t.options.baseClass+"-inverse"),t.$element.attr("id")&&e.push(t.options.baseClass+"-id-"+t.$element.attr("id")),e.join(" ")}}(this)()}),this.$container=e("
",{"class":this.options.baseClass+"-container"}),this.$on=e("",{html:this.options.onText,"class":this.options.baseClass+"-handle-on "+this.options.baseClass+"-"+this.options.onColor}),this.$off=e("",{html:this.options.offText,"class":this.options.baseClass+"-handle-off "+this.options.baseClass+"-"+this.options.offColor}),this.$label=e("",{html:this.options.labelText,"class":this.options.baseClass+"-label"}),this.$element.on("init.bootstrapSwitch",function(e){return function(){return e.options.onInit.apply(t,arguments)}}(this)),this.$element.on("switchChange.bootstrapSwitch",function(i){return function(n){return!1===i.options.onSwitchChange.apply(t,arguments)?i.$element.is(":radio")?e("[name='"+i.$element.attr("name")+"']").trigger("previousState.bootstrapSwitch",!0):i.$element.trigger("previousState.bootstrapSwitch",!0):void 0}}(this)),this.$container=this.$element.wrap(this.$container).parent(),this.$wrapper=this.$container.wrap(this.$wrapper).parent(),this.$element.before(this.options.inverse?this.$off:this.$on).before(this.$label).before(this.options.inverse?this.$on:this.$off),this.options.indeterminate&&this.$element.prop("indeterminate",!0),this._init(),this._elementHandlers(),this._handleHandlers(),this._labelHandlers(),this._formHandler(),this._externalLabelHandler(),this.$element.trigger("init.bootstrapSwitch",this.options.state)}return t.prototype._constructor=t,t.prototype.setPrevOptions=function(){return this.prevOptions=e.extend(!0,{},this.options)},t.prototype.state=function(t,i){return"undefined"==typeof t?this.options.state:this.options.disabled||this.options.readonly?this.$element:this.options.state&&!this.options.radioAllOff&&this.$element.is(":radio")?this.$element:(this.$element.is(":radio")?e("[name='"+this.$element.attr("name")+"']").trigger("setPreviousOptions.bootstrapSwitch"):this.$element.trigger("setPreviousOptions.bootstrapSwitch"),this.options.indeterminate&&this.indeterminate(!1),t=!!t,this.$element.prop("checked",t).trigger("change.bootstrapSwitch",i),this.$element)},t.prototype.toggleState=function(t){return this.options.disabled||this.options.readonly?this.$element:this.options.indeterminate?(this.indeterminate(!1),this.state(!0)):this.$element.prop("checked",!this.options.state).trigger("change.bootstrapSwitch",t)},t.prototype.size=function(t){return"undefined"==typeof t?this.options.size:(null!=this.options.size&&this.$wrapper.removeClass(this.options.baseClass+"-"+this.options.size),t&&this.$wrapper.addClass(this.options.baseClass+"-"+t),this._width(),this._containerPosition(),this.options.size=t,this.$element)},t.prototype.animate=function(t){return"undefined"==typeof t?this.options.animate:(t=!!t,t===this.options.animate?this.$element:this.toggleAnimate())},t.prototype.toggleAnimate=function(){return this.options.animate=!this.options.animate,this.$wrapper.toggleClass(this.options.baseClass+"-animate"),this.$element},t.prototype.disabled=function(t){return"undefined"==typeof t?this.options.disabled:(t=!!t,t===this.options.disabled?this.$element:this.toggleDisabled())},t.prototype.toggleDisabled=function(){return this.options.disabled=!this.options.disabled,this.$element.prop("disabled",this.options.disabled),this.$wrapper.toggleClass(this.options.baseClass+"-disabled"),this.$element},t.prototype.readonly=function(t){return"undefined"==typeof t?this.options.readonly:(t=!!t,t===this.options.readonly?this.$element:this.toggleReadonly())},t.prototype.toggleReadonly=function(){return this.options.readonly=!this.options.readonly,this.$element.prop("readonly",this.options.readonly),this.$wrapper.toggleClass(this.options.baseClass+"-readonly"),this.$element},t.prototype.indeterminate=function(t){return"undefined"==typeof t?this.options.indeterminate:(t=!!t,t===this.options.indeterminate?this.$element:this.toggleIndeterminate())},t.prototype.toggleIndeterminate=function(){return this.options.indeterminate=!this.options.indeterminate,this.$element.prop("indeterminate",this.options.indeterminate),this.$wrapper.toggleClass(this.options.baseClass+"-indeterminate"),this._containerPosition(),this.$element},t.prototype.inverse=function(t){return"undefined"==typeof t?this.options.inverse:(t=!!t,t===this.options.inverse?this.$element:this.toggleInverse())},t.prototype.toggleInverse=function(){var t,e;return this.$wrapper.toggleClass(this.options.baseClass+"-inverse"),e=this.$on.clone(!0),t=this.$off.clone(!0),this.$on.replaceWith(t),this.$off.replaceWith(e),this.$on=t,this.$off=e,this.options.inverse=!this.options.inverse,this.$element},t.prototype.onColor=function(t){var e;return e=this.options.onColor,"undefined"==typeof t?e:(null!=e&&this.$on.removeClass(this.options.baseClass+"-"+e),this.$on.addClass(this.options.baseClass+"-"+t),this.options.onColor=t,this.$element)},t.prototype.offColor=function(t){var e;return e=this.options.offColor,"undefined"==typeof t?e:(null!=e&&this.$off.removeClass(this.options.baseClass+"-"+e),this.$off.addClass(this.options.baseClass+"-"+t),this.options.offColor=t,this.$element)},t.prototype.onText=function(t){return"undefined"==typeof t?this.options.onText:(this.$on.html(t),this._width(),this._containerPosition(),this.options.onText=t,this.$element)},t.prototype.offText=function(t){return"undefined"==typeof t?this.options.offText:(this.$off.html(t),this._width(),this._containerPosition(),this.options.offText=t,this.$element)},t.prototype.labelText=function(t){return"undefined"==typeof t?this.options.labelText:(this.$label.html(t),this._width(),this.options.labelText=t,this.$element)},t.prototype.handleWidth=function(t){return"undefined"==typeof t?this.options.handleWidth:(this.options.handleWidth=t,this._width(),this._containerPosition(),this.$element)},t.prototype.labelWidth=function(t){return"undefined"==typeof t?this.options.labelWidth:(this.options.labelWidth=t,this._width(),this._containerPosition(),this.$element)},t.prototype.baseClass=function(t){return this.options.baseClass},t.prototype.wrapperClass=function(t){return"undefined"==typeof t?this.options.wrapperClass:(t||(t=e.fn.bootstrapSwitch.defaults.wrapperClass),this.$wrapper.removeClass(this._getClasses(this.options.wrapperClass).join(" ")),this.$wrapper.addClass(this._getClasses(t).join(" ")),this.options.wrapperClass=t,this.$element)},t.prototype.radioAllOff=function(t){return"undefined"==typeof t?this.options.radioAllOff:(t=!!t,t===this.options.radioAllOff?this.$element:(this.options.radioAllOff=t,this.$element))},t.prototype.onInit=function(t){return"undefined"==typeof t?this.options.onInit:(t||(t=e.fn.bootstrapSwitch.defaults.onInit),this.options.onInit=t,this.$element)},t.prototype.onSwitchChange=function(t){return"undefined"==typeof t?this.options.onSwitchChange:(t||(t=e.fn.bootstrapSwitch.defaults.onSwitchChange),this.options.onSwitchChange=t,this.$element)},t.prototype.destroy=function(){var t;return t=this.$element.closest("form"),t.length&&t.off("reset.bootstrapSwitch").removeData("bootstrap-switch"),this.$container.children().not(this.$element).remove(),this.$element.unwrap().unwrap().off(".bootstrapSwitch").removeData("bootstrap-switch"),this.$element},t.prototype._width=function(){var t,e;return t=this.$on.add(this.$off),t.add(this.$label).css("width",""),e="auto"===this.options.handleWidth?Math.max(this.$on.width(),this.$off.width()):this.options.handleWidth,t.width(e),this.$label.width(function(t){return function(i,n){return"auto"!==t.options.labelWidth?t.options.labelWidth:e>n?e:n}}(this)),this._handleWidth=this.$on.outerWidth(),this._labelWidth=this.$label.outerWidth(),this.$container.width(2*this._handleWidth+this._labelWidth),this.$wrapper.width(this._handleWidth+this._labelWidth)},t.prototype._containerPosition=function(t,e){return null==t&&(t=this.options.state),this.$container.css("margin-left",function(e){return function(){var i;return i=[0,"-"+e._handleWidth+"px"],e.options.indeterminate?"-"+e._handleWidth/2+"px":t?e.options.inverse?i[1]:i[0]:e.options.inverse?i[0]:i[1]}}(this)),e?setTimeout(function(){return e()},50):void 0},t.prototype._init=function(){var t,e;return t=function(t){return function(){return t.setPrevOptions(),t._width(),t._containerPosition(null,function(){return t.options.animate?t.$wrapper.addClass(t.options.baseClass+"-animate"):void 0})}}(this),this.$wrapper.is(":visible")?t():e=i.setInterval(function(n){return function(){return n.$wrapper.is(":visible")?(t(),i.clearInterval(e)):void 0}}(this),50)},t.prototype._elementHandlers=function(){return this.$element.on({"setPreviousOptions.bootstrapSwitch":function(t){return function(e){return t.setPrevOptions()}}(this),"previousState.bootstrapSwitch":function(t){return function(e){return t.options=t.prevOptions,t.options.indeterminate&&t.$wrapper.addClass(t.options.baseClass+"-indeterminate"),t.$element.prop("checked",t.options.state).trigger("change.bootstrapSwitch",!0)}}(this),"change.bootstrapSwitch":function(t){return function(i,n){var o;return i.preventDefault(),i.stopImmediatePropagation(),o=t.$element.is(":checked"),t._containerPosition(o),o!==t.options.state?(t.options.state=o,t.$wrapper.toggleClass(t.options.baseClass+"-off").toggleClass(t.options.baseClass+"-on"),n?void 0:(t.$element.is(":radio")&&e("[name='"+t.$element.attr("name")+"']").not(t.$element).prop("checked",!1).trigger("change.bootstrapSwitch",!0),t.$element.trigger("switchChange.bootstrapSwitch",[o]))):void 0}}(this),"focus.bootstrapSwitch":function(t){return function(e){return e.preventDefault(),t.$wrapper.addClass(t.options.baseClass+"-focused")}}(this),"blur.bootstrapSwitch":function(t){return function(e){return e.preventDefault(),t.$wrapper.removeClass(t.options.baseClass+"-focused")}}(this),"keydown.bootstrapSwitch":function(t){return function(e){if(e.which&&!t.options.disabled&&!t.options.readonly)switch(e.which){case 37:return e.preventDefault(),e.stopImmediatePropagation(),t.state(!1);case 39:return e.preventDefault(),e.stopImmediatePropagation(),t.state(!0)}}}(this)})},t.prototype._handleHandlers=function(){return this.$on.on("click.bootstrapSwitch",function(t){return function(e){return e.preventDefault(),e.stopPropagation(),t.state(!1),t.$element.trigger("focus.bootstrapSwitch")}}(this)),this.$off.on("click.bootstrapSwitch",function(t){return function(e){return e.preventDefault(),e.stopPropagation(),t.state(!0),t.$element.trigger("focus.bootstrapSwitch")}}(this))},t.prototype._labelHandlers=function(){return this.$label.on({click:function(t){return t.stopPropagation()},"mousedown.bootstrapSwitch touchstart.bootstrapSwitch":function(t){return function(e){return t._dragStart||t.options.disabled||t.options.readonly?void 0:(e.preventDefault(),e.stopPropagation(),t._dragStart=(e.pageX||e.originalEvent.touches[0].pageX)-parseInt(t.$container.css("margin-left"),10),t.options.animate&&t.$wrapper.removeClass(t.options.baseClass+"-animate"),t.$element.trigger("focus.bootstrapSwitch"))}}(this),"mousemove.bootstrapSwitch touchmove.bootstrapSwitch":function(t){return function(e){var i;if(null!=t._dragStart&&(e.preventDefault(),i=(e.pageX||e.originalEvent.touches[0].pageX)-t._dragStart,!(i<-t._handleWidth||i>0)))return t._dragEnd=i,t.$container.css("margin-left",t._dragEnd+"px")}}(this),"mouseup.bootstrapSwitch touchend.bootstrapSwitch":function(t){return function(e){var i;if(t._dragStart)return e.preventDefault(),t.options.animate&&t.$wrapper.addClass(t.options.baseClass+"-animate"),t._dragEnd?(i=t._dragEnd>-(t._handleWidth/2),t._dragEnd=!1,t.state(t.options.inverse?!i:i)):t.state(!t.options.state),t._dragStart=!1}}(this),"mouseleave.bootstrapSwitch":function(t){return function(e){return t.$label.trigger("mouseup.bootstrapSwitch")}}(this)})},t.prototype._externalLabelHandler=function(){var t;return t=this.$element.closest("label"),t.on("click",function(e){return function(i){return i.preventDefault(),i.stopImmediatePropagation(),i.target===t[0]?e.toggleState():void 0}}(this))},t.prototype._formHandler=function(){var t;return t=this.$element.closest("form"),t.data("bootstrap-switch")?void 0:t.on("reset.bootstrapSwitch",function(){return i.setTimeout(function(){return t.find("input").filter(function(){return e(this).data("bootstrap-switch")}).each(function(){return e(this).bootstrapSwitch("state",this.checked)})},1)}).data("bootstrap-switch",!0)},t.prototype._getClasses=function(t){var i,n,o,s;if(!e.isArray(t))return[this.options.baseClass+"-"+t];for(n=[],o=0,s=t.length;s>o;o++)i=t[o],n.push(this.options.baseClass+"-"+i);return n},t}(),e.fn.bootstrapSwitch=function(){var i,o,s;return o=arguments[0],i=2<=arguments.length?t.call(arguments,1):[],s=this,this.each(function(){var t,a;return t=e(this),a=t.data("bootstrap-switch"),a||t.data("bootstrap-switch",a=new n(this,o)),"string"==typeof o?s=a[o].apply(a,i):void 0}),s},e.fn.bootstrapSwitch.Constructor=n,e.fn.bootstrapSwitch.defaults={state:!0,size:null,animate:!0,disabled:!1,readonly:!1,indeterminate:!1,inverse:!1,radioAllOff:!1,onColor:"primary",offColor:"default",onText:"ON",offText:"OFF",labelText:" ",handleWidth:"auto",labelWidth:"auto",baseClass:"bootstrap-switch",wrapperClass:"wrapper",onInit:function(){},onSwitchChange:function(){}}}(window.jQuery,window)}).call(this); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/handlebars.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/handlebars.min.js new file mode 100644 index 00000000..4e2aa8fe --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/handlebars.min.js @@ -0,0 +1,29 @@ +/*! + + handlebars v4.0.5 + +Copyright (C) 2011-2015 by Yehuda Katz + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +@license +*/ +!function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(21),i=e(h),j=c(22),k=c(27),l=c(28),m=e(l),n=c(25),o=e(n),p=c(20),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(18),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(19),p=e(o),q=c(20),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(7),j=c(15),k=c(17),l=e(k),m="4.0.5";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;bc;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return a||0===a?p(a)&&0===a.length?!0:!1:!0}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`","=":"="},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===n.call(a):!1};b.isArray=p},function(a,b){"use strict";function c(a,b){var e=b&&b.loc,f=void 0,g=void 0;e&&(f=e.start.line,g=e.start.column,a+=" - "+f+":"+g);for(var h=Error.prototype.constructor.call(this,a),i=0;i0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;l>h;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;c>f;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=r.COMPILER_REVISION;if(b!==c){if(c>b){var d=r.REVISION_CHANGES[c],e=r.REVISION_CHANGES[b];throw new q["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new q["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=o.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;i>h&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new q["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!==f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new q["default"]("No environment passed to template");if(!a||!a.main)throw new q["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new q["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;c>d;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:o.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=o.extend({},b,a)),c},noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new q["default"]("must pass block params");if(a.useDepths&&!g)throw new q["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return g&&b!==g[0]&&(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var d=void 0;if(c.fn&&c.fn!==i&&(c.data=r.createFrame(c.data),d=c.data["partial-block"]=c.fn,d.partials&&(c.partials=o.extend({},c.partials,d.partials))),void 0===a&&d&&(a=d),void 0===a)throw new q["default"]("The partial "+c.name+" could not be found");return a instanceof Function?a(b,c):void 0}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?r.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),o.extend(b,g)}return b}var l=c(3)["default"],m=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var n=c(5),o=l(n),p=c(6),q=m(p),r=c(4)},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(23),h=e(g),i=c(24),j=e(i),k=c(26),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16], +48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:((null===n||"undefined"==typeof n)&&(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;gb[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b.__esModule=!0,b["default"]=c},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(25),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;j>i;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;c>b;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;i>h;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;cc;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;b>c;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(b.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;c>d;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");d>c;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;c>b;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;c>b;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;g>f;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(29),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;i>h;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;i>h;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;h>c;c++)this.replaceStack(function(e){var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e), +d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;g>f;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);null==h?(this.context.programs.push(""),h=this.context.programs.length,d.index=h,d.name="program"+h,this.context.programs[h]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[h]=e.decorators,this.context.environments[h]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams):(d.index=h,d.name="program"+h,this.useDepths=this.useDepths||d.useDepths,this.useBlockParams=this.useBlockParams||d.useBlockParams)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;c>b;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : {}");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;d>c;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;g>e;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;c>b;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;e>c;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.easy-autocomplete.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.easy-autocomplete.min.js new file mode 100644 index 00000000..926b946b --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.easy-autocomplete.min.js @@ -0,0 +1,10 @@ +/* + * easy-autocomplete + * jQuery plugin for autocompletion + * + * @author Łukasz Pawełczak (http://github.com/pawelczak) + * @version 1.3.5 + * Copyright License: + */ + +var EasyAutocomplete=function(a){return a.Configuration=function(a){function b(){if("xml"===a.dataType&&(a.getValue||(a.getValue=function(a){return $(a).text()}),a.list||(a.list={}),a.list.sort||(a.list.sort={}),a.list.sort.method=function(b,c){return b=a.getValue(b),c=a.getValue(c),c>b?-1:b>c?1:0},a.list.match||(a.list.match={}),a.list.match.method=function(a,b){return a.search(b)>-1}),void 0!==a.categories&&a.categories instanceof Array){for(var b=[],c=0,d=a.categories.length;d>c;c+=1){var e=a.categories[c];for(var f in h.categories[0])void 0===e[f]&&(e[f]=h.categories[0][f]);b.push(e)}a.categories=b}}function c(){function b(a,c){var d=a||{};for(var e in a)void 0!==c[e]&&null!==c[e]&&("object"!=typeof c[e]||c[e]instanceof Array?d[e]=c[e]:b(a[e],c[e]));return void 0!==c.data&&null!==c.data&&"object"==typeof c.data&&(d.data=c.data),d}h=b(h,a)}function d(){if("list-required"!==h.url&&"function"!=typeof h.url){var b=h.url;h.url=function(){return b}}if(void 0!==h.ajaxSettings.url&&"function"!=typeof h.ajaxSettings.url){var b=h.ajaxSettings.url;h.ajaxSettings.url=function(){return b}}if("string"==typeof h.listLocation){var c=h.listLocation;"XML"===h.dataType.toUpperCase()?h.listLocation=function(a){return $(a).find(c)}:h.listLocation=function(a){return a[c]}}if("string"==typeof h.getValue){var d=h.getValue;h.getValue=function(a){return a[d]}}void 0!==a.categories&&(h.categoriesAssigned=!0)}function e(){void 0!==a.ajaxSettings&&"object"==typeof a.ajaxSettings?h.ajaxSettings=a.ajaxSettings:h.ajaxSettings={}}function f(a){return void 0!==h[a]&&null!==h[a]}function g(a,b){function c(b,d){for(var e in d)void 0===b[e]&&a.log("Property '"+e+"' does not exist in EasyAutocomplete options API."),"object"==typeof b[e]&&-1===$.inArray(e,i)&&c(b[e],d[e])}c(h,b)}var h={data:"list-required",url:"list-required",dataType:"json",listLocation:function(a){return a},xmlElementName:"",getValue:function(a){return a},autocompleteOff:!0,placeholder:!1,ajaxCallback:function(){},matchResponseProperty:!1,list:{sort:{enabled:!1,method:function(a,b){return a=h.getValue(a),b=h.getValue(b),b>a?-1:a>b?1:0}},maxNumberOfElements:6,hideOnEmptyPhrase:!0,match:{enabled:!1,caseSensitive:!1,method:function(a,b){return a.search(b)>-1}},showAnimation:{type:"normal",time:400,callback:function(){}},hideAnimation:{type:"normal",time:400,callback:function(){}},onClickEvent:function(){},onSelectItemEvent:function(){},onLoadEvent:function(){},onChooseEvent:function(){},onKeyEnterEvent:function(){},onMouseOverEvent:function(){},onMouseOutEvent:function(){},onShowListEvent:function(){},onHideListEvent:function(){}},highlightPhrase:!0,theme:"",cssClasses:"",minCharNumber:0,requestDelay:0,adjustWidth:!0,ajaxSettings:{},preparePostData:function(a,b){return a},loggerEnabled:!0,template:"",categoriesAssigned:!1,categories:[{maxNumberOfElements:4}]},i=["ajaxSettings","template"];this.get=function(a){return h[a]},this.equals=function(a,b){return!(!f(a)||h[a]!==b)},this.checkDataUrlProperties=function(){return"list-required"!==h.url||"list-required"!==h.data},this.checkRequiredProperties=function(){for(var a in h)if("required"===h[a])return logger.error("Option "+a+" must be defined"),!1;return!0},this.printPropertiesThatDoesntExist=function(a,b){g(a,b)},b(),c(),h.loggerEnabled===!0&&g(console,a),e(),d()},a}(EasyAutocomplete||{}),EasyAutocomplete=function(a){return a.Logger=function(){this.error=function(a){console.log("ERROR: "+a)},this.warning=function(a){console.log("WARNING: "+a)}},a}(EasyAutocomplete||{}),EasyAutocomplete=function(a){return a.Constans=function(){var a={CONTAINER_CLASS:"easy-autocomplete-container",CONTAINER_ID:"eac-container-",WRAPPER_CSS_CLASS:"easy-autocomplete"};this.getValue=function(b){return a[b]}},a}(EasyAutocomplete||{}),EasyAutocomplete=function(a){return a.ListBuilderService=function(a,b){function c(b,c){function d(){var d,e={};return void 0!==b.xmlElementName&&(e.xmlElementName=b.xmlElementName),void 0!==b.listLocation?d=b.listLocation:void 0!==a.get("listLocation")&&(d=a.get("listLocation")),void 0!==d?"string"==typeof d?e.data=$(c).find(d):"function"==typeof d&&(e.data=d(c)):e.data=c,e}function e(){var a={};return void 0!==b.listLocation?"string"==typeof b.listLocation?a.data=c[b.listLocation]:"function"==typeof b.listLocation&&(a.data=b.listLocation(c)):a.data=c,a}var f={};if(f="XML"===a.get("dataType").toUpperCase()?d():e(),void 0!==b.header&&(f.header=b.header),void 0!==b.maxNumberOfElements&&(f.maxNumberOfElements=b.maxNumberOfElements),void 0!==a.get("list").maxNumberOfElements&&(f.maxListSize=a.get("list").maxNumberOfElements),void 0!==b.getValue)if("string"==typeof b.getValue){var g=b.getValue;f.getValue=function(a){return a[g]}}else"function"==typeof b.getValue&&(f.getValue=b.getValue);else f.getValue=a.get("getValue");return f}function d(b){var c=[];return void 0===b.xmlElementName&&(b.xmlElementName=a.get("xmlElementName")),$(b.data).find(b.xmlElementName).each(function(){c.push(this)}),c}this.init=function(b){var c=[],d={};return d.data=a.get("listLocation")(b),d.getValue=a.get("getValue"),d.maxListSize=a.get("list").maxNumberOfElements,c.push(d),c},this.updateCategories=function(b,d){if(a.get("categoriesAssigned")){b=[];for(var e=0;ee;e+=1)c[e].data=b(a,c[e],d);return c},this.checkIfDataExists=function(a){for(var b=0,c=a.length;c>b;b+=1)if(void 0!==a[b].data&&a[b].data instanceof Array&&a[b].data.length>0)return!0;return!1}},a}(EasyAutocomplete||{}),EasyAutocomplete=function(a){return a.proccess=function(b,c,d){function e(a,c){var d=[],e="";if(b.get("list").match.enabled)for(var g=0,h=a.length;h>g;g+=1)e=b.get("getValue")(a[g]),f(e,c)&&d.push(a[g]);else d=a;return d}function f(a,c){return b.get("list").match.caseSensitive||("string"==typeof a&&(a=a.toLowerCase()),c=c.toLowerCase()),!!b.get("list").match.method(a,c)}function g(a){return void 0!==c.maxNumberOfElements&&a.length>c.maxNumberOfElements&&(a=a.slice(0,c.maxNumberOfElements)),a}function h(a){return b.get("list").sort.enabled&&a.sort(b.get("list").sort.method),a}a.proccess.match=f;var i=c.data,j=d;return i=e(i,j),i=g(i),i=h(i)},a}(EasyAutocomplete||{}),EasyAutocomplete=function(a){return a.Template=function(a){var b={basic:{type:"basic",method:function(a){return a},cssClass:""},description:{type:"description",fields:{description:"description"},method:function(a){return a+" - description"},cssClass:"eac-description"},iconLeft:{type:"iconLeft",fields:{icon:""},method:function(a){return a},cssClass:"eac-icon-left"},iconRight:{type:"iconRight",fields:{iconSrc:""},method:function(a){return a},cssClass:"eac-icon-right"},links:{type:"links",fields:{link:""},method:function(a){return a},cssClass:""},custom:{type:"custom",method:function(){},cssClass:""}},c=function(a){var c,d=a.fields;return"description"===a.type?(c=b.description.method,"string"==typeof d.description?c=function(a,b){return a+" - "+b[d.description]+""}:"function"==typeof d.description&&(c=function(a,b){return a+" - "+d.description(b)+""}),c):"iconRight"===a.type?("string"==typeof d.iconSrc?c=function(a,b){return a+""}:"function"==typeof d.iconSrc&&(c=function(a,b){return a+""}),c):"iconLeft"===a.type?("string"==typeof d.iconSrc?c=function(a,b){return""+a}:"function"==typeof d.iconSrc&&(c=function(a,b){return""+a}),c):"links"===a.type?("string"==typeof d.link?c=function(a,b){return""+a+""}:"function"==typeof d.link&&(c=function(a,b){return""+a+""}),c):"custom"===a.type?a.method:b.basic.method},d=function(a){return a&&a.type&&a.type&&b[a.type]?c(a):b.basic.method},e=function(a){var c=function(){return""};return a&&a.type&&a.type&&b[a.type]?function(){var c=b[a.type].cssClass;return function(){return c}}():c};this.getTemplateClass=e(a),this.build=d(a)},a}(EasyAutocomplete||{}),EasyAutocomplete=function(a){return a.main=function(b,c){function d(){return 0===t.length?void p.error("Input field doesn't exist."):o.checkDataUrlProperties()?o.checkRequiredProperties()?(e(),void g()):void p.error("Will not work without mentioned properties."):void p.error("One of options variables 'data' or 'url' must be defined.")}function e(){function a(){var a=$("
"),c=n.getValue("WRAPPER_CSS_CLASS");o.get("theme")&&""!==o.get("theme")&&(c+=" eac-"+o.get("theme")),o.get("cssClasses")&&""!==o.get("cssClasses")&&(c+=" "+o.get("cssClasses")),""!==q.getTemplateClass()&&(c+=" "+q.getTemplateClass()),a.addClass(c),t.wrap(a),o.get("adjustWidth")===!0&&b()}function b(){var a=t.outerWidth();t.parent().css("width",a)}function c(){t.unwrap()}function d(){var a=$("
").addClass(n.getValue("CONTAINER_CLASS"));a.attr("id",f()).prepend($("
    ")),function(){a.on("show.eac",function(){switch(o.get("list").showAnimation.type){case"slide":var b=o.get("list").showAnimation.time,c=o.get("list").showAnimation.callback;a.find("ul").slideDown(b,c);break;case"fade":var b=o.get("list").showAnimation.time,c=o.get("list").showAnimation.callback;a.find("ul").fadeIn(b),c;break;default:a.find("ul").show()}o.get("list").onShowListEvent()}).on("hide.eac",function(){switch(o.get("list").hideAnimation.type){case"slide":var b=o.get("list").hideAnimation.time,c=o.get("list").hideAnimation.callback;a.find("ul").slideUp(b,c);break;case"fade":var b=o.get("list").hideAnimation.time,c=o.get("list").hideAnimation.callback;a.find("ul").fadeOut(b,c);break;default:a.find("ul").hide()}o.get("list").onHideListEvent()}).on("selectElement.eac",function(){a.find("ul li").removeClass("selected"),a.find("ul li").eq(w).addClass("selected"),o.get("list").onSelectItemEvent()}).on("loadElements.eac",function(b,c,d){var e="",f=a.find("ul");f.empty().detach(),v=[];for(var h=0,i=0,k=c.length;k>i;i+=1){var l=c[i].data;if(0!==l.length){void 0!==c[i].header&&c[i].header.length>0&&f.append("
    "+c[i].header+"
    ");for(var m=0,n=l.length;n>m&&h
    "),function(){var a=m,b=h,f=c[i].getValue(l[a]);e.find(" > div").on("click",function(){t.val(f).trigger("change"),w=b,j(b),o.get("list").onClickEvent(),o.get("list").onChooseEvent()}).mouseover(function(){w=b,j(b),o.get("list").onMouseOverEvent()}).mouseout(function(){o.get("list").onMouseOutEvent()}).html(q.build(g(f,d),l[a]))}(),f.append(e),v.push(l[m]),h+=1}}a.append(f),o.get("list").onLoadEvent()})}(),t.after(a)}function e(){t.next("."+n.getValue("CONTAINER_CLASS")).remove()}function g(a,b){return o.get("highlightPhrase")&&""!==b?i(a,b):a}function h(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}function i(a,b){var c=h(b);return(a+"").replace(new RegExp("("+c+")","gi"),"$1")}t.parent().hasClass(n.getValue("WRAPPER_CSS_CLASS"))&&(e(),c()),a(),d(),u=$("#"+f()),o.get("placeholder")&&t.attr("placeholder",o.get("placeholder"))}function f(){var a=t.attr("id");return a=n.getValue("CONTAINER_ID")+a}function g(){function a(){s("autocompleteOff",!0)&&n(),b(),c(),d(),e(),f(),g()}function b(){t.focusout(function(){var a,b=t.val();o.get("list").match.caseSensitive||(b=b.toLowerCase());for(var c=0,d=v.length;d>c;c+=1)if(a=o.get("getValue")(v[c]),o.get("list").match.caseSensitive||(a=a.toLowerCase()),a===b)return w=c,void j(w)})}function c(){t.off("keyup").keyup(function(a){function b(a){function b(){var a={},b=o.get("ajaxSettings")||{};for(var c in b)a[c]=b[c];return a}function c(a,b){return o.get("matchResponseProperty")!==!1?"string"==typeof o.get("matchResponseProperty")?b[o.get("matchResponseProperty")]===a:"function"==typeof o.get("matchResponseProperty")?o.get("matchResponseProperty")(b)===a:!0:!0}if(!(a.length0?h():i()}var f=b();void 0!==f.url&&""!==f.url||(f.url=o.get("url")),void 0!==f.dataType&&""!==f.dataType||(f.dataType=o.get("dataType")),void 0!==f.url&&"list-required"!==f.url&&(f.url=f.url(a),f.data=o.get("preparePostData")(f.data,a),$.ajax(f).done(function(b){var d=r.init(b);d=r.updateCategories(d,b),d=r.convertXml(d),c(a,b)&&(d=r.processData(d,a),k(d,a)),r.checkIfDataExists(d)&&t.parent().find("li").length>0?h():i(),o.get("ajaxCallback")()}).fail(function(){p.warning("Fail to load response data")}).always(function(){}))}}switch(a.keyCode){case 27:i(),l();break;case 38:a.preventDefault(),v.length>0&&w>0&&(w-=1,t.val(o.get("getValue")(v[w])),j(w));break;case 40:a.preventDefault(),v.length>0&&w40||8===a.keyCode){var c=t.val();o.get("list").hideOnEmptyPhrase!==!0||8!==a.keyCode||""!==c?o.get("requestDelay")>0?(void 0!==m&&clearTimeout(m),m=setTimeout(function(){b(c)},o.get("requestDelay"))):b(c):i()}}})}function d(){t.on("keydown",function(a){a=a||window.event;var b=a.keyCode;return 38===b?(suppressKeypress=!0,!1):void 0}).keydown(function(a){13===a.keyCode&&w>-1&&(t.val(o.get("getValue")(v[w])),o.get("list").onKeyEnterEvent(),o.get("list").onChooseEvent(),w=-1,i(),a.preventDefault())})}function e(){t.off("keypress")}function f(){t.focus(function(){""!==t.val()&&v.length>0&&(w=-1,h())})}function g(){t.blur(function(){setTimeout(function(){w=-1,i()},250)})}function n(){t.attr("autocomplete","off")}a()}function h(){u.trigger("show.eac")}function i(){u.trigger("hide.eac")}function j(a){u.trigger("selectElement.eac",a)}function k(a,b){u.trigger("loadElements.eac",[a,b])}function l(){t.trigger("blur")}var m,n=new a.Constans,o=new a.Configuration(c),p=new a.Logger,q=new a.Template(c.template),r=new a.ListBuilderService(o,a.proccess),s=o.equals,t=b,u="",v=[],w=-1;a.consts=n,this.getConstants=function(){return n},this.getConfiguration=function(){return o},this.getContainer=function(){return u},this.getSelectedItemIndex=function(){return w},this.getItems=function(){return v},this.getItemData=function(a){return v.length0},a.assignRandomId=function(b){var c="";do c="eac-"+Math.floor(1e4*Math.random());while(0!==$("#"+c).length);elementId=a.consts.getValue("CONTAINER_ID")+c,$(b).attr("id",c)},a.setHandle=function(b,c){a.eacHandles[c]=b},a}(EasyAutocomplete||{});!function(a){a.fn.easyAutocomplete=function(b){return this.each(function(){var c=a(this),d=new EasyAutocomplete.main(c,b);EasyAutocomplete.inputHasId(c)||EasyAutocomplete.assignRandomId(c),d.init(),EasyAutocomplete.setHandle(d,c.attr("id"))})},a.fn.getSelectedItemIndex=function(){var b=a(this).attr("id");return void 0!==b?EasyAutocomplete.getHandle(b).getSelectedItemIndex():-1},a.fn.getItems=function(){var b=a(this).attr("id");return void 0!==b?EasyAutocomplete.getHandle(b).getItems():-1},a.fn.getItemData=function(b){var c=a(this).attr("id");return void 0!==c&&b>-1?EasyAutocomplete.getHandle(c).getItemData(b):-1},a.fn.getSelectedItemData=function(){var b=a(this).attr("id");return void 0!==b?EasyAutocomplete.getHandle(b).getSelectedItemData():-1}}(jQuery); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.mask.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.mask.min.js new file mode 100644 index 00000000..c06471c5 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/jquery.mask.min.js @@ -0,0 +1,15 @@ +// jQuery Mask Plugin v1.14.0 +// github.com/igorescobar/jQuery-Mask-Plugin +(function(b){"function"===typeof define&&define.amd?define(["jquery"],b):"object"===typeof exports?module.exports=b(require("jquery")):b(jQuery||Zepto)})(function(b){var y=function(a,e,d){var c={invalid:[],getCaret:function(){try{var r,b=0,e=a.get(0),d=document.selection,f=e.selectionStart;if(d&&-1===navigator.appVersion.indexOf("MSIE 10"))r=d.createRange(),r.moveStart("character",-c.val().length),b=r.text.length;else if(f||"0"===f)b=f;return b}catch(g){}},setCaret:function(r){try{if(a.is(":focus")){var c, +b=a.get(0);b.setSelectionRange?(b.focus(),b.setSelectionRange(r,r)):(c=b.createTextRange(),c.collapse(!0),c.moveEnd("character",r),c.moveStart("character",r),c.select())}}catch(e){}},events:function(){a.on("keydown.mask",function(c){a.data("mask-keycode",c.keyCode||c.which)}).on(b.jMaskGlobals.useInput?"input.mask":"keyup.mask",c.behaviour).on("paste.mask drop.mask",function(){setTimeout(function(){a.keydown().keyup()},100)}).on("change.mask",function(){a.data("changed",!0)}).on("blur.mask",function(){n=== +c.val()||a.data("changed")||a.trigger("change");a.data("changed",!1)}).on("blur.mask",function(){n=c.val()}).on("focus.mask",function(a){!0===d.selectOnFocus&&b(a.target).select()}).on("focusout.mask",function(){d.clearIfNotMatch&&!p.test(c.val())&&c.val("")})},getRegexMask:function(){for(var a=[],c,b,d,f,l=0;l-1?g=h=d:(g=-c.moveStart("character",-d),g+=a.slice(0,g).split("\n").length-1,c.compareEndPoints("EndToEnd",e)>-1?h=d:(h=-c.moveEnd("character",-d),h+=a.slice(0,h).split("\n").length-1)))),{start:g,end:h}}function c(){var a=!(s.val().length>=s.attr("maxlength")&&s.attr("maxlength")>=0),c=b(),d=c.start,e=c.end,f=c.start!==c.end&&s.val().substring(d,e).match(/\d/)?!0:!1,g="0"===s.val().substring(0,1);return a||f||g}function d(a){s.each(function(b,c){if(c.setSelectionRange)c.focus(),c.setSelectionRange(a,a);else if(c.createTextRange){var d=c.createTextRange();d.collapse(!0),d.moveEnd("character",a),d.moveStart("character",a),d.select()}})}function e(b){var c="";return b.indexOf("-")>-1&&(b=b.replace("-",""),c="-"),c+a.prefix+b+a.suffix}function f(b){var c,d,f,g=b.indexOf("-")>-1&&a.allowNegative?"-":"",h=b.replace(/[^0-9]/g,""),i=h.slice(0,h.length-a.precision);return i=i.replace(/^0*/g,""),i=i.replace(/\B(?=(\d{3})+(?!\d))/g,a.thousands),""===i&&(i="0"),c=g+i,a.precision>0&&(d=h.slice(h.length-a.precision),f=new Array(a.precision+1-d.length).join(0),c+=a.decimal+f+d),e(c)}function g(a){var b,c=s.val().length;s.val(f(s.val())),b=s.val().length,a-=c-b,d(a)}function h(){var a=s.val();s.val(f(a))}function i(){var b=s.val();return a.allowNegative?""!==b&&"-"===b.charAt(0)?b.replace("-",""):"-"+b:b}function j(a){a.preventDefault?a.preventDefault():a.returnValue=!1}function k(a){a=a||window.event;var d,e,f,h,k,l=a.which||a.charCode||a.keyCode;return void 0===l?!1:48>l||l>57?45===l?(s.val(i()),!1):43===l?(s.val(s.val().replace("-","")),!1):13===l||9===l?!0:!$.browser.mozilla||37!==l&&39!==l||0!==a.charCode?(j(a),!0):!0:c()?(j(a),d=String.fromCharCode(l),e=b(),f=e.start,h=e.end,k=s.val(),s.val(k.substring(0,f)+d+k.substring(h,k.length)),g(f+1),!1):!1}function l(c){c=c||window.event;var d,e,f,h,i,k=c.which||c.charCode||c.keyCode;return void 0===k?!1:(d=b(),e=d.start,f=d.end,8===k||46===k||63272===k?(j(c),h=s.val(),e===f&&(8===k?""===a.suffix?e-=1:(i=h.split("").reverse().join("").search(/\d/),e=h.length-i-1,f=e+1):f+=1),s.val(h.substring(0,e)+h.substring(f,h.length)),g(e),!1):9===k?!0:!0)}function m(){r=s.val(),h();var a,b=s.get(0);b.createTextRange&&(a=b.createTextRange(),a.collapse(!1),a.select())}function n(){setTimeout(function(){h()},0)}function o(){var b=parseFloat("0")/Math.pow(10,a.precision);return b.toFixed(a.precision).replace(new RegExp("\\.","g"),a.decimal)}function p(b){if($.browser.msie&&k(b),""===s.val()||s.val()===e(o()))a.allowZero?a.affixesStay?s.val(e(o())):s.val(o()):s.val("");else if(!a.affixesStay){var c=s.val().replace(a.prefix,"").replace(a.suffix,"");s.val(c)}s.val()!==r&&s.change()}function q(){var a,b=s.get(0);b.setSelectionRange?(a=s.val().length,b.setSelectionRange(a,a)):s.val(s.val())}var r,s=$(this);a=$.extend(a,s.data()),s.unbind(".maskMoney"),s.bind("keypress.maskMoney",k),s.bind("keydown.maskMoney",l),s.bind("blur.maskMoney",p),s.bind("focus.maskMoney",m),s.bind("click.maskMoney",q),s.bind("cut.maskMoney",n),s.bind("paste.maskMoney",n),s.bind("mask.maskMoney",h)})}};$.fn.maskMoney=function(b){return a[b]?a[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?($.error("Method "+b+" does not exist on jQuery.maskMoney"),void 0):a.init.apply(this,arguments)}}(window.jQuery||window.Zepto); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/numeral.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/numeral.min.js new file mode 100644 index 00000000..d17b5571 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/numeral.min.js @@ -0,0 +1,8 @@ +/*! + * numeral.js + * version : 1.5.3 + * author : Adam Draper + * license : MIT + * http://adamwdraper.github.com/Numeral-js/ + */ +(function(){function a(a){this._value=a}function b(a,b,c,d){var e,f,g=Math.pow(10,b);return f=(c(a*g)/g).toFixed(b),d&&(e=new RegExp("0{1,"+d+"}$"),f=f.replace(e,"")),f}function c(a,b,c){var d;return d=b.indexOf("$")>-1?e(a,b,c):b.indexOf("%")>-1?f(a,b,c):b.indexOf(":")>-1?g(a,b):i(a._value,b,c)}function d(a,b){var c,d,e,f,g,i=b,j=["KB","MB","GB","TB","PB","EB","ZB","YB"],k=!1;if(b.indexOf(":")>-1)a._value=h(b);else if(b===q)a._value=0;else{for("."!==o[p].delimiters.decimal&&(b=b.replace(/\./g,"").replace(o[p].delimiters.decimal,".")),c=new RegExp("[^a-zA-Z]"+o[p].abbreviations.thousand+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),d=new RegExp("[^a-zA-Z]"+o[p].abbreviations.million+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),e=new RegExp("[^a-zA-Z]"+o[p].abbreviations.billion+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),f=new RegExp("[^a-zA-Z]"+o[p].abbreviations.trillion+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),g=0;g<=j.length&&!(k=b.indexOf(j[g])>-1?Math.pow(1024,g+1):!1);g++);a._value=(k?k:1)*(i.match(c)?Math.pow(10,3):1)*(i.match(d)?Math.pow(10,6):1)*(i.match(e)?Math.pow(10,9):1)*(i.match(f)?Math.pow(10,12):1)*(b.indexOf("%")>-1?.01:1)*((b.split("-").length+Math.min(b.split("(").length-1,b.split(")").length-1))%2?1:-1)*Number(b.replace(/[^0-9\.]+/g,"")),a._value=k?Math.ceil(a._value):a._value}return a._value}function e(a,b,c){var d,e,f=b.indexOf("$"),g=b.indexOf("("),h=b.indexOf("-"),j="";return b.indexOf(" $")>-1?(j=" ",b=b.replace(" $","")):b.indexOf("$ ")>-1?(j=" ",b=b.replace("$ ","")):b=b.replace("$",""),e=i(a._value,b,c),1>=f?e.indexOf("(")>-1||e.indexOf("-")>-1?(e=e.split(""),d=1,(g>f||h>f)&&(d=0),e.splice(d,0,o[p].currency.symbol+j),e=e.join("")):e=o[p].currency.symbol+j+e:e.indexOf(")")>-1?(e=e.split(""),e.splice(-1,0,j+o[p].currency.symbol),e=e.join("")):e=e+j+o[p].currency.symbol,e}function f(a,b,c){var d,e="",f=100*a._value;return b.indexOf(" %")>-1?(e=" ",b=b.replace(" %","")):b=b.replace("%",""),d=i(f,b,c),d.indexOf(")")>-1?(d=d.split(""),d.splice(-1,0,e+"%"),d=d.join("")):d=d+e+"%",d}function g(a){var b=Math.floor(a._value/60/60),c=Math.floor((a._value-60*b*60)/60),d=Math.round(a._value-60*b*60-60*c);return b+":"+(10>c?"0"+c:c)+":"+(10>d?"0"+d:d)}function h(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}function i(a,c,d){var e,f,g,h,i,j,k=!1,l=!1,m=!1,n="",r=!1,s=!1,t=!1,u=!1,v=!1,w="",x="",y=Math.abs(a),z=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],A="",B=!1;if(0===a&&null!==q)return q;if(c.indexOf("(")>-1?(k=!0,c=c.slice(1,-1)):c.indexOf("+")>-1&&(l=!0,c=c.replace(/\+/g,"")),c.indexOf("a")>-1&&(r=c.indexOf("aK")>=0,s=c.indexOf("aM")>=0,t=c.indexOf("aB")>=0,u=c.indexOf("aT")>=0,v=r||s||t||u,c.indexOf(" a")>-1?(n=" ",c=c.replace(" a","")):c=c.replace("a",""),y>=Math.pow(10,12)&&!v||u?(n+=o[p].abbreviations.trillion,a/=Math.pow(10,12)):y=Math.pow(10,9)&&!v||t?(n+=o[p].abbreviations.billion,a/=Math.pow(10,9)):y=Math.pow(10,6)&&!v||s?(n+=o[p].abbreviations.million,a/=Math.pow(10,6)):(y=Math.pow(10,3)&&!v||r)&&(n+=o[p].abbreviations.thousand,a/=Math.pow(10,3))),c.indexOf("b")>-1)for(c.indexOf(" b")>-1?(w=" ",c=c.replace(" b","")):c=c.replace("b",""),g=0;g<=z.length;g++)if(e=Math.pow(1024,g),f=Math.pow(1024,g+1),a>=e&&f>a){w+=z[g],e>0&&(a/=e);break}return c.indexOf("o")>-1&&(c.indexOf(" o")>-1?(x=" ",c=c.replace(" o","")):c=c.replace("o",""),x+=o[p].ordinal(a)),c.indexOf("[.]")>-1&&(m=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],j=c.indexOf(","),i?(i.indexOf("[")>-1?(i=i.replace("]",""),i=i.split("["),A=b(a,i[0].length+i[1].length,d,i[1].length)):A=b(a,i.length,d),h=A.split(".")[0],A=A.split(".")[1].length?o[p].delimiters.decimal+A.split(".")[1]:"",m&&0===Number(A.slice(1))&&(A="")):h=b(a,null,d),h.indexOf("-")>-1&&(h=h.slice(1),B=!0),j>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+o[p].delimiters.thousands)),0===c.indexOf(".")&&(h=""),(k&&B?"(":"")+(!k&&B?"-":"")+(!B&&l?"+":"")+h+A+(x?x:"")+(n?n:"")+(w?w:"")+(k&&B?")":"")}function j(a,b){o[a]=b}function k(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)}function l(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var c=k(a),d=k(b);return c>d?c:d},-1/0)}var m,n="1.5.3",o={},p="en",q=null,r="0,0",s="undefined"!=typeof module&&module.exports;m=function(b){return m.isNumeral(b)?b=b.value():0===b||"undefined"==typeof b?b=0:Number(b)||(b=m.fn.unformat(b)),new a(Number(b))},m.version=n,m.isNumeral=function(b){return b instanceof a},m.language=function(a,b){if(!a)return p;if(a&&!b){if(!o[a])throw new Error("Unknown language : "+a);p=a}return(b||!o[a])&&j(a,b),m},m.languageData=function(a){if(!a)return o[p];if(!o[a])throw new Error("Unknown language : "+a);return o[a]},m.language("en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),m.zeroFormat=function(a){q="string"==typeof a?a:null},m.defaultFormat=function(a){r="string"==typeof a?a:"0.0"},"function"!=typeof Array.prototype.reduce&&(Array.prototype.reduce=function(a,b){"use strict";if(null===this||"undefined"==typeof this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof a)throw new TypeError(a+" is not a function");var c,d,e=this.length>>>0,f=!1;for(1c;++c)this.hasOwnProperty(c)&&(f?d=a(d,this[c],c,this):(d=this[c],f=!0));if(!f)throw new TypeError("Reduce of empty array with no initial value");return d}),m.fn=a.prototype={clone:function(){return m(this)},format:function(a,b){return c(this,a?a:r,void 0!==b?b:Math.round)},unformat:function(a){return"[object Number]"===Object.prototype.toString.call(a)?a:d(this,a?a:r)},value:function(){return this._value},valueOf:function(){return this._value},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b){return a+c*b}var c=l.call(null,this._value,a);return this._value=[this._value,a].reduce(b,0)/c,this},subtract:function(a){function b(a,b){return a-c*b}var c=l.call(null,this._value,a);return this._value=[a].reduce(b,this._value*c)/c,this},multiply:function(a){function b(a,b){var c=l(a,b);return a*c*b*c/(c*c)}return this._value=[this._value,a].reduce(b,1),this},divide:function(a){function b(a,b){var c=l(a,b);return a*c/(b*c)}return this._value=[this._value,a].reduce(b),this},difference:function(a){return Math.abs(m(this._value).subtract(a).value())}},s&&(module.exports=m),"undefined"==typeof ender&&(this.numeral=m),"function"==typeof define&&define.amd&&define([],function(){return m})}).call(this); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/pt-br.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/pt-br.min.js new file mode 100644 index 00000000..3f57b0c6 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/pt-br.min.js @@ -0,0 +1,6 @@ +/*! + * numeral.js language configuration + * language : portuguese brazil (pt-br) + * author : Ramiro Varandas Jr : https://github.com/ramirovjr + */ +!function(){var a={delimiters:{thousands:".",decimal:","},abbreviations:{thousand:"mil",million:"milhões",billion:"b",trillion:"t"},ordinal:function(){return"º"},currency:{symbol:"R$"}};"undefined"!=typeof module&&module.exports&&(module.exports=a),"undefined"!=typeof window&&this.numeral&&this.numeral.language&&this.numeral.language("pt-br",a)}(); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/uikit.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/uikit.min.js new file mode 100644 index 00000000..daee0299 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/javascripts/vendors/uikit.min.js @@ -0,0 +1,3 @@ +/*! UIkit 2.26.3 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ +!function(t){if("function"==typeof define&&define.amd&&define("uikit",function(){var i=window.UIkit||t(window,window.jQuery,window.document);return i.load=function(t,e,n,o){var s,a=t.split(","),r=[],l=(o.config&&o.config.uikit&&o.config.uikit.base?o.config.uikit.base:"").replace(/\/+$/g,"");if(!l)throw new Error("Please define base path to UIkit in the requirejs config.");for(s=0;s0||t.navigator.pointerEnabled&&t.navigator.maxTouchPoints>0||!1,n.support.mutationobserver=t.MutationObserver||t.WebKitMutationObserver||null,n.Utils={},n.Utils.isFullscreen=function(){return document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.fullscreenElement||!1},n.Utils.str2json=function(t,i){try{return i?JSON.parse(t.replace(/([\$\w]+)\s*:/g,function(t,i){return'"'+i+'":'}).replace(/'([^']+)'/g,function(t,i){return'"'+i+'"'})):new Function("","var json = "+t+"; return JSON.parse(JSON.stringify(json));")()}catch(e){return!1}},n.Utils.debounce=function(t,i,e){var n;return function(){var o=this,s=arguments,a=function(){n=null,e||t.apply(o,s)},r=e&&!n;clearTimeout(n),n=setTimeout(a,i),r&&t.apply(o,s)}},n.Utils.throttle=function(t,i){var e=!1;return function(){e||(t.call(),e=!0,setTimeout(function(){e=!1},i))}},n.Utils.removeCssRules=function(t){var i,e,n,o,s,a,r,l,c,u;t&&setTimeout(function(){try{for(u=document.styleSheets,o=0,r=u.length;r>o;o++){for(n=u[o],e=[],n.cssRules=n.cssRules,i=s=0,l=n.cssRules.length;l>s;i=++s)n.cssRules[i].type===CSSRule.STYLE_RULE&&t.test(n.cssRules[i].selectorText)&&e.unshift(i);for(a=0,c=e.length;c>a;a++)n.deleteRule(e[a])}}catch(h){}},0)},n.Utils.isInView=function(t,e){var o=i(t);if(!o.is(":visible"))return!1;var s=n.$win.scrollLeft(),a=n.$win.scrollTop(),r=o.offset(),l=r.left,c=r.top;return e=i.extend({topoffset:0,leftoffset:0},e),c+o.height()>=a&&c-e.topoffset<=a+n.$win.height()&&l+o.width()>=s&&l-e.leftoffset<=s+n.$win.width()?!0:!1},n.Utils.checkDisplay=function(t,e){var o=n.$("[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]",t||document);return t&&!o.length&&(o=i(t)),o.trigger("display.uk.check"),e&&("string"!=typeof e&&(e='[class*="uk-animation-"]'),o.find(e).each(function(){var t=n.$(this),i=t.attr("class"),e=i.match(/uk\-animation\-(.+)/);t.removeClass(e[0]).width(),t.addClass(e[0])})),o},n.Utils.options=function(t){if("string"!=i.type(t))return t;-1!=t.indexOf(":")&&"}"!=t.trim().substr(-1)&&(t="{"+t+"}");var e=t?t.indexOf("{"):-1,o={};if(-1!=e)try{o=n.Utils.str2json(t.substr(e))}catch(s){}return o},n.Utils.animate=function(t,e){var o=i.Deferred();return t=n.$(t),t.css("display","none").addClass(e).one(n.support.animation.end,function(){t.removeClass(e),o.resolve()}),t.css("display",""),o.promise()},n.Utils.uid=function(t){return(t||"id")+(new Date).getTime()+"RAND"+Math.ceil(1e5*Math.random())},n.Utils.template=function(t,i){for(var e,n,o,s,a=t.replace(/\n/g,"\\n").replace(/\{\{\{\s*(.+?)\s*\}\}\}/g,"{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),r=0,l=[],c=0;r/g, '>');}"].join("\n")),i?s(i):s},n.Utils.events={},n.Utils.events.click=n.support.touch?"tap":"click",t.UIkit=n,n.fn=function(t,e){var o=arguments,s=t.match(/^([a-z\-]+)(?:\.([a-z]+))?/i),a=s[1],r=s[2];return n[a]?this.each(function(){var t=i(this),s=t.data(a);s||t.data(a,s=n[a](this,r?void 0:e)),r&&s[r].apply(s,Array.prototype.slice.call(o,1))}):(i.error("UIkit component ["+a+"] does not exist."),this)},i.UIkit=n,i.fn.uk=n.fn,n.langdirection="rtl"==n.$html.attr("dir")?"right":"left",n.components={},n.component=function(t,e){var o=function(e,s){var a=this;return this.UIkit=n,this.element=e?n.$(e):null,this.options=i.extend(!0,{},this.defaults,s),this.plugins={},this.element&&this.element.data(t,this),this.init(),(this.options.plugins.length?this.options.plugins:Object.keys(o.plugins)).forEach(function(t){o.plugins[t].init&&(o.plugins[t].init(a),a.plugins[t]=!0)}),this.trigger("init.uk.component",[t,this]),this};return o.plugins={},i.extend(!0,o.prototype,{defaults:{plugins:[]},boot:function(){},init:function(){},on:function(t,i,e){return n.$(this.element||this).on(t,i,e)},one:function(t,i,e){return n.$(this.element||this).one(t,i,e)},off:function(t){return n.$(this.element||this).off(t)},trigger:function(t,i){return n.$(this.element||this).trigger(t,i)},find:function(t){return n.$(this.element?this.element:[]).find(t)},proxy:function(t,i){var e=this;i.split(" ").forEach(function(i){e[i]||(e[i]=function(){return t[i].apply(t,arguments)})})},mixin:function(t,i){var e=this;i.split(" ").forEach(function(i){e[i]||(e[i]=t[i].bind(e))})},option:function(){return 1==arguments.length?this.options[arguments[0]]||void 0:(2==arguments.length&&(this.options[arguments[0]]=arguments[1]),void 0)}},e),this.components[t]=o,this[t]=function(){var e,o;if(arguments.length)switch(arguments.length){case 1:"string"==typeof arguments[0]||arguments[0].nodeType||arguments[0]instanceof jQuery?e=i(arguments[0]):o=arguments[0];break;case 2:e=i(arguments[0]),o=arguments[1]}return e&&e.data(t)?e.data(t):new n.components[t](e,o)},n.domready&&n.component.boot(t),o},n.plugin=function(t,i,e){this.components[t].plugins[i]=e},n.component.boot=function(t){n.components[t].prototype&&n.components[t].prototype.boot&&!n.components[t].booted&&(n.components[t].prototype.boot.apply(n,[]),n.components[t].booted=!0)},n.component.bootComponents=function(){for(var t in n.components)n.component.boot(t)},n.domObservers=[],n.domready=!1,n.ready=function(t){n.domObservers.push(t),n.domready&&t(document)},n.on=function(t,i,e){return t&&t.indexOf("ready.uk.dom")>-1&&n.domready&&i.apply(n.$doc),n.$doc.on(t,i,e)},n.one=function(t,i,e){return t&&t.indexOf("ready.uk.dom")>-1&&n.domready?(i.apply(n.$doc),n.$doc):n.$doc.one(t,i,e)},n.trigger=function(t,i){return n.$doc.trigger(t,i)},n.domObserve=function(t,i){n.support.mutationobserver&&(i=i||function(){},n.$(t).each(function(){var t=this,e=n.$(t);if(!e.data("observer"))try{var o=new n.support.mutationobserver(n.Utils.debounce(function(){i.apply(t,[]),e.trigger("changed.uk.dom")},50),{childList:!0,subtree:!0});o.observe(t,{childList:!0,subtree:!0}),e.data("observer",o)}catch(s){}}))},n.init=function(t){t=t||document,n.domObservers.forEach(function(i){i(t)})},n.on("domready.uk.dom",function(){n.init(),n.domready&&n.Utils.checkDisplay()}),document.addEventListener("DOMContentLoaded",function(){var t=function(){if(n.$body=n.$("body"),n.trigger("beforeready.uk.dom"),n.component.bootComponents(),requestAnimationFrame(function(){var t={dir:{x:0,y:0},x:window.pageXOffset,y:window.pageYOffset},i=function(){var e=window.pageXOffset,o=window.pageYOffset;(t.x!=e||t.y!=o)&&(t.dir.x=e!=t.x?e>t.x?1:-1:0,t.dir.y=o!=t.y?o>t.y?1:-1:0,t.x=e,t.y=o,n.$doc.trigger("scrolling.uk.document",[{dir:{x:t.dir.x,y:t.dir.y},x:e,y:o}])),requestAnimationFrame(i)};return n.support.touch&&n.$html.on("touchmove touchend MSPointerMove MSPointerUp pointermove pointerup",i),(t.x||t.y)&&i(),i}()),n.trigger("domready.uk.dom"),n.support.touch&&navigator.userAgent.match(/(iPad|iPhone|iPod)/g)&&n.$win.on("load orientationchange resize",n.Utils.debounce(function(){var t=function(){return i(".uk-height-viewport").css("height",window.innerHeight),t};return t()}(),100)),n.trigger("afterready.uk.dom"),n.domready=!0,n.support.mutationobserver){var t=n.Utils.debounce(function(){requestAnimationFrame(function(){n.init(document.body)})},10);new n.support.mutationobserver(function(i){var e=!1;i.every(function(t){if("childList"!=t.type)return!0;for(var i,n=0;n=Math.abs(e-n)?t-i>0?"Left":"Right":e-n>0?"Up":"Down"}function e(){c=null,h.last&&(void 0!==h.el&&h.el.trigger("longTap"),h={})}function n(){c&&clearTimeout(c),c=null}function o(){a&&clearTimeout(a),r&&clearTimeout(r),l&&clearTimeout(l),c&&clearTimeout(c),a=r=l=c=null,h={}}function s(t){return t.pointerType==t.MSPOINTER_TYPE_TOUCH&&t.isPrimary}if(!t.fn.swipeLeft){var a,r,l,c,u,h={},d=750;t(function(){var p,f,m,g=0,v=0;"MSGesture"in window&&(u=new MSGesture,u.target=document.body),t(document).on("MSGestureEnd gestureend",function(t){var i=t.originalEvent.velocityX>1?"Right":t.originalEvent.velocityX<-1?"Left":t.originalEvent.velocityY>1?"Down":t.originalEvent.velocityY<-1?"Up":null;i&&void 0!==h.el&&(h.el.trigger("swipe"),h.el.trigger("swipe"+i))}).on("touchstart MSPointerDown pointerdown",function(i){("MSPointerDown"!=i.type||s(i.originalEvent))&&(m="MSPointerDown"==i.type||"pointerdown"==i.type?i:i.originalEvent.touches[0],p=Date.now(),f=p-(h.last||p),h.el=t("tagName"in m.target?m.target:m.target.parentNode),a&&clearTimeout(a),h.x1=m.pageX,h.y1=m.pageY,f>0&&250>=f&&(h.isDoubleTap=!0),h.last=p,c=setTimeout(e,d),!u||"MSPointerDown"!=i.type&&"pointerdown"!=i.type&&"touchstart"!=i.type||u.addPointer(i.originalEvent.pointerId))}).on("touchmove MSPointerMove pointermove",function(t){("MSPointerMove"!=t.type||s(t.originalEvent))&&(m="MSPointerMove"==t.type||"pointermove"==t.type?t:t.originalEvent.touches[0],n(),h.x2=m.pageX,h.y2=m.pageY,g+=Math.abs(h.x1-h.x2),v+=Math.abs(h.y1-h.y2))}).on("touchend MSPointerUp pointerup",function(e){("MSPointerUp"!=e.type||s(e.originalEvent))&&(n(),h.x2&&Math.abs(h.x1-h.x2)>30||h.y2&&Math.abs(h.y1-h.y2)>30?l=setTimeout(function(){void 0!==h.el&&(h.el.trigger("swipe"),h.el.trigger("swipe"+i(h.x1,h.x2,h.y1,h.y2))),h={}},0):"last"in h&&(isNaN(g)||30>g&&30>v?r=setTimeout(function(){var i=t.Event("tap");i.cancelTouch=o,void 0!==h.el&&h.el.trigger(i),h.isDoubleTap?(void 0!==h.el&&h.el.trigger("doubleTap"),h={}):a=setTimeout(function(){a=null,void 0!==h.el&&h.el.trigger("singleTap"),h={}},250)},0):h={},g=v=0))}).on("touchcancel MSPointerCancel",o),t(window).on("scroll",o)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(i){t.fn[i]=function(e){return t(this).on(i,e)}})}}(jQuery),function(t){"use strict";var i=[];t.component("stackMargin",{defaults:{cls:"uk-margin-small-top",rowfirst:!1,observe:!1},boot:function(){t.ready(function(i){t.$("[data-uk-margin]",i).each(function(){var i=t.$(this);i.data("stackMargin")||t.stackMargin(i,t.Utils.options(i.attr("data-uk-margin")))})})},init:function(){var e=this;t.$win.on("resize orientationchange",function(){var i=function(){e.process()};return t.$(function(){i(),t.$win.on("load",i)}),t.Utils.debounce(i,20)}()),this.on("display.uk.check",function(){this.element.is(":visible")&&this.process()}.bind(this)),this.options.observe&&t.domObserve(this.element,function(){e.element.is(":visible")&&e.process()}),i.push(this)},process:function(){var i=this.element.children();if(t.Utils.stackMargin(i,this.options),!this.options.rowfirst||!i.length)return this;var e={},n=!1;return i.removeClass(this.options.rowfirst).each(function(i,o){o=t.$(this),"none"!=this.style.display&&(i=o.offset().left,((e[i]=e[i]||[])&&e[i]).push(this),n=n===!1?i:Math.min(n,i))}),t.$(e[n]).addClass(this.options.rowfirst),this}}),function(){var i=[],e=function(t){if(t.is(":visible")){var i=t.parent().width(),e=t.data("width"),n=i/e,o=Math.floor(n*t.data("height"));t.css({height:e>i?o:t.data("height")})}};t.component("responsiveElement",{defaults:{},boot:function(){t.ready(function(i){t.$("iframe.uk-responsive-width, [data-uk-responsive]",i).each(function(){var i,e=t.$(this);e.data("responsiveElement")||(i=t.responsiveElement(e,{}))})})},init:function(){var t=this.element;t.attr("width")&&t.attr("height")&&(t.data({width:t.attr("width"),height:t.attr("height")}).on("display.uk.check",function(){e(t)}),e(t),i.push(t))}}),t.$win.on("resize load",t.Utils.debounce(function(){i.forEach(function(t){e(t)})},15))}(),t.Utils.stackMargin=function(i,e){e=t.$.extend({cls:"uk-margin-small-top"},e),i=t.$(i).removeClass(e.cls);var n=!1;i.each(function(i,e,o,s){s=t.$(this),"none"!=s.css("display")&&(i=s.offset(),e=s.outerHeight(),o=i.top+e,s.data({ukMarginPos:o,ukMarginTop:i.top}),(n===!1||i.topn.top&&i.data("ukMarginPos")>n.pos&&i.addClass(e.cls)})},t.Utils.matchHeights=function(i,e){i=t.$(i).css("min-height",""),e=t.$.extend({row:!0},e);var n=function(i){if(!(i.length<2)){var e=0;i.each(function(){e=Math.max(e,t.$(this).outerHeight())}).each(function(){var i=t.$(this),n=e-("border-box"==i.css("box-sizing")?0:i.outerHeight()-i.height());i.css("min-height",n+"px")})}};e.row?(i.first().width(),setTimeout(function(){var e=!1,o=[];i.each(function(){var i=t.$(this),s=i.offset().top;s!=e&&o.length&&(n(t.$(o)),o=[],s=i.offset().top),o.push(i),e=s}),o.length&&n(t.$(o))},0)):n(i)},function(i){t.Utils.inlineSvg=function(e,n){t.$(e||'img[src$=".svg"]',n||document).each(function(){var e=t.$(this),n=e.attr("src");if(!i[n]){var o=t.$.Deferred();t.$.get(n,{nc:Math.random()},function(i){o.resolve(t.$(i).find("svg"))}),i[n]=o.promise()}i[n].then(function(i){var n=t.$(i).clone();e.attr("id")&&n.attr("id",e.attr("id")),e.attr("class")&&n.attr("class",e.attr("class")),e.attr("style")&&n.attr("style",e.attr("style")),e.attr("width")&&(n.attr("width",e.attr("width")),e.attr("height")||n.removeAttr("height")),e.attr("height")&&(n.attr("height",e.attr("height")),e.attr("width")||n.removeAttr("width")),e.replaceWith(n)})})},t.ready(function(i){t.Utils.inlineSvg("[data-uk-svg]",i)})}({})}(UIkit),function(t){"use strict";function i(i,e){e=t.$.extend({duration:1e3,transition:"easeOutExpo",offset:0,complete:function(){}},e);var n=i.offset().top-e.offset,o=t.$doc.height(),s=window.innerHeight;n+s>o&&(n=o-s),t.$("html,body").stop().animate({scrollTop:n},e.duration,e.transition).promise().done(e.complete)}t.component("smoothScroll",{boot:function(){t.$html.on("click.smooth-scroll.uikit","[data-uk-smooth-scroll]",function(){var i=t.$(this);if(!i.data("smoothScroll")){{t.smoothScroll(i,t.Utils.options(i.attr("data-uk-smooth-scroll")))}i.trigger("click")}return!1})},init:function(){var e=this;this.on("click",function(n){n.preventDefault(),i(t.$(this.hash).length?t.$(this.hash):t.$("body"),e.options)})}}),t.Utils.scrollToElement=i,t.$.easing.easeOutExpo||(t.$.easing.easeOutExpo=function(t,i,e,n,o){return i==o?e+n:n*(-Math.pow(2,-10*i/o)+1)+e})}(UIkit),function(t){"use strict";var i=t.$win,e=t.$doc,n=[],o=function(){for(var t=0;t=u)return e[t]}();if(!h)return;c.options.closest?(o.blur().closest(l).removeClass(r),s=o.filter("a[href='#"+h.attr("id")+"']").closest(l).addClass(r)):s=o.removeClass(r).filter("a[href='#"+h.attr("id")+"']").addClass(r),c.element.trigger("inview.uk.scrollspynav",[h,s])}};this.options.smoothscroll&&t.smoothScroll&&o.each(function(){t.smoothScroll(this,c.options.smoothscroll)}),u(),this.element.data("scrollspynav",this),this.check=u,s.push(this)}})}(UIkit),function(t){"use strict";var i=[];t.component("toggle",{defaults:{target:!1,cls:"uk-hidden",animation:!1,duration:200},boot:function(){t.ready(function(e){t.$("[data-uk-toggle]",e).each(function(){var i=t.$(this);if(!i.data("toggle")){t.toggle(i,t.Utils.options(i.attr("data-uk-toggle")))}}),setTimeout(function(){i.forEach(function(t){t.getToggles()})},0)})},init:function(){var t=this;this.aria=-1!==this.options.cls.indexOf("uk-hidden"),this.getToggles(),this.on("click",function(i){t.element.is('a[href="#"]')&&i.preventDefault(),t.toggle()}),i.push(this)},toggle:function(){if(this.totoggle.length){if(this.options.animation&&t.support.animation){var i=this,e=this.options.animation.split(",");1==e.length&&(e[1]=e[0]),e[0]=e[0].trim(),e[1]=e[1].trim(),this.totoggle.css("animation-duration",this.options.duration+"ms"),this.totoggle.each(function(){var n=t.$(this);n.hasClass(i.options.cls)?(n.toggleClass(i.options.cls),t.Utils.animate(n,e[0]).then(function(){n.css("animation-duration",""),t.Utils.checkDisplay(n)})):t.Utils.animate(this,e[1]+" uk-animation-reverse").then(function(){n.toggleClass(i.options.cls).css("animation-duration",""),t.Utils.checkDisplay(n)})})}else this.totoggle.toggleClass(this.options.cls),t.Utils.checkDisplay(this.totoggle);this.updateAria()}},getToggles:function(){this.totoggle=this.options.target?t.$(this.options.target):[],this.updateAria()},updateAria:function(){this.aria&&this.totoggle.length&&this.totoggle.each(function(){t.$(this).attr("aria-hidden",t.$(this).hasClass("uk-hidden"))})}})}(UIkit),function(t){"use strict";t.component("alert",{defaults:{fade:!0,duration:200,trigger:".uk-alert-close"},boot:function(){t.$html.on("click.alert.uikit","[data-uk-alert]",function(i){var e=t.$(this);if(!e.data("alert")){var n=t.alert(e,t.Utils.options(e.attr("data-uk-alert")));t.$(i.target).is(n.options.trigger)&&(i.preventDefault(),n.close())}})},init:function(){var t=this;this.on("click",this.options.trigger,function(i){i.preventDefault(),t.close()})},close:function(){var t=this.trigger("close.uk.alert"),i=function(){this.trigger("closed.uk.alert").remove()}.bind(this);this.options.fade?t.css("overflow","hidden").css("max-height",t.height()).animate({height:0,opacity:0,"padding-top":0,"padding-bottom":0,"margin-top":0,"margin-bottom":0},this.options.duration,i):i()}})}(UIkit),function(t){"use strict";t.component("buttonRadio",{defaults:{activeClass:"uk-active",target:".uk-button"},boot:function(){t.$html.on("click.buttonradio.uikit","[data-uk-button-radio]",function(i){var e=t.$(this);if(!e.data("buttonRadio")){var n=t.buttonRadio(e,t.Utils.options(e.attr("data-uk-button-radio"))),o=t.$(i.target);o.is(n.options.target)&&o.trigger("click")}})},init:function(){var i=this;this.find(i.options.target).attr("aria-checked","false").filter("."+i.options.activeClass).attr("aria-checked","true"),this.on("click",this.options.target,function(e){var n=t.$(this);n.is('a[href="#"]')&&e.preventDefault(),i.find(i.options.target).not(n).removeClass(i.options.activeClass).blur(),n.addClass(i.options.activeClass),i.find(i.options.target).not(n).attr("aria-checked","false"),n.attr("aria-checked","true"),i.trigger("change.uk.button",[n])})},getSelected:function(){return this.find("."+this.options.activeClass)}}),t.component("buttonCheckbox",{defaults:{activeClass:"uk-active",target:".uk-button"},boot:function(){t.$html.on("click.buttoncheckbox.uikit","[data-uk-button-checkbox]",function(i){var e=t.$(this);if(!e.data("buttonCheckbox")){var n=t.buttonCheckbox(e,t.Utils.options(e.attr("data-uk-button-checkbox"))),o=t.$(i.target);o.is(n.options.target)&&o.trigger("click")}})},init:function(){var i=this;this.find(i.options.target).attr("aria-checked","false").filter("."+i.options.activeClass).attr("aria-checked","true"),this.on("click",this.options.target,function(e){var n=t.$(this);n.is('a[href="#"]')&&e.preventDefault(),n.toggleClass(i.options.activeClass).blur(),n.attr("aria-checked",n.hasClass(i.options.activeClass)),i.trigger("change.uk.button",[n])})},getSelected:function(){return this.find("."+this.options.activeClass)}}),t.component("button",{defaults:{},boot:function(){t.$html.on("click.button.uikit","[data-uk-button]",function(){var i=t.$(this);if(!i.data("button")){{t.button(i,t.Utils.options(i.attr("data-uk-button")))}i.trigger("click")}})},init:function(){var t=this;this.element.attr("aria-pressed",this.element.hasClass("uk-active")),this.on("click",function(i){t.element.is('a[href="#"]')&&i.preventDefault(),t.toggle(),t.trigger("change.uk.button",[t.element.blur().hasClass("uk-active")])})},toggle:function(){this.element.toggleClass("uk-active"),this.element.attr("aria-pressed",this.element.hasClass("uk-active"))}})}(UIkit),function(t){"use strict";function i(i,e,n,o){if(i=t.$(i),e=t.$(e),n=n||window.innerWidth,o=o||i.offset(),e.length){var s=e.outerWidth();if(i.css("min-width",s),"right"==t.langdirection){var a=n-(e.offset().left+s),r=n-(i.offset().left+i.outerWidth());i.css("margin-right",a-r)}else i.css("margin-left",e.offset().left-o.left)}}var e,n=!1,o={x:{"bottom-left":"bottom-right","bottom-right":"bottom-left","bottom-center":"bottom-center","top-left":"top-right","top-right":"top-left","top-center":"top-center","left-top":"right-top","left-bottom":"right-bottom","left-center":"right-center","right-top":"left-top","right-bottom":"left-bottom","right-center":"left-center"},y:{"bottom-left":"top-left","bottom-right":"top-right","bottom-center":"top-center","top-left":"bottom-left","top-right":"bottom-right","top-center":"bottom-center","left-top":"left-bottom","left-bottom":"left-top","left-center":"left-center","right-top":"right-bottom","right-bottom":"right-top","right-center":"right-center"},xy:{"bottom-left":"top-right","bottom-right":"top-left","bottom-center":"top-center","top-left":"bottom-right","top-right":"bottom-left","top-center":"bottom-center","left-top":"right-bottom","left-bottom":"right-top","left-center":"right-center","right-top":"left-bottom","right-bottom":"left-top","right-center":"left-center"}};t.component("dropdown",{defaults:{mode:"hover",pos:"bottom-left",offset:0,remaintime:800,justify:!1,boundary:t.$win,delay:0,dropdownSelector:".uk-dropdown,.uk-dropdown-blank",hoverDelayIdle:250,preventflip:!1},remainIdle:!1,boot:function(){var i=t.support.touch?"click":"mouseenter";t.$html.on(i+".dropdown.uikit","[data-uk-dropdown]",function(e){var n=t.$(this);if(!n.data("dropdown")){var o=t.dropdown(n,t.Utils.options(n.attr("data-uk-dropdown")));("click"==i||"mouseenter"==i&&"hover"==o.options.mode)&&o.element.trigger(i),o.element.find(o.options.dropdownSelector).length&&e.preventDefault()}})},init:function(){var i=this;this.dropdown=this.find(this.options.dropdownSelector),this.offsetParent=this.dropdown.parents().filter(function(){return-1!==t.$.inArray(t.$(this).css("position"),["relative","fixed","absolute"])}).slice(0,1),this.centered=this.dropdown.hasClass("uk-dropdown-center"),this.justified=this.options.justify?t.$(this.options.justify):!1,this.boundary=t.$(this.options.boundary),this.boundary.length||(this.boundary=t.$win),this.dropdown.hasClass("uk-dropdown-up")&&(this.options.pos="top-left"),this.dropdown.hasClass("uk-dropdown-flip")&&(this.options.pos=this.options.pos.replace("left","right")),this.dropdown.hasClass("uk-dropdown-center")&&(this.options.pos=this.options.pos.replace(/(left|right)/,"center")),this.element.attr("aria-haspopup","true"),this.element.attr("aria-expanded",this.element.hasClass("uk-open")),"click"==this.options.mode||t.support.touch?this.on("click.uk.dropdown",function(e){var n=t.$(e.target);n.parents(i.options.dropdownSelector).length||((n.is("a[href='#']")||n.parent().is("a[href='#']")||i.dropdown.length&&!i.dropdown.is(":visible"))&&e.preventDefault(),n.blur()),i.element.hasClass("uk-open")?(!i.dropdown.find(e.target).length||n.is(".uk-dropdown-close")||n.parents(".uk-dropdown-close").length)&&i.hide():i.show()}):this.on("mouseenter",function(){i.trigger("pointerenter.uk.dropdown",[i]),i.remainIdle&&clearTimeout(i.remainIdle),e&&clearTimeout(e),n&&n==i||(e=n&&n!=i?setTimeout(function(){e=setTimeout(i.show.bind(i),i.options.delay)},i.options.hoverDelayIdle):setTimeout(i.show.bind(i),i.options.delay))}).on("mouseleave",function(){e&&clearTimeout(e),i.remainIdle=setTimeout(function(){n&&n==i&&i.hide()},i.options.remaintime),i.trigger("pointerleave.uk.dropdown",[i])}).on("click",function(e){var o=t.$(e.target);return i.remainIdle&&clearTimeout(i.remainIdle),n&&n==i?((!i.dropdown.find(e.target).length||o.is(".uk-dropdown-close")||o.parents(".uk-dropdown-close").length)&&i.hide(),void 0):((o.is("a[href='#']")||o.parent().is("a[href='#']"))&&e.preventDefault(),i.show(),void 0)})},show:function(){t.$html.off("click.outer.dropdown"),n&&n!=this&&n.hide(!0),e&&clearTimeout(e),this.trigger("beforeshow.uk.dropdown",[this]),this.checkDimensions(),this.element.addClass("uk-open"),this.element.attr("aria-expanded","true"),this.trigger("show.uk.dropdown",[this]),t.Utils.checkDisplay(this.dropdown,!0),n=this,this.registerOuterClick()},hide:function(t){this.trigger("beforehide.uk.dropdown",[this,t]),this.element.removeClass("uk-open"),this.remainIdle&&clearTimeout(this.remainIdle),this.remainIdle=!1,this.element.attr("aria-expanded","false"),this.trigger("hide.uk.dropdown",[this,t]),n==this&&(n=!1)},registerOuterClick:function(){var i=this;t.$html.off("click.outer.dropdown"),setTimeout(function(){t.$html.on("click.outer.dropdown",function(o){e&&clearTimeout(e);t.$(o.target);n!=i||i.element.find(o.target).length||(i.hide(!0),t.$html.off("click.outer.dropdown"))})},10)},checkDimensions:function(){if(this.dropdown.length){this.dropdown.removeClass("uk-dropdown-top uk-dropdown-bottom uk-dropdown-left uk-dropdown-right uk-dropdown-stack").css({"top-left":"",left:"","margin-left":"","margin-right":""}),this.justified&&this.justified.length&&this.dropdown.css("min-width","");var e,n=t.$.extend({},this.offsetParent.offset(),{width:this.offsetParent[0].offsetWidth,height:this.offsetParent[0].offsetHeight}),s=this.options.offset,a=this.dropdown,r=(a.show().offset()||{left:0,top:0},a.outerWidth()),l=a.outerHeight(),c=this.boundary.width(),u=(this.boundary[0]!==window&&this.boundary.offset()?this.boundary.offset():{top:0,left:0},this.options.pos),h={"bottom-left":{top:0+n.height+s,left:0},"bottom-right":{top:0+n.height+s,left:0+n.width-r},"bottom-center":{top:0+n.height+s,left:0+n.width/2-r/2},"top-left":{top:0-l-s,left:0},"top-right":{top:0-l-s,left:0+n.width-r},"top-center":{top:0-l-s,left:0+n.width/2-r/2},"left-top":{top:0,left:0-r-s},"left-bottom":{top:0+n.height-l,left:0-r-s},"left-center":{top:0+n.height/2-l/2,left:0-r-s},"right-top":{top:0,left:0+n.width+s},"right-bottom":{top:0+n.height-l,left:0+n.width+s},"right-center":{top:0+n.height/2-l/2,left:0+n.width+s}},d={};if(e=u.split("-"),d=h[u]?h[u]:h["bottom-left"],this.justified&&this.justified.length)i(a.css({left:0}),this.justified,c);else if(this.options.preventflip!==!0){var p;switch(this.checkBoundary(n.left+d.left,n.top+d.top,r,l,c)){case"x":"x"!==this.options.preventflip&&(p=o.x[u]||"right-top");break;case"y":"y"!==this.options.preventflip&&(p=o.y[u]||"top-left");break;case"xy":this.options.preventflip||(p=o.xy[u]||"right-bottom")}p&&(e=p.split("-"),d=h[p]?h[p]:h["bottom-left"],this.checkBoundary(n.left+d.left,n.top+d.top,r,l,c)&&(e=u.split("-"),d=h[u]?h[u]:h["bottom-left"]))}r>c&&(a.addClass("uk-dropdown-stack"),this.trigger("stack.uk.dropdown",[this])),a.css(d).css("display","").addClass("uk-dropdown-"+e[0]) +}},checkBoundary:function(i,e,n,o,s){var a="";return(0>i||i-t.$win.scrollLeft()+n>s)&&(a+="x"),(e-t.$win.scrollTop()<0||e-t.$win.scrollTop()+o>window.innerHeight)&&(a+="y"),a}}),t.component("dropdownOverlay",{defaults:{justify:!1,cls:"",duration:200},boot:function(){t.ready(function(i){t.$("[data-uk-dropdown-overlay]",i).each(function(){var i=t.$(this);i.data("dropdownOverlay")||t.dropdownOverlay(i,t.Utils.options(i.attr("data-uk-dropdown-overlay")))})})},init:function(){var e=this;this.justified=this.options.justify?t.$(this.options.justify):!1,this.overlay=this.element.find("uk-dropdown-overlay"),this.overlay.length||(this.overlay=t.$('
    ').appendTo(this.element)),this.overlay.addClass(this.options.cls),this.on({"beforeshow.uk.dropdown":function(t,n){e.dropdown=n,e.justified&&e.justified.length&&i(e.overlay.css({display:"block","margin-left":"","margin-right":""}),e.justified,e.justified.outerWidth())},"show.uk.dropdown":function(){var i=e.dropdown.dropdown.outerHeight(!0);e.dropdown.element.removeClass("uk-open"),e.overlay.stop().css("display","block").animate({height:i},e.options.duration,function(){e.dropdown.dropdown.css("visibility",""),e.dropdown.element.addClass("uk-open"),t.Utils.checkDisplay(e.dropdown.dropdown,!0)}),e.pointerleave=!1},"hide.uk.dropdown":function(){e.overlay.stop().animate({height:0},e.options.duration)},"pointerenter.uk.dropdown":function(){clearTimeout(e.remainIdle)},"pointerleave.uk.dropdown":function(){e.pointerleave=!0}}),this.overlay.on({mouseenter:function(){e.remainIdle&&(clearTimeout(e.dropdown.remainIdle),clearTimeout(e.remainIdle))},mouseleave:function(){e.pointerleave&&n&&(e.remainIdle=setTimeout(function(){n&&n.hide()},n.options.remaintime))}})}})}(UIkit),function(t){"use strict";var i=[];t.component("gridMatchHeight",{defaults:{target:!1,row:!0,ignorestacked:!1,observe:!1},boot:function(){t.ready(function(i){t.$("[data-uk-grid-match]",i).each(function(){var i,e=t.$(this);e.data("gridMatchHeight")||(i=t.gridMatchHeight(e,t.Utils.options(e.attr("data-uk-grid-match"))))})})},init:function(){var e=this;this.columns=this.element.children(),this.elements=this.options.target?this.find(this.options.target):this.columns,this.columns.length&&(t.$win.on("load resize orientationchange",function(){var i=function(){e.element.is(":visible")&&e.match()};return t.$(function(){i()}),t.Utils.debounce(i,50)}()),this.options.observe&&t.domObserve(this.element,function(){e.element.is(":visible")&&e.match()}),this.on("display.uk.check",function(){this.element.is(":visible")&&this.match()}.bind(this)),i.push(this))},match:function(){var i=this.columns.filter(":visible:first");if(i.length){var e=Math.ceil(100*parseFloat(i.css("width"))/parseFloat(i.parent().css("width")))>=100;return e&&!this.options.ignorestacked?this.revert():t.Utils.matchHeights(this.elements,this.options),this}},revert:function(){return this.elements.css("min-height",""),this}}),t.component("gridMargin",{defaults:{cls:"uk-grid-margin",rowfirst:"uk-row-first"},boot:function(){t.ready(function(i){t.$("[data-uk-grid-margin]",i).each(function(){var i,e=t.$(this);e.data("gridMargin")||(i=t.gridMargin(e,t.Utils.options(e.attr("data-uk-grid-margin"))))})})},init:function(){t.stackMargin(this.element,this.options)}})}(UIkit),function(t){"use strict";function i(i,e){return e?("object"==typeof i?(i=i instanceof jQuery?i:t.$(i),i.parent().length&&(e.persist=i,e.persist.data("modalPersistParent",i.parent()))):i="string"==typeof i||"number"==typeof i?t.$("
    ").html(i):t.$("
    ").html("UIkit.modal Error: Unsupported data type: "+typeof i),i.appendTo(e.element.find(".uk-modal-dialog")),e):void 0}var e,n=!1,o=0,s=t.$html;t.$win.on("resize orientationchange",t.Utils.debounce(function(){t.$(".uk-modal.uk-open").each(function(){t.$(this).data("modal").resize()})},150)),t.component("modal",{defaults:{keyboard:!0,bgclose:!0,minScrollHeight:150,center:!1,modal:!0},scrollable:!1,transition:!1,hasTransitioned:!0,init:function(){if(e||(e=t.$("body")),this.element.length){var i=this;this.paddingdir="padding-"+("left"==t.langdirection?"right":"left"),this.dialog=this.find(".uk-modal-dialog"),this.active=!1,this.element.attr("aria-hidden",this.element.hasClass("uk-open")),this.on("click",".uk-modal-close",function(t){t.preventDefault(),i.hide()}).on("click",function(e){var n=t.$(e.target);n[0]==i.element[0]&&i.options.bgclose&&i.hide()}),t.domObserve(this.element,function(){i.resize()})}},toggle:function(){return this[this.isActive()?"hide":"show"]()},show:function(){if(this.element.length){var i=this;if(!this.isActive())return this.options.modal&&n&&n.hide(!0),this.element.removeClass("uk-open").show(),this.resize(!0),this.options.modal&&(n=this),this.active=!0,o++,t.support.transition?(this.hasTransitioned=!1,this.element.one(t.support.transition.end,function(){i.hasTransitioned=!0}).addClass("uk-open")):this.element.addClass("uk-open"),s.addClass("uk-modal-page").height(),this.element.attr("aria-hidden","false"),this.element.trigger("show.uk.modal"),t.Utils.checkDisplay(this.dialog,!0),this}},hide:function(i){if(!i&&t.support.transition&&this.hasTransitioned){var e=this;this.one(t.support.transition.end,function(){e._hide()}).removeClass("uk-open")}else this._hide();return this},resize:function(t){if(this.isActive()||t){var i=e.width();if(this.scrollbarwidth=window.innerWidth-i,e.css(this.paddingdir,this.scrollbarwidth),this.element.css("overflow-y",this.scrollbarwidth?"scroll":"auto"),!this.updateScrollable()&&this.options.center){var n=this.dialog.outerHeight(),o=parseInt(this.dialog.css("margin-top"),10)+parseInt(this.dialog.css("margin-bottom"),10);n+oi?20:i)-e;return t.css({"max-height":o0?o--:o=0,this.element.hide().removeClass("uk-open"),this.element.attr("aria-hidden","true"),o||(s.removeClass("uk-modal-page"),e.css(this.paddingdir,"")),n===this&&(n=!1),this.trigger("hide.uk.modal")},isActive:function(){return this.element.hasClass("uk-open")}}),t.component("modalTrigger",{boot:function(){t.$html.on("click.modal.uikit","[data-uk-modal]",function(i){var e=t.$(this);if(e.is("a")&&i.preventDefault(),!e.data("modalTrigger")){var n=t.modalTrigger(e,t.Utils.options(e.attr("data-uk-modal")));n.show()}}),t.$html.on("keydown.modal.uikit",function(t){n&&27===t.keyCode&&n.options.keyboard&&(t.preventDefault(),n.hide())})},init:function(){var i=this;this.options=t.$.extend({target:i.element.is("a")?i.element.attr("href"):!1},this.options),this.modal=t.modal(this.options.target,this.options),this.on("click",function(t){t.preventDefault(),i.show()}),this.proxy(this.modal,"show hide isActive")}}),t.modal.dialog=function(e,n){var o=t.modal(t.$(t.modal.dialog.template).appendTo("body"),n);return o.on("hide.uk.modal",function(){o.persist&&(o.persist.appendTo(o.persist.data("modalPersistParent")),o.persist=!1),o.element.remove()}),i(e,o),o},t.modal.dialog.template='
    ',t.modal.alert=function(i,e){e=t.$.extend(!0,{bgclose:!1,keyboard:!1,modal:!1,labels:t.modal.labels},e);var n=t.modal.dialog(['
    '+String(i)+"
    ",'"].join(""),e);return n.on("show.uk.modal",function(){setTimeout(function(){n.element.find("button:first").focus()},50)}),n.show()},t.modal.confirm=function(i,e,n){var o=arguments.length>1&&arguments[arguments.length-1]?arguments[arguments.length-1]:{};e=t.$.isFunction(e)?e:function(){},n=t.$.isFunction(n)?n:function(){},o=t.$.extend(!0,{bgclose:!1,keyboard:!1,modal:!1,labels:t.modal.labels},t.$.isFunction(o)?{}:o);var s=t.modal.dialog(['
    '+String(i)+"
    ",'"].join(""),o);return s.element.find(".js-modal-confirm, .js-modal-confirm-cancel").on("click",function(){t.$(this).is(".js-modal-confirm")?e():n(),s.hide()}),s.on("show.uk.modal",function(){setTimeout(function(){s.element.find(".js-modal-confirm").focus()},50)}),s.show()},t.modal.prompt=function(i,e,n,o){n=t.$.isFunction(n)?n:function(){},o=t.$.extend(!0,{bgclose:!1,keyboard:!1,modal:!1,labels:t.modal.labels},o);var s=t.modal.dialog([i?'
    '+String(i)+"
    ":"",'

    ','"].join(""),o),a=s.element.find("input[type='text']").val(e||"").on("keyup",function(t){13==t.keyCode&&s.element.find(".js-modal-ok").trigger("click")});return s.element.find(".js-modal-ok").on("click",function(){n(a.val())!==!1&&s.hide()}),s.on("show.uk.modal",function(){setTimeout(function(){a.focus()},50)}),s.show()},t.modal.blockUI=function(i,e){var n=t.modal.dialog(['
    '+String(i||'
    ...
    ')+"
    "].join(""),t.$.extend({bgclose:!1,keyboard:!1,modal:!1},e));return n.content=n.element.find(".uk-modal-content:first"),n.show()},t.modal.labels={Ok:"Ok",Cancel:"Cancel"}}(UIkit),function(t){"use strict";function i(i){var e=t.$(i),n="auto";if(e.is(":visible"))n=e.outerHeight();else{var o={position:e.css("position"),visibility:e.css("visibility"),display:e.css("display")};n=e.css({position:"absolute",visibility:"hidden",display:"block"}).outerHeight(),e.css(o)}return n}t.component("nav",{defaults:{toggle:">li.uk-parent > a[href='#']",lists:">li.uk-parent > ul",multiple:!1},boot:function(){t.ready(function(i){t.$("[data-uk-nav]",i).each(function(){var i=t.$(this);if(!i.data("nav")){t.nav(i,t.Utils.options(i.attr("data-uk-nav")))}})})},init:function(){var i=this;this.on("click.uk.nav",this.options.toggle,function(e){e.preventDefault();var n=t.$(this);i.open(n.parent()[0]==i.element[0]?n:n.parent("li"))}),this.find(this.options.lists).each(function(){var e=t.$(this),n=e.parent(),o=n.hasClass("uk-active");e.wrap('
    '),n.data("list-container",e.parent()[o?"removeClass":"addClass"]("uk-hidden")),n.attr("aria-expanded",n.hasClass("uk-open")),o&&i.open(n,!0)})},open:function(e,n){var o=this,s=this.element,a=t.$(e),r=a.data("list-container");this.options.multiple||s.children(".uk-open").not(e).each(function(){var i=t.$(this);i.data("list-container")&&i.data("list-container").stop().animate({height:0},function(){t.$(this).parent().removeClass("uk-open").end().addClass("uk-hidden")})}),a.toggleClass("uk-open"),a.attr("aria-expanded",a.hasClass("uk-open")),r&&(a.hasClass("uk-open")&&r.removeClass("uk-hidden"),n?(r.stop().height(a.hasClass("uk-open")?"auto":0),a.hasClass("uk-open")||r.addClass("uk-hidden"),this.trigger("display.uk.check")):r.stop().animate({height:a.hasClass("uk-open")?i(r.find("ul:first")):0},function(){a.hasClass("uk-open")?r.css("height",""):r.addClass("uk-hidden"),o.trigger("display.uk.check")}))}})}(UIkit),function(t){"use strict";var i={x:window.scrollX,y:window.scrollY},e=(t.$win,t.$doc,t.$html),n={show:function(n){if(n=t.$(n),n.length){var o=t.$("body"),s=n.find(".uk-offcanvas-bar:first"),a="right"==t.langdirection,r=s.hasClass("uk-offcanvas-bar-flip")?-1:1,l=r*(a?-1:1),c=window.innerWidth-o.width();i={x:window.pageXOffset,y:window.pageYOffset},n.addClass("uk-active"),o.css({width:window.innerWidth-c,height:window.innerHeight}).addClass("uk-offcanvas-page"),o.css(a?"margin-right":"margin-left",(a?-1:1)*s.outerWidth()*l).width(),e.css("margin-top",-1*i.y),s.addClass("uk-offcanvas-bar-show"),this._initElement(n),s.trigger("show.uk.offcanvas",[n,s]),n.attr("aria-hidden","false")}},hide:function(n){var o=t.$("body"),s=t.$(".uk-offcanvas.uk-active"),a="right"==t.langdirection,r=s.find(".uk-offcanvas-bar:first"),l=function(){o.removeClass("uk-offcanvas-page").css({width:"",height:"","margin-left":"","margin-right":""}),s.removeClass("uk-active"),r.removeClass("uk-offcanvas-bar-show"),e.css("margin-top",""),window.scrollTo(i.x,i.y),r.trigger("hide.uk.offcanvas",[s,r]),s.attr("aria-hidden","true")};s.length&&(t.support.transition&&!n?(o.one(t.support.transition.end,function(){l()}).css(a?"margin-right":"margin-left",""),setTimeout(function(){r.removeClass("uk-offcanvas-bar-show")},0)):l())},_initElement:function(i){i.data("OffcanvasInit")||(i.on("click.uk.offcanvas swipeRight.uk.offcanvas swipeLeft.uk.offcanvas",function(i){var e=t.$(i.target);if(!i.type.match(/swipe/)&&!e.hasClass("uk-offcanvas-close")){if(e.hasClass("uk-offcanvas-bar"))return;if(e.parents(".uk-offcanvas-bar:first").length)return}i.stopImmediatePropagation(),n.hide()}),i.on("click","a[href*='#']",function(){var i=t.$(this),e=i.attr("href");"#"!=e&&(t.$doc.one("hide.uk.offcanvas",function(){var n;try{n=t.$(i[0].hash)}catch(o){n=""}n.length||(n=t.$('[name="'+i[0].hash.replace("#","")+'"]')),n.length&&t.Utils.scrollToElement?t.Utils.scrollToElement(n,t.Utils.options(i.attr("data-uk-smooth-scroll")||"{}")):window.location.href=e}),n.hide())}),i.data("OffcanvasInit",!0))}};t.component("offcanvasTrigger",{boot:function(){e.on("click.offcanvas.uikit","[data-uk-offcanvas]",function(i){i.preventDefault();var e=t.$(this);if(!e.data("offcanvasTrigger")){{t.offcanvasTrigger(e,t.Utils.options(e.attr("data-uk-offcanvas")))}e.trigger("click")}}),e.on("keydown.uk.offcanvas",function(t){27===t.keyCode&&n.hide()})},init:function(){var i=this;this.options=t.$.extend({target:i.element.is("a")?i.element.attr("href"):!1},this.options),this.on("click",function(t){t.preventDefault(),n.show(i.options.target)})}}),t.offcanvas=n}(UIkit),function(t){"use strict";function i(i,e,n){var o,s=t.$.Deferred(),a=i,r=i;return n[0]===e[0]?(s.resolve(),s.promise()):("object"==typeof i&&(a=i[0],r=i[1]||i[0]),t.$body.css("overflow-x","hidden"),o=function(){e&&e.hide().removeClass("uk-active "+r+" uk-animation-reverse"),n.addClass(a).one(t.support.animation.end,function(){n.removeClass(""+a).css({opacity:"",display:""}),s.resolve(),t.$body.css("overflow-x",""),e&&e.css({opacity:"",display:""})}.bind(this)).show()},n.css("animation-duration",this.options.duration+"ms"),e&&e.length?(e.css("animation-duration",this.options.duration+"ms"),e.css("display","none").addClass(r+" uk-animation-reverse").one(t.support.animation.end,function(){o()}.bind(this)).css("display","")):(n.addClass("uk-active"),o()),s.promise())}var e;t.component("switcher",{defaults:{connect:!1,toggle:">*",active:0,animation:!1,duration:200,swiping:!0},animating:!1,boot:function(){t.ready(function(i){t.$("[data-uk-switcher]",i).each(function(){var i=t.$(this);if(!i.data("switcher")){t.switcher(i,t.Utils.options(i.attr("data-uk-switcher")))}})})},init:function(){var i=this;if(this.on("click.uk.switcher",this.options.toggle,function(t){t.preventDefault(),i.show(this)}),this.options.connect){this.connect=t.$(this.options.connect),this.connect.children().removeClass("uk-active"),this.connect.length&&(this.connect.children().attr("aria-hidden","true"),this.connect.on("click","[data-uk-switcher-item]",function(e){e.preventDefault();var n=t.$(this).attr("data-uk-switcher-item");if(i.index!=n)switch(n){case"next":case"previous":i.show(i.index+("next"==n?1:-1));break;default:i.show(parseInt(n,10))}}),this.options.swiping&&this.connect.on("swipeRight swipeLeft",function(t){t.preventDefault(),window.getSelection().toString()||i.show(i.index+("swipeLeft"==t.type?1:-1))}));var e=this.find(this.options.toggle),n=e.filter(".uk-active");if(n.length)this.show(n,!1);else{if(this.options.active===!1)return;n=e.eq(this.options.active),this.show(n.length?n:e.eq(0),!1)}e.not(n).attr("aria-expanded","false"),n.attr("aria-expanded","true")}},show:function(n,o){if(!this.animating){if(isNaN(n))n=t.$(n);else{var s=this.find(this.options.toggle);n=0>n?s.length-1:n,n=s.eq(s[n]?n:0)}var a=this,s=this.find(this.options.toggle),r=t.$(n),l=e[this.options.animation]||function(t,n){if(!a.options.animation)return e.none.apply(a);var o=a.options.animation.split(",");return 1==o.length&&(o[1]=o[0]),o[0]=o[0].trim(),o[1]=o[1].trim(),i.apply(a,[o,t,n])};o!==!1&&t.support.animation||(l=e.none),r.hasClass("uk-disabled")||(s.attr("aria-expanded","false"),r.attr("aria-expanded","true"),s.filter(".uk-active").removeClass("uk-active"),r.addClass("uk-active"),this.options.connect&&this.connect.length&&(this.index=this.find(this.options.toggle).index(r),-1==this.index&&(this.index=0),this.connect.each(function(){var i=t.$(this),e=t.$(i.children()),n=t.$(e.filter(".uk-active")),o=t.$(e.eq(a.index));a.animating=!0,l.apply(a,[n,o]).then(function(){n.removeClass("uk-active"),o.addClass("uk-active"),n.attr("aria-hidden","true"),o.attr("aria-hidden","false"),t.Utils.checkDisplay(o,!0),a.animating=!1})})),this.trigger("show.uk.switcher",[r]))}}}),e={none:function(){var i=t.$.Deferred();return i.resolve(),i.promise()},fade:function(t,e){return i.apply(this,["uk-animation-fade",t,e])},"slide-bottom":function(t,e){return i.apply(this,["uk-animation-slide-bottom",t,e])},"slide-top":function(t,e){return i.apply(this,["uk-animation-slide-top",t,e])},"slide-vertical":function(t,e){var n=["uk-animation-slide-top","uk-animation-slide-bottom"];return t&&t.index()>e.index()&&n.reverse(),i.apply(this,[n,t,e])},"slide-left":function(t,e){return i.apply(this,["uk-animation-slide-left",t,e])},"slide-right":function(t,e){return i.apply(this,["uk-animation-slide-right",t,e])},"slide-horizontal":function(t,e){var n=["uk-animation-slide-right","uk-animation-slide-left"];return t&&t.index()>e.index()&&n.reverse(),i.apply(this,[n,t,e])},scale:function(t,e){return i.apply(this,["uk-animation-scale-up",t,e])}},t.switcher.animations=e}(UIkit),function(t){"use strict";t.component("tab",{defaults:{target:">li:not(.uk-tab-responsive, .uk-disabled)",connect:!1,active:0,animation:!1,duration:200,swiping:!0},boot:function(){t.ready(function(i){t.$("[data-uk-tab]",i).each(function(){var i=t.$(this);if(!i.data("tab")){t.tab(i,t.Utils.options(i.attr("data-uk-tab")))}})})},init:function(){var i=this;this.current=!1,this.on("click.uk.tab",this.options.target,function(e){if(e.preventDefault(),!i.switcher||!i.switcher.animating){var n=i.find(i.options.target).not(this);n.removeClass("uk-active").blur(),i.trigger("change.uk.tab",[t.$(this).addClass("uk-active"),i.current]),i.current=t.$(this),i.options.connect||(n.attr("aria-expanded","false"),t.$(this).attr("aria-expanded","true"))}}),this.options.connect&&(this.connect=t.$(this.options.connect)),this.responsivetab=t.$('
  • ').append('
      '),this.responsivetab.dropdown=this.responsivetab.find(".uk-dropdown"),this.responsivetab.lst=this.responsivetab.dropdown.find("ul"),this.responsivetab.caption=this.responsivetab.find("a:first"),this.element.hasClass("uk-tab-bottom")&&this.responsivetab.dropdown.addClass("uk-dropdown-up"),this.responsivetab.lst.on("click.uk.tab","a",function(e){e.preventDefault(),e.stopPropagation();var n=t.$(this);i.element.children("li:not(.uk-tab-responsive)").eq(n.data("index")).trigger("click")}),this.on("show.uk.switcher change.uk.tab",function(t,e){i.responsivetab.caption.html(e.text())}),this.element.append(this.responsivetab),this.options.connect&&(this.switcher=t.switcher(this.element,{toggle:">li:not(.uk-tab-responsive)",connect:this.options.connect,active:this.options.active,animation:this.options.animation,duration:this.options.duration,swiping:this.options.swiping})),t.dropdown(this.responsivetab,{mode:"click",preventflip:"y"}),i.trigger("change.uk.tab",[this.element.find(this.options.target).not(".uk-tab-responsive").filter(".uk-active")]),this.check(),t.$win.on("resize orientationchange",t.Utils.debounce(function(){i.element.is(":visible")&&i.check()},100)),this.on("display.uk.check",function(){i.element.is(":visible")&&i.check()})},check:function(){var i=this.element.children("li:not(.uk-tab-responsive)").removeClass("uk-hidden");if(!i.length)return this.responsivetab.addClass("uk-hidden"),void 0;var e,n,o,s=i.eq(0).offset().top+Math.ceil(i.eq(0).height()/2),a=!1;if(this.responsivetab.lst.empty(),i.each(function(){t.$(this).offset().top>s&&(a=!0)}),a)for(var r=0;r-1?"&":"?","enablejsapi=1&api=1"].join(""))}},check:function(){this.element.css({width:"",height:""}),this.dimension={w:this.element.width(),h:this.element.height()},this.element.attr("width")&&!isNaN(this.element.attr("width"))&&(this.dimension.w=this.element.attr("width")),this.element.attr("height")&&!isNaN(this.element.attr("height"))&&(this.dimension.h=this.element.attr("height")),this.ratio=this.dimension.w/this.dimension.h;var t,i,e=this.parent.width(),n=this.parent.height();e/this.ratio=a.filelimit&&(p=!1),p&&d>f?r([o[f]],a):a.allcomplete(e,t)},r([o[0]],a)}else a.complete=function(e,t){s(e,t),a.allcomplete(e,t)},r(o,a)}}function n(e,t){var n="^"+e.replace(/\//g,"\\/").replace(/\*\*/g,"(\\/[^\\/]+)*").replace(/\*/g,"[^\\/]+").replace(/((?!\\))\?/g,"$1.")+"$";return n="^"+n+"$",null!==t.match(new RegExp(n,"i"))}return e.component("uploadSelect",{init:function(){var e=this;this.on("change",function(){t(e.element[0].files,e.options);var n=e.element.clone(!0).data("uploadSelect",e);e.element.replaceWith(n),e.element=n})}}),e.component("uploadDrop",{defaults:{dragoverClass:"uk-dragover"},init:function(){var e=this,n=!1;this.on("drop",function(n){n.dataTransfer&&n.dataTransfer.files&&(n.stopPropagation(),n.preventDefault(),e.element.removeClass(e.options.dragoverClass),e.element.trigger("dropped.uk.upload",[n.dataTransfer.files]),t(n.dataTransfer.files,e.options))}).on("dragenter",function(e){e.stopPropagation(),e.preventDefault()}).on("dragover",function(t){t.stopPropagation(),t.preventDefault(),n||(e.element.addClass(e.options.dragoverClass),n=!0)}).on("dragleave",function(t){t.stopPropagation(),t.preventDefault(),e.element.removeClass(e.options.dragoverClass),n=!1})}}),e.support.ajaxupload=function(){function e(){var e=document.createElement("INPUT");return e.type="file","files"in e}function t(){var e=new XMLHttpRequest;return!!(e&&"upload"in e&&"onprogress"in e.upload)}function n(){return!!window.FormData}return e()&&t()&&n()}(),e.support.ajaxupload&&e.$.event.props.push("dataTransfer"),t.defaults={action:"",single:!0,method:"POST",param:"files[]",params:{},allow:"*.*",type:"text",filelimit:!1,before:function(){},beforeSend:function(){},beforeAll:function(){},loadstart:function(){},load:function(){},loadend:function(){},error:function(){},abort:function(){},progress:function(){},complete:function(){},allcomplete:function(){},readystatechange:function(){},notallowed:function(e,t){alert("Only the following file types are allowed: "+t.allow)}},e.Utils.xhrupload=t,t}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/images/logo-gray.png b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/images/logo-gray.png new file mode 100644 index 0000000000000000000000000000000000000000..545508318cd356c8cf8db090b9bce98cda27e0de GIT binary patch literal 4153 zcmV-95XSF`P)e6ZJ$0 zYDC0njEWK?ppiupL=-_#6xkPtVOVCsnf&opovyB~p7);2DCcCpbKaTP^{Tt8tM2mM zd#fjJ`0(MRpcEJg91Zj~$9X^%@ILS|@CL9p?E+sj3V|}90QdqZGJn?q+rP$f{Xd{N z&;h7Jb6x;c1M5s%qoFX+)(kii_!ZDA<-EbbkAVfiZ-H^Z*2Wm%4xktC4A27D2y_D0 z1IHtUY(nGVIAAm~92G!0Fbg;dsBFv|`vP5R269qL|LsWQip_Bk)Bn4`t-vC79>FdF zx|{Ev%-?3Fy$OwrG9*j(JHYP9OExN8fi44{0tR_~76Y#U(|}!pp8&ggeNF`q2i^mg z12cgafF%t*;2cnGKE+Pk7c{cVYXTs{SBEI7MJ=$cv2Sbzx*2dMabaE!+zmWpzV|~k zq>L~+n-9Qwz)IjBz`cl?eAUP!KA{bPHo#@TQOMei10JS{lV^*DUXKKq-^z-eC$ z{1BK5vg{aLrrhm5Rg}lYLka83vAzBB_0R9BLlf(7W&;_^< zI1&XgRuEU9c%TIl-I|Li)jTx0F1jNHKf+w67|qcdU^b#C)13ajf$NDrRxP@ku?;rYYKemQnl#Iq-AfOyJ+Z*<^3DdH~m&u~q|n0^`j%TpWWKL|-J(An!QUJmY-Zu@E@KIdL_j z7rUW}cZK;)AMV= zfKpu$d4~?(HK!5@bXW5n-OTYi-~p%aP~gvjYhcbf47eQl5%8qxY~UG7{|gG>;inlIqpGRm@GOv-}?|*FM!XGrv(YkSi-{WqAlE=SP{)u= zJq|)j>Ea;ZXI@(^vKrTt6j%`TvPNSnan4u-?Bg8oO}Gfw)A@cN;>8wknZF&8VQJx= zy8vad-t*cEfxAcwzt3rpMa4B&fo-1Ir(qD!I@!XVi+d2=us8wHBY(`-1HUI;p)Nwy zW0!m)tpW+s-Oj+)ASzLxFoP7M)H$vpJ^`bVmA5z?QH2oN09OUtN1_S5ov;x0M46Rb zuqUv8p#2eKeU}4I1b!bv#HX8?@f3J{?nf4E6q-Z7;Iuap&6r8Dg4W0RzF*4tT?^gY z`Cd)rO^*Wxc;_tx&OnChJQNtZ*q?|-givd)yH7oRe0+g;@7_qpTr2(p@^CH&5uej) zWHd%1>U+7@e-EHtK5}^${fJYLQG~6Fk5a@BEtUlO+(g`pAD?oqJjDOrN0!*Sx|f_j zvx(Cfkbvb{1>A$Ad#phva*$Gf5;(6LkwE96g_?&drIv=cu5%Vifh{4T5i?Ny;*YHu z8JEt4(b-(1h`6<`L|h+aJbX+9-gUJc0Q3D@ZYi080vybqJvf_-BTTS`0zF&tguX&r0BVBFnr#vO@E` zewB!#v_=cn1zESZoj%);5V-u! zs51Rs-rN;EdkvBM-+~sqxjF8Dj7cY=@;=C*EJ75_HBc4{h^M?lnT_6PF6t{9Z9}~G zaj!k32-}bq_IJbGLDFc{k<647Bg@{(+^-JNmRcO|R|rf;59sHbUjmkkK7K0hz2~2 zO5ZN#k#y@mnj zpe)FFXyIlOkA#<-0j$XI0PX~bl%)t2Wc)3xl_+y?7<%boWrq9Yf@LV916thWL<+M7 zDd8I^R=CSMHxIZ0c@r1a$dVt0D9nc$#;}<Ih#R~29){M+VlELK$|sq9 zfp~fk!iHrtnLTtxhTlW|Um(eu&n8^dnu6xw38M8$!*75AE_q*siYhLBC_>s3(jXTf zAZs=`L%$N@TrcG6dJ|5jUx}6gLvs3Hjxj#VQNE-fpTC{LSn&VA~tan3Pt_*4F2IM}cAt8R1`gfdJ6d=lCv5ce}&LN))paG=i)>ZB+f^Iv&nomqO{wGB>AS@Fy*3>_zt%H2=h^2c$cCK$^n7C z3(T16&^jFw=u?3xhsA2s*Uv8WFk`l~stZZXBVKgdQLH2?_WTDKPq#31Ac_a3qxHQ3 zWqG3M~5ne@mW?Z8IBp2c}qC8<6r0v%s8qyXC(IzzUp+KTObV4q}VlMIAvPH-% z^hIf}wMa02n&Z7g$Rk+*Xiu`-T8lhU6?*1{DBhUujMslVqbFJj%N0iu&UpAmok~O* zLIUmX?DJEd7H^O&&`cp&l^ueF`aN^6(*xIANc3O(an=+!-o_GX;ZksuEv z{>s)3=674T3cb#?z!&J(k%j1Ij_)!zug}G0ixI?=|1Ssn)Do{;TC_#(>Nyl79A?^m zLCOU+DBwLcLqEIUr36`&o@l?zP-Gz%p@nxRxCm{SdK7IVJtpPazSXWlwByo1Uw8jX z+8aP`lFVRCLTl(+^v;N{&O!q1Q;=Cm5gHPC#3{-Y;sOn#6XnPPKTkX{a4r(`Nr)}@ zIck7sd<(G@rSL4eBcV>qA!dtHh;KHUgZ6iXFo|#mV=xlx=Z;{CI$M0IOt50u6{FdAzn;)Q+~+ftw#G_`~a>e z+N17Q5^In(bknQuZbQ8G5Yk?MbK547EZlWN88y&GG?&BYAwx0>ZPV>a91j4KLxc1; zpr3&RDO8`&27^($&03?asECu6@>ysGoaXL6MnV{>M!E%tA~Fj!$bGNyj%T2Nb(Q(} zRu7^LJX_IjwzTJ2kFqvn0>5<(w5=g2n2U)jks#{h2dXPb?wqrD4rNa=rBv6Oe!lli z3jouC!cghkzs4NG!S-pWq(2E2U9!n_-;WAfHK7|0(3`8<`y|13Sh@0MY|aVGzCZ@XCq5K57DF1Xnyn2+%5?``)XuumLbdE z4Y_A`Vb>y0y3EW)S40y+donD>BT8~Ha_#Mi1grwN`MU{w$K^;NJDA@~5SI;Y+yXuK zSkq@CTK~l)vnF;MXqEY`y%|%vX&;Z2`yymK+7nT`Dx|;M+5H>LlfC`xxN z{0Nej(H3ao*Rb>akCG5d(b{gJk^lM2mw=sPKS5A}*rq#1xS~Yn=pekJmm6s6o(S8PIX3+f0{t=MUt+Bg0n4T zx2fyvhP$C^XG2>3!=_PFQJ+AAvH&a4D?{%7<#OVCIO@YH6!G6jcKPbB3QLi~+Bql$ z{)iOvZRFDGPyl!k@d_R&cx#B4bDPkB$RyC9+~z5WtdAgBYE45WDseu@&iTLOrlVZw zK&NdN^i~W+Rw5LwSEJH)Lu}4zLIWZjfd;wJF^B^nfP#tvh+^0`CN`pgVLmF*Ohtjx z&SaHcRH5AFL&PhX7HKJ|cTr$9qmjndgdIS(0&QWV;VFoq+daw!D1TXv1f?NMrj3b@ zQMvmlv>#<(6iK&2&sK$a=4zCwn23}$*EpaFUlINXLMytdfhMmd00000NkvXXu0mjf Dl+wDB literal 0 HcmV?d00001 diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/images/logo.png b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/images/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..cb83418cac66ff534af9801223cc69bedd6241c8 GIT binary patch literal 5004 zcmV;76Lai|P)KLZ*U+IBfRsybQWXdwQbLP>6pAqfylh#{fb6;Z(vMMVS~$e@S=j*ftg6;Uhf59&ghTmgWD0l;*T zI709Y^p6lP1rIRMx#05C~cW=H_Aw*bJ-5DT&Z2n+x)QHX^p z00esgV8|mQcmRZ%02D^@S3L16t`O%c004NIvOKvYIYoh62rY33S640`D9%Y2D-rV&neh&#Q1i z007~1e$oCcFS8neI|hJl{-P!B1ZZ9hpmq0)X0i`JwE&>$+E?>%_LC6RbVIkUx0b+_+BaR3cnT7Zv!AJxW zizFb)h!jyGOOZ85F;a?DAXP{m@;!0_IfqH8(HlgRxt7s3}k3K`kFu>>-2Q$QMFfPW!La{h336o>X zu_CMttHv6zR;&ZNiS=X8v3CR#fknUxHUxJ0uoBa_M6WNWeqIg~6QE69c9o#eyhGvpiOA@W-aonk<7r1(?fC{oI5N*U!4 zfg=2N-7=cNnjjOr{yriy6mMFgG#l znCF=fnQv8CDz++o6_Lscl}eQ+l^ZHARH>?_s@|##Rr6KLRFA1%Q+=*RRWnoLsR`7U zt5vFIcfW3@?wFpwUVxrVZ>QdQz32KIeJ}k~{cZZE^+ya? z2D1z#2HOnI7(B%_ac?{wFUQ;QQA1tBKtrWrm0_3Rgps+?Jfqb{jYbcQX~taRB;#$y zZN{S}1|}gUOHJxc?wV3fxuz+mJ4`!F$IZ;mqRrNsHJd##*D~ju=bP7?-?v~|cv>vB zsJ6IeNwVZxrdjT`yl#bBIa#GxRa#xMMy;K#CDyyGyQdMSxlWT#tDe?p!?5wT$+oGt z8L;Kp2HUQ-ZMJ=3XJQv;x5ci*?vuTfeY$;({XGW_huIFR9a(?@3)XSs8O^N5RyOM=TTmp(3=8^+zpz2r)C z^>JO{deZfso3oq3?Wo(Y?l$ge?uXo;%ru`Vo>?<<(8I_>;8Eq#KMS9gFl*neeosSB zfoHYnBQIkwkyowPu(zdms`p{<7e4kra-ZWq<2*OsGTvEV%s0Td$hXT+!*8Bnh2KMe zBmZRodjHV?r+_5^X9J0WL4jKW`}lf%A-|44I@@LTvf1rHjG(ze6+w@Jt%Bvjts!X0 z?2xS?_ve_-kiKB_KiJlZ$9G`c^=E@oNG)mWWaNo-3TIW8)$Hg0Ub-~8?KhvJ>$ z3*&nim@mj(aCxE5!t{lw7O5^0EIO7zOo&c6l<+|iDySBWCGrz@C5{St!X3hAA}`T4 z(TLbXTq+(;@<=L8dXnssyft|w#WSTW<++3>sgS%(4NTpeI-VAqb|7ssJvzNHgOZVu zaYCvgO_R1~>SyL=cFU|~g|hy|Zi}}s9+d~lYqOB71z9Z$wnC=pR9Yz4DhIM>Wmjgu z&56o6maCpC&F##y%G;1PobR9i?GnNg;gYtchD%p19a!eQtZF&3JaKv33gZ<8D~47E ztUS1iwkmDaPpj=$m#%)jCVEY4fnLGNg2A-`YwHVD3gv};>)hAvT~AmqS>Lr``i7kw zJ{5_It`yrBmlc25DBO7E8;5VoznR>Ww5hAaxn$2~(q`%A-YuS64wkBy=9dm`4cXeX z4c}I@?e+FW+b@^RDBHV(wnMq2zdX3SWv9u`%{xC-q*U}&`cyXV(%rRT*Z6MH?i+i& z_B8C(+grT%{XWUQ+f@NoP1R=AW&26{v-dx)iK^-Nmiuj8txj!m?Z*Ss1N{dh4z}01 z)YTo*JycSU)+_5r4#yw9{+;i4Ee$peRgIj+;v;ZGdF1K$3E%e~4LaI(jC-u%2h$&R z9cLXcYC@Xwnns&bn)_Q~Te?roKGD|d-g^8;+aC{{G(1^(O7m37Y1-+6)01cN&y1aw zoqc{T`P^XJqPBbIW6s}d4{z_f5Om?vMgNQEJG?v2T=KYd^0M3I6IZxbny)%vZR&LD zJpPl@Psh8QyPB@KTx+@RdcC!KX7}kEo;S|j^u2lU7XQ}Oo;f|;z4Ll+_r>@1-xl3| zawq-H%e&ckC+@AhPrP6BKT#_XdT7&;F71j}Joy zkC~6lh7E@6o;W@^IpRNZ{ptLtL(gQ-CY~4mqW;US7Zxvm_|@yz&e53Bp_lTPlfP|z zrTyx_>lv@x#=^!PzR7qqF<$gm`|ZJZ+;<)Cqu&ot2z=0000WV@Og>004R=004l4008;_004mL004C`008P>0026e000+nl3&F} z000QLNkl{mQmfGCR9&0HoXbzcd}rGANV4zep6r-~)^{sl8SptjzXl8g zMg!Y}T?_->0OkM_fs0R(Mehms@7J<#XP^sE@LznQ_lNrf!10qEFjMq{-W-5ifsX;3 zfuTT2(x=mk`mcV&HU0^q`;on?)dmGpZ;4QE1R<||u+9I9f zK1IL|U{h#23#j8wJpmjHZB6`J2iWI!Jbp9aD6luk*8{q_U%vON4>YpZsSIALi`P|I z&AXrN^#Ht^thKAh-v*S%7(K~x;C1`+heK?5S<+R(*VmI&=C*q!jR~@4k~&urCrTte zC~14>b3)QwNgq#SR|c86N!w+T{vhdKkXi5bACojr(lwGASiXm($0Y3z@`sH_x?5(b zq@9xfCTWAD3(UVn(%ZgDC0%EJb4g1j?UFQGQi1t5NLrJ`*G0)5B5Aawt=@~T8~40q z`3oeC4gGg}?~qjF`L;?rB)5i6uRMfa3+G_-BBk~4Z=QllW>S<-t|%v);tl7#;S_rERS|H}L;0`Jj0 zvMF5=)-@sU$A!ZtNf#vtXiosZ_XPg);a$I9#k}(*)y1e*KFOc`h4VQF0@PAPQML!w%2W>$3WM%Y_c?CXA8Eul(PtxtlMr5aAN#NaW-lRl! zw)vw1ub-s)iQHUCgC)I{7-fC;AD^tNB0Tr8|A=RjGI@9y6fftLZ(^ON~o`S&CKJz_xm*_g2c-vgcj?g{)(z@<6f zsiX1A4B&Qy;AWwHyRpa(A=G|pW-vqoFPDV{>a&i*J0bfhTnU?hF z4%`hq?|D}w>0p+=z3M6yZok+DyWHt#rhr~y(-$Wv9pF%?VjT>IN0|3Svc`$Yb4)3_ z0lmZX0A~;xz39En=tAI+u6O*@`%a-#jk|*2b-=*H;y>;3XXX~~Ox$1QQpy7Sk8~xl z-j+7dil6PdqcK!RzjqNQqaOhGhkC&MP7O1U2YMrf5KsNIy;7!-8-oG78NAvEV~)cj8s**w%pjE zFo3%fS1o5)R~;P6e&?&V!(0ZOdq!(pXMuNpYWn*N(jEhqm#X=Ka!mjS>vAB~6#RSw zIJXvxZW|U}Vg>B5VIDAGS_3>~g|^N!&eg6;<)YVox*8-d9fQl3fxk4|MS+_DOo8}{o^%ylmhdDn(gi^t@1&Tcqk~hoqL01|6C-s0%d1@6|!KAJEcjx%3H8A1*+Hz%qH#$|=GoeH{u!c%*DruGb z9g@^BX)lsAE5`;elyqNsUK{$9=Bc(d3vCs_xKf&u!(cL+krZB@P1gI%(6%A)$0XyF zB>nnW!MSLIq;^3zEyQ$7#(FquZ*P9@JO!L7RT%y(N%e~pH!%wMq`|~|=XNuya4TJ% z&SXGsv=ja`RTv7~YoJ$Xw>Q$MPjh30%}E;7)$Zuk5bvI_{A%as$DC?31HR&rlcD@9 zJWK#C@j4a&V;q)_yZ@SGz0>`Xqkd8=__F~|u|J}0Px`HN@nWo9cN2%Pg^sNUg6tw^ zCgpa^yOXizd;Y`z;E{dwSYWsb7psk-8c8k?g%TKk$a;LigEXVN^yIZo+v=eiF#Z@w~|kX;5cjgo5B z9WHI2N{R^fo6a9M+UnaTrPo%hC*lAHSRbKFVw+C z*rpn}XB{dk_<(Ax=vap9?9}0?Q-{?x_&|OtlzodmP8-MO= 992) { + var stickyRef = $('.js-sticky-reference'); + var stickyTable = $('.js-sticky-table'); + + if (stickyRef && stickyTable) { + stickyTable.stickyTableHeaders({fixedOffset: stickyRef}); + } + } +}; + +AW.onMenuGroupClick = function(event) { + var subItems = $(this).parent().find('ul'); + + if (subItems.length) { + event.preventDefault(); + $(this).parent().toggleClass('is-expanded'); + } +}; + +AW.initMenu = function() { + $('.js-menu > ul > li > a').bind('click', AW.onMenuGroupClick); + $('.aw-menu__item .is-active').parents('.aw-menu__item').addClass('is-expanded is-active'); +}; + +$(function() { + if (AW.init) { + AW.init(); + } + + AW.initMenu(); + AW.initStickyTableHeaders(); + + // Enable Bootstrap tooltip + $('.js-tooltip').tooltip(); + + // Bind events + $('.js-sidebar-toggle').bind('click', AW.onSidebarToggleRequest); + $('.js-search-modal-trigger-show').bind('click', AW.onSearchModalShowRequest); + $('.js-search-modal-close').bind('click', AW.onSearchModalCloseRequest); + //$('.js-form-loading').bind('submit', AW.onFormLoadingSubmit); +}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/algaworks.min.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/algaworks.min.js new file mode 100644 index 00000000..551aa441 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/algaworks.min.js @@ -0,0 +1 @@ +var AW=AW||{};AW.onSidebarToggleRequest=function(a){a.preventDefault(),$(this).blur(),$(".js-sidebar, .js-content").toggleClass("is-toggled")},AW.onSearchModalShowRequest=function(a){a.preventDefault(),$(".js-search-modal").fadeIn("slow"),$("body").addClass("aw-no-scroll"),$(".js-search-modal-input").val("").select()},AW.onSearchModalCloseRequest=function(a){a.preventDefault(),$(".js-search-modal").hide(),$("body").removeClass("aw-no-scroll")},AW.showLoadingComponent=function(){$(".js-loading-overlay").css("display","table").hide().fadeIn("slow")},AW.hideLoadingComponent=function(){$(".js-loading-component").fadeOut("fast")},AW.initStickyTableHeaders=function(){if($(window).width()>=992){var a=$(".js-sticky-reference"),b=$(".js-sticky-table");a&&b&&b.stickyTableHeaders({fixedOffset:a})}},AW.onMenuGroupClick=function(a){var b=$(this).parent().find("ul");b.length&&(a.preventDefault(),$(this).parent().toggleClass("is-expanded"))},AW.initMenu=function(){$(".js-menu > ul > li > a").bind("click",AW.onMenuGroupClick),$(".aw-menu__item .is-active").parents(".aw-menu__item").addClass("is-expanded is-active")},$(function(){AW.init&&AW.init(),AW.initMenu(),AW.initStickyTableHeaders(),$(".js-tooltip").tooltip(),$(".js-sidebar-toggle").bind("click",AW.onSidebarToggleRequest),$(".js-search-modal-trigger-show").bind("click",AW.onSearchModalShowRequest),$(".js-search-modal-close").bind("click",AW.onSearchModalCloseRequest)}); \ No newline at end of file diff --git a/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/vendors.js b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/vendors.js new file mode 100644 index 00000000..96ac0079 --- /dev/null +++ b/25.6-desafio-implementando-edicoes-e-exclusoes/brewer/src/main/resources/static/layout/javascripts/vendors.js @@ -0,0 +1,13808 @@ +/*! + * jQuery JavaScript Library v2.2.3 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-04-05T19:26Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Support: Firefox 18+ +// Can't be in strict mode, several libs including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +//"use strict"; +var arr = []; + +var document = window.document; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + version = "2.2.3", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + var realStringObj = obj && obj.toString(); + return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; + }, + + isPlainObject: function( obj ) { + var key; + + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call( obj, "constructor" ) && + !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android<4.0, iOS<6 (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + var script, + indirect = eval; + + code = jQuery.trim( code ); + + if ( code ) { + + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf( "use strict" ) === 1 ) { + script = document.createElement( "script" ); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { + + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval + + indirect( code ); + } + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE9-11+ + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android<4.1 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +// JSHint would error on this code due to the Symbol not being defined in ES5. +// Defining this global in .jshintrc would create a danger of using the global +// unguarded in another place, it seems safer to just disable JSHint for these +// three lines. +/* jshint ignore: start */ +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} +/* jshint ignore: end */ + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: iOS 8.2 (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.2.1 + * http://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2015-10-17 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, nidselect, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; + while ( i-- ) { + groups[i] = nidselect + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9-11, Edge + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + if ( (parent = document.defaultView) && parent.top !== parent ) { + // Support: IE 11 + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var m = context.getElementById( id ); + return m ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + docElem.appendChild( div ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( (oldCache = uniqueCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context === document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context || document, xml) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + } ); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, + len = this.length, + ret = [], + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + // Support: Blackberry 4.6 + // gEBID returns nodes no longer in the document (#6963) + if ( elem && elem.parentNode ) { + + // Inject the element directly into the jQuery object + this.length = 1; + this[ 0 ] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( pos ? + pos.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnotwhite = ( /\S+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], + [ "notify", "progress", jQuery.Callbacks( "memory" ) ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this === promise ? newDefer.promise() : this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( function() { + + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || + ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. + // If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // Add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .progress( updateFunc( i, progressContexts, progressValues ) ) + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ); + } else { + --remaining; + } + } + } + + // If we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +} ); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +} ); + +/** + * The ready event handler and self cleanup method + */ +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called + // after the browser event has already occurred. + // Support: IE9-10 only + // Older IE sometimes signals "interactive" too soon + if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + + } else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); + } + } + return readyList.promise( obj ); +}; + +// Kick off the DOM ready check even if the user does not +jQuery.ready.promise(); + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + len ? fn( elems[ 0 ], key ) : emptyGet; +}; +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + /* jshint -W018 */ + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + register: function( owner, initial ) { + var value = initial || {}; + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable, non-writable property + // configurability must be true to allow the property to be + // deleted with the delete operator + } else { + Object.defineProperty( owner, this.expando, { + value: value, + writable: true, + configurable: true + } ); + } + return owner[ this.expando ]; + }, + cache: function( owner ) { + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( !acceptData( owner ) ) { + return {}; + } + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + if ( typeof data === "string" ) { + cache[ data ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ prop ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + owner[ this.expando ] && owner[ this.expando ][ key ]; + }, + access: function( owner, key, value ) { + var stored; + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + stored = this.get( owner, key ); + + return stored !== undefined ? + stored : this.get( owner, jQuery.camelCase( key ) ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, name, camel, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key === undefined ) { + this.register( owner ); + + } else { + + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { + + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = key.concat( key.map( jQuery.camelCase ) ); + } else { + camel = jQuery.camelCase( key ); + + // Try the string as a key before any manipulation + if ( key in cache ) { + name = [ key, camel ]; + } else { + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + name = camel; + name = name in cache ? + [ name ] : ( name.match( rnotwhite ) || [] ); + } + } + + i = name.length; + + while ( i-- ) { + delete cache[ name[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <= 35-45+ + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://code.google.com/p/chromium/issues/detail?id=378607 + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data, camelKey; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // with the key as-is + data = dataUser.get( elem, key ) || + + // Try to find dashed key if it exists (gh-2779) + // This is for 2.2.x only + dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); + + if ( data !== undefined ) { + return data; + } + + camelKey = jQuery.camelCase( key ); + + // Attempt to get data from the cache + // with the key camelized + data = dataUser.get( elem, camelKey ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, camelKey, undefined ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + camelKey = jQuery.camelCase( key ); + this.each( function() { + + // First, attempt to store a copy or reference of any + // data that might've been store with a camelCased key. + var data = dataUser.get( this, camelKey ); + + // For HTML5 data-* attribute interop, we have to + // store property names with dashes in a camelCase form. + // This might not apply to all properties...* + dataUser.set( this, camelKey, value ); + + // *... In the case of properties that might _actually_ + // have dashes, we need to also store a copy of that + // unchanged property. + if ( key.indexOf( "-" ) > -1 && data !== undefined ) { + dataUser.set( this, key, value ); + } + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || + !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + maxIterations = 20, + currentValue = tween ? + function() { return tween.cur(); } : + function() { return jQuery.css( elem, prop, "" ); }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + do { + + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([\w:-]+)/ ); + +var rscriptType = ( /^$|\/(?:java|ecma)script/i ); + + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // Support: IE9 + option: [ 1, "" ], + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
      " ], + col: [ 2, "", "
      " ], + tr: [ 2, "", "
      " ], + td: [ 3, "", "
      " ], + + _default: [ 0, "", "" ] +}; + +// Support: IE9 +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + + +function getAll( context, tag ) { + + // Support: IE9-11+ + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== "undefined" ? + context.querySelectorAll( tag || "*" ) : + []; + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0-4.3, Safari<=5.1 + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Safari<=5.1, Android<4.2 + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<=11+ + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE9 +// See #13393 for more info +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Support (at least): Chrome, IE9 + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // + // Support: Firefox<=42+ + // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) + if ( delegateCount && cur.nodeType && + ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push( { elem: cur, handlers: matches } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split( " " ), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " + + "screenX screenY toElement" ).split( " " ), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - + ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - + ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: Cordova 2.5 (WebKit) (#13255) + // All events should have a target; Cordova deviceready doesn't + if ( !event.target ) { + event.target = document; + } + + // Support: Safari 6.0+, Chrome<28 + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android<4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://code.google.com/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, + + // Support: IE 10-11, Edge 10240+ + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName( "tbody" )[ 0 ] || + elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <= 35-45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <= 35-45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + + // Keep domManip exposed until 3.0 (gh-2225) + domManip: domManip, + + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: QtWebKit + // .get() because push.apply(_, arraylike) throws + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); + + +var iframe, + elemdisplay = { + + // Support: Firefox + // We have to pre-define these values for FF (#10227) + HTML: "block", + BODY: "block" + }; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ + +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + display = jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = ( iframe || jQuery( "